diff --git a/mergekit/__init__.py b/mergekit/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/mergekit/_data/__init__.py b/mergekit/_data/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/mergekit/_data/architectures/__init__.py b/mergekit/_data/architectures/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/mergekit/_data/architectures/baichuan.json b/mergekit/_data/architectures/baichuan.json deleted file mode 100644 index bc5cbbe1e772ca33440bf6c7b026048bf22f9c53..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/baichuan.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "model_type": "baichuan", - "architectures": [ - "BaichuanForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "model.norm.weight" - }, - { - "name": "lm_head.weight", - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.W_pack.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/bert-masked-lm.json b/mergekit/_data/architectures/bert-masked-lm.json deleted file mode 100644 index 5a887cb38aaec5d80a6c51d0485ebb053f062ae8..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/bert-masked-lm.json +++ /dev/null @@ -1,118 +0,0 @@ -{ - "model_type": "bert", - "architectures": [ - "BertForMaskedLM" - ], - "pre_weights": [ - { - "name": "bert.embeddings.position_embeddings.weight" - }, - { - "name": "bert.embeddings.token_type_embeddings.weight" - }, - { - "name": "bert.embeddings.word_embeddings.weight", - "is_embed": true - }, - { - "name": "bert.embeddings.LayerNorm.bias", - "aliases": [ - "bert.embeddings.LayerNorm.beta" - ] - }, - { - "name": "bert.embeddings.LayerNorm.weight", - "aliases": [ - "bert.embeddings.LayerNorm.gamma" - ] - }, - { - "name": "bert.embeddings.position_ids", - "optional": true, - "force_dtype": "int64" - } - ], - "post_weights": [ - { - "name": "bert.pooler.dense.weight" - }, - { - "name": "bert.pooler.dense.bias" - }, - { - "name": "cls.predictions.bias" - }, - { - "name": "cls.predictions.decoder.weight", - "aliases": [ - "bert.embeddings.word_embeddings.weight" - ], - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "bert.encoder.layer.${layer_index}.attention.self.query.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.query.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.key.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.key.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.value.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.value.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.dense.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.dense.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.beta" - ] - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.gamma" - ] - }, - { - "name": "bert.encoder.layer.${layer_index}.intermediate.dense.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.intermediate.dense.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.output.dense.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.output.dense.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.output.LayerNorm.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.output.LayerNorm.beta" - ] - }, - { - "name": "bert.encoder.layer.${layer_index}.output.LayerNorm.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.output.LayerNorm.gamma" - ] - } - ] - } -} diff --git a/mergekit/_data/architectures/bert-sequence-classification.json b/mergekit/_data/architectures/bert-sequence-classification.json deleted file mode 100644 index edc8acd4e7697dd48e7c6b1a90fa2eb60328ebc6..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/bert-sequence-classification.json +++ /dev/null @@ -1,118 +0,0 @@ -{ - "model_type": "bert", - "architectures": [ - "BertForSequenceClassification", - "BertForMultipleChoice", - "BertForTokenClassification" - ], - "pre_weights": [ - { - "name": "bert.embeddings.position_embeddings.weight" - }, - { - "name": "bert.embeddings.token_type_embeddings.weight" - }, - { - "name": "bert.embeddings.word_embeddings.weight", - "is_embed": true - }, - { - "name": "bert.embeddings.LayerNorm.bias", - "aliases": [ - "bert.embeddings.LayerNorm.beta" - ] - }, - { - "name": "bert.embeddings.LayerNorm.weight", - "aliases": [ - "bert.embeddings.LayerNorm.gamma" - ] - }, - { - "name": "bert.embeddings.position_ids", - "optional": true, - "force_dtype": "int64" - } - ], - "post_weights": [ - { - "name": "bert.pooler.dense.weight", - "optional": true - }, - { - "name": "bert.pooler.dense.bias", - "optional": true - }, - { - "name": "classifier.bias" - }, - { - "name": "classifier.weight" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "bert.encoder.layer.${layer_index}.attention.self.query.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.query.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.key.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.key.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.value.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.self.value.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.dense.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.dense.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.beta" - ] - }, - { - "name": "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.gamma" - ] - }, - { - "name": "bert.encoder.layer.${layer_index}.intermediate.dense.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.intermediate.dense.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.output.dense.weight" - }, - { - "name": "bert.encoder.layer.${layer_index}.output.dense.bias" - }, - { - "name": "bert.encoder.layer.${layer_index}.output.LayerNorm.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.output.LayerNorm.beta" - ] - }, - { - "name": "bert.encoder.layer.${layer_index}.output.LayerNorm.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.output.LayerNorm.gamma" - ] - } - ] - } -} diff --git a/mergekit/_data/architectures/bert.json b/mergekit/_data/architectures/bert.json deleted file mode 100644 index 4a6e5319dc1067480be1d0fdd397553f7b5e10e8..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/bert.json +++ /dev/null @@ -1,175 +0,0 @@ -{ - "model_type": "bert", - "architectures": [ - "BertModel" - ], - "pre_weights": [ - { - "name": "embeddings.position_embeddings.weight", - "aliases": [ - "bert.embeddings.position_embeddings.weight" - ] - }, - { - "name": "embeddings.token_type_embeddings.weight", - "aliases": [ - "bert.embeddings.token_type_embeddings.weight" - ] - }, - { - "name": "embeddings.word_embeddings.weight", - "is_embed": true, - "aliases": [ - "bert.embeddings.word_embeddings.weight" - ] - }, - { - "name": "embeddings.LayerNorm.bias", - "aliases": [ - "embeddings.LayerNorm.beta", - "bert.embeddings.LayerNorm.bias", - "bert.embeddings.LayerNorm.beta" - ] - }, - { - "name": "embeddings.LayerNorm.weight", - "aliases": [ - "embeddings.LayerNorm.gamma", - "bert.embeddings.LayerNorm.weight", - "bert.embeddings.LayerNorm.gamma", - "bert.embeddings.LayerNorm.weight" - ] - }, - { - "name": "embeddings.position_ids", - "optional": true, - "force_dtype": "int64", - "aliases": [ - "bert.embeddings.position_ids" - ] - } - ], - "post_weights": [ - { - "name": "pooler.dense.weight", - "aliases": [ - "bert.pooler.dense.weight" - ] - }, - { - "name": "pooler.dense.bias", - "aliases": [ - "bert.pooler.dense.bias" - ] - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "encoder.layer.${layer_index}.attention.self.query.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.self.query.weight" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.self.query.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.self.query.bias" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.self.key.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.self.key.weight" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.self.key.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.self.key.bias" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.self.value.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.self.value.weight" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.self.value.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.self.value.bias" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.output.dense.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.output.dense.weight" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.output.dense.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.attention.output.dense.bias" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.output.LayerNorm.bias", - "aliases": [ - "encoder.layer.${layer_index}.attention.output.LayerNorm.beta", - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.bias", - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.beta" - ] - }, - { - "name": "encoder.layer.${layer_index}.attention.output.LayerNorm.weight", - "aliases": [ - "encoder.layer.${layer_index}.attention.output.LayerNorm.gamma", - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.weight", - "bert.encoder.layer.${layer_index}.attention.output.LayerNorm.gamma" - ] - }, - { - "name": "encoder.layer.${layer_index}.intermediate.dense.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.intermediate.dense.weight" - ] - }, - { - "name": "encoder.layer.${layer_index}.intermediate.dense.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.intermediate.dense.bias" - ] - }, - { - "name": "encoder.layer.${layer_index}.output.dense.weight", - "aliases": [ - "bert.encoder.layer.${layer_index}.output.dense.weight" - ] - }, - { - "name": "encoder.layer.${layer_index}.output.dense.bias", - "aliases": [ - "bert.encoder.layer.${layer_index}.output.dense.bias" - ] - }, - { - "name": "encoder.layer.${layer_index}.output.LayerNorm.bias", - "aliases": [ - "encoder.layer.${layer_index}.output.LayerNorm.beta", - "bert.encoder.layer.${layer_index}.output.LayerNorm.bias", - "bert.encoder.layer.${layer_index}.output.LayerNorm.beta" - ] - }, - { - "name": "encoder.layer.${layer_index}.output.LayerNorm.weight", - "aliases": [ - "encoder.layer.${layer_index}.output.LayerNorm.gamma", - "bert.encoder.layer.${layer_index}.output.LayerNorm.weight", - "bert.encoder.layer.${layer_index}.output.LayerNorm.gamma" - ] - } - ] - } -} diff --git a/mergekit/_data/architectures/chatglm.json b/mergekit/_data/architectures/chatglm.json deleted file mode 100644 index bfaef67ac9a5ebc78f94439c2a5c9bd0ebff51a7..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/chatglm.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "model_type": "chatglm", - "architectures": [ - "ChatGLMModel" - ], - "pre_weights": [ - { - "name": "transformer.embedding.word_embeddings.weight", - "is_embed": true - }, - { - "name": "transformer.rotary_pos_emb.inv_freq" - } - ], - "post_weights": [ - { - "name": "transformer.encoder.final_layernorm.weight" - }, - { - "name": "transformer.output_layer.weight", - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "transformer.encoder.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "transformer.encoder.layers.${layer_index}.mlp.dense_4h_to_h.weight" - }, - { - "name": "transformer.encoder.layers.${layer_index}.mlp.dense_h_to_4h.weight" - }, - { - "name": "transformer.encoder.layers.${layer_index}.post_attention_layernorm.weight" - }, - { - "name": "transformer.encoder.layers.${layer_index}.self_attention.dense.weight" - }, - { - "name": "transformer.encoder.layers.${layer_index}.self_attention.query_key_value.bias" - }, - { - "name": "transformer.encoder.layers.${layer_index}.self_attention.query_key_value.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/cohere.json b/mergekit/_data/architectures/cohere.json deleted file mode 100644 index 0fcb3d698b1f729ec62356c63aeb1af89223623e..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/cohere.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "model_type": "cohere", - "architectures": [ - "CohereForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "model.norm.weight" - }, - { - "name": "lm_head.weight", - "is_embed": true, - "aliases": [ - "model.embed_tokens.weight" - ] - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/distilbert-masked-lm.json b/mergekit/_data/architectures/distilbert-masked-lm.json deleted file mode 100644 index d5218b23c669c7b118f347002a5337682642b057..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/distilbert-masked-lm.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "model_type": "distilbert", - "architectures": [ - "DistilBertForMaskedLM" - ], - "pre_weights": [ - { - "name": "distilbert.embeddings.position_embeddings.weight" - }, - { - "name": "distilbert.embeddings.word_embeddings.weight", - "is_embed": true - }, - { - "name": "distilbert.embeddings.LayerNorm.bias", - "aliases": [ - "distilbert.embeddings.LayerNorm.beta" - ] - }, - { - "name": "distilbert.embeddings.LayerNorm.weight", - "aliases": [ - "distilbert.embeddings.LayerNorm.gamma" - ] - } - ], - "post_weights": [ - { - "name": "vocab_transform.weight" - }, - { - "name": "vocab_transform.bias" - }, - { - "name": "vocab_layer_norm.bias" - }, - { - "name": "vocab_layer_norm.weight" - }, - { - "name": "vocab_projector.weight", - "is_embed": true, - "aliases": [ - "distilbert.embeddings.word_embeddings.weight" - ] - }, - { - "name": "vocab_projector.bias" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/distilbert-sequence-classification.json b/mergekit/_data/architectures/distilbert-sequence-classification.json deleted file mode 100644 index 92c28373bea4c561dd992364e4457bd0b107ae36..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/distilbert-sequence-classification.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "model_type": "distilbert", - "architectures": [ - "DistilBertForSequenceClassification" - ], - "pre_weights": [ - { - "name": "distilbert.embeddings.position_embeddings.weight" - }, - { - "name": "distilbert.embeddings.word_embeddings.weight", - "is_embed": true - }, - { - "name": "distilbert.embeddings.LayerNorm.bias", - "aliases": [ - "distilbert.embeddings.LayerNorm.beta" - ] - }, - { - "name": "distilbert.embeddings.LayerNorm.weight", - "aliases": [ - "distilbert.embeddings.LayerNorm.gamma" - ] - } - ], - "post_weights": [ - { - "name": "classifier.bias" - }, - { - "name": "classifier.weight" - }, - { - "name": "pre_classifier.bias" - }, - { - "name": "pre_classifier.weight" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/distilbert-token-classification.json b/mergekit/_data/architectures/distilbert-token-classification.json deleted file mode 100644 index f13bb3905b05ba4b1451822a8642d3f9a7e9a6ac..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/distilbert-token-classification.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "model_type": "distilbert", - "architectures": [ - "DistilBertForTokenClassification" - ], - "pre_weights": [ - { - "name": "distilbert.embeddings.position_embeddings.weight" - }, - { - "name": "distilbert.embeddings.word_embeddings.weight", - "is_embed": true - }, - { - "name": "distilbert.embeddings.LayerNorm.bias", - "aliases": [ - "distilbert.embeddings.LayerNorm.beta" - ] - }, - { - "name": "distilbert.embeddings.LayerNorm.weight", - "aliases": [ - "distilbert.embeddings.LayerNorm.gamma" - ] - } - ], - "post_weights": [ - { - "name": "classifier.bias" - }, - { - "name": "classifier.weight" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/distilbert.json b/mergekit/_data/architectures/distilbert.json deleted file mode 100644 index 4ec5d12b0f27dc6784ffb8744f336a5c5279af8c..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/distilbert.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "model_type": "distilbert", - "architectures": [ - "DistilBertModel" - ], - "pre_weights": [ - { - "name": "distilbert.embeddings.position_embeddings.weight" - }, - { - "name": "distilbert.embeddings.word_embeddings.weight", - "is_embed": true - }, - { - "name": "distilbert.embeddings.LayerNorm.bias", - "aliases": [ - "distilbert.embeddings.LayerNorm.beta" - ] - }, - { - "name": "distilbert.embeddings.LayerNorm.weight", - "aliases": [ - "distilbert.embeddings.LayerNorm.gamma" - ] - } - ], - "post_weights": [], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.k_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.q_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.v_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.attention.out_lin.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.sa_layer_norm.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin1.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.weight" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.ffn.lin2.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.bias" - }, - { - "name": "distilbert.transformer.layer.${layer_index}.output_layer_norm.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/falcon.json b/mergekit/_data/architectures/falcon.json deleted file mode 100644 index 14ad2dcf823882e58f05dc6d98aad90ac31e47af..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/falcon.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "model_type": "falcon", - "architectures": [ - "FalconForCausalLM" - ], - "pre_weights": [ - { - "name": "transformer.word_embeddings.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "transformer.ln_f.weight" - }, - { - "name": "transformer.ln_f.bias" - }, - { - "name": "lm_head.weight", - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "transformer.h.${layer_index}.ln_attn.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_attn.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_mlp.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_mlp.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.dense_4h_to_h.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.dense_h_to_4h.weight" - }, - { - "name": "transformer.h.${layer_index}.self_attention.dense.weight" - }, - { - "name": "transformer.h.${layer_index}.self_attention.query_key_value.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/gemma.json b/mergekit/_data/architectures/gemma.json deleted file mode 100644 index a716fae3184c33cb6dc9045163e9477c5a75ee5c..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/gemma.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "model_type": "gemma", - "architectures": [ - "GemmaForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true, - "output_space": "h_0" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight", - "input_space": "h_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_v_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight", - "input_space": "attn_v_${layer_index}", - "output_space": "post_attn_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight", - "input_space": "h_a_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight", - "input_space": "up_${layer_index}", - "output_space": "post_mlp_${layer_index}" - } - ], - "procedural_spaces": [ - { - "name": "h_a_${layer_index}", - "type": "residual", - "inputs": [ - "h_${layer_index}", - "post_attn_${layer_index}" - ] - }, - { - "name": "h_${layer_index+1}", - "type": "residual", - "inputs": [ - "h_a_${layer_index}", - "post_mlp_${layer_index}" - ] - } - ] - }, - "post_weights": [ - { - "name": "model.norm.weight", - "input_space": "h_${num_layers}" - } - ] -} diff --git a/mergekit/_data/architectures/gemma2.json b/mergekit/_data/architectures/gemma2.json deleted file mode 100644 index 5bb3346f892942171f1101c707eb2b6500c33435..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/gemma2.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "model_type": "gemma2", - "architectures": [ - "Gemma2ForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.pre_feedforward_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight" - }, - { - "name": "model.layers.${layer_index}.post_feedforward_layernorm.weight" - } - ] - }, - "post_weights": [ - { - "name": "model.norm.weight" - }, - { - "name": "lm_head.weight", - "is_embed": true, - "aliases": [ - "model.embed_tokens.weight" - ] - } - ] -} diff --git a/mergekit/_data/architectures/gpt-neox.json b/mergekit/_data/architectures/gpt-neox.json deleted file mode 100644 index 662f766b3da1971238417295a959c44a2cfb3061..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/gpt-neox.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "model_type": "gpt_neox", - "architectures": [ - "GPTNeoXForCausalLM" - ], - "pre_weights": [ - { - "name": "gpt_neox.embed_in.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "gpt_neox.final_layer_norm.bias" - }, - { - "name": "gpt_neox.final_layer_norm.weight" - }, - { - "name": "embed_out.weight", - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "gpt_neox.layers.${layer_index}.attention.dense.weight" - }, - { - "name": "gpt_neox.layers.${layer_index}.attention.dense.bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.attention.query_key_value.weight" - }, - { - "name": "gpt_neox.layers.${layer_index}.attention.query_key_value.bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "gpt_neox.layers.${layer_index}.input_layernorm.bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.mlp.dense_4h_to_h.weight" - }, - { - "name": "gpt_neox.layers.${layer_index}.mlp.dense_4h_to_h.bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.mlp.dense_h_to_4h.weight" - }, - { - "name": "gpt_neox.layers.${layer_index}.mlp.dense_h_to_4h.bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.post_attention_layernorm.weight" - }, - { - "name": "gpt_neox.layers.${layer_index}.post_attention_layernorm.bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.attention.bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.attention.masked_bias" - }, - { - "name": "gpt_neox.layers.${layer_index}.attention.rotary_emb.inv_freq" - } - ] - } -} diff --git a/mergekit/_data/architectures/gpt2-sequence-classification.json b/mergekit/_data/architectures/gpt2-sequence-classification.json deleted file mode 100644 index 112761e3d166094f39302161229149d6e0f1ddb8..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/gpt2-sequence-classification.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "model_type": "gpt2", - "architectures": [ - "GPT2ForSequenceClassification" - ], - "pre_weights": [ - { - "name": "transformer.wte.weight" - }, - { - "name": "transformer.wpe.weight" - } - ], - "post_weights": [ - { - "name": "transformer.ln_f.weight" - }, - { - "name": "transformer.ln_f.bias" - }, - { - "name": "score.weight" - } - ], - "num_layers_config_key": "n_layer", - "layer_templates": { - "weights": [ - { - "name": "transformer.h.${layer_index}.attn.c_attn.weight" - }, - { - "name": "transformer.h.${layer_index}.attn.c_attn.bias" - }, - { - "name": "transformer.h.${layer_index}.attn.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.attn.c_proj.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_1.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_1.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_2.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_2.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_proj.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/gpt2.json b/mergekit/_data/architectures/gpt2.json deleted file mode 100644 index e8245adfd683fb69f7b6c0a54b463eaa95eab4db..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/gpt2.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "model_type": "gpt2", - "architectures": [ - "GPT2LMHeadModel" - ], - "pre_weights": [ - { - "name": "wte.weight", - "is_embed": true - }, - { - "name": "wpe.weight" - } - ], - "post_weights": [ - { - "name": "ln_f.weight" - }, - { - "name": "ln_f.bias" - } - ], - "num_layers_config_key": "n_layer", - "layer_templates": { - "weights": [ - { - "name": "h.${layer_index}.attn.c_attn.weight" - }, - { - "name": "h.${layer_index}.attn.c_attn.bias" - }, - { - "name": "h.${layer_index}.attn.c_proj.weight" - }, - { - "name": "h.${layer_index}.attn.c_proj.bias" - }, - { - "name": "h.${layer_index}.ln_1.weight" - }, - { - "name": "h.${layer_index}.ln_1.bias" - }, - { - "name": "h.${layer_index}.ln_2.weight" - }, - { - "name": "h.${layer_index}.ln_2.bias" - }, - { - "name": "h.${layer_index}.mlp.c_proj.weight" - }, - { - "name": "h.${layer_index}.mlp.c_proj.bias" - }, - { - "name": "h.${layer_index}.mlp.c_fc.weight" - }, - { - "name": "h.${layer_index}.mlp.c_fc.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/gptbigcode.json b/mergekit/_data/architectures/gptbigcode.json deleted file mode 100644 index b47853b3cbdfd195a67a04e75480596c6efba1d5..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/gptbigcode.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "model_type": "gpt_bigcode", - "architectures": [ - "GPTBigCodeForCausalLM" - ], - "pre_weights": [ - { - "name": "transformer.wte.weight", - "is_embed": true - }, - { - "name": "transformer.wpe.weight" - } - ], - "post_weights": [ - { - "name": "transformer.ln_f.weight" - }, - { - "name": "transformer.ln_f.bias" - }, - { - "name": "lm_head.weight", - "aliases": [ - "transformer.wte.weight" - ] - } - ], - "num_layers_config_key": "n_layer", - "layer_templates": { - "weights": [ - { - "name": "transformer.h.${layer_index}.attn.c_attn.weight" - }, - { - "name": "transformer.h.${layer_index}.attn.c_attn.bias" - }, - { - "name": "transformer.h.${layer_index}.attn.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.attn.c_proj.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_1.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_1.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_2.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_2.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_proj.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/jais.json b/mergekit/_data/architectures/jais.json deleted file mode 100644 index 8d90873070e7291d3483ee9e5045d17672cadcac..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/jais.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "model_type": "jais", - "architectures": [ - "JAISLMHeadModel" - ], - "pre_weights": [ - { - "name": "transformer.wte.weight", - "is_embed": true - }, - { - "name": "transformer.relative_pe.slopes" - } - ], - "post_weights": [ - { - "name": "transformer.ln_f.weight" - }, - { - "name": "transformer.ln_f.bias" - } - ], - "num_layers_config_key": "n_layer", - "layer_templates": { - "weights": [ - { - "name": "transformer.h.${layer_index}.attn.c_attn.weight" - }, - { - "name": "transformer.h.${layer_index}.attn.c_attn.bias" - }, - { - "name": "transformer.h.${layer_index}.attn.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.attn.c_proj.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_1.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_1.bias" - }, - { - "name": "transformer.h.${layer_index}.ln_2.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_2.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc2.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_fc2.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_proj.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/llama.json b/mergekit/_data/architectures/llama.json deleted file mode 100644 index 0c5b216dc27011d1ccb927d3829b88c4e81f3f5f..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/llama.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "model_type": "llama", - "architectures": [ - "LlamaForCausalLM", - "LLaMaForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true, - "output_space": "h_0" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight", - "input_space": "h_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_v_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight", - "input_space": "attn_v_${layer_index}", - "output_space": "post_attn_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight", - "input_space": "h_a_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight", - "input_space": "up_${layer_index}", - "output_space": "post_mlp_${layer_index}" - } - ], - "procedural_spaces": [ - { - "name": "h_a_${layer_index}", - "type": "residual", - "inputs": [ - "h_${layer_index}", - "post_attn_${layer_index}" - ] - }, - { - "name": "h_${layer_index+1}", - "type": "residual", - "inputs": [ - "h_a_${layer_index}", - "post_mlp_${layer_index}" - ] - } - ] - }, - "post_weights": [ - { - "name": "model.norm.weight", - "input_space": "h_${num_layers}" - }, - { - "name": "lm_head.weight", - "input_space": "h_${num_layers}", - "is_embed": true - } - ] -} diff --git a/mergekit/_data/architectures/mamba.json b/mergekit/_data/architectures/mamba.json deleted file mode 100644 index fddd803b16f19efa403c2a024b27074bcee942c7..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/mamba.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "model_type": "mamba", - "architectures": [ - "MambaForCausalLM" - ], - "pre_weights": [ - { - "name": "backbone.embeddings.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "backbone.norm_f.weight" - }, - { - "name": "lm_head.weight", - "is_embed": true, - "aliases": ["backbone.embeddings.weight"] - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "backbone.layers.${layer_index}.mixer.A_log" - }, - { - "name": "backbone.layers.${layer_index}.mixer.conv1d.bias" - }, - { - "name": "backbone.layers.${layer_index}.mixer.conv1d.weight" - }, - { - "name": "backbone.layers.${layer_index}.mixer.D" - }, - { - "name": "backbone.layers.${layer_index}.mixer.dt_proj.bias" - }, - { - "name": "backbone.layers.${layer_index}.mixer.dt_proj.weight" - }, - { - "name": "backbone.layers.${layer_index}.mixer.in_proj.weight" - }, - { - "name": "backbone.layers.${layer_index}.mixer.out_proj.weight" - }, - { - "name": "backbone.layers.${layer_index}.mixer.x_proj.weight" - }, - { - "name": "backbone.layers.${layer_index}.norm.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/mistral.json b/mergekit/_data/architectures/mistral.json deleted file mode 100644 index 96bac73b0cc3300925fbcfbbca33e292f7929f6b..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/mistral.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "model_type": "mistral", - "architectures": [ - "MistralForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true, - "output_space": "h_0" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight", - "input_space": "h_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_v_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight", - "input_space": "attn_v_${layer_index}", - "output_space": "post_attn_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight", - "input_space": "h_a_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight", - "input_space": "up_${layer_index}", - "output_space": "post_mlp_${layer_index}" - } - ], - "procedural_spaces": [ - { - "name": "h_a_${layer_index}", - "type": "residual", - "inputs": [ - "h_${layer_index}", - "post_attn_${layer_index}" - ] - }, - { - "name": "h_${layer_index+1}", - "type": "residual", - "inputs": [ - "h_a_${layer_index}", - "post_mlp_${layer_index}" - ] - } - ] - }, - "post_weights": [ - { - "name": "model.norm.weight", - "input_space": "h_${num_layers}" - }, - { - "name": "lm_head.weight", - "input_space": "h_${num_layers}", - "is_embed": true - } - ] -} diff --git a/mergekit/_data/architectures/phi-1.json b/mergekit/_data/architectures/phi-1.json deleted file mode 100644 index 60ca0cd880ccd329cd65caf245e167b314023a1e..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/phi-1.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "model_type": "mixformer-sequential", - "architectures": [ - "MixFormerSequentialForCausalLM" - ], - "pre_weights": [ - { - "name": "layers.0.wte.weight", - "is_embed": true - } - ], - "num_layers_config_key": "n_layer", - "layer_templates": { - "weights": [ - { - "name": "layers.${layer_index}.ln.bias" - }, - { - "name": "layers.${layer_index}.ln.weight" - }, - { - "name": "layers.${layer_index}.mixer.Wqkv.bias" - }, - { - "name": "layers.${layer_index}.mixer.Wqkv.weight" - }, - { - "name": "layers.${layer_index}.mixer.out_proj.bias" - }, - { - "name": "layers.${layer_index}.mixer.out_proj.weight" - }, - { - "name": "layers.${layer_index}.mixer.rotary_emb.inv_freq" - }, - { - "name": "layers.${layer_index}.mlp.fc1.bias" - }, - { - "name": "layers.${layer_index}.mlp.fc1.weight" - }, - { - "name": "layers.${layer_index}.mlp.fc2.bias" - }, - { - "name": "layers.${layer_index}.mlp.fc2.weight" - } - ] - }, - "post_weights": [ - { - "name": "layers.${num_layers}.linear.bias", - "is_embed": true - }, - { - "name": "layers.${num_layers}.linear.weight", - "is_embed": true - }, - { - "name": "layers.${num_layers}.ln.bias" - }, - { - "name": "layers.${num_layers}.ln.weight" - } - ] -} diff --git a/mergekit/_data/architectures/phi2-old.json b/mergekit/_data/architectures/phi2-old.json deleted file mode 100644 index f45a491243c8175a65f80470ade390d67dd34892..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/phi2-old.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "model_type": "phi-msft", - "architectures": [ - "PhiForCausalLM" - ], - "pre_weights": [ - { - "name": "transformer.embd.wte.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "lm_head.linear.bias" - }, - { - "name": "lm_head.linear.weight", - "is_embed": true - }, - { - "name": "lm_head.ln.bias" - }, - { - "name": "lm_head.ln.weight" - } - ], - "num_layers_config_key": "n_layer", - "layer_templates": { - "weights": [ - { - "name": "transformer.h.${layer_index}.ln.bias" - }, - { - "name": "transformer.h.${layer_index}.ln.weight" - }, - { - "name": "transformer.h.${layer_index}.mixer.out_proj.bias" - }, - { - "name": "transformer.h.${layer_index}.mixer.out_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.mixer.Wqkv.bias" - }, - { - "name": "transformer.h.${layer_index}.mixer.Wqkv.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.fc1.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.fc1.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.fc2.bias" - }, - { - "name": "transformer.h.${layer_index}.mlp.fc2.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/phi2.json b/mergekit/_data/architectures/phi2.json deleted file mode 100644 index a98672b7653602253425f281b2d060c0e2fc909b..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/phi2.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "model_type": "phi", - "architectures": [ - "PhiForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "lm_head.bias" - }, - { - "name": "lm_head.weight", - "is_embed": true - }, - { - "name": "model.final_layernorm.bias" - }, - { - "name": "model.final_layernorm.weight" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.bias" - }, - { - "name": "model.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.dense.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.dense.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.fc1.bias" - }, - { - "name": "model.layers.${layer_index}.mlp.fc1.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.fc2.bias" - }, - { - "name": "model.layers.${layer_index}.mlp.fc2.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/phi3.json b/mergekit/_data/architectures/phi3.json deleted file mode 100644 index fe8b2d738b9909e02418e3dcc4332d3109710163..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/phi3.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "model_type": "phi", - "architectures": [ - "Phi3ForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "lm_head.weight", - "is_embed": true - }, - { - "name": "model.norm.weight" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight", - "is_embed": false - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight", - "is_embed": false - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight", - "is_embed": false - }, - { - "name": "model.layers.${layer_index}.self_attn.qkv_proj.weight", - "is_embed": false - }, - { - "name": "model.layers.${layer_index}.mlp.gate_up_proj.weight", - "is_embed": false - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight", - "is_embed": false - } - ] - } -} diff --git a/mergekit/_data/architectures/qwen.json b/mergekit/_data/architectures/qwen.json deleted file mode 100644 index a275e4e9eb431128d3434fbe74cda87e2c7e2af1..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/qwen.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "model_type": "qwen", - "architectures": [ - "QWenLMHeadModel" - ], - "pre_weights": [ - { - "name": "transformer.wte.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "transformer.ln_f.weight" - }, - { - "name": "lm_head.weight", - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "transformer.h.${layer_index}.attn.c_attn.bias" - }, - { - "name": "transformer.h.${layer_index}.attn.c_attn.weight" - }, - { - "name": "transformer.h.${layer_index}.attn.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_1.weight" - }, - { - "name": "transformer.h.${layer_index}.ln_2.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.c_proj.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.w1.weight" - }, - { - "name": "transformer.h.${layer_index}.mlp.w2.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/qwen2.json b/mergekit/_data/architectures/qwen2.json deleted file mode 100644 index 3a98b008ab255d196b49e2b2648b55623ea5bb02..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/qwen2.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "model_type": "qwen2", - "architectures": [ - "Qwen2ForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "model.norm.weight" - }, - { - "name": "lm_head.weight", - "is_embed": true, - "aliases": [ - "model.embed_tokens.weight" - ] - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/roberta-masked-lm.json b/mergekit/_data/architectures/roberta-masked-lm.json deleted file mode 100644 index 600fd5a10cd48de2abad41db6e02080874bc92a9..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/roberta-masked-lm.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "model_type": "roberta", - "architectures": [ - "RobertaForMaskedLM" - ], - "pre_weights": [ - { - "name": "roberta.embeddings.position_embeddings.weight" - }, - { - "name": "roberta.embeddings.word_embeddings.weight" - }, - { - "name": "roberta.embeddings.token_type_embeddings.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.bias" - }, - { - "name": "roberta.embeddings.position_ids", - "optional": true, - "force_dtype": "int64" - } - ], - "post_weights": [ - { - "name": "lm_head.bias" - }, - { - "name": "lm_head.dense.weight" - }, - { - "name": "lm_head.dense.bias" - }, - { - "name": "lm_head.layer_norm.weight" - }, - { - "name": "lm_head.layer_norm.bias" - }, - { - "name": "lm_head.decoder.weight", - "aliases": [ - "roberta.embeddings.word_embeddings.weight" - ] - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/roberta-sequence-classification.json b/mergekit/_data/architectures/roberta-sequence-classification.json deleted file mode 100644 index bb5b3964e15afebe9a5d69acd82d6be493815b29..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/roberta-sequence-classification.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "model_type": "roberta", - "architectures": [ - "RobertaForSequenceClassification" - ], - "pre_weights": [ - { - "name": "roberta.embeddings.position_embeddings.weight" - }, - { - "name": "roberta.embeddings.word_embeddings.weight" - }, - { - "name": "roberta.embeddings.token_type_embeddings.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.bias" - }, - { - "name": "roberta.embeddings.position_ids", - "optional": true, - "force_dtype": "int64" - } - ], - "post_weights": [ - { - "name": "classifier.dense.weight" - }, - { - "name": "classifier.dense.bias" - }, - { - "name": "classifier.out_proj.weight" - }, - { - "name": "classifier.out_proj.bias" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/roberta-token-classification.json b/mergekit/_data/architectures/roberta-token-classification.json deleted file mode 100644 index 6a6bbe61c81799c01647286ab7a509c9619dec12..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/roberta-token-classification.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "model_type": "roberta", - "architectures": [ - "RobertaForTokenClassification" - ], - "pre_weights": [ - { - "name": "roberta.embeddings.position_embeddings.weight" - }, - { - "name": "roberta.embeddings.word_embeddings.weight" - }, - { - "name": "roberta.embeddings.token_type_embeddings.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.bias" - }, - { - "name": "roberta.embeddings.position_ids", - "optional": true, - "force_dtype": "int64" - } - ], - "post_weights": [ - { - "name": "classifier.weight" - }, - { - "name": "classifier.bias" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/roberta.json b/mergekit/_data/architectures/roberta.json deleted file mode 100644 index 41a513b162e6e14c19dbca4e17453f426a592143..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/roberta.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "model_type": "roberta", - "architectures": [ - "RobertaModel" - ], - "pre_weights": [ - { - "name": "roberta.embeddings.position_embeddings.weight" - }, - { - "name": "roberta.embeddings.word_embeddings.weight" - }, - { - "name": "roberta.embeddings.token_type_embeddings.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.weight" - }, - { - "name": "roberta.embeddings.LayerNorm.bias" - }, - { - "name": "roberta.embeddings.position_ids", - "optional": true, - "force_dtype": "int64" - } - ], - "post_weights": [ - { - "name": "pooler.dense.weight" - }, - { - "name": "pooler.dense.bias" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.output.LayerNorm.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.query.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.key.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.attention.self.value.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.intermediate.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.dense.bias" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.weight" - }, - { - "name": "roberta.encoder.layer.${layer_index}.output.LayerNorm.bias" - } - ] - } -} diff --git a/mergekit/_data/architectures/stablelm.json b/mergekit/_data/architectures/stablelm.json deleted file mode 100644 index 646f88ffd72bbeccc73b59201a04537eb5d9e9ba..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/stablelm.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "model_type": "stablelm_epoch", - "architectures": [ - "StableLMEpochForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true, - "output_space": "h_0" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight", - "input_space": "h_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.input_layernorm.bias", - "input_space": "h_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_qk_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight", - "input_space": "h_${layer_index}", - "output_space": "attn_v_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight", - "input_space": "attn_v_${layer_index}", - "output_space": "post_attn_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight", - "input_space": "h_a_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.bias", - "input_space": "h_a_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight", - "input_space": "h_a_${layer_index}", - "output_space": "up_${layer_index}" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight", - "input_space": "up_${layer_index}", - "output_space": "post_mlp_${layer_index}" - } - ], - "procedural_spaces": [ - { - "name": "h_a_${layer_index}", - "type": "residual", - "inputs": [ - "h_${layer_index}", - "post_attn_${layer_index}" - ] - }, - { - "name": "h_${layer_index+1}", - "type": "residual", - "inputs": [ - "h_a_${layer_index}", - "post_mlp_${layer_index}" - ] - } - ] - }, - "post_weights": [ - { - "name": "model.norm.weight", - "input_space": "h_${num_layers}" - }, - { - "name": "lm_head.weight", - "input_space": "h_${num_layers}", - "is_embed": true - } - ] -} diff --git a/mergekit/_data/architectures/stablelm2.json b/mergekit/_data/architectures/stablelm2.json deleted file mode 100644 index b1d533afc8c21cce694ebdea756e29628830063a..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/stablelm2.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "model_type": "stablelm", - "architectures": [ - "StableLmForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "model.norm.weight" - }, - { - "name": "model.norm.bias" - }, - { - "name": "lm_head.weight", - "is_embed": true - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.input_layernorm.bias" - }, - { - "name": "model.layers.${layer_index}.mlp.down_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.gate_proj.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.up_proj.weight" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.bias", - "optional": true - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.bias", - "optional": true - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.bias", - "optional": true - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight" - } - ] - } -} diff --git a/mergekit/_data/architectures/starcoder2.json b/mergekit/_data/architectures/starcoder2.json deleted file mode 100644 index cc8e88f3e6737e21dd2a9385f9f013e7b75c72f7..0000000000000000000000000000000000000000 --- a/mergekit/_data/architectures/starcoder2.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "model_type": "starcoder2", - "architectures": [ - "Starcoder2ForCausalLM" - ], - "pre_weights": [ - { - "name": "model.embed_tokens.weight", - "is_embed": true - } - ], - "post_weights": [ - { - "name": "lm_head.weight", - "is_embed": true, - "aliases": ["model.embed_tokens.weight"] - }, - { - "name": "model.norm.bias" - }, - { - "name": "model.norm.weight" - } - ], - "num_layers_config_key": "num_hidden_layers", - "layer_templates": { - "weights": [ - { - "name": "model.layers.${layer_index}.input_layernorm.bias" - }, - { - "name": "model.layers.${layer_index}.input_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.q_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.k_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.v_proj.weight" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.bias" - }, - { - "name": "model.layers.${layer_index}.self_attn.o_proj.weight" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.bias" - }, - { - "name": "model.layers.${layer_index}.post_attention_layernorm.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.c_fc.bias" - }, - { - "name": "model.layers.${layer_index}.mlp.c_fc.weight" - }, - { - "name": "model.layers.${layer_index}.mlp.c_proj.bias" - }, - { - "name": "model.layers.${layer_index}.mlp.c_proj.weight" - } - ] - } -} diff --git a/mergekit/architecture.py b/mergekit/architecture.py deleted file mode 100644 index 22425ce42833a999625ffbdffccb81ad5d9b9365..0000000000000000000000000000000000000000 --- a/mergekit/architecture.py +++ /dev/null @@ -1,378 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import importlib.resources -import string -from abc import ABC, abstractmethod -from typing import ClassVar, Dict, List, Optional, Tuple, Union - -from pydantic import BaseModel, Field -from transformers import PretrainedConfig -from typing_extensions import Literal - -import mergekit._data.architectures - - -class WeightInfo(BaseModel, frozen=True): - """Information about an individual weight tensor in a model. - - Attributes: - name (str): - The name of the tensor representing the weight. - is_embed (bool): - Indicates whether the weight is for an embedding or language model head. - input_space (Optional[str]): - The name of the input space associated with the weight, if applicable. - output_space (Optional[str]): - The name of the output space associated with the weight, if applicable. - optional (bool): - Indicates whether the weight can be omitted from a model. - aliases (Optional[List[str]]): - List of alternative names for the weight, if applicable. - force_dtype (Optional[str]): - Mandatory dtype for the weight, if applicable. - """ - - name: str - is_embed: bool = False - input_space: Optional[str] = None - output_space: Optional[str] = None - optional: bool = False - aliases: Optional[Tuple[str, ...]] = None - force_dtype: Optional[str] = None - - -class ProceduralSpaceInfo(BaseModel, frozen=True): - """Defines a procedural space computed from one or more other spaces. - - Currently only supports residual connections. - - Attributes: - name (str): The name of the space defined. - type (str): The type of procedural space. - inputs (List[str]): List of names of spaces used to define this space.""" - - name: str - type: Literal["residual"] - inputs: List[str] - - -class ArchitectureInfo(ABC): - @abstractmethod - def name(self) -> str: - """Return the name of the architecture.""" - ... - - @abstractmethod - def pre_weights(self, config: PretrainedConfig) -> List[WeightInfo]: - """Return a list of all weights preceding the first layer.""" - ... - - @abstractmethod - def post_weights(self, config: PretrainedConfig) -> List[WeightInfo]: - """Return a list of all weights following the final layer.""" - ... - - @abstractmethod - def layer_weights( - self, index: int, config: PretrainedConfig - ) -> Optional[List[WeightInfo]]: - """Return a list of all weights associated with a given layer.""" - ... - - @abstractmethod - def sliceable(self) -> bool: - """ - Return True if the layers of this architecture can be meaningfully sliced. - """ - ... - - def num_layers_config_key(self) -> str: - """Key in config that represents number of layers""" - return "num_hidden_layers" - - def num_layers(self, config: PretrainedConfig) -> int: - """Return the number of layers in a model.""" - return getattr(config, self.num_layers_config_key()) - - def all_weights(self, config: PretrainedConfig) -> List[WeightInfo]: - """Return all weights associated with a model.""" - num_layers = self.num_layers(config) - res = list(self.pre_weights(config)) - for layer_idx in range(num_layers): - res.extend(self.layer_weights(layer_idx, config)) - res.extend(self.post_weights(config)) - return res - - def procedural_spaces(self, config: PretrainedConfig) -> List[ProceduralSpaceInfo]: - """Return a list of all procedurally defined spaces in a model.""" - return [] - - def has_defined_spaces(self) -> bool: - """ - Return True if this architecture defines space information needed for - matching-based merge methods. - """ - return False - - -class ConfiguredArchitectureInfo(BaseModel, frozen=True, arbitrary_types_allowed=True): - info: ArchitectureInfo - config: PretrainedConfig - - def name(self) -> str: - return self.info.name() - - def num_layers(self) -> int: - return self.info.num_layers(self.config) - - def pre_weights(self) -> List[WeightInfo]: - return self.info.pre_weights(self.config) - - def post_weights(self) -> List[WeightInfo]: - return self.info.post_weights(self.config) - - def layer_weights(self, index: int) -> List[WeightInfo]: - return self.info.layer_weights(index, self.config) - - def procedural_spaces(self) -> List[ProceduralSpaceInfo]: - return self.info.procedural_spaces(self.config) - - def all_weights(self) -> List[WeightInfo]: - return self.info.all_weights(self.config) - - -class JSONLayerTemplates(BaseModel, frozen=True): - weights: List[WeightInfo] - procedural_spaces: Optional[List[ProceduralSpaceInfo]] = None - - -class JSONArchitectureDefinition(BaseModel, frozen=True): - expected_model_type: str = Field(alias="model_type") - architectures: List[str] - pre_weights: List[WeightInfo] - layer_templates: JSONLayerTemplates - post_weights: List[WeightInfo] - procedural_spaces: Optional[List[ProceduralSpaceInfo]] = None - num_layers_config_key: Optional[str] = None - - -class TemplateWithArithmetic(string.Template): - idpattern = r"(?a:[_a-z][_a-z0-9]*([+-]1)?)" - - -def _template_substitution( - template: str, num_layers: int, layer_idx: Optional[int] = None -) -> str: - if "{" not in template: - return template - - substitutions = { - "num_layers": num_layers, - "num_layers+1": num_layers + 1, - "num_layers-1": num_layers - 1, - } - - if layer_idx is not None: - substitutions.update( - { - "layer_index": layer_idx, - "layer_index+1": layer_idx + 1, - "layer_index-1": layer_idx - 1, - } - ) - - return TemplateWithArithmetic(template).substitute(substitutions) - - -class JsonArchitectureInfo(ArchitectureInfo, BaseModel, frozen=True): - definition: JSONArchitectureDefinition - - def _substitute( - self, - item: Union[WeightInfo, ProceduralSpaceInfo], - config: PretrainedConfig, - layer_idx: Optional[int] = None, - ) -> Union[WeightInfo, ProceduralSpaceInfo]: - num_layers = self.num_layers(config) - - obj_dict = item.model_dump(mode="json", exclude_unset=True) - for key in obj_dict: - if isinstance(obj_dict[key], str): - obj_dict[key] = _template_substitution( - obj_dict[key], num_layers, layer_idx - ) - elif isinstance(obj_dict[key], list): - obj_dict[key] = [ - ( - _template_substitution(s, num_layers, layer_idx) - if isinstance(s, str) - else s - ) - for s in obj_dict[key] - ] - return type(item).model_validate(obj_dict) - - def name(self) -> str: - return self.definition.expected_model_type - - def pre_weights(self, config: PretrainedConfig) -> List[WeightInfo]: - return [ - self._substitute(wi, config=config) for wi in self.definition.pre_weights - ] - - def layer_weights( - self, index: int, config: PretrainedConfig - ) -> Optional[List[WeightInfo]]: - return [ - self._substitute(wi, config=config, layer_idx=index) - for wi in self.definition.layer_templates.weights - ] - - def post_weights(self, config: PretrainedConfig) -> List[WeightInfo]: - return [ - self._substitute(wi, config=config) for wi in self.definition.post_weights - ] - - def sliceable(self) -> bool: - return True - - def procedural_spaces(self, config: PretrainedConfig) -> List[ProceduralSpaceInfo]: - res = [] - for s in self.definition.procedural_spaces or []: - res.append(self._substitute(s, config=config)) - for idx in range(self.num_layers(config)): - for s in self.definition.layer_templates.procedural_spaces or []: - res.append(self._substitute(s, config=config, layer_idx=idx)) - return res - - def has_defined_spaces(self) -> bool: - if ( - self.definition.procedural_spaces - or self.definition.layer_templates.procedural_spaces - ): - return True - for wi in ( - self.definition.layer_templates.weights - + self.definition.pre_weights - + self.definition.post_weights - ): - if wi.input_space or wi.output_space: - return True - return False - - def num_layers_config_key(self) -> str: - return self.definition.num_layers_config_key - - -class MixtralTensorNames(ArchitectureInfo, BaseModel): - ARCHITECTURE_NAME: ClassVar[str] = "MixtralForCausalLM" - num_local_experts: int - - def name(self) -> str: - return "mixtral" - - @classmethod - def from_config(cls, config: PretrainedConfig): - return MixtralTensorNames(num_local_experts=config.num_local_experts) - - def pre_weights(self, config: PretrainedConfig) -> List[WeightInfo]: - return MISTRAL_INFO.pre_weights(config) - - def post_weights(self, config: PretrainedConfig) -> List[WeightInfo]: - return MISTRAL_INFO.post_weights(config) - - def num_layers_config_key(self) -> str: - return MISTRAL_INFO.num_layers_config_key() - - def layer_weights( - self, index: int, config: PretrainedConfig - ) -> Optional[List[WeightInfo]]: - num_experts = self.num_local_experts - prefix = f"model.layers.{index}" - tensor_names = [] - for expert_idx in range(num_experts): - for param in ("w1", "w2", "w3"): - tensor_names.append( - prefix + f".block_sparse_moe.experts.{expert_idx}.{param}.weight" - ) - tensor_names.append(prefix + ".block_sparse_moe.gate.weight") - res = [] - for name in tensor_names: - res.append(WeightInfo(name=name)) - for weight_info in MISTRAL_INFO.layer_weights(index, config): - if ".mlp." in weight_info.name: - continue - res.append(weight_info) - return res - - def sliceable(self) -> bool: - return True - - def has_defined_spaces(self) -> bool: - return False - - -def _load_json_arch(name: str) -> JsonArchitectureInfo: - text = importlib.resources.read_text(mergekit._data.architectures, name) - return JsonArchitectureInfo( - definition=JSONArchitectureDefinition.model_validate_json(text) - ) - - -def _load_all_architectures() -> ( - Tuple[List[JsonArchitectureInfo], Dict[str, List[JsonArchitectureInfo]]] -): - architectures: List[JsonArchitectureInfo] = [] - for f in importlib.resources.contents(mergekit._data.architectures): - if f.lower().endswith(".json"): - architectures.append(_load_json_arch(f)) - - name_to_arch: Dict[str, List[JsonArchitectureInfo]] = {} - for arch_info in architectures: - for name in arch_info.definition.architectures: - name_to_arch[name] = name_to_arch.get(name, []) - name_to_arch[name].append(arch_info) - return architectures, name_to_arch - - -JSON_ARCHITECTURES, NAME_TO_ARCH = _load_all_architectures() -MISTRAL_INFO = _load_json_arch("mistral.json") -QWEN2_INFO = _load_json_arch("qwen2.json") - - -def get_architecture_info(config: PretrainedConfig) -> ArchitectureInfo: - if len(config.architectures) != 1: - raise RuntimeError("More than one architecture in config?") - - arch_name = config.architectures[0] - - if arch_name == MixtralTensorNames.ARCHITECTURE_NAME: - return MixtralTensorNames.from_config(config) - - if arch_name not in NAME_TO_ARCH: - raise RuntimeError(f"Unsupported architecture {arch_name}") - - candidates = list(NAME_TO_ARCH[arch_name]) - if len(candidates) == 1: - return candidates[0] - - for c in candidates: - if c.definition.expected_model_type == config.model_type: - return c - - raise RuntimeError( - f"Unsupported model_type {config.model_type} for architecture {arch_name}" - ) diff --git a/mergekit/card.py b/mergekit/card.py deleted file mode 100644 index d5abfd79b8398db6efffecc7f8ad5ea30dc73e8f..0000000000000000000000000000000000000000 --- a/mergekit/card.py +++ /dev/null @@ -1,239 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -import os -from typing import Generator, List, Optional - -import huggingface_hub -import yaml -from huggingface_hub.utils import HFValidationError -from yaml.nodes import SequenceNode as SequenceNode - -from mergekit.config import MergeConfiguration, ModelReference - -CARD_TEMPLATE = """--- -{metadata} ---- -# {name} - -This is a merge of pre-trained language models created using [mergekit](https://github.com/cg123/mergekit). - -## Merge Details -### Merge Method - -This model was merged using the {merge_method} merge method{base_text}. - -### Models Merged - -The following models were included in the merge: -{model_list} - -### Configuration - -The following YAML configuration was used to produce this model: - -```yaml -{config_yaml} -``` -""" - -CARD_TEMPLATE_LORA = """--- -{metadata} ---- -# {name} - -This is a LoRA extracted from a language model. It was extracted using [mergekit](https://github.com/arcee-ai/mergekit). - -## LoRA Details - -{details} - -### Parameters - -The following command was used to extract this LoRA adapter: - -```sh -{invocation} -``` -""" - - -def is_hf(path: str) -> bool: - """ - Determines if the given path is a Hugging Face model repository. - - Args: - path: A string path to check. - """ - if path[0] in "/~" or path.count("/") > 1: - return False # definitely a local path - if not os.path.exists(path): - return True # If path doesn't exist locally, it must be a HF repo - try: - return huggingface_hub.repo_exists(path, repo_type="model", token=False) - except HFValidationError: - return False - - -def extract_hf_paths(models: List[ModelReference]) -> Generator[str, None, None]: - """ - Yields all valid Hugging Face paths from a list of ModelReference objects. - - Args: - models: A list of ModelReference objects. - """ - for model in models: - if is_hf(model.model.path): - yield model.model.path - - if model.lora and is_hf(model.lora.path): - yield model.lora.path - - -def method_md(merge_method: str) -> str: - """ - Returns a markdown string for the given merge method. - - Args: - merge_method: A string indicating the merge method used. - """ - methods = { - "linear": "[linear](https://arxiv.org/abs/2203.05482)", - "ties": "[TIES](https://arxiv.org/abs/2306.01708)", - "slerp": "SLERP", - "task_arithmetic": "[task arithmetic](https://arxiv.org/abs/2212.04089)", - "dare_ties": "[DARE](https://arxiv.org/abs/2311.03099) [TIES](https://arxiv.org/abs/2306.01708)", - "dare_linear": "linear [DARE](https://arxiv.org/abs/2311.03099)", - "model_stock": "[Model Stock](https://arxiv.org/abs/2403.19522)", - } - return methods.get(merge_method, merge_method) - - -def maybe_link_hf(path: str) -> str: - """ - Convert a path to a clickable link if it's a Hugging Face model path. - - Args: - path: A string path to possibly convert to a link. - """ - if is_hf(path): - return f"[{path}](https://huggingface.co/{path})" - return path - - -def modelref_md(model: ModelReference) -> str: - """ - Generates markdown description for a ModelReference object. - - Args: - model: A ModelReference object. - - Returns: - A markdown formatted string describing the model reference. - """ - text = maybe_link_hf(model.model.path) - if model.lora: - text += " + " + maybe_link_hf(model.lora.path) - return text - - -def generate_card( - config: MergeConfiguration, - config_yaml: str, - name: Optional[str] = None, -) -> str: - """ - Generates a markdown card for a merged model configuration. - - Args: - config: A MergeConfiguration object. - config_yaml: YAML source text of the config. - name: An optional name for the model. - """ - if not name: - name = "Untitled Model (1)" - - hf_bases = list(extract_hf_paths(config.referenced_models())) - tags = ["mergekit", "merge"] - - actual_base = config.base_model - if config.merge_method == "slerp": - # curse my past self - actual_base = None - - base_text = "" - if actual_base: - base_text = f" using {modelref_md(actual_base)} as a base" - - model_bullets = [] - for model in config.referenced_models(): - if model == actual_base: - # actual_base is mentioned in base_text - don't include in list - continue - - model_bullets.append("* " + modelref_md(model)) - - return CARD_TEMPLATE.format( - metadata=yaml.dump( - {"base_model": hf_bases, "tags": tags, "library_name": "transformers"} - ), - model_list="\n".join(model_bullets), - base_text=base_text, - merge_method=method_md(config.merge_method), - name=name, - config_yaml=config_yaml, - ) - - -def generate_card_lora( - base_model_ref: ModelReference, - finetuned_model_ref: ModelReference, - invocation: str, - name: str, -) -> str: - """ - Generates a markdown card for a merged model configuration. - - Args: - config: A MergeConfiguration object. - config_yaml: YAML source text of the config. - name: An optional name for the model. - """ - if not name: - name = "Untitled LoRA Model (1)" - - hf_bases = list(extract_hf_paths([base_model_ref, finetuned_model_ref])) - tags = ["mergekit", "peft"] - - details = f"This LoRA adapter was extracted from {modelref_md(finetuned_model_ref)} and uses {modelref_md(base_model_ref)} as a base." - - if os.path.isdir(base_model_ref.model.path) or os.path.isdir( - finetuned_model_ref.model.path - ): - logging.warning( - "Some model identifiers you provided are directory paths and will appear as such in the model card, you may want to edit it." - ) - - return CARD_TEMPLATE_LORA.format( - metadata=yaml.dump( - {"base_model": hf_bases, "tags": tags, "library_name": "transformers"} - ), - name=name, - details=details, - base_model=base_model_ref.model.path, - finetuned_model=finetuned_model_ref.model.path, - invocation=invocation, - ) diff --git a/mergekit/common.py b/mergekit/common.py deleted file mode 100644 index 91ed650bcd72f71317d352edb487712b6d288e9f..0000000000000000000000000000000000000000 --- a/mergekit/common.py +++ /dev/null @@ -1,290 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import binascii -import logging -import os -import os.path -from typing import ( - Any, - Callable, - Dict, - Generic, - Iterator, - Mapping, - Optional, - Tuple, - Union, - get_args, -) - -import huggingface_hub -import immutables -import peft -import torch -import transformers -from pydantic import BaseModel, model_serializer, model_validator -from pydantic_core import core_schema -from transformers import AutoConfig, PretrainedConfig -from typing_extensions import TypeVar - -from mergekit.io import LazyTensorLoader, ShardedTensorIndex - - -class ModelPath(BaseModel, frozen=True): - path: str - revision: Optional[str] = None - - @model_validator(mode="before") - def validate_string(cls, value): - if isinstance(value, str): - at_ct = value.count("@") - if at_ct > 1: - raise RuntimeError(f"Invalid model path - multiple @: {value}") - elif at_ct == 1: - path, rev = value.split("@") - return {"path": path, "revision": rev} - else: - return {"path": value} - return value - - def __str__(self): - if self.revision: - return f"{self.path}@{self.revision}" - return self.path - - def _unique_id(self): - return ( - os.path.basename(self.path) - + "_" - + str(binascii.crc32(self.__str__().encode())) - ) - - -class ModelReference(BaseModel, frozen=True): - """A reference to a language model. - - Can be a hf hub path (username/repo), or local. Optionally includes a LoRA.""" - - model: ModelPath - lora: Optional[ModelPath] = None - override_architecture: Optional[str] = None - - def merged( - self, cache_dir: Optional[str] = None, trust_remote_code: bool = False - ) -> "ModelReference": - """Merge the LoRA if applicable and return a reference to the result.""" - if not self.lora: - return self - - if not cache_dir: - raise RuntimeError("Need to specify cache dir to merge adapters") - - out_path = os.path.join( - cache_dir, - self.model._unique_id() + "_" + self.lora._unique_id(), - ) - - if not os.path.exists(out_path): - os.makedirs(out_path, exist_ok=True) - - config = self.config(trust_remote_code) - auto_cls = _get_auto_cls(config.architectures[0]) - - logging.info(f"Loading {self.model} for merge...") - model = auto_cls.from_pretrained( - self.model.path, - revision=self.model.revision, - torch_dtype=torch.float16, - low_cpu_mem_usage=True, - trust_remote_code=trust_remote_code, - ) - model = peft.PeftModel.from_pretrained( - model, self.lora.path, revision=self.lora.revision, is_trainable=False - ) - logging.info(f"Merging {self.lora} into {self.model}") - model = model.merge_and_unload() - model.save_pretrained(out_path, safe_serialization=True) - del model - - return ModelReference(model=out_path) - - def config(self, trust_remote_code: bool = False) -> PretrainedConfig: - res = AutoConfig.from_pretrained( - self.model.path, - revision=self.model.revision, - trust_remote_code=trust_remote_code, - ) - if self.override_architecture: - res.architectures = [self.override_architecture] - return res - - def tensor_index(self, cache_dir: Optional[str] = None) -> ShardedTensorIndex: - assert self.lora is None - - path = self.model.path - if not os.path.exists(path): - has_safetensors = any( - fn.lower().endswith(".safetensors") - for fn in huggingface_hub.list_repo_files( - path, repo_type="model", revision=self.model.revision - ) - ) - patterns = ["tokenizer.model", "*.json"] - if has_safetensors: - patterns.append("*.safetensors") - else: - patterns.append("*.bin") - - path = huggingface_hub.snapshot_download( - path, - revision=self.model.revision, - cache_dir=cache_dir, - allow_patterns=patterns, - ) - - return ShardedTensorIndex.from_disk(path) - - def lazy_loader( - self, cache_dir: Optional[str] = None, lazy_unpickle: bool = True - ) -> LazyTensorLoader: - return LazyTensorLoader( - self.tensor_index(cache_dir), - lazy_unpickle=lazy_unpickle, - ) - - @model_validator(mode="before") - def validate_string(cls, value): - if isinstance(value, str): - chunks = value.split("+") - if len(chunks) == 1: - return {"model": value} - elif len(chunks) == 2: - return {"model": chunks[0], "lora": chunks[1]} - raise RuntimeError(f"Can't parse {value}") - return value - - @model_serializer() - def serialize(self): - res = str(self) - if '"' in res or " " in res: - return self - return res - - @classmethod - def parse(cls, value: str) -> "ModelReference": - """Parse a ModelReference. Format: '(+)?'""" - return ModelReference.model_validate(value) - - def __str__(self) -> str: - if self.lora: - return f"{str(self.model)}+{str(self.lora)}" - return str(self.model) - - -def dtype_from_name(name: Optional[str]) -> Optional[torch.dtype]: - if not name: - return None - - if name.startswith("torch."): - name = name[len("torch.") :] - - if name == "bfloat16": - return torch.bfloat16 - elif name == "float16": - return torch.float16 - elif name == "float32": - return torch.float32 - elif name == "int64": - return torch.int64 - raise RuntimeError(f'Unimplemented dtype "{name}"') - - -def parse_kmb(value: Union[str, int]) -> int: - if isinstance(value, int): - return value - elif value.isnumeric(): - return int(value) - elif value[-1].lower() == "k": - return int(value[:-1]) * 1000 - elif value[-1].lower() == "m": - return int(value[:-1]) * 1000 * 1000 - elif value[-1].lower() == "b": - return int(value[:-1]) * 1000 * 1000 * 1000 - else: - raise ValueError(value) - - -T_K = TypeVar("T_K") -T_V = TypeVar("T_V") - - -class ImmutableMap(Generic[T_K, T_V]): - data: immutables.Map[T_K, T_V] - - def __init__(self, data: Mapping[T_K, T_V]): - self.data = data - - @classmethod - def __get_pydantic_core_schema__( - cls, source: Any, handler: Callable[[Any], core_schema.CoreSchema] - ) -> core_schema.CoreSchema: - instance_schema = core_schema.is_instance_schema(cls) - - args = get_args(source) - if args: - dict_schema = handler(Dict[args[0], args[1]]) - else: - dict_schema = handler(Dict) - - non_instance_schema = core_schema.with_info_after_validator_function( - lambda value, _info: immutables.Map(value), dict_schema - ) - return core_schema.union_schema([instance_schema, non_instance_schema]) - - def __iter__(self): - return self.data.__iter__() - - def __getitem__(self, key: T_K) -> T_V: - return self.data[key] - - def __len__(self) -> int: - return len(self.data) - - def keys(self) -> Iterator[T_K]: - return self.data.keys() - - def items(self) -> Iterator[Tuple[T_K, T_V]]: - return self.data.items() - - def values(self) -> Iterator[T_V]: - return self.data.values() - - -def _get_auto_cls(arch_name: str): - """Get the AutoModel class for a given architecture name.""" - if arch_name.endswith("ForMaskedLM"): - auto_cls = transformers.AutoModelForMaskedLM - elif arch_name.endswith("ForSequenceClassification"): - auto_cls = transformers.AutoModelForSequenceClassification - elif arch_name.endswith("ForTokenClassification"): - auto_cls = transformers.AutoModelForTokenClassification - else: - if not arch_name.endswith("ForCausalLM") or arch_name.endswith("LMHeadModel"): - logging.warning( - f"Unknown model type {arch_name} - assuming AutoModelForCausalLM" - ) - auto_cls = transformers.AutoModelForCausalLM - return auto_cls diff --git a/mergekit/config.py b/mergekit/config.py deleted file mode 100644 index 75869e9b732b61180a39a3b5a8715a9dc4bfdbac..0000000000000000000000000000000000000000 --- a/mergekit/config.py +++ /dev/null @@ -1,210 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import Any, Dict, Iterable, List, Optional, Tuple, Union - -import yaml -from pydantic import BaseModel, model_validator -from typing_extensions import TypeAlias - -from mergekit.common import ModelReference - -ScalarOrGradient: TypeAlias = Union[float, List[float]] - - -class ConditionalParameter(BaseModel): - value: ScalarOrGradient - filter: Optional[str] = None - - -ParameterSetting: TypeAlias = Union[ - ConditionalParameter, List[ConditionalParameter], ScalarOrGradient -] - - -def evaluate_setting( - tensor_name: str, setting: ParameterSetting, t: float = 0 -) -> float: - if isinstance(setting, (float, int, bool, str)): - return setting - elif isinstance(setting, list): - if all(isinstance(e, (int, float)) for e in setting): - scaled = t * (len(setting) - 1) - i0 = int(scaled) - i1 = min(len(setting) - 1, i0 + 1) - frac = scaled - i0 - - return (1 - frac) * setting[i0] + frac * setting[i1] - elif all(isinstance(e, (float, int, bool, str)) for e in setting): - return setting[int(t * (len(setting) - 1))] - else: - for cond in setting: - if ( - (cond.filter is None) - or (cond.filter == "*") - or (tensor_name and cond.filter in tensor_name) - ): - res = evaluate_setting(tensor_name, cond.value, t) - return res - else: - raise RuntimeError(f"Unexpected setting value: {setting}") - return None - - -class InputSliceDefinition(BaseModel): - model: ModelReference - layer_range: Tuple[int, int] - parameters: Optional[Dict[str, ParameterSetting]] = None - - -class InputModelDefinition(BaseModel): - model: ModelReference - parameters: Optional[Dict[str, ParameterSetting]] = None - - -class OutputSliceDefinition(BaseModel): - sources: List[InputSliceDefinition] - base_model: Optional[ModelReference] = None - residual_weight: Optional[float] = None - parameters: Optional[Dict[str, ParameterSetting]] = None - - -class MergeConfiguration(BaseModel): - merge_method: str - slices: Optional[List[OutputSliceDefinition]] = None - models: Optional[List[InputModelDefinition]] = None - parameters: Optional[Dict[str, ParameterSetting]] = None - base_model: Optional[ModelReference] = None - dtype: Optional[str] = None - tokenizer_source: Optional[str] = None - out_dtype: Optional[str] = None - - def referenced_models(self) -> List[ModelReference]: - models = set() - if self.base_model: - models.add(self.base_model) - if self.models: - for model_in in self.models: - models.add(model_in.model) - if self.slices: - for s in self.slices: - for src in s.sources: - models.add(src.model) - return list(models) - - @model_validator(mode="after") - def validate_inputs(self): - if ((not self.slices) and (not self.models)) or (self.slices and self.models): - raise RuntimeError("Must specify either output slices or models to merge") - return self - - def to_yaml(self) -> str: - return yaml.dump( - self.model_dump(exclude_defaults=True, mode="json"), - Dumper=ConfigYamlDumper, - ).rstrip() - - -class ConfigReader(BaseModel): - config: MergeConfiguration - t: float - tensor_name: Optional[str] = None - slice_out: Optional[OutputSliceDefinition] = None - - @property - def base_model(self) -> Optional[ModelReference]: - if self.slice_out and self.slice_out.base_model: - res = self.slice_out.base_model - else: - res = self.config.base_model - - return res - - def for_out_slice(self, slice: OutputSliceDefinition) -> "ConfigReader": - return ConfigReader( - config=self.config, - t=self.t, - tensor_name=self.tensor_name, - slice_out=slice, - ) - - def for_tensor(self, tensor_name: str) -> "ConfigReader": - return ConfigReader( - config=self.config, - t=self.t, - tensor_name=tensor_name, - slice_out=self.slice_out, - ) - - def with_t(self, t: float) -> "ConfigReader": - return ConfigReader( - config=self.config, - t=t, - tensor_name=self.tensor_name, - slice_out=self.slice_out, - ) - - def parameter( - self, - name: str, - model: Optional[ModelReference] = None, - default: Any = None, - required: bool = False, - ) -> Any: - if self.slice_out: - if model: - for s in self.slice_out.sources: - if s.model == model and s.parameters and name in s.parameters: - value = evaluate_setting( - self.tensor_name, s.parameters[name], self.t - ) - if value is not None: - return value - - if self.slice_out.parameters and name in self.slice_out.parameters: - value = evaluate_setting( - self.tensor_name, self.slice_out.parameters[name], self.t - ) - if value is not None: - return value - - if self.config.parameters and name in self.config.parameters: - value = evaluate_setting( - self.tensor_name, - self.config.parameters[name], - self.t, - ) - if value is not None: - return value - - if required: - path_paths = [str(s) for s in [model, self.tensor_name] if s] - p = ".".join(path_paths) - suffix = f" for {p}" if p else "" - raise RuntimeError(f"Missing required parameter {name}{suffix}") - return default - - -class ConfigYamlDumper(yaml.Dumper): - """Custom YAML dumper to format lists of numbers in flow style.""" - - def represent_list(self, data: Iterable[Any]) -> yaml.SequenceNode: - flow_style = all(isinstance(e, (int, float)) for e in data) - return self.represent_sequence( - "tag:yaml.org,2002:seq", data, flow_style=flow_style - ) - - -ConfigYamlDumper.add_representer(list, ConfigYamlDumper.represent_list) diff --git a/mergekit/evo/__init__.py b/mergekit/evo/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/mergekit/evo/actors.py b/mergekit/evo/actors.py deleted file mode 100644 index ef83f7233fe3765847618881d5aa3c166f3e9dee..0000000000000000000000000000000000000000 --- a/mergekit/evo/actors.py +++ /dev/null @@ -1,324 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import gc -import logging -import tempfile -from typing import Optional, Union - -import lm_eval -import lm_eval.api.model -import lm_eval.models.huggingface -import lm_eval.tasks -import ray -import ray.util.queue -import ray.util.scheduling_strategies -import torch -import transformers -from transformers.utils import is_flash_attn_2_available - -try: - import vllm -except ImportError: - vllm = None - - -from mergekit.architecture import ConfiguredArchitectureInfo, get_architecture_info -from mergekit.config import MergeConfiguration -from mergekit.evo.config import EvolMergeConfiguration -from mergekit.evo.genome import InvalidGenotypeError, ModelGenome -from mergekit.evo.helpers import _eval_model, evaluate_model, merge_model -from mergekit.evo.monkeypatch import ( - NoInit, - monkeypatch_lmeval_shuffle, - monkeypatch_lmeval_vllm, -) -from mergekit.graph import Executor -from mergekit.io.tasks import LoaderCache, ReturnTensor -from mergekit.merge import _model_out_config -from mergekit.options import MergeOptions -from mergekit.plan import MergePlanner - - -class MergeActorBase: - def __init__( - self, - config: EvolMergeConfiguration, - genome: ModelGenome, - merge_options: MergeOptions, - model_storage_path: Optional[str] = None, - vllm: bool = False, - batch_size: Optional[int] = None, - task_manager: Optional[lm_eval.tasks.TaskManager] = None, - ): - self.config = config - self.genome = genome - self.merge_options = merge_options - self.cache = LoaderCache() - self.cache.setup(merge_options) - self.model_storage_path = model_storage_path - self.vllm = vllm - self.batch_size = batch_size - self.task_manager = task_manager - - if config.shuffle: - monkeypatch_lmeval_shuffle() - - # monkeypatch_tqdm() - monkeypatch_lmeval_vllm() - - -@ray.remote(num_cpus=1, num_gpus=1.0) -class OnDiskMergeEvaluator(MergeActorBase): - """ - Merges models to disk then evaluates them in a separate process. - - Maximum compatibility and potential for parallelism, but higher overhead. - """ - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def evaluate_genotype( - self, - genotype: torch.Tensor, - ) -> dict: - gc.collect() - torch.cuda.empty_cache() - logging.info("Merging model") - merged_path = merge_model( - genotype, self.genome, self.model_storage_path, self.merge_options - ) - if not merged_path: - logging.error("Model merge failed") - return {"score": None, "results": None} - - logging.info(f"Model merged to {merged_path}") - return evaluate_model( - merged_path, - self.config.tasks, - num_fewshot=self.config.num_fewshot, - limit=self.config.limit, - vllm=self.vllm, - batch_size=self.batch_size, - task_manager=self.task_manager, - ) - - -@ray.remote(num_cpus=1, num_gpus=1) -class InMemoryMergeEvaluator(MergeActorBase): - """ - Performs merges in memory, using a single model instance. - - This reduces overhead from disk I/O and model loading, but prevents - parallelism and may be slower for large models. - - Implementation is dark sorcery tampering with the internals of lm-eval, - transformers, and vLLM and may break at any time. - """ - - model: Union[ - lm_eval.models.huggingface.HFLM, lm_eval.models.vllm_causallms.VLLM, None - ] = None - arch_info: Optional[ConfiguredArchitectureInfo] = None - - def __init__( - self, - *args, - vllm: bool = False, - **kwargs, - ): - # assert not vllm, "VLLM is not supported for in-memory merging" - super().__init__(*args, vllm=vllm, **kwargs) - - def _maybe_init_model(self, config: MergeConfiguration): - ai = get_architecture_info(self.genome._input_config_example) - cfg_out = _model_out_config( - config, - ai, - trust_remote_code=self.merge_options.trust_remote_code, - ) - cfg_out.use_cache = True - cfg_out.torch_dtype = torch.bfloat16 - - if self.arch_info is not None: - different = False - for key in cfg_out.to_diff_dict(): - if key in ["architectures", "model_type"]: - # to get to here we must have --allow-crimes set, so let it ride - continue - elif key in ["use_cache", "torch_dtype"]: - continue - elif key.endswith("_token_id"): - # update our config but don't fail if it's different - setattr(self.arch_info.config, key, getattr(cfg_out, key, None)) - continue - - if getattr(cfg_out, key) != getattr(self.arch_info.config, key, None): - logging.warn(f"Config key {key} changed, reinitializing model") - different = True - break - - if not different: - return - - self.inner_model = None - - model_kwargs = { - "trust_remote_code": self.merge_options.trust_remote_code, - "torch_dtype": torch.bfloat16, - } - if is_flash_attn_2_available(): - model_kwargs["attn_implementation"] = "flash_attention_2" - - with NoInit(): - inner_model = ( - transformers.AutoModelForCausalLM.from_config( - cfg_out, - **model_kwargs, - ) - .bfloat16() - .cuda() - .eval() - .requires_grad_(False) - ) - - if self.vllm: - # oh i hate this - with tempfile.TemporaryDirectory( - dir=self.model_storage_path, prefix="vllm" - ) as tempdir: - inner_model.save_pretrained( - tempdir, safe_serialization=True, out_shard_size=1_000_000_000_000 - ) - del inner_model - tokenizer_donor = self.genome.definition.base_model - if tokenizer_donor is None: - logging.warning( - f"Base model not set, using tokenizer from first model in genome" - ) - tokenizer_donor = self.genome.definition.models[0] - tok = transformers.AutoTokenizer.from_pretrained( - tokenizer_donor.model.path, use_fast=True - ) - tok.save_pretrained(tempdir) - - max_model_len = None - if ( - seq_len := getattr(cfg_out, "max_position_embeddings", None) - ) is not None: - max_model_len = seq_len - if (window_sz := getattr(cfg_out, "sliding_window", None)) is not None: - max_model_len = min(max_model_len or 1024, window_sz) - if max_model_len and max_model_len > 8192: - max_model_len = 8192 - logging.warn(f"Clipping sequence length to {max_model_len}") - - mem_util = ( - 0.7 if self.merge_options.cuda else 0.9 - ) # reduce memory usage if we're also using cuda for the merge - self.model = lm_eval.models.vllm_causallms.VLLM( - pretrained=tempdir, - batch_size=self.batch_size or "auto", - max_model_len=max_model_len, - gpu_memory_utilization=mem_util, - dtype="bfloat16", - device="cuda", - trust_remote_code=self.merge_options.trust_remote_code, - ) - else: - self.model = lm_eval.models.huggingface.HFLM(pretrained=inner_model) - self.arch_info = ConfiguredArchitectureInfo(info=ai, config=cfg_out) - logging.info("Model initialized") - - def evaluate(self, genotype: torch.Tensor) -> dict: - try: - config = self.genome.genotype_merge_config(genotype) - except InvalidGenotypeError as e: - logging.error("Invalid genotype", exc_info=e) - return {"score": None, "results": None} - - self._maybe_init_model(config) - - planner = MergePlanner( - config, - self.arch_info.info, - self.merge_options, - self.arch_info.config, - ) - - tasks = planner.plan_in_memory() - - model = self.model.model - if vllm is not None and isinstance(model, vllm.LLM): - assert ( - model.llm_engine.parallel_config.world_size == 1 - ), "Must be single GPU" - worker = model.llm_engine.driver_worker - model = worker.model_runner.model - param_dict = dict(model.named_parameters()) - - stacked_mapping = { - # mappings for Llama/Mistral attention weights to vLLM packed tensors - ".q_proj.": (".qkv_proj.", "q"), - ".k_proj.": (".qkv_proj.", "k"), - ".v_proj.": (".qkv_proj.", "v"), - ".gate_proj.": (".gate_up_proj.", 0), - ".up_proj.": (".gate_up_proj.", 1), - } - - executor = Executor( - tasks, - math_device="cuda" if self.merge_options.cuda else "cpu", - storage_device="cuda" if self.merge_options.cuda else "cpu", - ) - for tensor_task, value in executor.run(quiet=True): - assert isinstance(tensor_task, ReturnTensor) - name = tensor_task.weight_info.name - - if name in param_dict: - param_dict[name].data.copy_(value, non_blocking=True) - elif self.vllm: - stacked = False - for needle, (replacement, shard_id) in stacked_mapping.items(): - if needle in name: - target = name.replace(needle, replacement) - param = param_dict[target] - weight_loader = param.weight_loader - weight_loader(param, value, shard_id) - stacked = True - break - - if not stacked: - raise ValueError(f"Unknown parameter {name}") - else: - raise ValueError(f"Unknown parameter {name}") - - del value - - return _eval_model( - self.model, - self.config.tasks, - num_fewshot=self.config.num_fewshot, - limit=self.config.limit, - task_manager=self.task_manager, - batch_size=self.batch_size, - ) - - def evaluate_genotype( - self, - genotype: torch.Tensor, - ) -> dict: - return self.evaluate(genotype) diff --git a/mergekit/evo/config.py b/mergekit/evo/config.py deleted file mode 100644 index e20ece663b04457be83a2e30305ccc9ef7f6be64..0000000000000000000000000000000000000000 --- a/mergekit/evo/config.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -from typing import List, Optional - -from pydantic import BaseModel, model_validator - -from mergekit.evo.genome import ModelGenomeDefinition - - -class TaskConfiguration(BaseModel, frozen=True): - name: str - weight: float = 1.0 - metric: str = "acc,none" - - @model_validator(mode="before") - def validate_string(cls, value): - if isinstance(value, str): - return {"name": value} - return value - - -class EvolMergeConfiguration(BaseModel, frozen=True): - genome: ModelGenomeDefinition - tasks: List[TaskConfiguration] - limit: Optional[int] = None - num_fewshot: Optional[int] = None - shuffle: bool = False - random_init: bool = False - - -NAUGHTY_PREFIXES = [ - "mmlu", - "hendrycks", - "agieval", - "gsm8k", - "hellaswag", - "winogrande", - "arc_", - "ai2_arc", - "truthfulqa", - "bigbench", - "piqa", - "openbookqa", -] - - -def check_for_naughty_config(config: EvolMergeConfiguration, allow: bool = False): - """ - Check if the given configuration is naughty and should be disallowed. - - mergekit-evolve is perfectly set up to directly optimize against the test set - of common benchmarks, which just makes the world a worse place. There are - cases where this is useful but it deserves a giant honking warning. - """ - suffix = "" - if not allow: - suffix = ( - " To proceed, set the " - "--i-understand-the-depths-of-the-evils-i-am-unleashing flag." - ) - for task in config.tasks: - for prefix in NAUGHTY_PREFIXES: - if task.name.startswith(prefix): - if task.name.endswith("_train"): - # there aren't any tasks that match this pattern in base - # lm-eval, but it'd be a sane thing to do to add tasks for - # the training sets of these benchmarks. don't warn about - # them - continue - - message = ( - f"Task {task.name} is a common benchmark task. " - "Optimizing against this task directly is unsporting at best " - "and outright malicious at worst. Using mergekit-evolve to " - "game benchmarks will be a black mark on your name for a " - f"thousand generations.{suffix}" - ) - if not allow: - raise ValueError(message) - else: - logging.warning(message) diff --git a/mergekit/evo/genome.py b/mergekit/evo/genome.py deleted file mode 100644 index a1801d128566a3b0c86687c477c844def5a80dc5..0000000000000000000000000000000000000000 --- a/mergekit/evo/genome.py +++ /dev/null @@ -1,383 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -import os -from typing import Any, Dict, List, Optional, Union - -import numpy as np -import torch -import transformers -from pydantic import BaseModel, model_validator - -from mergekit.common import ModelReference -from mergekit.config import MergeConfiguration - -METHOD_PARAM_MAPS = { - "linear": ["weight"], - "task_arithmetic": ["weight"], - "ties": ["weight", "density"], - "dare_ties": ["weight", "density"], - "slerp": ["t"], -} - - -class InvalidGenotypeError(RuntimeError): - pass - - -class ModelGenomeDefinition(BaseModel, frozen=True): - models: List[ModelReference] - merge_method: str - base_model: Optional[ModelReference] = None - tokenizer_source: Optional[str] = None - layer_granularity: int = 0 - normalize: Optional[bool] = None - allow_negative_weights: bool = False - filters: Optional[List[str]] = None - smooth: bool = False - - @model_validator(mode="after") - def validate(self): - assert self.merge_method in METHOD_PARAM_MAPS, "Invalid merge method" - - if self.merge_method in ["ties", "dare_ties", "task_arithmetic"]: - assert self.base_model is not None, "base_model is required for this method" - - if self.merge_method == "slerp": - assert not self.smooth, "smooth is not supported for slerp merge method" - assert ( - not self.filters - ), "tensor name filtering is not supported for slerp merge method" - - return self - - -class ModelGenome: - definiton: ModelGenomeDefinition - num_layers: int - _input_config_example: transformers.PretrainedConfig - - def __init__( - self, definition: ModelGenomeDefinition, trust_remote_code: bool = False - ): - self.definition = definition - - self._input_config_example = self.definition.models[0].config( - trust_remote_code=trust_remote_code - ) - self.num_layers = self._input_config_example.num_hidden_layers - - assert ( - self.definition.layer_granularity < 1 - or self.num_layers % self.definition.layer_granularity == 0 - ), "Number of layers must be a multiple of layer_granularity" - - def initial_genotype(self, random: bool = False) -> torch.Tensor: - """Generate an initial genotype for the given number of layers.""" - if self.definition.layer_granularity > 0: - n_layer_groups = self.num_layers // self.definition.layer_granularity - else: - n_layer_groups = 1 - n_param_sets = len(self.definition.filters or []) + 1 - n_models = len(self.definition.models) - n_params = len(METHOD_PARAM_MAPS[self.definition.merge_method]) - - if random: - return torch.rand(n_layer_groups, n_models, n_param_sets, n_params) - else: - x0_t = torch.zeros(n_layer_groups, n_models, n_param_sets, n_params) - # weight is always first - x0_t[:, :, :, 0] = 1 / n_models - if n_params > 1: - # sometimes followed by density - x0_t[:, :, :, 1:] = 1 - return x0_t - - def genotype_merge_config( - self, genotype: Union[torch.Tensor, np.ndarray] - ) -> MergeConfiguration: - """Convert a genotype tensor to a mergekit configuration.""" - - genotype = self._to_torch(genotype) - - (n_layer_groups, n_models, n_param_sets, n_params) = genotype.shape - if self.definition.layer_granularity > 0: - assert n_layer_groups * self.definition.layer_granularity == self.num_layers - assert n_models == len(self.definition.models) - assert n_params == len(METHOD_PARAM_MAPS[self.definition.merge_method]) - - if self.definition.merge_method == "slerp": - slices = self._slerp_slices(genotype) - models = None - else: - param_arrays = {} - for param_idx, param in enumerate( - METHOD_PARAM_MAPS[self.definition.merge_method] - ): - values = genotype[:, :, :, param_idx] - if param == "density": - # ensure density is in [0, 1] - values = torch.abs(values).clamp(0, 1) - if not self.definition.allow_negative_weights and param in [ - "weight", - "t", - ]: - values = torch.abs(values) - param_arrays[param] = values - - if self.definition.smooth: - slices = None - models = self._smooth_config_models(n_param_sets, param_arrays) - else: - models = None - slices = self._discrete_config_slices( - n_layer_groups, n_param_sets, param_arrays - ) - - normalize = self.definition.normalize - if normalize is None: - normalize = self.definition.merge_method in ["ties", "dare_ties", "linear"] - return MergeConfiguration.model_validate( - { - "merge_method": self.definition.merge_method, - "slices": slices, - "models": models, - "parameters": { - "normalize": normalize, - "int8_mask": True, - }, - "dtype": "bfloat16", - "base_model": self.definition.base_model, - "tokenizer_source": self.definition.tokenizer_source, - } - ) - - def _discrete_config_slices( - self, - n_layer_groups: int, - n_param_sets: int, - param_arrays: Dict[str, torch.Tensor], - ) -> List[Dict]: - """Generate merge config output slices for non-interpolated parameters.""" - slices = [] - layer_step = ( - self.definition.layer_granularity - if self.definition.layer_granularity > 0 - else self.num_layers - ) - for slice_idx in range(n_layer_groups): - sources = [] - for model_idx, model in enumerate(self.definition.models): - params = {} - if n_param_sets > 1: - for param, values in param_arrays.items(): - params[param] = [] - for set_idx in range(n_param_sets): - value = values[ - slice_idx, - model_idx, - set_idx, - ] - filter_ = (self.definition.filters + [None])[set_idx] - params[param].append( - {"filter": filter_, "value": value.item()} - ) - else: - for param, values in param_arrays.items(): - params[param] = values[ - slice_idx, - model_idx, - 0, - ].item() - - sources.append( - { - "model": model, - "layer_range": [ - slice_idx * layer_step, - (slice_idx + 1) * layer_step, - ], - "parameters": params, - } - ) - - if self.definition.base_model and ( - self.definition.base_model not in self.definition.models - ): - sources.append( - { - "model": self.definition.base_model, - "layer_range": [ - slice_idx * layer_step, - (slice_idx + 1) * layer_step, - ], - } - ) - slices.append({"sources": sources}) - return slices - - def _smooth_config_models( - self, n_param_sets: int, param_arrays: Dict[str, torch.Tensor] - ) -> List[Dict]: - """Generate merge config model section with parameter interpolation.""" - models = [] - for model_idx, model in enumerate(self.definition.models): - params = {} - if n_param_sets > 1: - for param, values in param_arrays.items(): - params[param] = [] - for set_idx in range(n_param_sets): - value = values[:, model_idx, set_idx] - filter_ = (self.definition.filters + [None])[set_idx] - params[param].append( - { - "filter": filter_, - "value": _unpack_single_element(value.tolist()), - } - ) - else: - for param, values in param_arrays.items(): - params[param] = _unpack_single_element( - values[:, model_idx, 0].tolist() - ) - - models.append( - { - "model": model, - "layer_range": [0, self.num_layers], - "parameters": params, - } - ) - - if self.definition.base_model and ( - self.definition.base_model not in self.definition.models - ): - models.append({"model": self.definition.base_model}) - return models - - def _slerp_slices(self, genotype: torch.Tensor) -> List[Dict]: - """Generate merge config output slices for SLERP. - - This method is a bit more complex because it requires choosing the - two models with the highest weight for each layer group and calculating - the interpolation parameter t. Parameter interpolation and component - splitting are not supported because it's too hard and I don't want to. - """ - n_layer_groups, n_models, _, _ = genotype.shape - layer_step = ( - self.definition.layer_granularity - if self.definition.layer_granularity > 0 - else self.num_layers - ) - slices = [] - for slice_idx in range(n_layer_groups): - s = { - "sources": [ - { - "model": self.definition.models[i], - "layer_range": [ - slice_idx * layer_step, - (slice_idx + 1) * layer_step, - ], - } - for i in range(n_models) - ] - } - - # Choose the two models with the highest weight and - # calculate the interpolation parameter t - chosen = torch.topk(genotype[slice_idx, :, 0, 0], 2) - t = torch.softmax(chosen.values, dim=-1)[1].item() - s["parameters"] = {"t": t} - s["base_model"] = self.definition.models[chosen.indices[0].item()] - s["sources"] = [ - s["sources"][chosen.indices[0].item()], - s["sources"][chosen.indices[1].item()], - ] - if self.definition.tokenizer_source: - s["sources"][0]["parameters"] = {"weight": 1 - t} - s["sources"][1]["parameters"] = {"weight": t} - - if self.definition.base_model and ( - self.definition.base_model not in self.definition.models - ): - s["sources"].append( - { - "model": self.definition.base_model, - "layer_range": [ - slice_idx * layer_step, - (slice_idx + 1) * layer_step, - ], - } - ) - - slices.append(s) - return slices - - def _to_torch(self, genotype: Union[torch.Tensor, np.ndarray]) -> torch.Tensor: - """Convert a genotype to a torch tensor of the correct shape.""" - if not isinstance(genotype, torch.Tensor): - genotype = torch.tensor(genotype) - if len(genotype.shape) == 1: - num_layer_groups = ( - self.num_layers // self.definition.layer_granularity - if self.definition.layer_granularity > 0 - else 1 - ) - genotype = genotype.view( - num_layer_groups, - len(self.definition.models), - len(self.definition.filters or []) + 1, - -1, - ) - - if len(genotype.shape) != 4: - logging.error(f"Invalid genotype shape: {genotype.shape}") - raise InvalidGenotypeError( - "Invalid genotype shape - must be 4D tensor or 1D array" - ) - - return genotype - - def genotype_to_param_arrays( - self, genotype: Union[torch.Tensor, np.ndarray] - ) -> Dict[str, torch.Tensor]: - """Convert a genotype tensor to a dictionary of numpy arrays.""" - genotype = self._to_torch(genotype) - - res = {} - for idx, param_name in enumerate( - METHOD_PARAM_MAPS[self.definition.merge_method] - ): - for model_idx, model in enumerate(self.definition.models): - model_name = os.path.basename(model.model.path) - for set_idx, filter_ in enumerate( - (self.definition.filters or []) + [None] - ): - suffix = "" - if filter_ is not None: - suffix = f"_{filter_}" - res[f"{model_name}_{param_name}{suffix}"] = genotype[ - :, model_idx, set_idx, idx - ] - - return res - - -def _unpack_single_element(x: List) -> Any: - if len(x) == 1: - return x[0] - return x diff --git a/mergekit/evo/helpers.py b/mergekit/evo/helpers.py deleted file mode 100644 index 9340cdbb2c2dcd6dbc420bdc475abf94d7f0ce09..0000000000000000000000000000000000000000 --- a/mergekit/evo/helpers.py +++ /dev/null @@ -1,126 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -import os -import shutil -import tempfile -from typing import Any, Dict, List, Optional, Union - -import lm_eval -import lm_eval.api.model -import lm_eval.models.huggingface -import lm_eval.tasks -import ray -import ray.util.queue -import ray.util.scheduling_strategies -import torch - -from mergekit.evo.config import TaskConfiguration -from mergekit.evo.genome import InvalidGenotypeError, ModelGenome -from mergekit.evo.monkeypatch import monkeypatch_lmeval_vllm -from mergekit.merge import run_merge -from mergekit.options import MergeOptions - - -def _eval_model( - model: Union[str, lm_eval.api.model.LM], - tasks: List[TaskConfiguration], - model_args: Optional[Dict[str, Any]] = None, - task_manager: Optional[lm_eval.tasks.TaskManager] = None, - **kwargs, -) -> Dict[str, Any]: - results = lm_eval.evaluator.simple_evaluate( - model=model, - model_args=model_args, - tasks=list(set([task.name for task in tasks])), - log_samples=False, - verbosity="WARNING", - task_manager=task_manager, - **kwargs, - ) - - logging.info(results["results"]) - res = 0 - for task in tasks: - res += results["results"][task.name][task.metric] * task.weight - return {"score": res, "results": results["results"]} - - -def evaluate_model( - merged_path: str, - tasks: List[TaskConfiguration], - num_fewshot: Optional[int], - limit: Optional[int], - vllm: bool, - batch_size: Optional[int] = None, - task_manager: Optional[lm_eval.tasks.TaskManager] = None, -) -> dict: - # monkeypatch_tqdm() - monkeypatch_lmeval_vllm() - try: - model_args = { - "pretrained": merged_path, - "dtype": "bfloat16", - } - if vllm: - model_args["gpu_memory_utilization"] = 0.8 - model_args["tensor_parallel_size"] = 1 - model_args["batch_size"] = "auto" - model_args["max_model_len"] = 4096 - else: - model_args["use_cache"] = True - - res = _eval_model( - "vllm" if vllm else "huggingface", - tasks, - model_args, - num_fewshot=num_fewshot, - limit=limit, - batch_size=batch_size, - task_manager=task_manager, - ) - return res - finally: - shutil.rmtree(merged_path) - - -evaluate_model_ray = ray.remote(num_cpus=1, num_gpus=1.0)(evaluate_model) - - -def merge_model( - genotype: torch.Tensor, - genome: ModelGenome, - model_storage_path: str, - merge_options: MergeOptions, -) -> str: - # monkeypatch_tqdm() - try: - cfg = genome.genotype_merge_config(genotype) - except InvalidGenotypeError as e: - logging.error("Invalid genotype", exc_info=e) - return None - os.makedirs(model_storage_path, exist_ok=True) - res = tempfile.mkdtemp(prefix="merged", dir=model_storage_path) - run_merge(cfg, out_path=res, options=merge_options) - return res - - -merge_model_ray = ray.remote( - num_cpus=1, - num_gpus=1, - max_retries=3, - retry_exceptions=[ConnectionError], -)(merge_model) diff --git a/mergekit/evo/monkeypatch.py b/mergekit/evo/monkeypatch.py deleted file mode 100644 index ef474d3bda99c81be12dbf9520ef0cf0936ea79d..0000000000000000000000000000000000000000 --- a/mergekit/evo/monkeypatch.py +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - - -import torch -import transformers - - -def monkeypatch_lmeval_shuffle(): - """Monkeypatch lm_eval to shuffle the dataset after downloading.""" - import lm_eval.api.task - - if hasattr(lm_eval.api.task.Task, "_monkey_patched"): - return - - _old_task_dl = lm_eval.api.task.Task.download - - def _dl_shuffled(self: lm_eval.api.task.Task, *args, **kwargs): - _old_task_dl(self, *args, **kwargs) - self.dataset = self.dataset.shuffle() - - lm_eval.api.task.Task.download = _dl_shuffled - - _old_ct_dl = lm_eval.api.task.ConfigurableTask.download - - def _ct_dl_shuffled(self, *args, **kwargs): - _old_ct_dl(self, *args, **kwargs) - self.dataset = self.dataset.shuffle() - - lm_eval.api.task.ConfigurableTask.download = _ct_dl_shuffled - - lm_eval.api.task.Task._monkey_patched = True - print("monkey has been patched") - - -def monkeypatch_tqdm(lm_eval: bool = True, mergekit: bool = True): - """Patch lm_eval & mergekit to use Ray's tqdm for progress bars.""" - - from ray.experimental.tqdm_ray import tqdm as tqdm_ray - - def _tqdm_wrap(iterable=None, disable: bool = False, **kwargs): - if disable: - if iterable is not None: - return iterable - return lambda x: x - res = tqdm_ray(iterable=iterable, **kwargs, flush_interval_s=1.0) - res.refresh() - return res - - def _patch_lm_eval(): - import lm_eval - - if hasattr(lm_eval, "_mk_tqdm_patched"): - return - - import lm_eval.api.metrics - import lm_eval.api.model - import lm_eval.api.task - import lm_eval.models.huggingface - import lm_eval.models.vllm_causallms - - for module in ( - lm_eval.models.huggingface, - lm_eval.models.vllm_causallms, - lm_eval.api.model, - lm_eval.api.task, - lm_eval.api.metrics, - ): - setattr(module, "tqdm", _tqdm_wrap) - - lm_eval._mk_tqdm_patched = True - - if lm_eval: - _patch_lm_eval() - - if mergekit: - del mergekit - - import mergekit - import mergekit.graph - import mergekit.merge - import mergekit.tokenizer - - fake_module = type("fake_module", (), {"tqdm": staticmethod(_tqdm_wrap)})() - - mergekit.graph.tqdm = fake_module - mergekit.merge.tqdm = fake_module - mergekit.tokenizer.tqdm = fake_module - - -def monkeypatch_lmeval_vllm(): - # HACK: fix crash on some tasks due to unset AUTO_MODEL_CLASS for vLLM - import lm_eval.models.vllm_causallms - - lm_eval.models.vllm_causallms.VLLM.AUTO_MODEL_CLASS = ( - transformers.AutoModelForCausalLM - ) - - -class NoInit: - def __enter__(self): - def noop(*args, **kwargs): - pass - - (k, u, n) = ( - torch.nn.init.kaiming_uniform_, - torch.nn.init.uniform_, - torch.nn.init.normal_, - ) - torch.nn.init.kaiming_uniform_ = noop - torch.nn.init.uniform_ = noop - torch.nn.init.normal_ = noop - - transformers.modeling_utils._init_weights = False - self.funcs = (k, u, n) - - def __exit__(self, *args): - (k, u, n) = self.funcs - ( - torch.nn.init.kaiming_uniform_, - torch.nn.init.uniform_, - torch.nn.init.normal_, - ) = ( - k, - u, - n, - ) - transformers.modeling_utils._init_weights = True diff --git a/mergekit/evo/strategy.py b/mergekit/evo/strategy.py deleted file mode 100644 index 29ff9dadcbe8015140ff53cc09bd83f20c855ec6..0000000000000000000000000000000000000000 --- a/mergekit/evo/strategy.py +++ /dev/null @@ -1,301 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import asyncio -import logging -import os -from abc import ABC, abstractmethod -from typing import Dict, List, Optional, Tuple, Union - -import lm_eval.tasks -import numpy as np -import ray -import ray.util.queue -import ray.util.scheduling_strategies -import torch - -from mergekit.evo.actors import InMemoryMergeEvaluator, OnDiskMergeEvaluator -from mergekit.evo.config import EvolMergeConfiguration -from mergekit.evo.genome import ModelGenome -from mergekit.evo.helpers import evaluate_model_ray, merge_model_ray -from mergekit.options import MergeOptions - - -class EvaluationStrategyBase(ABC): - def __init__( - self, - config: EvolMergeConfiguration, - genome: ModelGenome, - merge_options: MergeOptions, - num_gpus: Optional[int] = None, - batch_size: Optional[int] = None, - task_search_path: Union[str, List[str], None] = None, - model_storage_path: Optional[str] = None, - ): - self.config = config - self.genome = genome - self.merge_options = merge_options - self.num_gpus = num_gpus or torch.cuda.device_count() - self.batch_size = batch_size - self.task_manager = lm_eval.tasks.TaskManager(include_path=task_search_path) - self.model_storage_path = model_storage_path - if self.model_storage_path: - os.makedirs(self.model_storage_path, exist_ok=True) - - @abstractmethod - def evaluate_genotypes(self, genotypes: List[np.ndarray]) -> List[dict]: - pass - - @abstractmethod - def evaluate_genotype(self, genotype: np.ndarray) -> dict: - pass - - -class ActorPoolEvaluationStrategy(EvaluationStrategyBase): - """ - Uses a fixed-size pool of actors to evaluate genotypes in parallel. - """ - - def __init__( - self, - *args, - in_memory: bool = False, - vllm: bool = False, - **kwargs, - ): - super().__init__(*args, **kwargs) - if in_memory: - self.actor_cls = InMemoryMergeEvaluator - else: - self.actor_cls = OnDiskMergeEvaluator - - self.actor_pool = ray.util.ActorPool( - [ - self.actor_cls.remote( - self.config, - self.genome, - self.merge_options, - model_storage_path=self.model_storage_path, - vllm=vllm, - batch_size=self.batch_size, - task_manager=self.task_manager, - ) - for _ in range(self.num_gpus) - ] - ) - - def evaluate_genotypes(self, genotypes: List[np.ndarray]) -> List[dict]: - return list( - self.actor_pool.map( - lambda a, x: a.evaluate_genotype.remote(x), - genotypes, - ) - ) - - def evaluate_genotype(self, genotype: np.ndarray) -> dict: - return self.evaluate_genotypes([genotype])[0] - - -@ray.remote -class BufferedRayEvaluationStrategyActor: - def __init__( - self, - config: EvolMergeConfiguration, - genome: ModelGenome, - merge_options: MergeOptions, - vllm: bool = False, - num_gpus: Optional[int] = None, - batch_size: Optional[int] = None, - task_manager: Optional[lm_eval.tasks.TaskManager] = None, - model_storage_path: Optional[str] = None, - ): - self.config = config - self.genome = genome - self.merge_options = merge_options - self.vllm = vllm - self.num_gpus = num_gpus or torch.cuda.device_count() - self.input_queue = [] - self.batch_size = batch_size - self.task_manager = task_manager - self.model_storage_path = model_storage_path - self._shutdown = False - - async def evaluate_genotype(self, genotype: np.ndarray): - future_result = asyncio.Future() - self.input_queue.append((genotype, future_result)) - return await future_result - - async def process_queue(self): - merging: Dict[ray.ObjectRef, asyncio.Future] = {} - merged: List[Tuple[asyncio.Future, ray.ObjectRef]] = [] - evaluating: Dict[ray.ObjectRef, asyncio.Future] = {} - - logging.info("Starting processing loop") - - try: - while not self._shutdown: - while self.input_queue and (len(merging) + len(merged) < self.num_gpus): - genotype, future_result = self.input_queue.pop(0) - merging[ - merge_model_ray.remote( - genotype, - self.genome, - self.model_storage_path, - self.merge_options, - ) - ] = future_result - - while merged and len(evaluating) < self.num_gpus: - future_result, merged_path = merged.pop() - evaluating[ - evaluate_model_ray.remote( - merged_path, - self.config.tasks, - num_fewshot=self.config.num_fewshot, - limit=self.config.limit, - vllm=self.vllm, - batch_size=self.batch_size, - task_manager=self.task_manager, - ) - ] = future_result - - ready, _ = ray.wait( - list(merging.keys()) + list(evaluating.keys()), - num_returns=1, - fetch_local=False, - timeout=1, - ) - for r in ready: - if r in merging: - future_result = merging.pop(r) - merged.append((future_result, r)) - elif r in evaluating: - future_result = evaluating.pop(r) - future_result.set_result(await r) - - if ( - not self.input_queue - and not merging - and not merged - and not evaluating - ): - await asyncio.sleep(1) - except Exception as e: - logging.error("Error in processing loop", exc_info=e) - raise - - async def shutdown(self): - self._shutdown = True - - -class BufferedRayEvaluationStrategy(EvaluationStrategyBase): - def __init__( - self, - *args, - vllm: bool = False, - in_memory: bool = False, - **kwargs, - ): - if in_memory: - raise ValueError("In-memory evaluation is not supported for buffered mode") - - super().__init__(*args, **kwargs) - self.actor = BufferedRayEvaluationStrategyActor.options( - max_concurrency=1000 - ).remote( - self.config, - self.genome, - self.merge_options, - model_storage_path=self.model_storage_path, - vllm=vllm, - num_gpus=self.num_gpus, - task_manager=self.task_manager, - ) - self.actor.process_queue.remote() - - def evaluate_genotypes(self, genotypes: List[np.ndarray]) -> List[dict]: - return ray.get([self.actor.evaluate_genotype.remote(x) for x in genotypes]) - - def evaluate_genotype(self, genotype: np.ndarray) -> dict: - return ray.get(self.actor.evaluate_genotype.remote(genotype)) - - -@ray.remote -def evaluate_genotype_serial( - genotype: np.ndarray, - config: EvolMergeConfiguration, - genome: ModelGenome, - merge_options: MergeOptions, - model_storage_path: Optional[str] = None, - vllm: bool = False, - batch_size: Optional[int] = None, - task_manager: Optional[lm_eval.tasks.TaskManager] = None, -): - pg = ray.util.placement_group([{"CPU": 1, "GPU": 1}], strategy="STRICT_PACK") - strat = ray.util.scheduling_strategies.PlacementGroupSchedulingStrategy( - placement_group=pg - ) - merged_path = merge_model_ray.options(scheduling_strategy=strat).remote( - genotype, genome, model_storage_path, merge_options - ) - if not merged_path: - return {"score": None, "results": None} - res = ray.get( - evaluate_model_ray.options(scheduling_strategy=strat).remote( - merged_path, - config.tasks, - num_fewshot=config.num_fewshot, - limit=config.limit, - vllm=vllm, - batch_size=batch_size, - task_manager=task_manager, - ) - ) - ray.util.remove_placement_group(pg) - return res - - -class SerialEvaluationStrategy(EvaluationStrategyBase): - def __init__( - self, - *args, - vllm: bool = False, - in_memory: bool = False, - **kwargs, - ): - self.vllm = vllm - if in_memory: - raise ValueError("In-memory evaluation is not supported for serial mode") - super().__init__(*args, **kwargs) - - def evaluate_genotypes(self, genotypes: List[np.ndarray]) -> List[dict]: - return ray.get( - [ - evaluate_genotype_serial.remote( - x, - self.config, - self.genome, - self.merge_options, - model_storage_path=self.model_storage_path, - vllm=self.vllm, - batch_size=self.batch_size, - task_manager=self.task_manager, - ) - for x in genotypes - ] - ) - - def evaluate_genotype(self, genotype: np.ndarray) -> dict: - return self.evaluate_genotypes([genotype])[0] diff --git a/mergekit/graph.py b/mergekit/graph.py deleted file mode 100644 index 0870918f66f6e90a3f1984af8b11e363c77e1f29..0000000000000000000000000000000000000000 --- a/mergekit/graph.py +++ /dev/null @@ -1,272 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. -""" -Module for computational graph execution. - -Classes: - Task: Abstract base class representing a computational task. - Executor: Class for scheduling and executing directed acyclic task graphs. -""" - -from abc import ABC, abstractmethod -from typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Union - -import networkx -import torch -import tqdm -from pydantic import BaseModel -from typing_extensions import Generic, TypeVar - -ValueT = TypeVar("ValueT") - - -class Task(ABC, BaseModel, Generic[ValueT], frozen=True): - """ - Abstract base class representing a task in a computational graph. - - This class should be extended to define specific tasks. Each task can have arguments (dependencies) and a defined execution strategy. - - Attributes: - Generic[ValueT] (TypeVar): The type of the value that the task returns upon execution. - - Methods: - arguments: Abstract method to define task arguments (dependencies). - execute: Abstract method to execute the task. - priority: Returns the priority of the task for scheduling purposes. - group_label: Returns an optional label for task grouping. - """ - - @abstractmethod - def arguments(self) -> Dict[str, "Task"]: - """ - Returns a dictionary of arguments required for this task. The keys of the dictionary - are argument names, and the values are Task instances. These keys correspond to the - keyword argument names expected by the execute method. - - For example, if this method returns {'input1': taskA, 'input2': taskB}, the execute - method should expect to be called as execute(input1=valueA, input2=valueB), where - valueA and valueB are the outputs of taskA and taskB respectively. - - Returns: - Dict[str, "Task"]: A dictionary mapping argument names to Task instances. - """ - ... - - @abstractmethod - def execute(self, **kwargs) -> ValueT: - """ - Executes the task using the results of its dependencies. - - The keyword arguments (**kwargs) for this method are dynamically determined based on - the dictionary returned by the 'arguments' method. Each key in the 'arguments' method's - return dictionary becomes a keyword argument in this method, with its value being - the result of the corresponding task's execution. - - Returns: - ValueT: The result of the task execution. - """ - ... - - def priority(self) -> int: - """ - Returns the priority of the task for scheduling. - - Higher numbers indicate higher priority. Default is 0. - - Returns: - int: The priority of the task. - """ - return 0 - - def group_label(self) -> Optional[str]: - """ - Returns an optional label used for grouping tasks together. - - Returns: - Optional[str]: The group label of the task, if any. - """ - return None - - def uses_accelerator(self) -> bool: - """ - Returns True if the task can take advantage of matrix operation - acceleration (such as on a GPU). - """ - return False - - -class Executor: - """ - Schedules and executes a set of tasks and their dependencies. - - Handles scheduling, execution, the movement of data between devices, and the lifecycle of intermediate results. - - Attributes: - math_device (torch.device): Device used for tensor computations. - storage_device (torch.device): Device used for storing intermediate results. - targets (List[Task]): List of target tasks to be executed. - schedule (List[Task]): Calculated execution schedule of tasks. - dependencies (Dict[Task, Set[Task]]): Dependencies of each task. - """ - - math_device: torch.device - storage_device: torch.device - targets: List[Task] - schedule: List[Task] - dependencies: Dict[Task, Set[Task]] - - def __init__( - self, - tasks: List[Task], - math_device: torch.device = torch.device("cpu"), - storage_device: torch.device = torch.device("cpu"), - ): - """ - Initializes the Executor with a list of tasks and device configurations. - - Args: - tasks (List[Task]): The list of tasks to be executed. - math_device (torch.device, optional): The device for tensor computations. Defaults to CPU. - storage_device (torch.device, optional): The device for storing results. Defaults to CPU. - """ - self.math_device = math_device - self.storage_device = storage_device - self.schedule = self._make_schedule(tasks) - self.targets = tasks - - def run(self, quiet: bool = False) -> Iterator[Tuple[Task, Any]]: - """ - Execute the computed schedule and yield the target values. - - Yields: - Iterator[Tuple[Task, Any]]: An iterator of task-result pairs. - """ - # determine last usage of each value, so they can be evicted afterwards - last_use_index = {} - for idx, task in reversed(list(enumerate(self.schedule))): - for t in self.dependencies[task]: - if t not in last_use_index: - last_use_index[t] = idx - if task not in last_use_index: - last_use_index[task] = idx - - values: Dict[Task, Any] = {} - for idx, task in ( - pbar := tqdm.tqdm( - list(enumerate(self.schedule)), - disable=quiet, - desc="Executing graph", - ) - ): - use_math_device = task.uses_accelerator() - - arguments = {} - for name, dep in task.arguments().items(): - value = values[dep] - - # ensure any input tensors are on math device if task asks for it - if use_math_device: - if ( - isinstance(value, torch.Tensor) - and value.device != self.math_device - ): - value = value.to(self.math_device) - elif isinstance(value, dict): - for key in value: - if ( - isinstance(value[key], torch.Tensor) - and value[key].device != self.math_device - ): - value[key] = value[key].to(self.math_device) - - arguments[name] = value - del value - - res = task.execute(**arguments) - del arguments - - if isinstance(res, torch.Tensor) and res.device != self.storage_device: - res = res.to(self.storage_device) - - values[task] = res - del res - - if task in self.targets: - yield (task, values[task]) - - # evict unreferenced values - expired = [] - for key in values: - if idx >= last_use_index[key]: - expired.append(key) - - for key in expired: - del values[key] - - del values - del pbar - - def execute(self) -> None: - """ - Execute all tasks and discard results. - """ - for task, value in self.run(): - pass - - DUMMY_TASK_VALUE = "!!DUMMY!!" - - def _make_schedule(self, targets: List[Task]) -> List[Task]: - self.schedule = [] - self.dependencies = self._build_dependencies(targets) - - edge_tups = [] - for node in self.dependencies: - for dependency in self.dependencies[node]: - edge_tups.append((dependency, node)) - - for task in targets: - # add edges from a dummy node to each target to guarantee - # they will be included in the final schedule - edge_tups.append((Executor.DUMMY_TASK_VALUE, task)) - - def _compare_key(task: Union[Task, str]): - if task == Executor.DUMMY_TASK_VALUE: - return ("", 0) - return ( - task.group_label() or "", - -task.priority(), - ) - - graph = networkx.DiGraph(edge_tups) - res = [ - t - for t in networkx.lexicographical_topological_sort(graph, key=_compare_key) - if t != Executor.DUMMY_TASK_VALUE - ] - return res - - def _build_dependencies(self, targets: List[Task]) -> Dict[Task, Set[Task]]: - task_dependencies: Dict[Task, Set[Task]] = {} - to_process = list(targets) - while to_process: - child = to_process.pop() - if child in task_dependencies: - continue - - task_dependencies[child] = set() - for _, dep in child.arguments().items(): - task_dependencies[child].add(dep) - to_process.append(dep) - return task_dependencies diff --git a/mergekit/io/__init__.py b/mergekit/io/__init__.py deleted file mode 100644 index ac9f03d200f848e511a7d446afc7ea6e4397312a..0000000000000000000000000000000000000000 --- a/mergekit/io/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from mergekit.io.lazy_tensor_loader import ( - LazyTensorLoader, - ShardedTensorIndex, - ShardInfo, -) -from mergekit.io.tensor_writer import TensorWriter - -__all__ = [ - "LazyTensorLoader", - "ShardedTensorIndex", - "ShardInfo", - "TensorWriter", -] diff --git a/mergekit/io/lazy_tensor_loader.py b/mergekit/io/lazy_tensor_loader.py deleted file mode 100644 index 6e28ea4549020fd688c4e011c81b7cc6e1776ee2..0000000000000000000000000000000000000000 --- a/mergekit/io/lazy_tensor_loader.py +++ /dev/null @@ -1,149 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import json -import logging -import os -import os.path -from dataclasses import dataclass -from typing import Dict, List, Optional - -import safetensors -import safetensors.torch -import torch -from torch import Tensor - -from mergekit.io.loader import TensorLoader - - -@dataclass -class ShardInfo: - filename: str - contained_keys: List[str] - - -@dataclass -class ShardedTensorIndex: - base_path: str - is_safetensors: bool - tensor_paths: Dict[str, str] - shards: List[ShardInfo] - - @classmethod - def from_disk(cls, base_path: str) -> "ShardedTensorIndex": - model_path = None - for model_file_name in [ - "model.safetensors", - "pytorch_model.bin", - ]: - candidate_path = os.path.join(base_path, model_file_name) - if os.path.exists(candidate_path) or os.path.exists( - candidate_path + ".index.json" - ): - model_path = candidate_path - break - - if not model_path: - raise RuntimeError(f"Unable to find model files at {base_path}") - - is_safetensors = model_path.endswith(".safetensors") - tensor_paths = None - shards = [] - - if os.path.exists(model_path + ".index.json"): - # shared model - parse index - with open(model_path + ".index.json", "r") as fd: - weight_map = json.load(fd)["weight_map"] - tensor_paths = weight_map - - shard_names = list(sorted(set(tensor_paths[e] for e in tensor_paths))) - for shard_name in shard_names: - info = ShardInfo( - shard_name, - [key for key in tensor_paths if tensor_paths[key] == shard_name], - ) - shards.append(info) - - elif os.path.exists(model_path): - shard_name = os.path.basename(model_path) - - # get list of tensors contained in single-file checkpoint - if model_path.lower().endswith(".safetensors"): - with safetensors.safe_open(model_path, framework="pt") as st: - tensor_paths = {key: shard_name for key in st.keys()} - else: - # this is ugly but not much else can be done - shard = torch.load(model_path, map_location="meta") - if "state_dict" in shard: - shard = shard["state_dict"] - - tensor_paths = {key: shard_name for key in shard} - - shards.append( - ShardInfo(os.path.basename(model_path), list(tensor_paths.keys())) - ) - - return ShardedTensorIndex( - base_path=base_path, - is_safetensors=is_safetensors, - tensor_paths=tensor_paths, - shards=shards, - ) - - -class LazyTensorLoader: - index: ShardedTensorIndex - current_shard: Optional[TensorLoader] - lazy_unpickle: bool - - def __init__(self, index: ShardedTensorIndex, lazy_unpickle: bool = True): - self.index = index - self.current_shard = None - self.lazy_unpickle = lazy_unpickle - - def get_tensor( - self, key: str, device: str = "cpu", aliases: Optional[List[str]] = None - ) -> Optional[Tensor]: - if aliases and key not in self.index.tensor_paths: - for alias in aliases: - if alias in self.index.tensor_paths: - key = alias - break - - if self.current_shard is None or key not in self.current_shard.keys(): - if key not in self.index.tensor_paths: - raise KeyError(key) - - self.current_shard = None - self.current_keys = None - - shard_file = self.index.tensor_paths[key] - shard_full_path = os.path.join(self.index.base_path, shard_file) - logging.debug(f"Opening shard {shard_full_path}") - self.current_shard = TensorLoader.get( - shard_full_path, use_lazy_unpickle=self.lazy_unpickle, device=device - ) - - return self.current_shard.get_tensor(key).to(device) - - def flush(self): - self.current_shard = None - self.current_keys = None - - @classmethod - def from_disk( - cls, base_path: str, lazy_unpickle: bool = True - ) -> "LazyTensorLoader": - return LazyTensorLoader(ShardedTensorIndex.from_disk(base_path), lazy_unpickle) diff --git a/mergekit/io/lazy_unpickle.py b/mergekit/io/lazy_unpickle.py deleted file mode 100644 index 7b392f3ed7697774885e0d8f1cccdcafbe6308d3..0000000000000000000000000000000000000000 --- a/mergekit/io/lazy_unpickle.py +++ /dev/null @@ -1,200 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import codecs -import collections -import contextlib -import operator -import os -import pickle -import zipfile -from functools import reduce -from typing import Any, Optional, Tuple, Union - -import accelerate -import numpy -import torch -from pydantic import BaseModel, PrivateAttr - -ACCEPTABLE_TYPES = { - ("torch._utils", "_rebuild_tensor_v2"): torch._utils._rebuild_tensor_v2, - ("collections", "OrderedDict"): collections.OrderedDict, - ("numpy.core.multiarray", "scalar"): numpy.core.multiarray.scalar, - ("numpy", "dtype"): numpy.core.multiarray.scalar, - ("_codecs", "encode"): codecs.encode, - **{ - ("torch", name): getattr(torch, name) - for name in [ - "DoubleStorage", - "FloatStorage", - "HalfStorage", - "LongStorage", - "IntStorage", - "ShortStorage", - "CharStorage", - "ByteStorage", - "BoolStorage", - "BFloat16Storage", - ] - }, -} - - -class DeferredLoad(BaseModel, arbitrary_types_allowed=True): - name: str - location: str - dtype: torch.dtype - - # set after construction by rebuild() - file_offset: Optional[int] = None - shape: Optional[Union[torch.Size, Tuple[int, ...]]] = None - stride: Optional[Tuple[int, ...]] = None - - # set arbitrarily in Torch innards - requires_grad: bool = False - _backward_hooks: Any = PrivateAttr(None) - - @staticmethod - def rebuild( - load: "DeferredLoad", - offset: int, - shape: Union[torch.Size, Tuple[int, ...]], - stride: Tuple[int, ...], - ) -> "DeferredLoad": - load.shape = shape - load.stride = stride - load.file_offset = offset * dtype_bytes(load.dtype) - return load - - def execute( - self, - reader: "TorchArchiveReader", - map_location: Any = None, - ) -> torch.Tensor: - total_params = reduce(operator.mul, self.shape) - total_bytes = total_params * dtype_bytes(self.dtype) - - f = reader.open_file(file_name=self.name, offset=self.file_offset) - storage = torch.UntypedStorage.from_buffer( - f.read(total_bytes), "little", dtype=self.dtype - ) - storage = torch.serialization._get_restore_location(map_location)( - storage, self.location - ) - - tensor = torch.tensor([], dtype=self.dtype, device=storage.device) - tensor.set_(storage, 0, self.shape, self.stride) - tensor.requires_grad = self.requires_grad - tensor._backward_hooks = self._backward_hooks - return tensor - - -class LazyTorchUnpickler(pickle.Unpickler): - def find_class(self, module: str, name: str) -> Any: - if (module, name) in ACCEPTABLE_TYPES: - return ACCEPTABLE_TYPES[(module, name)] - raise pickle.UnpicklingError(f"Unsupported type {module}.{name}") - - def persistent_load(self, pid: Any) -> Any: - if not isinstance(pid, tuple) or pid[0] != "storage": - raise RuntimeError(f"Unpickling object with unexpected PID: {repr(pid)}") - - storage_type, key, location, _ = pid[1:] - return DeferredLoad(name=key, location=location, dtype=get_dtype(storage_type)) - - -class TorchArchiveReader: - """ - Class for lazily reading (sections of) files from a torch ZIP archive. - - Maintains a handle to the most recently opened file for faster access with - consecutive reads from the same file. - """ - - archive: zipfile.ZipFile - archive_name: str - file_name: Optional[str] = None - file: Optional[zipfile.ZipExtFile] = None - - def __init__(self, path: str): - self.archive = zipfile.ZipFile(path, mode="r") - self.archive_name = os.path.basename(os.path.normpath(path)).split(".")[0] - - def open_file(self, file_name: str, offset: int = 0) -> zipfile.ZipExtFile: - if self.file_name != file_name or ( - self.file is not None and self.file.tell() > offset - ): - if self.file is not None: - self.file.close() - - try: - fd = self.archive.open(f"archive/data/{file_name}", mode="r") - except Exception: - fd = self.archive.open( - f"{self.archive_name}/data/{file_name}", mode="r" - ) - self.file = fd - self.file_name = file_name - - skip_bytes = offset - self.file.tell() - assert skip_bytes >= 0 - self.file.seek(skip_bytes, os.SEEK_CUR) - - return self.file - - -@contextlib.contextmanager -def torch_lazy_load(): - """ - Context manager under which `torch.load` will return a `DeferredLoad` instead - of `torch.Tensor.` - """ - old_unpickler = pickle.Unpickler - old_load = pickle.load - old_rebuild_tensor = torch._utils._rebuild_tensor - try: - - def load_monkeypatch(*args, **kwargs): - return pickle.Unpickler(*args, **kwargs).load() - - pickle.Unpickler = LazyTorchUnpickler - pickle.load = load_monkeypatch - torch._utils._rebuild_tensor = DeferredLoad.rebuild - - with accelerate.init_empty_weights(): - yield - - finally: - torch._utils._rebuild_tensor = old_rebuild_tensor - pickle.Unpickler = old_unpickler - pickle.load = old_load - - -def dtype_bytes(dtype: torch.dtype) -> int: - """Return the number of bytes used to store a single instance of `dtype`.""" - if dtype.is_floating_point: - ti = torch.finfo(dtype) - else: - ti = torch.iinfo(dtype) - return max(1, ti.bits // 8) - - -def get_dtype(storage_type: Any): - if isinstance(storage_type, torch.dtype): - return storage_type - dtype = storage_type.dtype - if not isinstance(dtype, torch.dtype): - dtype = storage_type(0).dtype - return dtype diff --git a/mergekit/io/loader.py b/mergekit/io/loader.py deleted file mode 100644 index 8a8eb4fac64c92953ef5eabe559840f2c43e2c34..0000000000000000000000000000000000000000 --- a/mergekit/io/loader.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from abc import ABC, abstractmethod -from typing import Dict, Optional, Sequence - -import safetensors -import torch - -from mergekit.io.lazy_unpickle import DeferredLoad, TorchArchiveReader, torch_lazy_load - - -class TensorLoader(ABC): - """Base class for (potentially lazy) tensor loaders.""" - - @abstractmethod - def get_tensor(self, key: str) -> torch.Tensor: - ... - - @abstractmethod - def keys(self) -> Sequence[str]: - ... - - @classmethod - def get( - cls, - shard_path: str, - use_lazy_unpickle: bool = False, - device: Optional[str] = None, - ) -> "TensorLoader": - if shard_path.lower().endswith(".safetensors"): - # not a subclass of TensorLoader, but exposes same api - return safetensors.safe_open( - shard_path, framework="pt", device=device or "cpu" - ) - elif use_lazy_unpickle: - return LazyPickleLoader(shard_path, device=device) - return DumbPytorchLoader(shard_path, device=device) - - -class LazyPickleLoader(TensorLoader): - """Loader for pytorch files using a custom unpickler and vigorous monkeypatching.""" - - zip_reader: TorchArchiveReader - index: Dict[str, DeferredLoad] - device: Optional[str] = None - - def __init__(self, path: str, device: Optional[str] = None): - self.zip_reader = TorchArchiveReader(path) - self.device = device - with torch_lazy_load(): - self.index = torch.load(path) - - def get_tensor(self, key: str) -> torch.Tensor: - if key not in self.index: - raise KeyError(key) - - return self.index[key].execute(self.zip_reader, map_location=self.device) - - def keys(self) -> Sequence[str]: - return self.index.keys() - - -class DumbPytorchLoader(TensorLoader): - """Naive `torch.load` shard loading.""" - - tensors: Dict[str, torch.Tensor] - - def __init__(self, path: str, device: Optional[str] = None): - self.tensors = torch.load(path, map_location=device, weights_only=True) - - def get_tensor(self, key: str) -> torch.Tensor: - return self.tensors[key] - - def keys(self) -> Sequence[str]: - return self.tensors.keys() diff --git a/mergekit/io/tasks.py b/mergekit/io/tasks.py deleted file mode 100644 index 7c42968f948a906ab23a907e9778dacbfd565094..0000000000000000000000000000000000000000 --- a/mergekit/io/tasks.py +++ /dev/null @@ -1,226 +0,0 @@ -import os -import re -from typing import Dict, Optional, Tuple - -import torch - -from mergekit.architecture import WeightInfo -from mergekit.common import ImmutableMap, ModelReference, dtype_from_name -from mergekit.graph import Task -from mergekit.io.lazy_tensor_loader import LazyTensorLoader -from mergekit.io.tensor_writer import TensorWriter -from mergekit.options import MergeOptions - - -class LoaderCache: - loaders: Dict[ModelReference, LazyTensorLoader] = {} - lora_cache_dir: Optional[str] = None - hf_cache_dir: Optional[str] = None - lazy_unpickle: bool = False - trust_remote_code: bool = False - - # singleton instance - _instance: Optional["LoaderCache"] = None - - def __new__(cls) -> "LoaderCache": - if cls._instance is None: - cls._instance = super(LoaderCache, cls).__new__(cls) - return cls._instance - - def get(self, model: ModelReference) -> LazyTensorLoader: - if model not in self.loaders: - merged = model.merged( - cache_dir=self.lora_cache_dir, trust_remote_code=self.trust_remote_code - ) - self.loaders[model] = merged.lazy_loader( - cache_dir=self.hf_cache_dir, lazy_unpickle=self.lazy_unpickle - ) - return self.loaders[model] - - def flush_all(self): - for loader in self.loaders.values(): - loader.flush() - - def setup(self, options: MergeOptions): - self.lora_cache_dir = options.lora_merge_cache - self.hf_cache_dir = options.transformers_cache - self.lazy_unpickle = options.lazy_unpickle - self.trust_remote_code = options.trust_remote_code - - -shard_name_re = re.compile(r"model\-([0-9]+)-of-([0-9]+)") - - -def _normalized_shard_name(path: str) -> int: - name, _ext = os.path.splitext(os.path.basename(path)) - name = name.lower().replace("pytorch_model", "model") - if m := shard_name_re.search(name): - frac = int(m.group(1)) / int(m.group(2)) - name = f"model-{int(frac*100):03d}pct" - return name - - -class LoadTensor(Task[Optional[torch.Tensor]]): - model: ModelReference - tensor: str - dtype: Optional[str] = None - device: Optional[str] = None - optional: bool = False - aliases: Optional[Tuple[str, ...]] = None - - def arguments(self) -> Dict[str, Task]: - return {} - - def _resolve_name(self, loader: LazyTensorLoader) -> Optional[str]: - all_names = [self.tensor] + list(self.aliases or []) - for name in all_names: - if name in loader.index.tensor_paths: - return name - return None - - def execute(self) -> Optional[torch.Tensor]: - loader = LoaderCache().get(self.model) - name = self._resolve_name(loader) - if not name: - if not self.optional: - raise RuntimeError( - f"Tensor {self.tensor} required but not present in model {self.model}" - ) - return None - - x = loader.get_tensor(name, device=self.device or "cpu") - if self.dtype and (dtype := dtype_from_name(self.dtype)) != x.dtype: - x = x.to(dtype=dtype) - return x - - def priority(self) -> int: - return -1000 - - def group_label(self) -> Optional[str]: - loader = LoaderCache().get(self.model) - name = self._resolve_name(loader) - # if name: - # shard_path = loader.index.tensor_paths[name] - # return _normalized_shard_name(shard_path) - # return None - return name - - -class GatherTensors(Task[Dict[ModelReference, torch.Tensor]]): - weight_info: ImmutableMap[ModelReference, WeightInfo] - dtype: Optional[str] = None - device: Optional[str] = None - - def arguments(self) -> Dict[str, Task]: - return { - f"{str(model)}:{wi.name}": LoadTensor( - model=model, - tensor=wi.name, - dtype=wi.force_dtype or self.dtype, - device=self.device, - optional=wi.optional, - aliases=wi.aliases, - ) - for (model, wi) in self.weight_info.items() - } - - def group_label(self) -> Optional[str]: - return max(t.group_label() or "" for t in self.arguments().values()) - - def priority(self) -> int: - return -10 - - def execute(self, **kwargs) -> Dict[ModelReference, torch.Tensor]: - key2model = { - f"{str(model)}:{wi.name}": model for (model, wi) in self.weight_info.items() - } - return { - key2model[key]: kwargs[key] for key in key2model if kwargs[key] is not None - } - - -class TensorWriterTask(Task[TensorWriter]): - out_path: str - max_shard_size: int - safe_serialization: bool = True - - def arguments(self) -> Dict[str, Task]: - return {} - - def execute(self, **_kwargs) -> TensorWriter: - return TensorWriter( - self.out_path, - max_shard_size=self.max_shard_size, - safe_serialization=self.safe_serialization, - ) - - -class SaveTensor(Task[None]): - tensor_name: str - tensor_task: Task - writer_task: TensorWriterTask - clone: bool - optional: bool = False - dtype: Optional[str] = None - - def arguments(self) -> Dict[str, Task]: - return {"writer": self.writer_task, "tensor": self.tensor_task} - - def priority(self) -> int: - return 1000 - - def group_label(self) -> Optional[str]: - return self.tensor_task.group_label() - - def execute(self, writer: TensorWriter, tensor: Optional[torch.Tensor]) -> None: - if tensor is None: - if not self.optional: - raise RuntimeError(f"No value for required tensor {self.tensor_name}") - return - if self.dtype: - tensor = tensor.to(dtype=dtype_from_name(self.dtype)) - writer.save_tensor(name=self.tensor_name, tensor=tensor, clone=self.clone) - - -class FinalizeModel(Task[None]): - tensor_save_tasks: Tuple[Task, ...] - writer_task: TensorWriterTask - - def arguments(self) -> Dict[str, Task]: - return { - "writer": self.writer_task, - **{f"_unused_{idx}": t for idx, t in enumerate(self.tensor_save_tasks)}, - } - - def execute(self, writer: TensorWriter, **kwargs) -> None: - writer.finalize() - - -class BuildStateDict(Task[Dict[str, torch.Tensor]]): - tensors: ImmutableMap[WeightInfo, Task[torch.Tensor]] - - def arguments(self) -> Dict[str, Task]: - return {str(wi): t for wi, t in self.tensors.items()} - - def execute(self, **kwargs) -> Dict[str, torch.Tensor]: - return {str(wi): t for wi, t in self.tensors.items()} - - -class ReturnTensor(Task[torch.Tensor]): - weight_info: WeightInfo - tensor_task: Task[torch.Tensor] - dtype: Optional[str] = None - - def arguments(self) -> Dict[str, Task]: - return {"tensor": self.tensor_task} - - def priority(self) -> int: - return 10000 - - def group_label(self) -> Optional[str]: - return self.tensor_task.group_label() - - def execute(self, tensor: torch.Tensor) -> torch.Tensor: - if self.dtype and (dtype := dtype_from_name(self.dtype)) != tensor.dtype: - tensor = tensor.to(dtype=dtype) - return tensor diff --git a/mergekit/io/tensor_writer.py b/mergekit/io/tensor_writer.py deleted file mode 100644 index fe0c22b7fb710e5724281362cc1a6c26bed5da8a..0000000000000000000000000000000000000000 --- a/mergekit/io/tensor_writer.py +++ /dev/null @@ -1,162 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import json -import logging -import os -from typing import Dict - -import safetensors -import torch - - -class TensorWriter: - out_path: str - max_shard_size: int - shards_written: int - weight_map = Dict[str, str] - current_shard: Dict[str, torch.Tensor] - current_shard_size: int - total_size: int - safe_serialization: bool - - def __init__( - self, - out_path: str, - max_shard_size: int = 1000 * 1000 * 1000 * 5, - safe_serialization: bool = True, - ) -> None: - os.makedirs(out_path, exist_ok=True) - - self.out_path = out_path - self.max_shard_size = max_shard_size - self.safe_serialization = safe_serialization - self.shards_written = 0 - self.weight_map = {} - self.current_shard = {} - self.current_shard_size = 0 - self.total_size = 0 - - def save_tensor(self, name: str, tensor: torch.Tensor, clone: bool = False): - if not tensor.is_contiguous(): - tensor = tensor.contiguous() - - tensor_size = tensor.numel() * tensor.element_size() - if ( - self.current_shard - and self.current_shard_size + tensor_size > self.max_shard_size - ): - self.flush_current_shard() - - if clone: - tensor = tensor.clone() - - self.current_shard[name] = tensor - self.total_size += tensor_size - self.current_shard_size += tensor_size - - def flush_current_shard(self): - if not self.current_shard: - return - - logging.info(f"Writing shard #{self.shards_written+1} to disk") - - prefix, extension = self._get_name_components() - shard_name = f"{prefix}-{self.shards_written+1}.{extension}" - - for key in self.current_shard: - self.weight_map[key] = shard_name - - shard_path = os.path.join(self.out_path, shard_name) - if self.safe_serialization: - self._save_st(shard_path) - else: - torch.save(self.current_shard, shard_path) - - self.current_shard = {} - self.current_shard_size = 0 - self.shards_written = self.shards_written + 1 - - def finalize(self): - self.flush_current_shard() - - logging.info("Finalizing shard names") - - prefix, extension = self._get_name_components() - - # standardize shard names to hf format - total_shards = self.shards_written - name_remap = {} - for idx in range(total_shards): - name_remap[ - f"{prefix}-{idx+1}.{extension}" - ] = f"{prefix}-{idx+1:05d}-of-{total_shards:05d}.{extension}" - - for old_name, new_name in name_remap.items(): - os.rename( - os.path.join(self.out_path, old_name), - os.path.join(self.out_path, new_name), - ) - - for key in self.weight_map: - self.weight_map[key] = name_remap[self.weight_map[key]] - - with open( - os.path.join(self.out_path, f"{prefix}.{extension}.index.json"), - "w", - encoding="utf-8", - ) as file: - json.dump( - { - "metadata": { - "mergekit_version": "0.0.4.4", - "total_size": self.total_size, - }, - "weight_map": self.weight_map, - }, - file, - ) - - def _get_name_components(self): - if self.safe_serialization: - return "model", "safetensors" - return "pytorch_model", "bin" - - def _save_st(self, shard_path: str): - def _do_save(): - safetensors.torch.save_file( - self.current_shard, - shard_path, - metadata={"format": "pt"}, - ) - - try: - _do_save() - except RuntimeError as e: - if ( - len(e.args) > 0 - and isinstance(e.args[0], str) - and "share memory" in e.args[0] - ): - logging.warning( - "Your model has duplicated tensors but the --clone-tensors " - "flag is not set." - ) - self.current_shard = { - key: self.current_shard[key].clone() for key in self.current_shard - } - _do_save() - else: - raise diff --git a/mergekit/merge.py b/mergekit/merge.py deleted file mode 100644 index cdb7a1aa4aaf7b69bbfe947b57d6f4cd3cc2370f..0000000000000000000000000000000000000000 --- a/mergekit/merge.py +++ /dev/null @@ -1,216 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -import os -import shutil -from typing import Optional - -import tqdm -import transformers - -from mergekit.architecture import ArchitectureInfo, get_architecture_info -from mergekit.card import generate_card -from mergekit.config import MergeConfiguration -from mergekit.graph import Executor -from mergekit.io.tasks import LoaderCache -from mergekit.options import MergeOptions -from mergekit.plan import MergePlanner -from mergekit.tokenizer import TokenizerInfo - - -def run_merge( - merge_config: MergeConfiguration, - out_path: str, - options: MergeOptions, - config_source: Optional[str] = None, -): - if options.random_seed is not None: - transformers.trainer_utils.set_seed(options.random_seed) - - if not merge_config.models and not merge_config.slices: - raise RuntimeError("No output requested") - - model_arch_info = [ - get_architecture_info(m.config(trust_remote_code=options.trust_remote_code)) - for m in merge_config.referenced_models() - ] - if not options.allow_crimes: - if not all(a == model_arch_info[0] for a in model_arch_info[1:]): - raise RuntimeError( - "Must specify --allow-crimes to attempt to mix different architectures" - ) - arch_info = model_arch_info[0] - - # initialize loader cache and set options - loader_cache = LoaderCache() - loader_cache.setup(options=options) - - # create config for output model - cfg_out = _model_out_config( - merge_config, arch_info, trust_remote_code=options.trust_remote_code - ) - - # warm up loader cache - for model in ( - pbar := tqdm.tqdm( - merge_config.referenced_models(), - desc="Warmup loader cache", - disable=options.quiet, - ) - ): - loader_cache.get(model) - del pbar - - logging.info("Planning operations") - targets = MergePlanner( - merge_config, - arch_info, - options=options, - out_model_config=cfg_out, - ).plan_to_disk(out_path=out_path) - - exec = Executor( - tasks=targets, - math_device="cuda" if options.cuda else "cpu", - storage_device="cuda" if options.low_cpu_memory else "cpu", - ) - - tokenizer = None - for _task, value in exec.run(quiet=options.quiet): - if isinstance(value, TokenizerInfo): - tokenizer = value.tokenizer - - if tokenizer: - _update_config_vocab(cfg_out, tokenizer) - - logging.info("Saving config") - cfg_out.save_pretrained(out_path) - - if options.write_model_card: - if not config_source: - config_source = merge_config.to_yaml() - - card_md = generate_card( - config=merge_config, - config_yaml=config_source, - name=os.path.basename(out_path), - ) - with open(os.path.join(out_path, "README.md"), "w", encoding="utf-8") as fp: - fp.write(card_md) - - with open( - os.path.join(out_path, "mergekit_config.yml"), "w", encoding="utf-8" - ) as fp: - fp.write(config_source) - - if tokenizer is None and options.copy_tokenizer: - try: - _copy_tokenizer( - merge_config, out_path, trust_remote_code=options.trust_remote_code - ) - except Exception as e: - logging.error( - "Failed to copy tokenizer. The merge was still successful, just copy it from somewhere else.", - exc_info=e, - ) - - if tokenizer: - logging.info("Saving tokenizer") - tokenizer.save_pretrained(out_path, safe_serialization=True) - - -def _copy_tokenizer( - merge_config: MergeConfiguration, out_path: str, trust_remote_code: bool = False -): - donor_model = merge_config.base_model or (merge_config.referenced_models()[0]) - - if os.path.exists( - os.path.join(donor_model.model.path, "tokenizer_config.json") - ) and ( - os.path.exists(os.path.join(donor_model.model.path, "tokenizer.json")) - or os.path.exists(os.path.join(donor_model.model.path, "tokenizer.model")) - ): - logging.info(f"Copying tokenizer from {donor_model}") - - for file_name in [ - "tokenizer_config.json", - "special_tokens_map.json", - "tokenizer.json", - "tokenizer.model", - ]: - if os.path.exists(os.path.join(donor_model.model.path, file_name)): - shutil.copy( - os.path.join(donor_model.model.path, file_name), - os.path.join(out_path, file_name), - ) - - return - - # fallback: try actually loading the tokenizer and saving it - logging.info(f"Reserializing tokenizer from {donor_model}") - tokenizer = transformers.AutoTokenizer.from_pretrained( - donor_model.model.path, - revision=donor_model.model.revision, - trust_remote_code=trust_remote_code, - ) - tokenizer.save_pretrained(out_path, safe_serialization=True) - - -def _model_out_config( - config: MergeConfiguration, - arch_info: ArchitectureInfo, - trust_remote_code: bool = False, -) -> transformers.PretrainedConfig: - """Return a configuration for the resulting model.""" - if config.base_model: - res = config.base_model.config(trust_remote_code=trust_remote_code) - else: - res = config.referenced_models()[0].config(trust_remote_code=trust_remote_code) - if config.out_dtype: - res.torch_dtype = config.out_dtype - elif config.dtype: - res.torch_dtype = config.dtype - - if config.slices: - try: - num_layers = sum( - s.sources[0].layer_range[1] - s.sources[0].layer_range[0] - for s in config.slices - ) - setattr(res, arch_info.num_layers_config_key(), num_layers) - except Exception as e: - logging.warning( - "Unable to set number of layers in output config - you may need to manually correct it.", - exc_info=e, - ) - - return res - - -def _update_config_vocab( - config: transformers.PretrainedConfig, - tokenizer: transformers.PreTrainedTokenizerBase, -): - try: - config.vocab_size = len(tokenizer.get_vocab()) - except Exception as e: - logging.warning( - "Unable to set vocabulary size in output config - you may need to manually correct it.", - exc_info=e, - ) - - -__all__ = ["MergeOptions", "run_merge"] diff --git a/mergekit/merge_methods/__init__.py b/mergekit/merge_methods/__init__.py deleted file mode 100644 index d0f6462b1a82473ba01da67b43987395bcd481bc..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/__init__.py +++ /dev/null @@ -1,91 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from mergekit.merge_methods.base import MergeMethod -from mergekit.merge_methods.generalized_task_arithmetic import ( - ConsensusMethod, - GeneralizedTaskArithmeticMerge, - SparsificationMethod, -) -from mergekit.merge_methods.linear import LinearMerge -from mergekit.merge_methods.model_stock import ModelStockMerge -from mergekit.merge_methods.passthrough import PassthroughMerge -from mergekit.merge_methods.slerp import SlerpMerge -from mergekit.merge_methods.tokenizer_permute import TokenizerPermutationMerge - - -def get(method: str) -> MergeMethod: - if method == "linear": - return LinearMerge() - elif method == "slerp": - return SlerpMerge() - elif method == "passthrough": - return PassthroughMerge() - elif method == "task_arithmetic": - return GeneralizedTaskArithmeticMerge( - consensus_method=None, - sparsification_method=None, - default_normalize=False, - default_rescale=False, - ) - elif method == "ties": - return GeneralizedTaskArithmeticMerge( - consensus_method=ConsensusMethod.sum, - sparsification_method=SparsificationMethod.magnitude, - default_normalize=True, - default_rescale=False, - ) - elif method == "dare_ties": - return GeneralizedTaskArithmeticMerge( - consensus_method=ConsensusMethod.sum, - sparsification_method=SparsificationMethod.random, - default_normalize=False, - default_rescale=True, - ) - elif method == "dare_linear": - return GeneralizedTaskArithmeticMerge( - consensus_method=None, - sparsification_method=SparsificationMethod.random, - default_normalize=False, - default_rescale=True, - ) - elif method == "breadcrumbs": - return GeneralizedTaskArithmeticMerge( - consensus_method=None, - sparsification_method=SparsificationMethod.magnitude_outliers, - default_normalize=False, - default_rescale=False, - ) - elif method == "breadcrumbs_ties": - return GeneralizedTaskArithmeticMerge( - consensus_method=ConsensusMethod.sum, - sparsification_method=SparsificationMethod.magnitude_outliers, - default_normalize=False, - default_rescale=False, - ) - elif method == "model_stock": - return ModelStockMerge() - raise RuntimeError(f"Unimplemented merge method {method}") - - -__all__ = [ - "MergeMethod", - "get", - "LinearMerge", - "SlerpMerge", - "PassthroughMerge", - "GeneralizedTaskArithmeticMerge", - "TokenizerPermutationMerge", -] diff --git a/mergekit/merge_methods/base.py b/mergekit/merge_methods/base.py deleted file mode 100644 index e637ac66c571cf3d6755e738228ec04a6fbaa018..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/base.py +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from abc import ABC, abstractmethod -from typing import Any, List, Optional - -from pydantic import BaseModel - -from mergekit.architecture import WeightInfo -from mergekit.common import ImmutableMap, ModelReference -from mergekit.graph import Task -from mergekit.io.tasks import GatherTensors - - -class ConfigParameterDef(BaseModel): - name: str - required: bool = False - default_value: Any = None - - -class MergeMethod(ABC): - def tensor_parameters(self) -> List[ConfigParameterDef]: - return [] - - def parameters(self) -> List[ConfigParameterDef]: - return [] - - @abstractmethod - def make_task( - self, - *, - output_weight: WeightInfo, - tensors: GatherTensors, - parameters: ImmutableMap[str, Any], - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]], - base_model: Optional[ModelReference], - ) -> Task: - ... diff --git a/mergekit/merge_methods/generalized_task_arithmetic.py b/mergekit/merge_methods/generalized_task_arithmetic.py deleted file mode 100644 index dd81a0b47111e8daa22da3fa8112d97b046264c1..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/generalized_task_arithmetic.py +++ /dev/null @@ -1,232 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -from enum import Enum -from typing import Any, Dict, List, Optional, Tuple - -import torch -from pydantic import BaseModel -from typing_extensions import Literal - -from mergekit.architecture import WeightInfo -from mergekit.common import ImmutableMap, ModelReference -from mergekit.graph import Task -from mergekit.io.tasks import GatherTensors -from mergekit.merge_methods.base import ConfigParameterDef, MergeMethod -from mergekit.sparsify import SparsificationMethod, sparsify - - -class ConsensusMethod(str, Enum): - count = "count" - sum = "sum" - - -class GeneralizedTaskArithmeticMerge(MergeMethod, BaseModel, frozen=True): - consensus_method: Optional[ConsensusMethod] - sparsification_method: Optional[SparsificationMethod] - default_normalize: bool - default_rescale: bool - - def parameters(self) -> List[ConfigParameterDef]: - return [ - ConfigParameterDef(name="int8_mask", required=False, default_value=False), - ConfigParameterDef( - name="normalize", required=False, default_value=self.default_normalize - ), - ConfigParameterDef( - name="rescale", required=False, default_value=self.default_rescale - ), - ] - - def tensor_parameters(self) -> List[ConfigParameterDef]: - res = [ - ConfigParameterDef(name="weight", required=True), - ConfigParameterDef(name="density", required=False, default_value=1.0), - ] - if self.sparsification_method == SparsificationMethod.magnitude_outliers: - res.append( - ConfigParameterDef( - name="gamma", - default_value=0.01, - ) - ) - return res - - def make_task( - self, - output_weight: WeightInfo, - tensors: GatherTensors, - base_model: Optional[ModelReference], - parameters: ImmutableMap[str, Any], - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]], - ) -> Task: - return GTATask( - method=self, - tensors=tensors, - base_model=base_model, - tensor_parameters=tensor_parameters, - int8_mask=parameters["int8_mask"], - normalize=parameters["normalize"], - rescale=parameters["rescale"], - weight_info=output_weight, - ) - - -class GTATask(Task[torch.Tensor]): - method: GeneralizedTaskArithmeticMerge - tensors: GatherTensors - base_model: ModelReference - weight_info: WeightInfo - tensor_parameters: ImmutableMap[ModelReference, Any] - int8_mask: bool - normalize: bool - rescale: bool - - def uses_accelerator(self) -> bool: - return True - - def arguments(self) -> Dict[str, Task]: - return {"tensors": self.tensors} - - def execute( - self, - tensors: Dict[ModelReference, torch.Tensor], - **_kwargs, - ) -> torch.Tensor: - # collect task vectors - tvs, base = get_task_vectors( - self.weight_info, - self.base_model, - tensors, - tensor_parameters=self.tensor_parameters.data, - ) - if not tvs: - return base - - # sparsify - if self.method.sparsification_method: - for tv_info in tvs: - kwargs = {} - if "gamma" in tv_info: - kwargs["gamma"] = tv_info["gamma"] - - tv_info["delta"] = sparsify( - tv_info["delta"], - density=tv_info["density"], - method=self.method.sparsification_method, - rescale=self.rescale, - **kwargs, - ) - - deltas = torch.stack([tv["delta"] for tv in tvs], dim=0) - weights = torch.tensor( - [tv["weight"] for tv in tvs], dtype=deltas.dtype, device=deltas.device - ) - while len(deltas.shape) > len(weights.shape): - weights.unsqueeze_(-1) - - weighted_deltas = deltas * weights - - # get sign consensus and mix deltas - if self.method.consensus_method: - mask_dtype = torch.int8 if self.int8_mask else base.dtype - mask = get_mask( - weighted_deltas, - method=self.method.consensus_method, - mask_dtype=mask_dtype, - ) - mixed_delta = (weighted_deltas * mask).sum(dim=0) - divisor = (weights * mask).sum(dim=0) - divisor[divisor == 0] = 1 - else: - mixed_delta = weighted_deltas.sum(dim=0) - divisor = weights.sum(dim=0) - divisor[divisor.abs() < 1e-8] = 1 - - if self.normalize: - mixed_delta /= divisor - - return (base + mixed_delta).to(base.dtype) - - def group_label(self) -> Optional[str]: - return self.tensors.group_label() - - -def get_task_vectors( - weight_info: WeightInfo, - base_model: ModelReference, - tensors: ImmutableMap[ModelReference, torch.Tensor], - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]], -) -> Tuple[List[Dict[str, Any]], torch.Tensor]: - keys = list(tensors.keys()) - base = tensors[base_model] - - parameter_name = weight_info.name - - res = [] - for model in keys: - if model == base_model: - continue - - x = tensors[model].to(base.dtype) - if x.shape != base.shape: - if weight_info.is_embed: - x = x[: base.shape[0], : base.shape[1]] - logging.warning(f"Using submatrix of {model}:{parameter_name}") - else: - logging.warning( - f"skipping {model}:{parameter_name} due to size mismatch" - ) - continue - - delta = x - base - del x - del tensors[model] - - d = {} - d["model"] = model - d["delta"] = delta - for p in tensor_parameters[model]: - d[p] = tensor_parameters[model][p] - res.append(d) - return res, base - - -def get_mask( - delta: torch.Tensor, - method: Literal["sum", "count"] = "sum", - mask_dtype: Optional[torch.dtype] = None, -): - """Returns a mask determining which delta vectors should be merged - into the final model. - - For the methodology described in the TIES paper use 'sum'. For a - simpler naive count of signs, use 'count'.""" - if mask_dtype is None: - mask_dtype = delta.dtype - - sign = delta.sign().to(mask_dtype) - - if method == "sum": - sign_weight = delta.sum(dim=0) - majority_sign = (sign_weight >= 0).to(mask_dtype) * 2 - 1 - del sign_weight - elif method == "count": - majority_sign = (sign.sum(dim=0) >= 0).to(mask_dtype) * 2 - 1 - else: - raise RuntimeError(f'Unimplemented mask method "{method}"') - - return sign == majority_sign diff --git a/mergekit/merge_methods/linear.py b/mergekit/merge_methods/linear.py deleted file mode 100644 index 250093df2a8c87ccd652e48f3551d8f212b6ed2e..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/linear.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import Any, Dict, List, Optional - -import torch - -from mergekit.architecture import WeightInfo -from mergekit.common import ImmutableMap, ModelReference -from mergekit.graph import Task -from mergekit.io.tasks import GatherTensors -from mergekit.merge_methods.base import ConfigParameterDef, MergeMethod -from mergekit.merge_methods.rectify_embed import rectify_embed_sizes - - -class LinearMergeTask(Task[torch.Tensor]): - gather_tensors: GatherTensors - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]] - normalize: bool - weight_info: WeightInfo - - def uses_accelerator(self) -> bool: - return True - - def arguments(self) -> Dict[str, Task]: - return {"tensors": self.gather_tensors} - - def execute( - self, tensors: Dict[ModelReference, torch.Tensor], **_kwargs - ) -> torch.Tensor: - keys = list(tensors.keys()) - - tensors = [tensors[key] for key in keys] - weights = [self.tensor_parameters[key]["weight"] for key in keys] - - rectify_embed_sizes(self.weight_info, tensors) - - unique_shapes = set(t.shape for t in tensors) - if len(unique_shapes) != 1: - raise RuntimeError( - f"Tensor size mismatch for {self.weight_info.name}, sizes: {list(unique_shapes)}" - ) - - tensors = torch.stack(tensors, dim=0) - weights = torch.tensor(weights, dtype=tensors.dtype, device=tensors.device) - while len(weights.shape) < len(tensors.shape): - weights.unsqueeze_(-1) - - res = (weights * tensors).sum(dim=0) - if self.normalize: - res = res / weights.sum(dim=0) - - return res - - def group_label(self) -> Optional[str]: - return self.gather_tensors.group_label() - - -class LinearMerge(MergeMethod): - def parameters(self) -> List[ConfigParameterDef]: - return [ - ConfigParameterDef(name="normalize", required=False, default_value=True), - ] - - def tensor_parameters(self) -> List[ConfigParameterDef]: - return [ConfigParameterDef(name="weight", required=True)] - - def make_task( - self, - *, - output_weight: WeightInfo, - tensors: GatherTensors, - parameters: Dict[str, Any], - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]], - **_kwargs, - ) -> Task: - return LinearMergeTask( - gather_tensors=tensors, - tensor_parameters=tensor_parameters, - normalize=parameters["normalize"], - weight_info=output_weight, - ) diff --git a/mergekit/merge_methods/model_stock.py b/mergekit/merge_methods/model_stock.py deleted file mode 100644 index 062366b0c9028d9b7092cc5c9a9f4f95ad09ad80..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/model_stock.py +++ /dev/null @@ -1,133 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -from typing import Any, Dict, List, Optional - -import torch - -from mergekit.architecture import WeightInfo -from mergekit.common import ImmutableMap, ModelReference -from mergekit.graph import Task -from mergekit.io.tasks import GatherTensors -from mergekit.merge_methods.base import ConfigParameterDef, MergeMethod -from mergekit.merge_methods.rectify_embed import rectify_embed_sizes - - -class ModelStockMergeTask(Task[torch.Tensor]): - gather_tensors: GatherTensors - base_model: ModelReference - weight_info: WeightInfo - filter_wise: bool = False - - def uses_accelerator(self) -> bool: - return True - - def arguments(self) -> Dict[str, Task]: - return {"tensors": self.gather_tensors} - - def execute(self, tensors: Dict[ModelReference, torch.Tensor]) -> torch.Tensor: - if len(tensors) == 1 and self.base_model in tensors: - return tensors[self.base_model] - if len(tensors) < 3: - if self.weight_info.optional: - logging.warning( - f"Optional weight {self.weight_info.name} not present in enough models, discarding" - ) - return None - - raise ValueError( - "ModelStockMerge requires at least 3 models (base plus two+ others)" - ) - - w_0, ws = self.get_rectified_weights(tensors) - out_shape = w_0.shape - - if self.filter_wise: - if w_0.dim() == 1: - # bias (or other single-vector) parameters should be treated as row vectors - w_0 = w_0.unsqueeze(0) - ws = [w.unsqueeze(0) for w in ws] - else: - w_0 = w_0.view(-1) - ws = [w.view(-1) for w in ws] - - offsets = [w - w_0 for w in ws] - - # now there is a question of how to come up with a value for theta. - # in the two-vector case, we can get an exact angle between the two vectors - # but the paper doesn't explicitly say what to do in the multi-vector case - - # they keep using a singular theta value and don't elaborate on how to - # calculate it. i'm going to assume an average of pairwise angles for now? i guess? - - cos_thetas = [] - for i, w_0_offset in enumerate(offsets): - for j in range(i + 1, len(offsets)): - w_1_offset = offsets[j] - - norm_product = torch.norm(w_0_offset, dim=-1) * torch.norm( - w_1_offset, dim=-1 - ) - cos_theta = ( - (w_0_offset * w_1_offset).sum(dim=-1) / norm_product.clamp(min=1e-6) - ).clamp(-1, 1) - cos_thetas.append(cos_theta) - - cos_theta = torch.stack(cos_thetas).mean(dim=0).unsqueeze(-1) - N = len(ws) - t = (N * cos_theta) / (1 + (N - 1) * cos_theta) - - w_avg = sum(ws) / len(ws) - w_h = t * w_avg + (1 - t) * w_0 - - return w_h.reshape(out_shape) - - def get_rectified_weights(self, tensors: Dict[ModelReference, torch.Tensor]): - if self.base_model not in tensors: - raise ValueError("Base model tensor not found") - - all_weights = [tensors[self.base_model]] + [ - tensors[k] for k in tensors if k != self.base_model - ] - rectify_embed_sizes(self.weight_info, all_weights) - w_0 = all_weights[0] - ws = all_weights[1:] - return w_0, ws - - def group_label(self) -> Optional[str]: - return self.gather_tensors.group_label() - - -class ModelStockMerge(MergeMethod): - def parameters(self) -> List[ConfigParameterDef]: - return [ - ConfigParameterDef(name="filter_wise", required=False, default_value=False) - ] - - def make_task( - self, - *, - output_weight: WeightInfo, - tensors: GatherTensors, - base_model: Optional[ModelReference], - parameters: ImmutableMap[str, Any], - **_kwargs, - ) -> Task: - return ModelStockMergeTask( - gather_tensors=tensors, - base_model=base_model, - weight_info=output_weight, - filter_wise=parameters["filter_wise"], - ) diff --git a/mergekit/merge_methods/passthrough.py b/mergekit/merge_methods/passthrough.py deleted file mode 100644 index 867011202e6f8c31142e6b8730a4586dcabe5a80..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/passthrough.py +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import Any, Dict, List, Optional - -import torch - -from mergekit.common import ImmutableMap, ModelReference -from mergekit.graph import Task -from mergekit.io.tasks import GatherTensors -from mergekit.merge_methods.base import ConfigParameterDef, MergeMethod - - -class PassthroughMergeTask(Task[torch.Tensor]): - gather_tensors: GatherTensors - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]] - - def arguments(self) -> Dict[str, Task]: - return {"tensors": self.gather_tensors} - - def execute(self, tensors: Dict[ModelReference, torch.Tensor]) -> torch.Tensor: - if len(tensors) != 1: - raise RuntimeError("Passthrough merge expects exactly one tensor") - - model, tensor = list(tensors.items())[0] - scale = self.tensor_parameters[model].data.get("scale", None) - if scale is not None: - tensor = tensor * scale - - return tensor - - def group_label(self) -> Optional[str]: - return self.gather_tensors.group_label() - - -class PassthroughMerge(MergeMethod): - def tensor_parameters(self) -> List[ConfigParameterDef]: - return [ConfigParameterDef(name="scale", required=False, default_value=None)] - - def make_task( - self, - *, - tensors: GatherTensors, - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]], - **kwargs, - ) -> Task: - return PassthroughMergeTask( - gather_tensors=tensors, tensor_parameters=tensor_parameters - ) diff --git a/mergekit/merge_methods/rectify_embed.py b/mergekit/merge_methods/rectify_embed.py deleted file mode 100644 index 52c494b22d4e45d205d88aa47e958baa176a85b4..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/rectify_embed.py +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - - -import logging -from typing import List - -import torch - -from mergekit.architecture import WeightInfo - - -def rectify_embed_sizes(weight_info: WeightInfo, tensors: List[torch.Tensor]): - # TODO: use arch_info.embed_weights() instead - if weight_info.is_embed and all(len(t.shape) == 2 for t in tensors): - # special case - if lm_head.weight or embed_tokens.weight have a size - # mismatch, take the largest common submatrix of all of them - if take_common_submatrix(tensors): - logging.warning( - f"Using common submatrix of size {tensors[0].shape} for {weight_info.name}" - ) - - -def take_common_submatrix(tensors: List[torch.Tensor]) -> bool: - min_size = [None, None] - for t in tensors: - for idx in range(2): - if min_size[idx] is None or t.shape[idx] < min_size[idx]: - min_size[idx] = t.shape[idx] - - if not all(t.shape == torch.Size(min_size) for t in tensors): - for idx in range(len(tensors)): - tensors[idx] = tensors[idx][: min_size[0], : min_size[1]] - return True - return False diff --git a/mergekit/merge_methods/slerp.py b/mergekit/merge_methods/slerp.py deleted file mode 100644 index 4cc95f4706f0e24bfd001b760a62384622ead865..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/slerp.py +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import Any, Dict, List, Optional, Union - -import numpy as np -import torch - -from mergekit.architecture import WeightInfo -from mergekit.common import ImmutableMap, ModelReference -from mergekit.graph import Task -from mergekit.io.tasks import GatherTensors -from mergekit.merge_methods.base import ConfigParameterDef, MergeMethod -from mergekit.merge_methods.rectify_embed import rectify_embed_sizes - - -class SlerpTask(Task[torch.Tensor]): - gather_tensors: GatherTensors - base_model: ModelReference - t: float - weight_info: WeightInfo - - def uses_accelerator(self) -> bool: - return True - - def arguments(self) -> Dict[str, Task]: - return {"tensors": self.gather_tensors} - - def execute(self, tensors: Dict[ModelReference, torch.Tensor]) -> torch.Tensor: - if len(tensors) == 1: - return list(tensors.values())[0] - elif len(tensors) != 2: - raise RuntimeError("Slerp merge expects exactly two models") - elif self.base_model not in tensors: - raise RuntimeError("Base model not in input tensors") - - [a, b] = list(tensors.items()) - if a[0] != self.base_model: - [a, b] = [b, a] - prepped_tensors = [a[1], b[1]] - - rectify_embed_sizes(self.weight_info, prepped_tensors) - - return ( - slerp( - self.t, - prepped_tensors[0], - prepped_tensors[1], - ) - .to(prepped_tensors[0].dtype) - .to(prepped_tensors[0].device) - ) - - def group_label(self) -> Optional[str]: - return self.gather_tensors.group_label() - - -class SlerpMerge(MergeMethod): - def parameters(self) -> List[ConfigParameterDef]: - return [ConfigParameterDef(name="t", required=True)] - - def make_task( - self, - *, - output_weight: WeightInfo, - tensors: GatherTensors, - parameters: ImmutableMap[str, Any], - base_model: Optional[ModelReference], - **_kwargs, - ) -> Task: - return SlerpTask( - gather_tensors=tensors, - base_model=base_model, - weight_info=output_weight, - t=parameters["t"], - ) - - -def lerp( - t: float, v0: Union[np.ndarray, torch.Tensor], v1: Union[np.ndarray, torch.Tensor] -) -> Union[np.ndarray, torch.Tensor]: - return (1 - t) * v0 + t * v1 - - -def slerp( - t: Union[float, np.ndarray], - v0: Union[np.ndarray, torch.Tensor], - v1: Union[np.ndarray, torch.Tensor], - DOT_THRESHOLD: float = 0.9995, - eps: float = 1e-8, -): - """ - Spherical linear interpolation - - From: https://gist.github.com/dvschultz/3af50c40df002da3b751efab1daddf2c - Args: - t (float/np.ndarray): Float value between 0.0 and 1.0 - v0 (np.ndarray): Starting vector - v1 (np.ndarray): Final vector - DOT_THRESHOLD (float): Threshold for considering the two vectors as - colinear. Not recommended to alter this. - Returns: - v2 (np.ndarray): Interpolation vector between v0 and v1 - """ - is_torch = False - if not isinstance(v0, np.ndarray): - is_torch = True - v0 = v0.detach().cpu().float().numpy() - if not isinstance(v1, np.ndarray): - is_torch = True - v1 = v1.detach().cpu().float().numpy() - - # Copy the vectors to reuse them later - v0_copy = np.copy(v0) - v1_copy = np.copy(v1) - - # Normalize the vectors to get the directions and angles - v0 = normalize(v0, eps) - v1 = normalize(v1, eps) - - # Dot product with the normalized vectors (can't use np.dot in W) - dot = np.sum(v0 * v1) - - # If absolute value of dot product is almost 1, vectors are ~colinear, so use lerp - if np.abs(dot) > DOT_THRESHOLD: - res = lerp(t, v0_copy, v1_copy) - return maybe_torch(res, is_torch) - - # Calculate initial angle between v0 and v1 - theta_0 = np.arccos(dot) - sin_theta_0 = np.sin(theta_0) - - # Angle at timestep t - theta_t = theta_0 * t - sin_theta_t = np.sin(theta_t) - - # Finish the slerp algorithm - s0 = np.sin(theta_0 - theta_t) / sin_theta_0 - s1 = sin_theta_t / sin_theta_0 - res = s0 * v0_copy + s1 * v1_copy - - return maybe_torch(res, is_torch) - - -def maybe_torch(v: np.ndarray, is_torch: bool): - if is_torch: - return torch.from_numpy(v) - return v - - -def normalize(v: np.ndarray, eps: float): - norm_v = np.linalg.norm(v) - if norm_v > eps: - v = v / norm_v - return v diff --git a/mergekit/merge_methods/tokenizer_permute.py b/mergekit/merge_methods/tokenizer_permute.py deleted file mode 100644 index 8dda6c022e85933f6d329a280370a1fe06e991e4..0000000000000000000000000000000000000000 --- a/mergekit/merge_methods/tokenizer_permute.py +++ /dev/null @@ -1,150 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import Any, Dict, List, Optional - -import torch -from pydantic import BaseModel - -from mergekit.common import ImmutableMap, ModelReference -from mergekit.graph import Task -from mergekit.io.tasks import GatherTensors -from mergekit.merge_methods.base import ConfigParameterDef, MergeMethod -from mergekit.merge_methods.slerp import slerp -from mergekit.tokenizer import BuildTokenizer, TokenizerInfo - - -class TokenizerPermutationMergeTask(Task[torch.Tensor]): - tokenizer_task: BuildTokenizer - gather_tensors: GatherTensors - base_model: Optional[ModelReference] - use_slerp: bool - slerp_t: Optional[float] - tensor_parameters: ImmutableMap[ModelReference, Any] - - def uses_accelerator(self) -> bool: - return True - - def arguments(self) -> Dict[str, Task]: - return {"tokenizer_info": self.tokenizer_task, "tensors": self.gather_tensors} - - def execute( - self, tokenizer_info: TokenizerInfo, tensors: Dict[ModelReference, torch.Tensor] - ) -> torch.Tensor: - if not tensors: - return None - if len(tensors) == 1: - return list(tensors.values())[0] - - if self.use_slerp and self.slerp_t is None: - raise RuntimeError("Must set t to use embed_slerp") - - models = [] - expanded = [] - masks = [] - weights = [] - for model in tensors: - models.append(model) - - x = tensors[model] - p = tokenizer_info.permutations[model] - - xp = torch.zeros((len(p), x.shape[-1]), dtype=x.dtype, device=x.device) - mask = torch.zeros((len(p),), dtype=torch.bool, device=x.device) - for out_idx in p: - in_idx = p[out_idx] - if in_idx < 0: - continue - - xp[out_idx, :] = x[in_idx, :] - mask[out_idx] = 1 - - expanded.append(xp) - masks.append(mask) - - is_base = model == self.base_model - if self.use_slerp: - weight = (1.0 - self.slerp_t) if is_base else self.slerp_t - else: - weight = self.tensor_parameters[model]["weight"] - - weights.append(weight) - - expanded = torch.stack(expanded, dim=0) - masks = torch.stack(masks, dim=0).unsqueeze(-1) - weights = ( - torch.tensor(weights, dtype=expanded.dtype, device=expanded.device) - .unsqueeze(-1) - .unsqueeze(-1) - ) - - total_weight = (masks * weights).sum(dim=0) - scale = 1 / total_weight - scale[total_weight.abs() < 1e-8] = 0 - - linear_merged = (expanded * weights * masks).sum(dim=0) * scale - - if self.use_slerp: - if expanded.shape[0] != 2: - raise RuntimeError("SLERP takes exactly two models") - - if models[0] == self.base_model: - v0 = expanded[0, ...] - v1 = expanded[1, ...] - else: - v0 = expanded[1, ...] - v1 = expanded[0, ...] - - res = slerp(self.slerp_t, v0, v1) - need_linear = (masks.sum(dim=0) != 2).squeeze(dim=-1) - res[need_linear, :] = linear_merged[need_linear, :].to( - device=res.device, dtype=res.dtype - ) - return res - - return linear_merged - - -class TokenizerPermutationMerge(MergeMethod, BaseModel): - tokenizer_task: BuildTokenizer - - def parameters(self) -> List[ConfigParameterDef]: - return [ - ConfigParameterDef(name="t", required=False), - ConfigParameterDef(name="embed_slerp", required=False, default_value=False), - ] - - def tensor_parameters(self) -> List[ConfigParameterDef]: - return [ - ConfigParameterDef(name="weight", required=False), - ] - - def make_task( - self, - *, - tensors: GatherTensors, - parameters: Dict[str, Any], - tensor_parameters: ImmutableMap[ModelReference, ImmutableMap[str, Any]], - base_model: Optional[ModelReference], - **_kwargs, - ) -> Task: - return TokenizerPermutationMergeTask( - base_model=base_model, - tokenizer_task=self.tokenizer_task, - gather_tensors=tensors, - use_slerp=parameters["embed_slerp"], - slerp_t=parameters["t"], - tensor_parameters=tensor_parameters, - ) diff --git a/mergekit/moe/__init__.py b/mergekit/moe/__init__.py deleted file mode 100644 index f032c93e1c8effcdc3b584148a9a6a43dbb32bcd..0000000000000000000000000000000000000000 --- a/mergekit/moe/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import List - -from mergekit.moe.arch import MoEOutputArchitecture -from mergekit.moe.deepseek import DeepseekMoE -from mergekit.moe.mixtral import MixtralMoE - -ALL_OUTPUT_ARCHITECTURES: List[MoEOutputArchitecture] = [MixtralMoE(), DeepseekMoE()] - -try: - from mergekit.moe.qwen import QwenMoE -except ImportError: - pass -else: - ALL_OUTPUT_ARCHITECTURES.append(QwenMoE()) - -__all__ = [ - "ALL_OUTPUT_ARCHITECTURES", - "MoEOutputArchitecture", -] diff --git a/mergekit/moe/arch.py b/mergekit/moe/arch.py deleted file mode 100644 index 66e8e0ca44116c6003f81bd35278c0060ea75b0f..0000000000000000000000000000000000000000 --- a/mergekit/moe/arch.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from abc import ABC, abstractmethod -from typing import List, Optional - -import torch - -from mergekit.moe.config import MoEMergeConfig -from mergekit.options import MergeOptions - - -class MoEOutputArchitecture(ABC): - @abstractmethod - def name(self) -> str: - """Return a human-readable name for the architecture.""" - pass - - @abstractmethod - def supports_config( - self, - config: MoEMergeConfig, - explain: bool = False, - trust_remote_code: bool = False, - ) -> bool: - """Return whether this architecture supports the given config. - - If `explain` is True, log an explanation of why the config is not supported.""" - pass - - @abstractmethod - def write_model( - self, - out_path: str, - config: MoEMergeConfig, - merge_options: MergeOptions, - router_weights: List[torch.Tensor], - shared_router_weights: Optional[List[torch.Tensor]] = None, - ): - """Write the config and tensors for the output MoE to the given path.""" - pass diff --git a/mergekit/moe/common.py b/mergekit/moe/common.py deleted file mode 100644 index 478b8cc9d426525642127cdb3ee19071539ad586..0000000000000000000000000000000000000000 --- a/mergekit/moe/common.py +++ /dev/null @@ -1,75 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import Dict, Optional, Tuple - -import torch -import tqdm -import transformers - -from mergekit.common import ModelReference, dtype_from_name -from mergekit.io import LazyTensorLoader, TensorWriter -from mergekit.merge import MergeOptions -from mergekit.moe.config import Expert, MoEMergeConfig - - -def initialize_io( - config: MoEMergeConfig, - out_path: str, - merge_options: MergeOptions, -) -> Tuple[Dict[ModelReference, LazyTensorLoader], LazyTensorLoader, TensorWriter]: - base_model = config.base_model - loaders: Dict[ModelReference, LazyTensorLoader] = {} - for model in tqdm.tqdm( - [base_model] + [e.source_model for e in config.experts], desc="Warm up loaders" - ): - loaders[model] = model.lazy_loader( - cache_dir=merge_options.transformers_cache, - lazy_unpickle=merge_options.lazy_unpickle, - ) - - base_loader = loaders.get(base_model) - writer = TensorWriter( - out_path=out_path, - max_shard_size=merge_options.out_shard_size, - safe_serialization=merge_options.safe_serialization, - ) - - return loaders, base_loader, writer - - -def select_dtype( - config: MoEMergeConfig, base_cfg: transformers.PretrainedConfig -) -> Optional[torch.dtype]: - out_dtype = None - if config.dtype: - out_dtype = dtype_from_name(config.dtype) - - if out_dtype is None and base_cfg.torch_dtype: - out_dtype = base_cfg.torch_dtype - if isinstance(out_dtype, str): - out_dtype = dtype_from_name(out_dtype) - return out_dtype - - -def noise_and_scale( - tensor: torch.Tensor, expert: Expert, is_residual: bool = False -) -> torch.Tensor: - if expert.noise_scale is not None: - noise = torch.randn_like(tensor) * expert.noise_scale - tensor = tensor + noise - if is_residual and expert.residual_scale is not None: - tensor = tensor * expert.residual_scale - return tensor diff --git a/mergekit/moe/config.py b/mergekit/moe/config.py deleted file mode 100644 index 41bae6640b0c709c7db8ceb7bf9375ff3938fa9c..0000000000000000000000000000000000000000 --- a/mergekit/moe/config.py +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -from typing import List, Optional - -from pydantic import BaseModel - -from mergekit.common import ModelReference - - -class Expert(BaseModel): - """ - Defines a model to be used as a set of layerwise experts in a MoE model. - """ - - source_model: ModelReference - - positive_prompts: Optional[List[str]] = None - negative_prompts: Optional[List[str]] = None - noise_scale: Optional[float] = None - residual_scale: Optional[float] = None - - -class MoEMergeConfig(BaseModel): - """ - Configuration for merging a set of "expert" models into a MoE model. - """ - - base_model: ModelReference - experts: List[Expert] - gate_mode: str = ( - "hidden" # possible values: "hidden", "cheap_embed", "random", "uniform_random" - ) - # "hidden" uses hidden state vectors for the given prompts for each layer - # "cheap_embed" uses the average of token embeddings for the prompts, same for each layer - # "random" is random - # "uniform_random" matches default initialization for torch.nn.Linear - dtype: Optional[str] = None - experts_per_token: int = 2 - shared_experts: Optional[List[Expert]] = None - architecture: Optional[str] = None - - -def is_bad_config(config: MoEMergeConfig, allow_all_same: bool = False) -> bool: - if config.experts_per_token < 1: - logging.error("Experts per token must be >= 1") - return True - - if len(config.experts) < config.experts_per_token: - logging.error("Must include at least as many experts as experts_per_token.") - return True - - if config.gate_mode == "random": - return False # eh we're good - - for expert_idx, expert in enumerate(config.experts): - if not expert.positive_prompts: - logging.error(f"Expert {expert_idx} has no positive prompts.") - return True - - def prompt_tup(e: Expert): - return (tuple(e.positive_prompts), tuple(e.negative_prompts or [])) - - # let's just nip this trend in the bud - p_first = prompt_tup(config.experts[0]) - if all(prompt_tup(e) == p_first for e in config.experts[1:]): - logging.error( - "Your positive and negative prompts are identical for all experts. This will not produce a functioning MoE." - ) - logging.error( - "For each expert, `positive_prompts` must contain one or more example prompt reflecting what should be routed to that expert." - ) - return True - - if not allow_all_same: - if all( - e.source_model == config.experts[0].source_model for e in config.experts[1:] - ): - logging.error( - "All of your expert models are the same. This will produce " - "a model that uses more resources but gives the exact same output. " - "If you plan to train the model after merging, proceed with the " - "--i-understand-this-is-not-useful-without-training flag." - ) - return True diff --git a/mergekit/moe/deepseek.py b/mergekit/moe/deepseek.py deleted file mode 100644 index f36e8fe97bc4958d6390882eb5e459b6ee4353f0..0000000000000000000000000000000000000000 --- a/mergekit/moe/deepseek.py +++ /dev/null @@ -1,196 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import json -import logging -import os -from typing import Dict, List, Optional - -import torch -import tqdm -import transformers - -from mergekit.architecture import get_architecture_info -from mergekit.moe.arch import MoEOutputArchitecture -from mergekit.moe.common import initialize_io, noise_and_scale, select_dtype -from mergekit.moe.config import MoEMergeConfig -from mergekit.options import MergeOptions - - -class DeepseekMoE(MoEOutputArchitecture): - def name(self) -> str: - return "DeepSeek MoE" - - def supports_config( - self, - config: MoEMergeConfig, - explain: bool = False, - trust_remote_code: bool = False, - ) -> bool: - if config.shared_experts: - if len(config.shared_experts) > 1: - if explain: - logging.warning( - "DeepSeek MoE merge does not support more than one shared expert" - ) - return False - - if ( - config.shared_experts[0].positive_prompts - or config.shared_experts[0].negative_prompts - ): - if explain: - logging.warning( - "DeepSeek MoE merge does not support gating shared experts" - ) - return False - - model_types = [] - for model_ref in ( - [config.base_model] - + [e.source_model for e in config.experts] - + [e.source_model for e in (config.shared_experts or [])] - ): - model_cfg = model_ref.config(trust_remote_code=trust_remote_code) - model_types.append(model_cfg.model_type) - - if len(set(model_types)) != 1: - if explain: - logging.warning( - "Deepseek MoE requires all input models to have the same architecture" - ) - return False - if model_types[0] not in ("llama", "mistral"): - if explain: - logging.warning( - "Deepseek MoE requires all input models to be Llama or Mistral models" - ) - return False - return True - - def _generate_config( - self, - base_config: transformers.PretrainedConfig, - num_experts: int, - shared_experts: Optional[int] = None, - experts_per_token: Optional[int] = None, - ) -> Dict: - if shared_experts and shared_experts > 1: - raise NotImplementedError( - "Shared experts must be 0 or 1 for DeepSeek output" - ) - - res = base_config.to_dict() - res["architectures"] = ["DeepseekForCausalLM"] - res["model_type"] = "deepseek" - res["n_routed_experts"] = num_experts - res["n_shared_experts"] = shared_experts or None - res["num_experts_per_tok"] = experts_per_token or (1 if shared_experts else 2) - res["first_k_dense_replace"] = 0 - res["moe_layer_freq"] = 1 - res["scoring_func"] = "softmax" - res["norm_topk_prob"] = True - res["moe_intermediate_size"] = res["intermediate_size"] - res["auto_map"] = { - "AutoConfig": "deepseek-ai/deepseek-moe-16b-base--configuration_deepseek.DeepseekConfig", - "AutoModel": "deepseek-ai/deepseek-moe-16b-base--modeling_deepseek.DeepseekModel", - "AutoModelForCausalLM": "deepseek-ai/deepseek-moe-16b-base--modeling_deepseek.DeepseekForCausalLM", - } - return res - - def write_model( - self, - out_path: str, - config: MoEMergeConfig, - merge_options: MergeOptions, - router_weights: List[torch.Tensor], - shared_router_weights: Optional[List[torch.Tensor]] = None, - ): - base_model = config.base_model - base_cfg = base_model.config(trust_remote_code=merge_options.trust_remote_code) - - out_dtype = select_dtype(config, base_cfg) - out_cfg = self._generate_config( - base_cfg, - len(config.experts), - len(config.shared_experts or []), - config.experts_per_token, - ) - if out_dtype is not None: - out_cfg["torch_dtype"] = str(out_dtype).removeprefix("torch.") - with open(os.path.join(out_path, "config.json"), "w", encoding="utf-8") as f: - json.dump(out_cfg, f, indent=4) - - shared_def = config.shared_experts[0] if config.shared_experts else None - - loaders, base_loader, writer = initialize_io(config, out_path, merge_options) - shared_loader = loaders.get(shared_def.source_model) if shared_def else None - for weight_info in tqdm.tqdm( - get_architecture_info(base_cfg).all_weights(base_cfg), - desc="Weights", - ): - tensor_name = weight_info.name - if ".mlp." in tensor_name: - for expert_idx, expert in enumerate(config.experts): - expert_name = tensor_name.replace( - ".mlp.", f".mlp.experts.{expert_idx}." - ) - expert_loader = loaders.get(expert.source_model) - tensor = expert_loader.get_tensor( - weight_info.name, aliases=weight_info.aliases - ) - tensor = noise_and_scale( - tensor, expert, is_residual="down_proj" in tensor_name - ) - writer.save_tensor( - expert_name, - tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - - if shared_def is not None: - shared_tensor = shared_loader.get_tensor( - weight_info.name, aliases=weight_info.aliases - ) - shared_tensor = noise_and_scale( - shared_tensor, - shared_def, - is_residual="down_proj" in tensor_name, - ) - writer.save_tensor( - tensor_name.replace(".mlp.", ".mlp.shared_experts."), - shared_tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - else: - tensor = base_loader.get_tensor( - tensor_name, aliases=weight_info.aliases - ) - writer.save_tensor( - tensor_name, - tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - - for layer_idx, weight in enumerate( - tqdm.tqdm(router_weights, desc="Router weights") - ): - writer.save_tensor( - f"model.layers.{layer_idx}.mlp.gate.weight", - weight.to(dtype=out_dtype).contiguous(), - clone=merge_options.clone_tensors, - ) - - writer.finalize() diff --git a/mergekit/moe/mixtral.py b/mergekit/moe/mixtral.py deleted file mode 100644 index fbb598affcf1b6b8113e5bd7c0681546d022387b..0000000000000000000000000000000000000000 --- a/mergekit/moe/mixtral.py +++ /dev/null @@ -1,178 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -from typing import List, Optional - -import torch -import tqdm -import transformers - -from mergekit.architecture import MISTRAL_INFO, WeightInfo -from mergekit.moe.arch import MoEOutputArchitecture -from mergekit.moe.common import initialize_io, noise_and_scale, select_dtype -from mergekit.moe.config import MoEMergeConfig -from mergekit.options import MergeOptions - - -class MixtralMoE(MoEOutputArchitecture): - def name(self) -> str: - return "Mixtral" - - def supports_config( - self, - config: MoEMergeConfig, - explain: bool = False, - trust_remote_code: bool = False, - ) -> bool: - if config.shared_experts: - if explain: - logging.warning("Mixtral does not support shared experts") - return False - - model_types = [] - for model_ref in [config.base_model] + [e.source_model for e in config.experts]: - model_cfg = model_ref.config(trust_remote_code=trust_remote_code) - model_types.append(model_cfg.model_type) - - if len(set(model_types)) != 1: - if explain: - logging.warning( - "Mixtral requires all input models to have the same architecture" - ) - return False - if model_types[0] not in ("llama", "mistral"): - if explain: - logging.warning( - "Mixtral requires all input models to be Llama or Mistral models" - ) - return False - return True - - def _generate_config( - self, - base_config: transformers.PretrainedConfig, - num_experts: int, - shared_experts: Optional[int] = None, - experts_per_token: Optional[int] = None, - ) -> transformers.PretrainedConfig: - if shared_experts: - raise NotImplementedError("Shared experts not supported for Mixtral output") - - if not isinstance(base_config, transformers.MistralConfig): - base_cfg_mistral = transformers.MistralConfig(**base_config.to_dict()) - base_cfg_mistral.sliding_window = None - base_cfg_mistral.max_position_embeddings = ( - base_config.max_position_embeddings - ) - base_config = base_cfg_mistral - - out_cfg = transformers.MixtralConfig(**base_config.to_dict()) - out_cfg.architectures = ["MixtralForCausalLM"] - out_cfg.num_local_experts = num_experts - out_cfg.num_experts_per_tok = experts_per_token or 2 - out_cfg.sliding_window = None - - if (out_cfg.num_local_experts & (out_cfg.num_local_experts - 1)) != 0: - logging.warning( - f"Your model has {out_cfg.num_local_experts} experts, which is " - "not a power of two. The model will not be usable in llama.cpp." - ) - return out_cfg - - def _remap_weight_name(self, weight: WeightInfo) -> str: - if ".mlp." not in weight.name: - # Everything but MLP is identical to base Mistral - return weight.name - - res = weight.name - for needle, replacement in [ - (".mlp.gate_proj", ".block_sparse_moe.experts.{expert_idx}.w1"), - (".mlp.down_proj", ".block_sparse_moe.experts.{expert_idx}.w2"), - (".mlp.up_proj", ".block_sparse_moe.experts.{expert_idx}.w3"), - ]: - res = res.replace(needle, replacement) - return res - - def _router_weight_name(self, layer_idx: int) -> str: - return f"model.layers.{layer_idx}.block_sparse_moe.gate.weight" - - def write_model( - self, - out_path: str, - config: MoEMergeConfig, - merge_options: MergeOptions, - router_weights: List[torch.Tensor], - shared_router_weights: Optional[List[torch.Tensor]] = None, - ): - base_model = config.base_model - base_cfg = base_model.config(trust_remote_code=merge_options.trust_remote_code) - - assert len(router_weights) == base_cfg.num_hidden_layers, ( - f"Expected {base_cfg.num_hidden_layers} router weights, " - f"got {len(router_weights)}" - ) - - out_dtype = select_dtype(config, base_cfg) - out_cfg = self._generate_config( - base_cfg, - len(config.experts), - len(config.shared_experts or []), - config.experts_per_token, - ) - out_cfg.torch_dtype = out_dtype - out_cfg.save_pretrained(out_path) - - loaders, base_loader, writer = initialize_io(config, out_path, merge_options) - for weight_info in tqdm.tqdm( - MISTRAL_INFO.all_weights(base_cfg), - desc="Weights", - ): - tensor_name = self._remap_weight_name(weight_info) - if "{expert_idx}" in tensor_name: - for expert_index, expert in enumerate(config.experts): - expert_name = tensor_name.replace("{expert_idx}", str(expert_index)) - expert_loader = loaders.get(expert.source_model) - tensor = expert_loader.get_tensor( - weight_info.name, aliases=weight_info.aliases - ) - tensor = noise_and_scale( - tensor, expert, is_residual="down_proj" in tensor_name - ) - writer.save_tensor( - expert_name, - tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - else: - tensor = base_loader.get_tensor( - tensor_name, aliases=weight_info.aliases - ) - writer.save_tensor( - tensor_name, - tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - - for layer_idx, weight in enumerate( - tqdm.tqdm(router_weights, desc="Router weights") - ): - writer.save_tensor( - self._router_weight_name(layer_idx), - weight.to(dtype=out_dtype).contiguous(), - clone=merge_options.clone_tensors, - ) - - writer.finalize() diff --git a/mergekit/moe/qwen.py b/mergekit/moe/qwen.py deleted file mode 100644 index f4780bee8bdd911b29ce9bd3cc772925e9bbb3e8..0000000000000000000000000000000000000000 --- a/mergekit/moe/qwen.py +++ /dev/null @@ -1,206 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -from typing import List, Optional - -import torch -import tqdm -import transformers - -# explicitly import the config class so that we can catch errors upstream -# if the transformers version installed is too old -from transformers.models.qwen2_moe import Qwen2MoeConfig - -from mergekit.architecture import QWEN2_INFO -from mergekit.moe.arch import MoEOutputArchitecture -from mergekit.moe.common import initialize_io, noise_and_scale, select_dtype -from mergekit.moe.config import MoEMergeConfig -from mergekit.options import MergeOptions - - -class QwenMoE(MoEOutputArchitecture): - def name(self) -> str: - return "Qwen MoE" - - def supports_config( - self, - config: MoEMergeConfig, - explain: bool = False, - trust_remote_code: bool = False, - ) -> bool: - if len(config.shared_experts or []) != 1: - if explain: - logging.warning("Qwen MoE merge requires exactly one shared expert") - return False - - if ( - config.gate_mode != "random" - and not config.shared_experts[0].positive_prompts - ): - if explain: - logging.warning("Qwen MoE requires the shared expert to have prompts") - return False - - model_types = [] - for model_ref in ( - [config.base_model] - + [e.source_model for e in config.experts] - + [e.source_model for e in (config.shared_experts or [])] - ): - model_cfg = model_ref.config(trust_remote_code=trust_remote_code) - model_types.append(model_cfg.model_type) - - if len(set(model_types)) != 1: - if explain: - logging.warning( - "Qwen MoE requires all input models to have the same architecture" - ) - return False - if model_types[0] not in ("llama", "mistral", "qwen2"): - if explain: - logging.warning( - "Qwen MoE requires all input models to be Qwen2, Llama or Mistral models" - ) - return False - return True - - def _generate_config( - self, - base_config: transformers.PretrainedConfig, - num_experts: int, - experts_per_token: Optional[int] = None, - ) -> Qwen2MoeConfig: - out_cfg = Qwen2MoeConfig(**base_config.to_dict()) - out_cfg.architectures = ["Qwen2MoeForCausalLM"] - out_cfg.num_experts = num_experts - out_cfg.num_experts_per_tok = experts_per_token or 2 - out_cfg.decoder_sparse_step = 1 - out_cfg.norm_topk_prob = True - out_cfg.sliding_window = None - out_cfg.use_sliding_window = False - out_cfg.shared_expert_intermediate_size = out_cfg.intermediate_size - out_cfg.moe_intermediate_size = out_cfg.intermediate_size - - if (out_cfg.num_experts & (out_cfg.num_experts - 1)) != 0: - logging.warning( - f"Your model has {out_cfg.num_experts} experts, which is " - "not a power of two. The model will not be usable in llama.cpp." - ) - return out_cfg - - def write_model( - self, - out_path: str, - config: MoEMergeConfig, - merge_options: MergeOptions, - router_weights: List[torch.Tensor], - shared_router_weights: Optional[List[torch.Tensor]] = None, - ): - base_model = config.base_model - base_cfg = base_model.config(trust_remote_code=merge_options.trust_remote_code) - - out_dtype = select_dtype(config, base_cfg) - out_cfg = self._generate_config( - base_cfg, - len(config.experts), - config.experts_per_token, - ) - if out_dtype is not None: - out_cfg.torch_dtype = out_dtype - out_cfg.save_pretrained(out_path) - - shared_def = config.shared_experts[0] - - loaders, base_loader, writer = initialize_io(config, out_path, merge_options) - shared_loader = loaders.get(shared_def.source_model) if shared_def else None - for weight_info in tqdm.tqdm( - QWEN2_INFO.all_weights(base_cfg), - desc="Weights", - ): - tensor_name = weight_info.name - if ".mlp." in tensor_name: - for expert_idx, expert in enumerate(config.experts): - expert_name = tensor_name.replace( - ".mlp.", f".mlp.experts.{expert_idx}." - ) - expert_loader = loaders.get(expert.source_model) - tensor = expert_loader.get_tensor( - weight_info.name, aliases=weight_info.aliases - ) - tensor = noise_and_scale( - tensor, expert, is_residual="down_proj" in tensor_name - ) - writer.save_tensor( - expert_name, - tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - - shared_tensor = shared_loader.get_tensor( - weight_info.name, aliases=weight_info.aliases - ) - shared_tensor = noise_and_scale( - shared_tensor, - shared_def, - is_residual="down_proj" in tensor_name, - ) - writer.save_tensor( - tensor_name.replace(".mlp.", ".mlp.shared_expert."), - shared_tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - else: - try: - tensor = base_loader.get_tensor( - tensor_name, aliases=weight_info.aliases - ) - except KeyError: - if tensor_name.endswith("_proj.bias"): - # qwen 2 moe wants attention bias, give it zeros - head_dim = out_cfg.hidden_size // out_cfg.num_attention_heads - num_heads = ( - out_cfg.num_key_value_heads - if ( - tensor_name.endswith("k_proj.bias") - or tensor_name.endswith("v_proj.bias") - ) - else out_cfg.num_attention_heads - ) - tensor = torch.zeros(num_heads * head_dim, dtype=out_dtype) - else: - raise - - writer.save_tensor( - tensor_name, - tensor.to(dtype=out_dtype), - clone=merge_options.clone_tensors, - ) - - for layer_idx, weight in enumerate( - tqdm.tqdm(router_weights, desc="Router weights") - ): - writer.save_tensor( - f"model.layers.{layer_idx}.mlp.gate.weight", - weight.to(dtype=out_dtype).contiguous(), - clone=merge_options.clone_tensors, - ) - writer.save_tensor( - f"model.layers.{layer_idx}.mlp.shared_expert_gate.weight", - shared_router_weights[layer_idx].to(dtype=out_dtype).contiguous(), - clone=merge_options.clone_tensors, - ) - - writer.finalize() diff --git a/mergekit/moe/router.py b/mergekit/moe/router.py deleted file mode 100644 index f3a8a2bad355cdd3cbc1ae0f7f7442011c105be6..0000000000000000000000000000000000000000 --- a/mergekit/moe/router.py +++ /dev/null @@ -1,189 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -import math -from typing import Dict, List, Union - -import torch -import tqdm -import transformers -from transformers import AutoModelForCausalLM, LlamaForCausalLM, MistralForCausalLM -from transformers.modeling_outputs import CausalLMOutputWithPast - -from mergekit.common import ModelReference -from mergekit.moe.config import Expert - - -def get_hidden_states( - model: Union[MistralForCausalLM, LlamaForCausalLM], - tokenized: transformers.BatchEncoding, - average: bool = True, -) -> List[torch.Tensor]: - with torch.no_grad(): - output: CausalLMOutputWithPast = model( - **tokenized.to(model.device), output_hidden_states=True, return_dict=True - ) - hidden_states = torch.stack( - output.hidden_states[:-1] - ) # (num_layers, batch_size, seq_len, hidden_size) - if average: - # use average over sequence - hidden_states = hidden_states.sum(dim=2) / hidden_states.shape[2] - else: - # take last value - hidden_states = hidden_states[:, :, -1, :] - return hidden_states.sum(dim=1) / hidden_states.shape[1] - - -def get_cheap_embedding( - embed: torch.Tensor, - tokenized: Dict[str, torch.Tensor], - num_layers: int, - vocab_size: int, -) -> torch.Tensor: - onehot = torch.nn.functional.one_hot( - tokenized["input_ids"], num_classes=vocab_size - ) # (batch_size, seq_len, 32000) - h = onehot.float() @ embed.float() # (batch_size, seq_len, hidden_size) - embedded = ( - (h * tokenized["attention_mask"].unsqueeze(-1)) - .sum(dim=1) - .sum(dim=0, keepdim=True) - ) # (1, hidden_size) - res = embedded / embedded.norm(dim=-1, keepdim=True).clamp( - min=1e-8 - ) # (1, hidden_size) - return res.repeat(num_layers, 1) - - -def tokenize_prompts( - prompts: List[str], tokenizer: transformers.PreTrainedTokenizerBase -): - return tokenizer( - [(tokenizer.bos_token or "") + p for p in prompts], - return_tensors="pt", - padding=True, - add_special_tokens=False, - ) - - -def get_gate_params( - model_ref: ModelReference, - tokenizer: transformers.PreTrainedTokenizerBase, - experts: List[Expert], - mode: str = "hidden", - load_in_4bit: bool = False, - load_in_8bit: bool = False, - lazy_unpickle: bool = False, - trust_remote_code: bool = False, - device: str = "auto", -): - gate_vecs = [] - _do_it = None - - model_cfg = model_ref.config(trust_remote_code=trust_remote_code) - - if mode == "random": - return torch.randn( - (model_cfg.num_hidden_layers, len(experts), model_cfg.hidden_size) - ) - elif mode == "uniform_random": - in_features = model_cfg.hidden_size - scale = math.sqrt(1.0 / in_features) - return ( - torch.rand( - (model_cfg.num_hidden_layers, len(experts), model_cfg.hidden_size) - ) - * 2 - * scale - - scale - ) - elif mode == "cheap_embed": - embed = model_ref.lazy_loader(lazy_unpickle=lazy_unpickle).get_tensor( - "model.embed_tokens.weight" - ) - - def _do_it(tokenized): - return get_cheap_embedding( - embed, - tokenized, - num_layers=model_cfg.num_hidden_layers, - vocab_size=model_cfg.vocab_size, - ) - - elif mode in ("hidden", "hidden_avg", "hidden_last"): - model = AutoModelForCausalLM.from_pretrained( - model_ref.model.path, - revision=model_ref.model.revision, - torch_dtype=torch.bfloat16, - device_map=device, - low_cpu_mem_usage=True, - load_in_4bit=load_in_4bit, - load_in_8bit=load_in_8bit, - trust_remote_code=trust_remote_code, - ) - - def _do_it(tokenized): - return get_hidden_states( - model, tokenized=tokenized, average=mode == "hidden_avg" - ) - - gate_vecs = [] - for expert in tqdm.tqdm(experts, desc="expert prompts"): - hidden_states = _do_it(tokenize_prompts(expert.positive_prompts, tokenizer)) - if expert.negative_prompts: - hidden_states -= _do_it( - tokenize_prompts(expert.negative_prompts, tokenizer) - ) - - hidden_states /= hidden_states.norm(p=2, dim=-1, keepdim=True).clamp(min=1e-8) - gate_vecs.append(hidden_states) - gate_vecs = torch.stack(gate_vecs, dim=0) # (num_expert, num_layer, hidden_size) - return gate_vecs.permute(1, 0, 2) - - -def warn_degenerate_gates(gate_vecs: torch.Tensor, threshold: float = 5.0): - degen_indices = [] - num_layers, _num_experts, _hidden_size = gate_vecs.shape - for idx in range(num_layers): - c = torch.linalg.cond(gate_vecs[idx, :, :].float()) - if c > threshold: - degen_indices.append(idx) - - if degen_indices: - if len(degen_indices) == 1: - layer_str = f"layer {degen_indices[0]}" - verb = "has" - elif len(degen_indices) == 2: - layer_str = f"layers {' and '.join(map(str, degen_indices))}" - verb = "have" - elif len(degen_indices) >= num_layers: - layer_str = "ALL layers" - verb = "have" - else: - layer_str = ( - "layers " - + ", ".join(map(str, degen_indices[:-1])) - + ", and " - + str(degen_indices[-1]) - ) - verb = "have" - - logging.warning( - f"{layer_str} {verb} degenerate routing parameters " - "- your prompts may be too similar." - ) - logging.warning("One or more experts will be underutilized in your model.") diff --git a/mergekit/options.py b/mergekit/options.py deleted file mode 100644 index caaf36f94a8d682a572db3109fa1ec149b534911..0000000000000000000000000000000000000000 --- a/mergekit/options.py +++ /dev/null @@ -1,111 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import functools -import typing -from typing import Any, Callable, Optional, Union - -import click -from click.core import Context, Parameter -from pydantic import BaseModel - -from mergekit.common import parse_kmb - - -class MergeOptions(BaseModel): - allow_crimes: bool = False - transformers_cache: Optional[str] = None - lora_merge_cache: Optional[str] = None - cuda: bool = False - low_cpu_memory: bool = False - out_shard_size: int = parse_kmb("5B") - copy_tokenizer: bool = True - clone_tensors: bool = False - trust_remote_code: bool = False - random_seed: Optional[int] = None - lazy_unpickle: bool = False - write_model_card: bool = True - safe_serialization: bool = True - quiet: bool = False - read_to_gpu: bool = False - - -OPTION_HELP = { - "allow_crimes": "Allow mixing architectures", - "transformers_cache": "Override storage path for downloaded models", - "lora_merge_cache": "Path to store merged LORA models", - "cuda": "Perform matrix arithmetic on GPU", - "low_cpu_memory": "Store results and intermediate values on GPU. Useful if VRAM > RAM", - "out_shard_size": "Number of parameters per output shard [default: 5B]", - "copy_tokenizer": "Copy a tokenizer to the output", - "clone_tensors": "Clone tensors before saving, to allow multiple occurrences of the same layer", - "trust_remote_code": "Trust remote code from huggingface repos (danger)", - "random_seed": "Seed for reproducible use of randomized merge methods", - "lazy_unpickle": "Experimental lazy unpickler for lower memory usage", - "write_model_card": "Output README.md containing details of the merge", - "safe_serialization": "Save output in safetensors. Do this, don't poison the world with more pickled models.", - "quiet": "Suppress progress bars and other non-essential output", - "read_to_gpu": "Read model weights directly to GPU", -} - - -class ShardSizeParamType(click.ParamType): - name = "size" - - def convert( - self, value: Any, param: Optional[Parameter], ctx: Optional[Context] - ) -> int: - return parse_kmb(value) - - -def add_merge_options(f: Callable) -> Callable: - @functools.wraps(f) - def wrapper(*args, **kwargs): - arg_dict = {} - for field_name in MergeOptions.model_fields: - if field_name in kwargs: - arg_dict[field_name] = kwargs.pop(field_name) - - kwargs["merge_options"] = MergeOptions(**arg_dict) - f(*args, **kwargs) - - for field_name, info in reversed(MergeOptions.model_fields.items()): - origin = typing.get_origin(info.annotation) - if origin is Union: - ty, prob_none = typing.get_args(info.annotation) - assert prob_none is type(None) - field_type = ty - else: - field_type = info.annotation - - if field_name == "out_shard_size": - field_type = ShardSizeParamType() - - arg_name = field_name.replace("_", "-") - if field_type == bool: - arg_str = f"--{arg_name}/--no-{arg_name}" - else: - arg_str = f"--{arg_name}" - - help_str = OPTION_HELP.get(field_name, None) - wrapper = click.option( - arg_str, - type=field_type, - default=info.default, - help=help_str, - show_default=field_name != "out_shard_size", - )(wrapper) - - return wrapper diff --git a/mergekit/plan.py b/mergekit/plan.py deleted file mode 100644 index 4150d7495f8f432dcec162f438bab14560d0ccc9..0000000000000000000000000000000000000000 --- a/mergekit/plan.py +++ /dev/null @@ -1,316 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -from functools import lru_cache -from typing import Any, List, Optional, Tuple - -from mergekit import merge_methods -from mergekit.architecture import ( - ArchitectureInfo, - ConfiguredArchitectureInfo, - WeightInfo, -) -from mergekit.common import ImmutableMap, ModelReference -from mergekit.config import ( - ConfigReader, - InputSliceDefinition, - MergeConfiguration, - OutputSliceDefinition, -) -from mergekit.graph import Task -from mergekit.io.tasks import ( - FinalizeModel, - GatherTensors, - LoaderCache, - ReturnTensor, - SaveTensor, - TensorWriterTask, -) -from mergekit.merge_methods import MergeMethod -from mergekit.merge_methods.tokenizer_permute import TokenizerPermutationMerge -from mergekit.options import MergeOptions -from mergekit.tokenizer import BuildTokenizer - - -class MergePlanner: - config: MergeConfiguration - arch_info: ArchitectureInfo - options: MergeOptions - out_model_config: Any - _method: MergeMethod - _tensors: List[Tuple[WeightInfo, Task]] - _current_layers: int = 0 - _tokenizer_task: Optional[BuildTokenizer] = None - - def __init__( - self, - config: MergeConfiguration, - arch_info: ArchitectureInfo, - options: MergeOptions, - out_model_config: Any, - ): - self.config = config - self.arch_info = arch_info - self.options = options - self.out_model_config = out_model_config - self._method = merge_methods.get(config.merge_method) - - if config.tokenizer_source: - self._tokenizer_task = BuildTokenizer( - base_model=config.base_model, - referenced_models=tuple(config.referenced_models()), - tokenizer_source=config.tokenizer_source, - trust_remote_code=options.trust_remote_code, - ) - - @lru_cache - def model_arch_info(self, model: ModelReference): - return ConfiguredArchitectureInfo( - info=self.arch_info, - config=model.config(trust_remote_code=self.options.trust_remote_code), - ) - - def normalize_config(self): - base_model = self.config.base_model - - # if models to merge are specified instead of output slices, compute them - if self.config.models: - if self.config.slices: - raise RuntimeError( - "Must specify either models to merge or output slices" - ) - - slices_in = [] - base_included = False - - for model_in in self.config.models: - if base_model and model_in.model == base_model: - base_included = True - - model_info = self.model_arch_info(model_in.model) - slices_in.append( - InputSliceDefinition( - layer_range=[0, model_info.num_layers()], - model=model_in.model, - parameters=model_in.parameters, - ) - ) - - if base_model and not base_included: - logging.info("Base model specified but not in input models - adding") - base_info = self.model_arch_info(base_model) - slices_in.append( - InputSliceDefinition( - layer_range=[0, base_info.num_layers()], - model=base_model, - ) - ) - - self.config.slices = [OutputSliceDefinition(sources=slices_in)] - self.config.models = None - - def plan_tensor( - self, - weight: WeightInfo, - weights_in: List[WeightInfo], - models: List[ModelReference], - cfg_reader: ConfigReader, - ): - if weight.optional: - # check if any input weights are present - any_weight = False - for model, w_in in zip(models, weights_in): - index = LoaderCache().get(model).index - if w_in.name in index.tensor_paths: - any_weight = True - break - - if not any_weight: - logging.info(f"Skipping optional weight {weight.name}") - return - - tensor_merge_method = self._method - if self._tokenizer_task and weight.is_embed: - tensor_merge_method = TokenizerPermutationMerge( - tokenizer_task=self._tokenizer_task - ) - - cfg_g = cfg_reader.for_tensor(weight.name) - global_params = {} - for p in tensor_merge_method.parameters(): - global_params[p.name] = cfg_g.parameter( - p.name, model=None, required=p.required, default=p.default_value - ) - - base_model = cfg_reader.base_model - - tensor_params = {} - for model, weight_in in zip(models, weights_in): - is_base = model == base_model - tensor_params[model] = {} - cfg_m = cfg_reader.for_tensor(weight_in.name) - for p in tensor_merge_method.tensor_parameters(): - tensor_params[model][p.name] = cfg_m.parameter( - p.name, - model=model, - required=p.required and not is_base, - default=p.default_value, - ) - - gather_tensors = GatherTensors( - weight_info=ImmutableMap(data=dict(zip(models, weights_in))), - dtype=self.config.dtype, - device="cuda" if self.options.read_to_gpu else None, - ) - - tensor_task = tensor_merge_method.make_task( - output_weight=weight, - tensors=gather_tensors, - parameters=ImmutableMap(data=global_params), - tensor_parameters=ImmutableMap( - data={ - key: ImmutableMap(data=tensor_params[key]) for key in tensor_params - } - ), - base_model=base_model, - ) - self._tensors.append((weight, tensor_task)) - - def plan_layer( - self, - sources: List[InputSliceDefinition], - layer_offset: int, - t: float, - cfg_reader: ConfigReader, - ): - weights_out: List[WeightInfo] = self.arch_info.layer_weights( - index=self._current_layers, - config=self.out_model_config, - ) - weights_in: List[List[WeightInfo]] = [ - self.model_arch_info(s.model).layer_weights( - index=s.layer_range[0] + layer_offset - ) - for s in sources - ] - - for idx, w_o in enumerate(weights_out): - self.plan_tensor( - weight=w_o, - weights_in=[weights_in[j][idx] for j in range(len(weights_in))], - models=[s.model for s in sources], - cfg_reader=cfg_reader.with_t(t), - ) - - self._current_layers += 1 - - def plan_slice(self, definition: OutputSliceDefinition): - slice_lengths = [ - s.layer_range[1] - s.layer_range[0] for s in definition.sources - ] - if not all(s == slice_lengths[0] for s in slice_lengths): - raise RuntimeError( - "All inputs to a slice must contain the same number of layers" - ) - num_layers = slice_lengths[0] - - cfg_reader = ConfigReader(config=self.config, slice_out=definition, t=0) - for idx in range(num_layers): - # compute t for interpolated gradients - if num_layers > 1: - t = idx / (num_layers - 1) - else: - t = 1 - - self.plan_layer( - definition.sources, - layer_offset=idx, - t=t, - cfg_reader=cfg_reader, - ) - - def plan_to_disk(self, out_path: str) -> List[Task]: - """Plan the merge to be streamed to disk, returning a list of tasks.""" - self._plan() - - writer_task = TensorWriterTask( - out_path=out_path, - max_shard_size=self.options.out_shard_size, - safe_serialization=self.options.safe_serialization, - ) - save_tasks = [] - for weight, tensor_task in self._tensors: - save_tasks.append( - SaveTensor( - tensor_name=weight.name, - tensor_task=tensor_task, - writer_task=writer_task, - clone=self.options.clone_tensors, - optional=weight.optional, - dtype=weight.force_dtype or self.config.out_dtype, - ) - ) - finalize = FinalizeModel( - tensor_save_tasks=tuple(save_tasks), writer_task=writer_task - ) - - res = save_tasks + [finalize] - if self._tokenizer_task: - res.append(self._tokenizer_task) - return res - - def plan_in_memory(self) -> List[ReturnTensor]: - """Plan the merge to be performed in memory.""" - self._plan() - return [ - ReturnTensor( - weight_info=w, - tensor_task=t, - dtype=w.force_dtype or self.config.out_dtype, - ) - for w, t in self._tensors - ] - - def _plan(self): - self.normalize_config() - self._tensors = [] - - for weight_info in self.arch_info.pre_weights(config=self.out_model_config): - self.plan_tensor( - weight_info, - [weight_info] * len(self.config.slices[0].sources), - [s.model for s in self.config.slices[0].sources], - ConfigReader( - config=self.config, - t=0, - tensor_name=weight_info.name, - ).for_out_slice(self.config.slices[0]), - ) - - for out_slice in self.config.slices: - self.plan_slice(out_slice) - - for weight_info in self.arch_info.post_weights(config=self.out_model_config): - self.plan_tensor( - weight_info, - [weight_info] * len(self.config.slices[-1].sources), - [s.model for s in self.config.slices[-1].sources], - ConfigReader( - config=self.config, - t=1, - tensor_name=weight_info.name, - ).for_out_slice(self.config.slices[-1]), - ) diff --git a/mergekit/scripts/__init__.py b/mergekit/scripts/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/mergekit/scripts/bakllama.py b/mergekit/scripts/bakllama.py deleted file mode 100644 index 02c9b7274ad9d32b8e1324b516b979981d15a292..0000000000000000000000000000000000000000 --- a/mergekit/scripts/bakllama.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import List, Optional - -import click -import yaml -from pydantic import BaseModel - -from mergekit.common import MergeOptions -from mergekit.config import ( - ConditionalParameter, - InputSliceDefinition, - MergeConfiguration, -) -from mergekit.merge import run_merge - - -class LayerSlice(BaseModel): - model: str - start: int - end: int - scale: Optional[float] = None - - -class BakllamaConfig(BaseModel): - layer_slices: List[LayerSlice] - embedding_source: Optional[str] = None - lm_head_source: Optional[str] = None - - -@click.command("bakllama") -@click.argument("config_path", type=click.Path(exists=True, dir_okay=False)) -@click.argument("out_path", type=str) -@click.option( - "--clone-tensors/--no-clone-tensors", - type=bool, - is_flag=True, - help="Clone tensors before saving, to allow multiple occurrences of the same layer", - default=False, -) -@click.option("--fp16/--no-fp16", type=bool, default=False) -def main( - config_path: str, - out_path: str, - clone_tensors: bool, - fp16: bool, -): - """Wrapper for using legacy bakllama configuration files.""" - with open(config_path, "r", encoding="utf-8") as file: - config = BakllamaConfig.model_validate(yaml.safe_load(file)) - - slices = [] - for s in config.layer_slices: - parameters = {} - if s.scale is not None: - parameters["scale"] = ConditionalParameter( - value=s.scale, filter="down_proj" - ) - slices.append( - InputSliceDefinition( - model=s.model, layer_range=(s.start, s.end), parameters=parameters - ) - ) - - merge_config = MergeConfiguration( - merge_method="passthrough", slices=slices, dtype="float16" if fp16 else None - ) - run_merge(merge_config, out_path, MergeOptions(clone_tensors=clone_tensors)) - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/evolve.py b/mergekit/scripts/evolve.py deleted file mode 100644 index 896e4a95a947f885a5a6946670f383276db77f2f..0000000000000000000000000000000000000000 --- a/mergekit/scripts/evolve.py +++ /dev/null @@ -1,395 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -import os -import time -from typing import List, Optional - -import click -import cma -import numpy as np -import pandas -import ray -import torch -import tqdm -import transformers -import yaml - -try: - import wandb -except ImportError: - wandb = None - - -from mergekit.common import ModelReference -from mergekit.evo.config import ( - EvolMergeConfiguration, - ModelGenomeDefinition, - check_for_naughty_config, -) -from mergekit.evo.genome import ModelGenome -from mergekit.evo.strategy import ( - ActorPoolEvaluationStrategy, - BufferedRayEvaluationStrategy, - SerialEvaluationStrategy, -) -from mergekit.merge import run_merge -from mergekit.options import MergeOptions - - -@click.command("mergekit-evolve") -@click.argument("genome-config-path", type=str) -@click.option("--max-fevals", type=int, default=100) -@click.option("--vllm/--no-vllm", is_flag=True, default=False, help="Use vLLM") -@click.option( - "--strategy", - "-s", - type=click.Choice(["pool", "buffered", "serial"]), - default="pool", - help="Evaluation scheduling strategy", -) -@click.option( - "--in-memory/--no-in-memory", - is_flag=True, - default=False, - help="Use in-memory merge & evaluation", -) -@click.option( - "--storage-path", - type=str, - help="Path to storage accessible to all nodes for model storage", - required=True, -) -@click.option("--num-gpus", type=int, help="Number of GPUs to use across all nodes") -@click.option("--merge-cuda/--no-merge-cuda", is_flag=True, default=True) -@click.option("--trust-remote-code/--no-trust-remote-code", is_flag=True, default=False) -@click.option("--allow-crimes/--no-allow-crimes", is_flag=True, default=False) -@click.option("--random-seed", type=int, default=0) -@click.option("--batch-size", type=int, default=None, help="Batch size for evaluation") -@click.option("--sigma0", type=float, default=1 / 6, help="Initial sigma for CMA-ES") -@click.option("use_wandb", "--wandb/--no-wandb", is_flag=True, default=False) -@click.option("--wandb-project", type=str, help="Wandb project name") -@click.option("--wandb-entity", type=str, help="Wandb entity name") -@click.option( - "--task-search-path", - type=str, - multiple=True, - help="Path to search for lmeval tasks", -) -@click.option( - "--i-understand-the-depths-of-the-evils-i-am-unleashing", - "allow_benchmark_tasks", - is_flag=True, - default=False, - help="Allow benchmark tasks as objectives", -) -@click.option( - "--save-final-model/--no-save-final-model", - is_flag=True, - default=True, - help="Save the final merged model", -) -@click.option( - "--reshard/--no-reshard", - is_flag=True, - default=True, - help="Convert models to single-shard safetensors for faster merge", -) -@click.option( - "--timeout", - type=float, - default=None, - help="Maximum time to run the optimization in seconds", -) -@click.option( - "--force-population-size", - type=int, - default=None, - help="Force a specific initial population size for CMA-ES", -) -def main( - genome_config_path: str, - max_fevals: int, - vllm: bool, - strategy: str, - in_memory: bool, - storage_path: Optional[str], - num_gpus: Optional[int], - merge_cuda: bool, - trust_remote_code: bool, - allow_crimes: bool, - random_seed: int, - batch_size: Optional[int], - sigma0: float, - use_wandb: bool, - wandb_project: Optional[str], - wandb_entity: Optional[str], - task_search_path: List[str], - allow_benchmark_tasks: bool, - save_final_model: bool, - reshard: bool, - timeout: Optional[float], - force_population_size: Optional[int], -): - config = EvolMergeConfiguration.model_validate( - yaml.safe_load(open(genome_config_path, "r", encoding="utf-8")) - ) - - check_for_naughty_config(config, allow=allow_benchmark_tasks) - - if use_wandb: - if not wandb: - raise RuntimeError("wandb is not installed") - run = wandb.init( - project=wandb_project or "mergekit-evolve", - entity=wandb_entity, - config=config.model_dump(mode="json"), - ) - else: - run = None - - merge_options = MergeOptions( - transformers_cache=os.path.join(storage_path, "transformers_cache"), - lora_merge_cache=os.path.join(storage_path, "lora_merge_cache"), - cuda=merge_cuda, - low_cpu_memory=merge_cuda and not in_memory, - out_shard_size=1_000_000_000_000, # one trillion bytes! - trust_remote_code=trust_remote_code, - allow_crimes=allow_crimes, - random_seed=random_seed, - quiet=True, - read_to_gpu=merge_cuda and not in_memory, - copy_tokenizer=True, - safe_serialization=True, - ) - - # convert models to single-shard safetensors - if reshard: - resharded_models = [] - resharded_base = None - for model in tqdm.tqdm(config.genome.models, desc="Resharding models"): - resharded_models.append( - _reshard_model( - model, - storage_path, - merge_options.lora_merge_cache, - trust_remote_code, - ) - ) - if config.genome.base_model is not None: - resharded_base = _reshard_model( - config.genome.base_model, - storage_path, - merge_options.lora_merge_cache, - trust_remote_code, - ) - else: - resharded_models = config.genome.models - resharded_base = config.genome.base_model - - genome = ModelGenome( - ModelGenomeDefinition.model_validate( - { - **config.genome.model_dump( - exclude=[ - "models", - "base_model", - ] - ), - "models": resharded_models, - "base_model": resharded_base, - } - ), - trust_remote_code=trust_remote_code, - ) - - if strategy == "pool": - strat_cls = ActorPoolEvaluationStrategy - elif strategy == "buffered": - strat_cls = BufferedRayEvaluationStrategy - elif strategy == "serial": - strat_cls = SerialEvaluationStrategy - else: - raise ValueError(f"Unknown strategy {strategy}") - - strat = strat_cls( - config, - genome, - merge_options, - num_gpus=num_gpus, - vllm=vllm, - in_memory=in_memory, - model_storage_path=os.path.join(storage_path, "merged"), - batch_size=batch_size, - task_search_path=task_search_path, - ) - - x0 = genome.initial_genotype(random=config.random_init).view(-1).numpy() - xbest = x0 - xbest_cost = np.inf - - def progress_callback(es: cma.CMAEvolutionStrategy): - nonlocal xbest, xbest_cost - - res = es.result - if use_wandb: - best_params = genome.genotype_to_param_arrays(res.xbest) - mean_params = genome.genotype_to_param_arrays(res.xfavorite) - run.log( - { - "best_score": -res.fbest, - "best_genome": wandb.Table(data=pandas.DataFrame(best_params)), - "mean_genome": wandb.Table(data=pandas.DataFrame(mean_params)), - "mean_std": genome.genotype_to_param_arrays(res.stds), - "evaluations": res.evaluations, - }, - commit=True, - step=res.evaluations, - ) - - if res.fbest < xbest_cost: - xbest = res.xbest - xbest_cost = res.fbest - print(f"New best score: {-xbest_cost:.4f}") - best_yaml = genome.genotype_merge_config(xbest).to_yaml() - with open(os.path.join(storage_path, "best_config.yaml"), "w") as f: - f.write(best_yaml) - print(f"Merge configuration:\n{best_yaml}") - - if use_wandb: - art = wandb.Artifact("best_config", type="merge_config") - art.add_file(os.path.join(storage_path, "best_config.yaml")) - run.log_artifact(art) - - def parallel_evaluate(x: List[np.ndarray]) -> List[float]: - print(f"Received {len(x)} genotypes") - res = strat.evaluate_genotypes(x) - - if use_wandb: - res = list(res) - score_mean = np.mean([r["score"] for r in res]) - score_std = np.std([r["score"] for r in res]) - run.log( - { - "population/score_mean": score_mean, - "population/score_std": score_std, - }, - commit=False, - ) - for task in res[0]["results"]: - for metric in res[0]["results"][task]: - values = [r["results"][task][metric] for r in res] - values = [v for v in values if v is not None] - if not values or all(isinstance(v, str) for v in values): - continue - - mean = np.mean(values) - max_val = max(values) - min_val = min(values) - - metric_pretty = metric.replace(",none", "") - if metric_pretty.endswith("_stderr"): - # don't log stats for stderr that's just silly - continue - - run.log( - { - f"population/{task}_{metric_pretty}_mean": mean, - f"population/{task}_{metric_pretty}_max": max_val, - f"population/{task}_{metric_pretty}_min": min_val, - }, - commit=False, - ) - - return [-x["score"] for x in res] # maximize - - try: - cma_opts = {"maxfevals": max_fevals, "timeout": timeout} - if force_population_size is not None: - cma_opts["popsize"] = force_population_size - xbest, es = cma.fmin2( - None, - parallel_objective=parallel_evaluate, - x0=x0, - sigma0=sigma0, - options=cma_opts, - callback=progress_callback, - ) - xbest_cost = es.result.fbest - except KeyboardInterrupt: - ray.shutdown() - - print("!!! OPTIMIZATION COMPLETE !!!") - print(f"Best cost: {xbest_cost:.4f}") - print() - - # pause for a bit to let any CUDA-using processes clean up - time.sleep(1.0) - - # save the best merge configuration using original model references - genome_pretty = ModelGenome(config.genome, trust_remote_code=trust_remote_code) - best_config = genome_pretty.genotype_merge_config(xbest) - print("Best merge configuration:") - print(best_config.to_yaml()) - - if save_final_model: - print("Saving final model...") - run_merge(best_config, os.path.join(storage_path, "final_model"), merge_options) - - -def _reshard_model( - model: ModelReference, storage_path: str, merge_cache: str, trust_remote_code: bool -) -> ModelReference: - merged = model.merged( - cache_dir=merge_cache, - trust_remote_code=trust_remote_code, - ) - out_path = os.path.join( - storage_path, - "input_models", - merged.model._unique_id(), - ) - - if os.path.exists(out_path): - logging.info(f"Using existing resharded model at {out_path}") - return ModelReference(model=out_path) - - model_hf = transformers.AutoModelForCausalLM.from_pretrained( - merged.model.path, - revision=merged.model.revision, - trust_remote_code=trust_remote_code, - torch_dtype=torch.bfloat16, - cache_dir=os.path.join(storage_path, "transformers_cache"), - ) - model_hf.save_pretrained( - out_path, safe_serialization=True, out_shard_size=1_000_000_000_000 - ) - try: - tokenizer = transformers.AutoTokenizer.from_pretrained( - model.model.path, - revision=model.model.revision, - trust_remote_code=trust_remote_code, - use_fast=True, - ) - tokenizer.save_pretrained(out_path) - except Exception as e: - logging.warning(f"Could not save tokenizer for {model.model}", exc_info=e) - - return ModelReference(model=out_path) - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/extract_lora.py b/mergekit/scripts/extract_lora.py deleted file mode 100644 index 5235b852a0c47e89cee432daf33ab08efa35c79b..0000000000000000000000000000000000000000 --- a/mergekit/scripts/extract_lora.py +++ /dev/null @@ -1,284 +0,0 @@ -import json -import logging -import os -from typing import Any, Dict, List, Optional, Tuple - -import bitsandbytes as bnb -import click -import torch -from peft.tuners.lora import QuantLinear -from safetensors.torch import save_file -from tqdm import tqdm -from transformers import AutoModelForCausalLM -from transformers.modeling_utils import PreTrainedModel - -from mergekit.card import generate_card_lora -from mergekit.common import ModelReference -from mergekit.io import LazyTensorLoader - - -def _low_rank_decomposition( - weight: torch.Tensor, reduced_rank: int = 16 -) -> Tuple[torch.Tensor, torch.Tensor]: - """ - Decompose a 2D matrix into low-rank matrices A and B using SVD.a - - :param weight: The matrix to decompose, of shape (H, W) - :param reduced_rank: The final rank of the decomposition - :return: A tuple of tensors (A, B) - """ - if weight.dim() != 2: - raise ValueError( - f"Only support 2D matrix, but your input has {weight.dim()} dimensions." - ) - - dtype = weight.dtype - - # SVD Decomposition - U, S, Vh = torch.linalg.svd(weight.float(), full_matrices=False) - - # Truncated matrices - A = Vh[:reduced_rank, :] - B = U[:, :reduced_rank] @ torch.diag(S[:reduced_rank]) - - return A.to(dtype), B.to(dtype) - - -def decompose_delta_weight( - new_weight: torch.Tensor, - base_weight: torch.Tensor, - reduced_rank: int, - device: Optional[str] = None, -) -> Tuple[torch.Tensor, torch.Tensor]: - if device is None: - device = "cuda" if torch.cuda.is_available() else "cpu" - - new_weight = new_weight.to(device) - base_weight = base_weight.to(device) - - """ - Decompose the delta weight into low-rank matrices A and B. - - :param new_weight: The updated weight matrix after applying LoRA. - :param base_weight: The original weight matrix before LoRA. - :param reduced_rank: The rank for the low-rank decomposition. - :param device: The device to perform computation on. - :return: A tuple of tensors (A, B) - """ - delta_weight = new_weight - base_weight - - max_rank = min(delta_weight.shape) - assert ( - reduced_rank <= max_rank - ), f"The specified rank ({reduced_rank}) must be smaller than or equal to the rank of the weight matrices ({max_rank})" - - A, B = _low_rank_decomposition(delta_weight, reduced_rank=reduced_rank) - - return A, B - - -def find_all_linear_names(model: PreTrainedModel) -> List[str]: - cls = (bnb.nn.Linear4bit, bnb.nn.Linear8bitLt, torch.nn.Linear, QuantLinear) - - names = [] - for name, module in model.named_modules(): - if ( - isinstance(module, cls) - or "Linear" in module.__class__.__name__ - and module.__class__.__name__ not in ("LlamaLinearScalingRotaryEmbedding",) - ): - names.append(name) - - return names - - -def get_linear_module_names(model_id: str) -> List[str]: - model = AutoModelForCausalLM.from_pretrained( - model_id, state_dict={}, device_map="meta" - ) # avoid loading weights as we won't need them - linear_module_names = find_all_linear_names(model) - - return linear_module_names - - -def create_peft_config( - base_model_name_or_path: str, rank: int, alpha: int, target_modules: List[str] -) -> Dict[str, Any]: - return { - "alpha_pattern": {}, - "auto_mapping": None, - "base_model_name_or_path": base_model_name_or_path, - "bias": "none", - "fan_in_fan_out": False, - "inference_mode": True, - "init_lora_weights": True, - "layers_pattern": None, - "layers_to_transform": None, - "loftq_config": {}, - "lora_alpha": alpha, - "lora_dropout": 0, - "megatron_config": None, - "megatron_core": "megatron.core", - "modules_to_save": None, - "peft_type": "LORA", - "r": rank, - "rank_pattern": {}, - "revision": None, - "target_modules": target_modules, - "task_type": "CAUSAL_LM", - "use_rslora": False, - } - - -def reconstruct_invocation(args): - """ - Reconstructs the command-line invocation string based on the given arguments stored in a dictionary. - - Parameters: - - args: A dictionary containing the command arguments with keys matching the parameter names. - Expected keys are 'base_model', 'finetuned_model', 'out_path', 'no_lazy_unpickle', 'desired_rank', 'model_name' and 'device'. - - Returns: - - The reconstructed command-line invocation string. - """ - # Provide a default value for out_path if it's not in the dictionary - out_path = args.get("out_path", "OUTPUT_PATH") - - invocation = f"mergekit-extract-lora {args['base_model']} {args['finetuned_model']} {out_path}" - if args.get("no_lazy_unpickle"): - invocation += " --no-lazy-unpickle" - invocation += f" --rank={args['desired_rank']}" - if args.get("model_name"): - invocation += f" --model_name={args['model_name']}" - if args.get("device"): - invocation += f" --device={args['device']}" - - return invocation - - -@click.command("mergekit-extract-lora") -@click.argument("finetuned_model", type=str) -@click.argument("base_model", type=str) -@click.argument("out_path", type=click.Path()) -@click.option( - "--no-lazy-unpickle", - is_flag=True, - help="Disable lazy unpickler (more stable, higher memory usage)", -) -@click.option( - "--rank", - "desired_rank", - type=int, - default=32, - help="Rank for the low-rank decomposition", -) -@click.option( - "--model_name", - type=str, - default=None, - help="Name of the resulting model (shown in the model card)", -) -@click.option( - "--device", - type=str, - default=None, - help="PyTorch device to perform SVD computation on", -) -def main( - finetuned_model: str, - base_model: str, - out_path: str, - no_lazy_unpickle: bool, - desired_rank: int, - model_name: str, - device: str, -) -> None: - """ - Decomposes delta weights between a base model and a finetuned model, saving a PEFT model to the specified output path. - - \b - Arguments: - FINETUNED_MODEL - the model ID or path to use as the PEFT extraction target model. - BASE_MODEL - the model ID or path to use as the base model. - OUT_PATH - the output path where the PEFT model will be saved. - """ - - invocation_args = { - "base_model": base_model, - "finetuned_model": finetuned_model, - "desired_rank": desired_rank, - "device": device, - "out_path": out_path, - "model_name": model_name, - "no_lazy_unpickle": no_lazy_unpickle, - } - - os.makedirs(out_path, exist_ok=True) - - base_model_ref = ModelReference.parse(base_model) - finetuned_model_ref = ModelReference.parse(finetuned_model) - - linear_module_names = get_linear_module_names(base_model_ref.model.path) - finetuned_model_linear_module_names = get_linear_module_names( - finetuned_model_ref.model.path - ) - - assert set(linear_module_names) == set( - finetuned_model_linear_module_names - ), "Model architecture mismatch" - - base_loader = LazyTensorLoader( - base_model_ref.tensor_index(), lazy_unpickle=(not no_lazy_unpickle) - ) - finetuned_loader = LazyTensorLoader( - finetuned_model_ref.tensor_index(), lazy_unpickle=(not no_lazy_unpickle) - ) - - lora_weights = {} - for layer_name in tqdm(linear_module_names): - base_weight = base_loader.get_tensor(f"{layer_name}.weight") - finetuned_weight = finetuned_loader.get_tensor(f"{layer_name}.weight") - - lora_A, lora_B = decompose_delta_weight( - finetuned_weight, base_weight, desired_rank, device=device - ) - - lora_weights[f"base_model.model.{layer_name}.lora_A.weight"] = lora_A.to( - "cpu" - ).contiguous() - lora_weights[f"base_model.model.{layer_name}.lora_B.weight"] = lora_B.to( - "cpu" - ).contiguous() - - lora_config = create_peft_config( - base_model_name_or_path=base_model_ref.model.path, - alpha=desired_rank, # Setting the alpha to the reduced rank value as `peft` will scale the LoRA weights by alpha/r when applying the adapter - rank=desired_rank, - target_modules=list( - set([module_name.split(".")[-1] for module_name in linear_module_names]) - ), - ) - - with open(os.path.join(out_path, "adapter_config.json"), "w") as f: - json.dump(lora_config, f, indent=2) - - save_file(lora_weights, os.path.join(out_path, "adapter_model.safetensors")) - - invocation_args.pop("out_path") # don't include out_path for privacy - invocation = reconstruct_invocation(invocation_args) - - card_md = generate_card_lora( - base_model_ref=base_model_ref, - finetuned_model_ref=finetuned_model_ref, - invocation=invocation, - name=model_name, - ) - - with open(os.path.join(out_path, "README.md"), "w", encoding="utf-8") as fp: - fp.write(card_md) - - logging.info(f"PEFT LoRA adapters saved to {out_path}") - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/layershuffle.py b/mergekit/scripts/layershuffle.py deleted file mode 100644 index a750e93d97dc3a211419bb69d7effe50313d518c..0000000000000000000000000000000000000000 --- a/mergekit/scripts/layershuffle.py +++ /dev/null @@ -1,144 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import random -from typing import List - -import click -import yaml - -from mergekit.architecture import get_architecture_info -from mergekit.common import ModelReference -from mergekit.config import ( - InputSliceDefinition, - MergeConfiguration, - OutputSliceDefinition, -) -from mergekit.merge import run_merge -from mergekit.options import MergeOptions, add_merge_options - - -@click.command("mergekit-layershuffle") -@click.argument("out_path", type=str) -@click.option("--model", "-m", multiple=True, type=str, help="Add a model to the merge") -@click.option( - "--weight", - "-w", - multiple=True, - type=float, - default=[], - show_default=False, - help="Weighting for a model", -) -@click.option( - "--print-yaml/--no-print-yaml", - is_flag=True, - help="Print YAML merge config for resulting model", -) -@click.option( - "--write-yaml", - type=click.Path(writable=True), - help="Path to write YAML merge config to", -) -@click.option( - "--dry-run", is_flag=True, help="Generate a config but do not run the merge" -) -@click.option("--fp16/--no-fp16", is_flag=True, help="Use FP16 precision") -@click.option( - "--full-random/--no-full-random", - is_flag=True, - help="Randomize layer index as well as source model", -) -@add_merge_options -def main( - out_path: str, - model: List[str], - weight: List[float], - print_yaml: bool, - write_yaml: bool, - dry_run: bool, - fp16: bool, - full_random: bool, - merge_options: MergeOptions, -): - models = [ModelReference.parse(m) for m in model] - - m0_cfg = models[0].config() - arch_info = get_architecture_info(m0_cfg) - total_num_layers = arch_info.num_layers(m0_cfg) - - out_slices: List[OutputSliceDefinition] = [] - - if full_random: - for model, frac in zip(models, weight): - cfg = model.config() - num_layers = int(arch_info.num_layers(cfg) * frac) - for _ in range(num_layers): - src_idx = random.randrange(0, num_layers) - out_slices.append( - OutputSliceDefinition( - sources=[ - InputSliceDefinition( - model=str(model), - layer_range=(src_idx, src_idx + 1), - ) - ] - ) - ) - random.shuffle(out_slices) - else: - for layer_idx in range(total_num_layers): - src_model = random.choices(models, weights=weight, k=1)[0] - if out_slices and out_slices[-1].sources[0].model == str(src_model): - out_slices[-1].sources[0].layer_range = ( - out_slices[-1].sources[0].layer_range[0], - layer_idx + 1, - ) - else: - out_slices.append( - OutputSliceDefinition( - sources=[ - InputSliceDefinition( - model=str(src_model), - layer_range=(layer_idx, layer_idx + 1), - ) - ] - ) - ) - merge_config = MergeConfiguration( - merge_method="passthrough", slices=out_slices, dtype="float16" if fp16 else None - ) - - if print_yaml or write_yaml: - yaml_str = yaml.dump(merge_config.model_dump(exclude_none=True, mode="json")) - - if print_yaml: - print(yaml_str) - if write_yaml: - with open(write_yaml, "w", encoding="utf-8") as file: - file.write(yaml_str) - - if dry_run: - return - - run_merge( - merge_config, - out_path, - options=merge_options, - ) - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/legacy.py b/mergekit/scripts/legacy.py deleted file mode 100644 index dcd84bc766010f9abd28eabfaa81308d8d15845e..0000000000000000000000000000000000000000 --- a/mergekit/scripts/legacy.py +++ /dev/null @@ -1,142 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from typing import List, Optional - -import click -import yaml - -from mergekit.config import InputModelDefinition, MergeConfiguration -from mergekit.merge import run_merge -from mergekit.options import MergeOptions, add_merge_options - - -@click.command("mergekit-legacy") -@click.argument("out_path", type=str) -@click.option( - "--merge", "merge", type=str, multiple=True, help="Add a model to the merge" -) -@click.option( - "--density", - "density", - type=float, - multiple=True, - default=[], - help="Fraction of weights to keep for each model (ties only)", -) -@click.option( - "--weight", - "weight", - type=float, - multiple=True, - default=[], - help="Weighting for a model (default 1.0 for all models if not specified)", -) -@click.option( - "--method", "method", type=str, default="ties", help="Method used to merge models" -) -@click.option( - "--base-model", "base_model", type=str, default=None, help="Base model for merge" -) -@click.option( - "--normalize/--no-normalize", - "normalize", - is_flag=True, - default=True, - help="Divide merged parameters by the sum of weights", -) -@click.option( - "--int8-mask/--no-int8-mask", - "int8_mask", - is_flag=True, - help="Store intermediate masks in int8 to save memory", -) -@click.option("--bf16/--no-bf16", "bf16", is_flag=True, help="Use bfloat16") -@click.option( - "--naive-count/--no-naive-count", - "naive_count", - is_flag=True, - help="Use naive sign count instead of weight (ties only)", -) -@click.option( - "--print-yaml/--no-print-yaml", - "print_yaml", - is_flag=True, - help="Print generated YAML configuration", -) -@add_merge_options -def main( - out_path: str, - merge: List[str], - density: List[float], - weight: List[float], - method: str, - base_model: Optional[str], - normalize: bool, - int8_mask: bool, - bf16: bool, - naive_count: bool, - print_yaml: bool, - merge_options: MergeOptions, -): - """Wrapper for using a subset of legacy-style script arguments.""" - models = [InputModelDefinition(model=model, parameters={}) for model in merge] - if base_model and base_model not in merge: - models.append(InputModelDefinition(model=base_model, parameters={})) - - parameters = {} - - if density: - if len(density) == 1: - density = [density[0]] * len(models) - for idx, d in enumerate(density): - models[idx].parameters["density"] = d - - if method == "slerp": - assert len(weight) == 1, "Must specify exactly one weight for SLERP" - parameters["t"] = weight[0] - else: - if weight: - if len(weight) == 1: - weight = [weight[0]] * len(models) - for idx, w in enumerate(weight): - models[idx].parameters["weight"] = w - - if int8_mask: - parameters["int8_mask"] = True - if naive_count: - parameters["consensus_method"] = "count" - parameters["normalize"] = normalize - - merge_config = MergeConfiguration( - merge_method=method, - models=models, - parameters=parameters, - base_model=base_model, - dtype="bfloat16" if bf16 else None, - ) - - if print_yaml: - print(yaml.dump(merge_config.model_dump(mode="json", exclude_none=True))) - - run_merge( - merge_config, - out_path, - options=merge_options, - ) - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/megamerge.py b/mergekit/scripts/megamerge.py deleted file mode 100644 index 21e2892dc03cd34eef9dbce8a10c9dd968e4f707..0000000000000000000000000000000000000000 --- a/mergekit/scripts/megamerge.py +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/env python3 -""" -Merges multiple models and their dependencies into a single model -using multiple merge yaml documents in a single yaml file as the input -""" - -import logging -import os -import sys -from pathlib import Path - -import click -import yaml - -from mergekit.config import MergeConfiguration -from mergekit.merge import MergeOptions, run_merge -from mergekit.options import add_merge_options - -merges = {} - - -def has_circular_dependency(nodes): - """ - Detects circular in merges dependencies using DFS - Returns the node where the cycle is detected - """ - - def dfs(node, visited, stack): - """ - Returns True if a cycle is detected - """ - visited[node] = True - stack[node] = True - - for dependency in nodes[node]["deps"]: - if not visited[dependency]: - if dfs(dependency, visited, stack): - return True - elif stack[dependency]: - return True - - stack[node] = False - return False - - visited = {key: False for key in nodes} - stack = {key: False for key in nodes} - - for node in nodes: - if not visited[node]: - if dfs(node, visited, stack): - return node - - return None - - -def merge(m: str, merge_options: MergeOptions, force: bool, out_path: Path): - """ - Merges a model and its dependencies - - Params: - m: name of the model to merge - merge_options: MergeOptions - force: overwrite existing merge results - out_path: output path - """ - # check if output_path exists - if os.path.exists(out_path / m): - if not force: - logging.info("Skipping %s as it already exists", m) - del merges[m] - return - logging.info("Overwriting %s as --force was specified", m) - - if len(merges[m]["deps"]) != 0: - for dep in merges[m]["deps"]: - if dep in merges: - merge(dep, merge_options, force, out_path) - - logging.info("Merging model %s", m) - merge_config: MergeConfiguration = MergeConfiguration.model_validate(merges[m]) - run_merge( - merge_config, - str(out_path / merges[m]["name"]), - options=merge_options, - ) - del merges[m] - - -def add_model_deps(model: str, name: str, out_path: Path): - """ - Adds a model to `name`s dependencies if it is not already there and is a merge - """ - model_lora = model.split("+") - # name must not have a slash to avoid path traversal - # therefore, we can use it to check if its a merge from the config - if "/" not in model_lora[0]: - # avoid duplicate deps - if model_lora[0] not in merges[name]["deps"]: - merges[name]["deps"].append(model_lora[0]) - model = str(out_path / model_lora[0]) - if len(model_lora) == 2: - model += "+" + model_lora[1] - - return model - - -@click.command("mergekit-mega") -@click.argument("config_file") -@click.argument("out_path") -@click.option( - "--verbose", "-v", type=bool, default=False, is_flag=True, help="Verbose logging" -) -@click.option( - "--force", - "-f", - type=bool, - default=False, - is_flag=True, - help="Overwrite existing merge results instead of skipping them", -) -@click.option( - "--require-nameless", - "-R", - type=bool, - default=False, - is_flag=True, - help="Enforces exactly one unnamed merge in the YAML, which will inherit the input file's name.", -) -@add_merge_options -def main( - merge_options: MergeOptions, - config_file: str, - out_path: str, - force: bool, - verbose: bool, - require_nameless: bool, -): - """ - Main entrypoint for mergekit-mega command see module docstring for more info - Params are supplied by click decorators - """ - logging.basicConfig(level=logging.INFO if verbose else logging.WARNING) - - out_path = Path(out_path) - final_found = False - - with open(config_file, "r", encoding="utf-8") as f: - data = yaml.load_all(f, Loader=yaml.FullLoader) - - for d in data: - if "name" not in d: - if final_found: - logging.error("Only one merge must not have a name") - sys.exit(1) - # this sets the name of the final merge to the config file name without the extension - d["name"] = os.path.basename(config_file).rsplit(".", maxsplit=1)[0] - final_found = True - - if "/" in d["name"]: - logging.error("name must not contain a slash") - sys.exit(1) - - merges[d["name"]] = d - merges[d["name"]]["deps"] = [] - if "base_model" in d: - d["base_model"] = add_model_deps(d["base_model"], d["name"], out_path) - if "slices" in d: - for slc in d["slices"]: - for src in slc["sources"]: - src["model"] = add_model_deps(src["model"], d["name"], out_path) - if "models" in d: - for mdl in d["models"]: - mdl["model"] = add_model_deps(mdl["model"], d["name"], out_path) - - if require_nameless and not final_found: - logging.error("No final merge found") - sys.exit(1) - - logging.info("Merging: %s", ", ".join(merges)) - - if (dep := has_circular_dependency(merges)) is not None: - logging.error("Circular dependency detected: %s", dep) - sys.exit(1) - - while len(merges) != 0: - m = list(merges.keys())[0] - merge(m, merge_options, force, out_path) - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/moe.py b/mergekit/scripts/moe.py deleted file mode 100644 index f843192855d0ac6b4ef58c00170f0a1cd3a5bee7..0000000000000000000000000000000000000000 --- a/mergekit/scripts/moe.py +++ /dev/null @@ -1,231 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging -import os -import sys -from typing import List - -import click -import transformers -import yaml - -from mergekit.merge import MergeOptions -from mergekit.moe import ALL_OUTPUT_ARCHITECTURES, MoEOutputArchitecture -from mergekit.moe.config import MoEMergeConfig, is_bad_config -from mergekit.moe.router import get_gate_params, warn_degenerate_gates -from mergekit.options import add_merge_options - - -def build( - config: MoEMergeConfig, - out_path: str, - merge_options: MergeOptions, - load_in_4bit: bool = False, - load_in_8bit: bool = False, - device: str = "auto", - allow_all_same: bool = False, - verbose: bool = False, -): - if is_bad_config(config, allow_all_same=allow_all_same): - sys.exit(1) - - base_model = config.base_model - out_arch = select_output_arch(config, merge_options, verbose=verbose) - - tokenizer = transformers.AutoTokenizer.from_pretrained( - base_model.model.path, revision=base_model.model.revision - ) - tokenizer.padding_side = "left" - tokenizer.pad_token_id = tokenizer.bos_token_id - if tokenizer.pad_token_id is None: - tokenizer.pad_token = tokenizer.eos_token - - logging.info("Getting gate parameters...") - need_gates = list(config.experts) - if config.shared_experts: - has_prompts = any(e.positive_prompts for e in config.shared_experts) - assert all( - bool(e.positive_prompts) == has_prompts for e in config.shared_experts - ), "Must specify prompts for all shared experts or none, not a mix" - if has_prompts: - need_gates.extend(config.shared_experts) - - gate_vecs = get_gate_params( - base_model, - tokenizer, - need_gates, - mode=config.gate_mode, - load_in_4bit=load_in_4bit, - load_in_8bit=load_in_8bit, - lazy_unpickle=merge_options.lazy_unpickle, - trust_remote_code=merge_options.trust_remote_code, - device=device, - ) - # gate_vecs: (num_layers, num_experts, hidden_size) - router_weights = gate_vecs[:, : len(config.experts), :] - shared_router_weights = gate_vecs[:, len(config.experts) :, :] - warn_degenerate_gates(gate_vecs) - - out_arch.write_model( - out_path, - config, - merge_options, - router_weights=[router_weights[i, ...] for i in range(router_weights.shape[0])], - shared_router_weights=[ - shared_router_weights[i, ...] for i in range(router_weights.shape[0]) - ], - ) - - if merge_options.copy_tokenizer: - logging.info("Saving tokenizer...") - tokenizer.save_pretrained(out_path, safe_serialization=True) - - logging.info("Done.") - - -def select_output_arch( - config: MoEMergeConfig, - merge_options: MergeOptions, - verbose: bool = False, -) -> MoEOutputArchitecture: - candidates_in = ALL_OUTPUT_ARCHITECTURES - if config.architecture: - candidates_in = [ - a - for a in candidates_in - if a.name().lower().startswith(config.architecture.lower()) - ] - if not candidates_in: - logging.error( - f"No output architecture found that matches the given architecture: {config.architecture}" - ) - logging.error("All supported output architectures:") - for arch in ALL_OUTPUT_ARCHITECTURES: - logging.error(f" * {arch.name()}") - sys.exit(1) - - candidates: List[MoEOutputArchitecture] = [] - for arch in candidates_in: - if arch.supports_config( - config, explain=verbose, trust_remote_code=merge_options.trust_remote_code - ): - candidates.append(arch) - else: - logging.info(f"Output architecture {arch.name()} does not support config.") - - if not candidates: - logging.error( - "No output architecture found that is compatible with the given models." - ) - - logging.error("All supported output architectures:") - for arch in ALL_OUTPUT_ARCHITECTURES: - logging.error(f" * {arch.name()}") - sys.exit(1) - - # for compatibility with older configs, default to Mixtral if available - for arch in candidates: - if arch.name() == "Mixtral": - return arch - - if len(candidates) > 1: - logging.warning( - "Multiple output architectures found that are compatible with the given models." - ) - logging.warning(f"Defaulting to {candidates[0].name()}") - else: - logging.info(f"Selected output architecture: {candidates[0].name()}") - return candidates[0] - - -@click.command("mergekit-moe") -@click.argument("config_path", type=click.Path(exists=True, dir_okay=False)) -@click.argument("out_path", type=click.Path()) -@click.option( - "--load-in-4bit", - is_flag=True, - type=bool, - default=False, - help="Load model in 4bit for computing hidden states", -) -@click.option( - "--load-in-8bit", - is_flag=True, - type=bool, - default=False, - help="Load model in 8bit for computing hidden states", -) -@click.option( - "--device", - type=str, - default="auto", - help="Device to use to compute embeddings", - show_default=True, -) -@click.option( - "--verbose", "-v", type=bool, default=False, is_flag=True, help="Verbose logging" -) -@click.option( - "--i-understand-this-is-not-useful-without-training", - type=bool, - default=False, - is_flag=True, - help="Really make the questionable model you want.", -) -@add_merge_options -def main( - config_path: str, - out_path: str, - load_in_4bit: bool, - load_in_8bit: bool, - device: str, - merge_options: MergeOptions, - verbose: bool, - i_understand_this_is_not_useful_without_training: bool, -): - """Create a Mixture of Experts model by combining the pretrained weights of multiple models.""" - logging.basicConfig(level=logging.INFO if verbose else logging.WARNING) - - if merge_options.cuda: - logging.warning( - '--cuda is a no-op for mergekit-moe, use "--device cuda" instead' - ) - - with open(config_path, "r", encoding="utf-8") as file: - config_source = file.read() - - config = MoEMergeConfig.model_validate(yaml.safe_load(config_source)) - build( - config, - out_path=out_path, - merge_options=merge_options, - load_in_4bit=load_in_4bit, - load_in_8bit=load_in_8bit, - device=device, - allow_all_same=i_understand_this_is_not_useful_without_training, - verbose=verbose, - ) - - if merge_options.write_model_card: - # TODO: generate a README.md as well - with open( - os.path.join(out_path, "mergekit_moe_config.yml"), "w", encoding="utf-8" - ) as fp: - fp.write(config_source) - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/run_yaml.py b/mergekit/scripts/run_yaml.py deleted file mode 100644 index 22f0fc42c9e7351fa7c27d45e551355cb49f0387..0000000000000000000000000000000000000000 --- a/mergekit/scripts/run_yaml.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import logging - -import click -import yaml - -from mergekit.config import MergeConfiguration -from mergekit.merge import run_merge -from mergekit.options import MergeOptions, add_merge_options - - -@click.command("mergekit-yaml") -@click.argument("config_file") -@click.argument("out_path") -@click.option( - "--verbose", "-v", type=bool, default=False, is_flag=True, help="Verbose logging" -) -@add_merge_options -def main( - merge_options: MergeOptions, - config_file: str, - out_path: str, - verbose: bool, -): - logging.basicConfig(level=logging.INFO if verbose else logging.WARNING) - - with open(config_file, "r", encoding="utf-8") as file: - config_source = file.read() - - merge_config: MergeConfiguration = MergeConfiguration.model_validate( - yaml.safe_load(config_source) - ) - run_merge( - merge_config, - out_path, - options=merge_options, - config_source=config_source, - ) - - -if __name__ == "__main__": - main() diff --git a/mergekit/scripts/tokensurgeon.py b/mergekit/scripts/tokensurgeon.py deleted file mode 100644 index 7dc152195838d5d4cadccbf307ac6d9508c6f454..0000000000000000000000000000000000000000 --- a/mergekit/scripts/tokensurgeon.py +++ /dev/null @@ -1,592 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import enum -import logging -import sys -from typing import Dict, Generator, List, Optional, Tuple, Union - -import click -import torch -import tqdm -import transformers -from typing_extensions import TypeAlias - -from mergekit.architecture import ( - ConfiguredArchitectureInfo, - WeightInfo, - get_architecture_info, -) -from mergekit.common import ModelReference -from mergekit.io import TensorWriter -from mergekit.io.tasks import LoaderCache -from mergekit.options import MergeOptions, add_merge_options - -LOG = logging.getLogger(__name__) - - -@click.command("mergekit-tokensurgeon") -@click.argument("model", type=str) -@click.argument("donor", type=str) -@click.argument("out_path", type=str) -@click.option( - "-v", "verbosity", count=True, help="Verbose logging", default=0, show_default=False -) -@click.option( - "-k", - type=int, - default=8, - help="Number of nearest neighbours to use for embedding interpolation", -) -@click.option( - "--barycentric/--no-barycentric", - "-b/-nb", - is_flag=True, - default=False, - help="Use barycentric interpolation instead of distance weighting", -) -@click.option( - "--cosine-similarity/--no-cosine-similarity", - "-c/-nc", - is_flag=True, - default=False, - help="Use cosine similarity for nearest neighbour search", -) -@add_merge_options -def main( - model: str, - donor: str, - out_path: str, - verbosity: int, - k: int, - barycentric: bool, - cosine_similarity: bool, - merge_options: MergeOptions, -): - """ - Replace the tokenizer of a model with that of a donor model. Attempts to - approximate embeddings for tokens that are in the donor model but not the - original model. - - This greatly reduces the amount of training required to settle in the new - embeddings, and potentially removes the need for fine-tuning entirely for - tokenizers that are sufficiently similar. - - The model and donor model must have the same architecture. - """ - log_level = logging.WARNING - if verbosity == 1: - log_level = logging.INFO - elif verbosity > 1: - log_level = logging.DEBUG - logging.basicConfig(level=log_level) - LOG.warning("This tool is experimental and may produce unexpected results.") - - model = ModelReference.model_validate(model) - donor = ModelReference.model_validate(donor) - - cache = LoaderCache() - cache.setup(options=merge_options) - - device = "cuda" if merge_options.cuda else "cpu" - - arch_info, donor_cfg = validate_architecture(model, donor, merge_options) - embed_info, lm_head_info = get_embedding_info(model, merge_options) - donor_embed_info, donor_lm_head_info = get_embedding_info(donor, merge_options) - - _, old_vocab = load_tokenizer(model, merge_options) - tokenizer, new_vocab = load_tokenizer(donor, merge_options) - common_tokens = list(set(old_vocab.keys()) & set(new_vocab.keys())) - - old_embed = cache.get(model).get_tensor( - embed_info.name, aliases=embed_info.aliases, device=device - ) - donor_embed = cache.get(donor).get_tensor( - donor_embed_info.name, aliases=donor_embed_info.aliases, device=device - ) - - (_, hidden_size_0) = old_embed.shape - (_, hidden_size_1) = donor_embed.shape - if hidden_size_1 != hidden_size_0: - report_issue( - f"Embedding sizes do not match: {hidden_size_0} vs {hidden_size_1}", - error=not merge_options.allow_crimes, - ) - - min_overlap = max(hidden_size_0, hidden_size_1) - if len(common_tokens) < min_overlap: - report_issue( - f"Common tokens ({len(common_tokens)}) less than embedding size ({min_overlap})", - error=not merge_options.allow_crimes, - ) - - LOG.info("Computing new embeddings") - new_embed = get_embeddings( - old_embed, - donor_embed, - old_vocab, - new_vocab, - common_tokens, - accept_prefix=False, - k=k, - barycentric=barycentric, - cosine_similarity=cosine_similarity, - name=embed_info.name, - ) - - if lm_head_info: - old_lm_head = cache.get(model).get_tensor( - lm_head_info.name, aliases=lm_head_info.aliases, device=device - ) - donor_lm_head = cache.get(donor).get_tensor( - donor_lm_head_info.name, aliases=donor_lm_head_info.aliases, device=device - ) - - LOG.info("Computing new lm_head embeddings") - new_lm_head = get_embeddings( - old_lm_head, - donor_lm_head, - old_vocab, - new_vocab, - common_tokens, - accept_prefix=True, - k=k, - barycentric=barycentric, - cosine_similarity=cosine_similarity, - name=lm_head_info.name, - ) - - # Save out the new model - LOG.info(f"Saving new model to {out_path}") - writer = TensorWriter( - out_path, - max_shard_size=merge_options.out_shard_size, - safe_serialization=merge_options.safe_serialization, - ) - for weight_info in tqdm.tqdm(arch_info.all_weights(), desc="Saving weights"): - if weight_info.name == embed_info.name: - tensor = new_embed - elif lm_head_info is not None and weight_info.name == lm_head_info.name: - tensor = new_lm_head - else: - tensor = cache.get(model).get_tensor( - weight_info.name, aliases=weight_info.aliases - ) - writer.save_tensor(weight_info.name, tensor, clone=merge_options.clone_tensors) - writer.finalize() - - tokenizer.save_pretrained(out_path) - cfg_out = arch_info.config - try: - cfg_out.vocab_size = tokenizer.vocab_size - except AttributeError: - LOG.error( - "Could not set vocab size in config.json - you may need to update it manually." - ) - for key in [ - "pad_token_id", - "eos_token_id", - "bos_token_id", - "unk_token_id", - "mask_token_id", - "padding_side", - ]: - if hasattr(donor_cfg, key) and (value := getattr(donor_cfg, key)) is not None: - try: - setattr(cfg_out, key, value) - except AttributeError: - LOG.error(f"Could not set {key}!") - cfg_out.save_pretrained(out_path) - - -class TokenMarker(enum.Enum): - SPECIAL = "special" - WORD_START = "word_start" - - -NormalizedToken: TypeAlias = Union[str, Tuple[TokenMarker, str]] - - -def normalize_token( - token: str, - special_tokens_map: Dict[str, Union[str, List[str]]], - word_start_prefix: str = "▁", -) -> NormalizedToken: - """ - Normalize a token for comparison. - """ - if token.startswith(word_start_prefix): - return (TokenMarker.WORD_START, token[len(word_start_prefix) :]) - - for special_token_type, values in special_tokens_map.items(): - if isinstance(values, str): - values = [values] - if token in values: - return (TokenMarker.SPECIAL, special_token_type) - return token - - -def token_prefixes( - token: NormalizedToken, allow_whitespace: bool = False -) -> Generator[NormalizedToken, None, None]: - """Yield potential prefixes of a token.""" - marker = None - if isinstance(token, tuple): - marker, token = token - - for i in range(len(token) - 1, 0, -1): - prefix = token[:i] - if not allow_whitespace and not prefix.strip(): - break - if marker is not None: - yield (marker, prefix) - else: - yield prefix - - -def get_embedding_info( - model: ModelReference, options: MergeOptions -) -> Tuple[WeightInfo, WeightInfo]: - """Get WeightInfo for the input and output embeddings of a model.""" - cfg = model.config(trust_remote_code=options.trust_remote_code) - arch_info = get_architecture_info(cfg) - - embed, lm_head = None, None - for weight_info in arch_info.pre_weights(cfg): - if weight_info.is_embed: - if embed is not None: - raise RuntimeError("Multiple input embeddings found") - embed = weight_info - - for weight_info in arch_info.post_weights(cfg): - if weight_info.is_embed: - if lm_head is not None: - raise RuntimeError("Multiple output embeddings found") - lm_head = weight_info - - return embed, lm_head - - -def report_issue(message: str, error: bool = False): - """Log an issue and exit if error is True.""" - if error: - LOG.error(message) - sys.exit(1) - else: - LOG.warning(message) - - -def get_embeddings( - original_embed: torch.Tensor, - donor_embed: torch.Tensor, - original_vocab: Dict[NormalizedToken, int], - donor_vocab: Dict[NormalizedToken, int], - common_tokens: List[str], - *, - accept_prefix: bool = False, - k: int = 8, - barycentric: bool = False, - cosine_similarity: bool = False, - log_reconstruction_error: bool = True, - log_statistics: bool = True, - name: Optional[str] = None, -) -> torch.Tensor: - """ - Generate embeddings for a target vocabulary. - - For tokens present in both vocabularies, the embedding from original_embed is - directly copied. For tokens not present in the original vocabulary, the - embedding is approximated using the k-nearest neighbours among the tokens that - are present in both vocabularies. This can be done using either barycentric - interpolation or distance weighted averaging. - - Args: - original_embed (torch.Tensor): Embedding matrix for the original vocabulary. - donor_embed (torch.Tensor): Embedding matrix for the new vocabulary. - original_vocab (Dict[NormalizedToken, int]): Maps tokens to indices in - original_embed. - donor_vocab (Dict[NormalizedToken, int]): Maps tokens to indices in - donor_embed. - common_tokens (List[str]): Tokens that are common to both vocabularies. - accept_prefix (bool): If True, allows using prefix matches for tokens when - an exact match is not found. - k (int): Number of nearest neighbours to use for embedding interpolation. - barycentric (bool): If True, uses barycentric interpolation for embedding - approximation. Otherwise, uses distance weighting. - cosine_similarity (bool): If True, uses cosine similarity to find nearest - neighbors. Otherwise, uses Euclidean distance. - log_reconstruction_error (bool): If True, logs the mean squared error of - the reconstructed embeddings. - log_statistics (bool): If True, logs statistics about the embedding - approximation process. - name (Optional[str]): Name of the embedding matrix. Used for logging. - - Returns: - torch.Tensor: Embedding matrix for the new vocabulary. - Shape is (len(donor_vocab), original_embed.shape[1]). - """ - hidden_size_0 = original_embed.shape[1] - hidden_size_1 = donor_embed.shape[1] - - e_c_0 = torch.empty( - len(common_tokens), - hidden_size_0, - device=original_embed.device, - dtype=original_embed.dtype, - ) - e_c_1 = torch.empty( - len(common_tokens), - hidden_size_1, - device=donor_embed.device, - dtype=donor_embed.dtype, - ) - for i, token in enumerate(common_tokens): - idx_0 = original_vocab[token] - idx_1 = donor_vocab[token] - e_c_0[i] = original_embed[idx_0] - e_c_1[i] = donor_embed[idx_1] - - exact_matches = 0 - prefix_matches = 0 - knn_matches = 0 - res = torch.zeros( - max(donor_vocab.values()) + 1, - hidden_size_0, - device=original_embed.device, - dtype=original_embed.dtype, - ) - - # message for tqdm - desc = "Computing embeddings" - if name: - desc += f" ({name})" - - knn_reconstruction_error = [] - for token in tqdm.tqdm(donor_vocab, desc=desc): - idx_1 = donor_vocab[token] - if token in original_vocab: - res[idx_1] = original_embed[original_vocab[token]] - exact_matches += 1 - continue - - if isinstance(token, str): - if len(token) == 1 and ord(token) < 256: - # check for matching byte tokens - byte_tok = f"<0x{ord(token):02X}>" - if byte_tok in original_vocab: - res[idx_1] = original_embed[original_vocab[byte_tok]] - exact_matches += 1 - continue - elif token.startswith("<0x") and token.endswith(">") and len(token) == 6: - # check for character tokens matching byte tokens - try: - byte = int(token[3:-1], 16) - except ValueError: - pass - else: - if chr(byte) in original_vocab: - res[idx_1] = original_embed[original_vocab[chr(byte)]] - exact_matches += 1 - continue - - if accept_prefix: - # For the LM head, we can accept prefix matches so long as the prefix is - # not also in the new vocab - this is to avoid including the same embedding - # vector multiple times - found_prefix = False - for prefix in token_prefixes(token, allow_whitespace=False): - if prefix in original_vocab and prefix not in donor_vocab: - res[idx_1] = original_embed[original_vocab[prefix]] - found_prefix = True - break - - if found_prefix: - prefix_matches += 1 - continue - - # If we can't find a prefix match, approximate from k nearest neighbours - token_embedding = donor_embed[idx_1] - if cosine_similarity: - cos_similarities = torch.nn.functional.cosine_similarity( - token_embedding.unsqueeze(0), e_c_1, dim=1 - ) - distances = 1 - cos_similarities - else: - # euclidean distance - distances = torch.cdist(token_embedding.unsqueeze(0), e_c_1).squeeze() - _, indices = torch.topk(distances, k, largest=False) - knn_embeddings = e_c_1[indices] - - if barycentric: - # Find least squares barycentric weights - # Constrain sum of weights to 1 by adding a row of 1s - constraint_row = torch.ones( - (1, knn_embeddings.shape[0]), device=original_embed.device - ) - knn_e_c = torch.cat([knn_embeddings.T, constraint_row], dim=0) - e_c = torch.cat( - [ - token_embedding, - torch.tensor([1.0], device=e_c_0.device, dtype=e_c_0.dtype), - ] - ).unsqueeze(-1) - weights = torch.linalg.lstsq( - knn_e_c.float(), e_c.float(), rcond=1e-6 - ).solution.to(dtype=e_c_0.dtype) - else: - # Just weight by distance - if cosine_similarity: - weights = cos_similarities[indices].unsqueeze(-1).to(dtype=e_c_0.dtype) - else: - # weights = 1 / distances[indices].to(dtype=e_c_0.dtype).clamp(min=1e-6) - weights = torch.nn.functional.softmin( - distances[indices].to(dtype=e_c_0.dtype), dim=0 - ) - weights /= weights.sum() - - if log_reconstruction_error: - # compute reconstruction error in donor_embed space - knn_reconstruction_error.append( - torch.nn.functional.mse_loss( - (knn_embeddings.T.to(weights.dtype) @ weights).squeeze(), - token_embedding, - ).item() - ) - - # Reconstruct the embedding in original_embed space - res[idx_1] = (e_c_0[indices].T @ weights).squeeze() - knn_matches += 1 - - if log_statistics: - LOG.info("Token breakdown:") - LOG.info(f"\tExact matches: {exact_matches}") - if prefix_matches: - LOG.info(f"\tPrefix matches: {prefix_matches}") - LOG.info(f"\tKNN solutions: {knn_matches}") - - pct_approx = int((len(donor_vocab) - exact_matches) * 100 / len(donor_vocab)) - if pct_approx > 10: - # encourage best practices - LOG.warning( - f"Large number of tokens ({pct_approx}%) could not be exactly " - "matched - be sure to fine tune this sucker!" - ) - - if knn_reconstruction_error: - knn_err = torch.tensor( - knn_reconstruction_error, device=original_embed.device, dtype=torch.float32 - ) - LOG.info("KNN reconstruction error:") - LOG.info(f"\tMean: {knn_err.mean().item()}") - LOG.debug(f"\tMedian: {knn_err.median().item()}") - LOG.debug(f"\tMax: {knn_err.max().item()}") - LOG.debug(f"\tMin: {knn_err.min().item()}") - LOG.debug(f"\tStddev: {knn_err.std().item()}") - if knn_err.mean().isnan() or knn_err.mean().isinf(): - LOG.error( - "NaN or infinite reconstruction error detected - output is " - "definitely broken!" - ) - if knn_err.mean().item() >= 0.01: - LOG.warning("Unreasonably high reconstruction error - expect some issues!") - - return res - - -def load_tokenizer( - model: ModelReference, options: MergeOptions -) -> Tuple[transformers.PreTrainedTokenizerBase, Dict[NormalizedToken, int]]: - """Load a tokenizer from a model. Returns the tokenizer and a mapping of - normalized tokens to indices.""" - tokenizer = transformers.AutoTokenizer.from_pretrained( - model.model.path, - revision=model.model.revision, - trust_remote_code=options.trust_remote_code, - ) - - gpt2_style = [ - transformers.GPT2Tokenizer, - transformers.GPT2TokenizerFast, - transformers.OpenAIGPTTokenizer, - transformers.OpenAIGPTTokenizerFast, - ] - for candidate in ["Qwen2Tokenizer", "Qwen2TokenizerFast"]: - if hasattr(transformers, candidate): - gpt2_style.append(getattr(transformers, candidate)) - - sp_style = [ - transformers.LlamaTokenizer, - transformers.LlamaTokenizerFast, - transformers.T5Tokenizer, - transformers.T5TokenizerFast, - ] - for candidate in ["GemmaTokenizer", "GemmaTokenizerFast"]: - if hasattr(transformers, candidate): - sp_style.append(getattr(transformers, candidate)) - - vocab = tokenizer.get_vocab() - if isinstance( - tokenizer, - tuple(gpt2_style), - ): - word_start_prefix = "Ġ" - elif isinstance( - tokenizer, - tuple(sp_style), - ): - if "Ġhello" in vocab: - # dumb special case for deepseek's tokenizer - word_start_prefix = "Ġ" - else: - word_start_prefix = "▁" - else: - LOG.warning("Unknown tokenizer type - assuming 'Ġ' word start prefix") - word_start_prefix = "Ġ" - - tokenizer.all_special_tokens - return tokenizer, { - normalize_token( - token, - special_tokens_map=tokenizer.special_tokens_map, - word_start_prefix=word_start_prefix, - ): i - for token, i in vocab.items() - } - - -def validate_architecture( - model: ModelReference, donor: ModelReference, options: MergeOptions -) -> Tuple[ConfiguredArchitectureInfo, transformers.PretrainedConfig]: - """ - Validate that the architectures of two models match. - - Returns the architecture info for the model and the config for the donor. - """ - model_cfg = model.config(trust_remote_code=options.trust_remote_code) - donor_cfg = donor.config(trust_remote_code=options.trust_remote_code) - model_arch_info = get_architecture_info(model_cfg) - donor_arch_info = get_architecture_info(donor_cfg) - if donor_arch_info != model_arch_info: - report_issue( - f"Model architectures do not match: {model_arch_info.name()} vs {donor_arch_info.name()}", - error=not options.allow_crimes, - ) - - return ConfiguredArchitectureInfo(info=model_arch_info, config=model_cfg), donor_cfg - - -if __name__ == "__main__": - with torch.no_grad(): - main() diff --git a/mergekit/sparsify.py b/mergekit/sparsify.py deleted file mode 100644 index ea016fe87a1986dbfd44e61b427fe71467fa900a..0000000000000000000000000000000000000000 --- a/mergekit/sparsify.py +++ /dev/null @@ -1,135 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -from enum import Enum - -import torch - - -class SparsificationMethod(str, Enum): - magnitude = "magnitude" - random = "random" - magnitude_outliers = "magnitude_outliers" - - -def rescale_sum(tensor: torch.Tensor, mask: torch.Tensor): - """Rescales the values to match the original tensor sum.""" - org_sum = tensor.abs().sum() - new_sum = (tensor * mask).abs().sum() - - if org_sum >= 1e-8 and new_sum >= 1e-8: - tensor *= org_sum / new_sum - return tensor * mask - - -def magnitude(tensor: torch.Tensor, density: float, rescale: bool) -> torch.Tensor: - """Masks out the smallest values, retaining a proportion of `density`.""" - if density >= 1: - return tensor - - k = int(density * tensor.numel()) - - assert k > 0, "not gonna zero out the whole tensor buddy" - mask = torch.zeros_like(tensor) - w = tensor.abs().view(-1) - if w.device.type == "cpu": - w = w.float() - topk = torch.argsort(w, descending=True)[:k] - mask.view(-1)[topk] = 1 - - if rescale: - res = rescale_sum(tensor, mask) - else: - res = tensor * mask - - return res - - -def magnitude_outliers( - tensor: torch.Tensor, density: float, rescale: bool, gamma: float = 0.01 -): - """Masks out smallest values in addition to large outliers. - - The `gamma` proportion of the largest weights are first removed, then the - smallest weights are removed to achieve the desired density. - - Args: - tensor (torch.Tensor): The tensor to sparsify. - density (float): The proportion of weights to retain. - gamma (float): Percent of largest weights to remove. - """ - if density >= 1: - return tensor - - num_elems = tensor.numel() - target_n = int(density * num_elems) - n_top = int(gamma * num_elems) - n_bot = num_elems - target_n - n_top - - if n_bot < 0: - # cut down on the number of large weights to remove in - # order to hit the target density - n_top += n_bot - n_bot = 0 - - w = tensor.abs().view(-1) - if w.device.type == "cpu": - w = w.float() - indices = torch.sort(w, descending=False).indices - mask = torch.zeros_like(tensor) - - mask.view(-1)[indices[n_bot:-n_top]] = 1 - - if rescale: - res = rescale_sum(tensor, mask) - else: - res = tensor * mask - return res - - -def bernoulli(tensor: torch.Tensor, density: float, rescale: bool) -> torch.Tensor: - if density >= 1: - return tensor - - if (tensor.device.type != "cpu") or tensor.dtype == torch.bfloat16: - work_dtype = tensor.dtype - else: - # torch.bernoulli not implemented for float16 on CPU, upcast to float32 - work_dtype = torch.float32 - - mask = torch.bernoulli( - torch.full_like(input=tensor, fill_value=density, dtype=work_dtype) - ) - res = tensor.to(work_dtype) * mask - if rescale: - res /= density - return res.to(tensor.dtype) - - -def sparsify( - tensor: torch.Tensor, - density: float, - method: SparsificationMethod, - gamma: float = 0, - rescale: bool = False, -) -> torch.Tensor: - if method == SparsificationMethod.magnitude: - return magnitude(tensor, density=density, rescale=rescale) - elif method == SparsificationMethod.random: - return bernoulli(tensor, density=density, rescale=rescale) - elif method == SparsificationMethod.magnitude_outliers: - return magnitude_outliers(tensor, density=density, rescale=rescale, gamma=gamma) - else: - raise NotImplementedError(method) diff --git a/mergekit/tokenizer.py b/mergekit/tokenizer.py deleted file mode 100644 index ae6153af02b3b3bc96da7cd67f310fd9f04695ea..0000000000000000000000000000000000000000 --- a/mergekit/tokenizer.py +++ /dev/null @@ -1,286 +0,0 @@ -# Copyright (C) 2024 Charles O. Goddard -# -# This software is free software: you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This software is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see http://www.gnu.org/licenses/. - -import json -import logging -import tempfile -from typing import Dict, List, Optional, Tuple - -import tokenizers -import tokenizers.models -import torch -import tqdm -import transformers -from pydantic import BaseModel - -from mergekit.common import ModelPath, ModelReference -from mergekit.graph import Task - - -def get_vocab_size(model_path: ModelPath, trust_remote_code: bool) -> Optional[int]: - try: - cfg = transformers.AutoConfig.from_pretrained( - model_path.path, - revision=model_path.revision, - trust_remote_code=trust_remote_code, - ) - return cfg.vocab_size - except Exception as e: - logging.warning(f"Unable to get vocab size for {model_path}", exc_info=e) - - return None - - -def get_stripped_tokenizer( - path: ModelPath, trust_remote_code: bool = False -) -> transformers.PreTrainedTokenizerFast: - """ - Return a tokenizer for a model that only contains used tokens. - - Strips any tokens with indices >= model.vocab_size. - """ - tokenizer = transformers.AutoTokenizer.from_pretrained( - path.path, - revision=path.revision, - trust_remote_code=trust_remote_code, - use_fast=True, - ) - vocab_size = get_vocab_size(path, trust_remote_code=trust_remote_code) or len( - tokenizer.get_vocab() - ) - - unused_toks = [ - tok for tok, idx in tokenizer.get_vocab().items() if idx >= vocab_size - ] - if not unused_toks: - # we're good, ship it - return tokenizer - - if not tokenizer.is_fast: - raise RuntimeError( - f"Model {path} has unused tokens and does not support fast " - "tokenizer - can not be used in tokenizer merge" - ) - - tok_dict = json.loads(tokenizer._tokenizer.to_str()) - if tok_dict["model"]["type"] != "BPE": - raise RuntimeError( - f"Tokenizer for {path} has type {tok_dict['model']['type']}, " - "but only BPE is currently supported for tokenizer merge" - ) - - tok_dict["added_tokens"] = [ - e for e in tok_dict["added_tokens"] if e["id"] < vocab_size - ] - - for tok in unused_toks: - if tok in tok_dict["model"]["vocab"]: - del tok_dict["model"]["vocab"][tok] - - def _keep_merge(m): - toks = m.split(" ") - for tok in toks: - if tok in unused_toks: - return False - return True - - tok_dict["model"]["merges"] = [ - e for e in tok_dict["model"]["merges"] if _keep_merge(e) - ] - tokenizer._tokenizer = tokenizers.Tokenizer.from_str(json.dumps(tok_dict)) - return tokenizer - - -def build_union_tokenizer( - base_tok: transformers.PreTrainedTokenizerBase, - tokenizers: Dict[ModelReference, transformers.PreTrainedTokenizerBase], - trust_remote_code: bool = False, -) -> transformers.PreTrainedTokenizerBase: - out_added_tokens = {} - out_vocab = {} - - warned_added_tokens = set() - - for model, tokenizer in tokenizers.items(): - vocab_size = ( - get_vocab_size(model.model, trust_remote_code=trust_remote_code) - or tokenizer.vocab_size - ) - added_tokens = tokenizer.added_tokens_decoder - - vocab = tokenizer.get_vocab() - for tok, idx in vocab.items(): - if idx >= vocab_size: - logging.warning( - f"Token {repr(tok)} present in {str(model)} tokenizer but >= vocab_size" - ) - continue - if tok in added_tokens: - # deal with later - continue - - if tok not in out_vocab: - out_vocab[tok] = len(out_vocab) - - for tok_idx, info in tokenizer.added_tokens_decoder.items(): - tok = info.content - if tok_idx >= vocab_size: - continue - - if tok in out_added_tokens: - if (out_added_tokens[tok] != info) and tok not in warned_added_tokens: - logging.warning( - f"Token '{tok}' added with multiple different settings, using first" - ) - warned_added_tokens.add(tok) - - continue - out_added_tokens[tok] = info - - # HACK: save base tokenizer to temp dir and reload to avoid mutating base_tok - with tempfile.TemporaryDirectory() as p: - base_tok.save_pretrained(p, legacy_format=False, safe_serialization=True) - res = transformers.AutoTokenizer.from_pretrained( - p, use_fast=True, trust_remote_code=trust_remote_code - ) - - orig_base_vocab = base_tok.get_vocab() - for tok in out_vocab: - if tok in out_added_tokens: - continue - - if tok not in orig_base_vocab: - res.add_tokens(tok) - - for info in out_added_tokens.values(): - res.add_tokens(info) - return res - - -def build_tokenizer( - base_model: Optional[ModelReference], - referenced_models: List[ModelReference], - tokenizer_source: str, - trust_remote_code: bool, -) -> Tuple[transformers.PreTrainedTokenizer, Dict[ModelReference, torch.IntTensor]]: - if base_model is None: - base_model = referenced_models[0] - if base_model is None: - raise RuntimeError("No models referenced") - - # - tokenizer_base = get_stripped_tokenizer( - base_model.model, trust_remote_code=trust_remote_code - ) - - # load all tokenizers - logging.info("Loading tokenizers") - tokenizers = {base_model: tokenizer_base} - for model in referenced_models: - if model == base_model: - continue - - try: - model_tok = transformers.AutoTokenizer.from_pretrained( - model.model.path, - revision=model.model.revision, - trust_remote_code=trust_remote_code, - ) - except Exception as e: - logging.error(e) - logging.warning( - f"Unable to load tokenizer for {model}. Assuming same as {base_model}." - ) - continue - tokenizers[model] = model_tok - - logging.info("Building output tokenizer") - # build final vocabulary - if tokenizer_source == "base": - # it done - tokenizer_out = tokenizer_base - elif tokenizer_source == "union": - tokenizer_out = build_union_tokenizer( - tokenizer_base, tokenizers, trust_remote_code=trust_remote_code - ) - elif tokenizer_source.startswith("model:"): - tokenizer_out = transformers.AutoTokenizer.from_pretrained( - tokenizer_source[len("model:") :], - trust_remote_code=trust_remote_code, - ) - else: - raise RuntimeError(f"Unimplemented tokenizer source: {tokenizer_source}") - - vocab_out = tokenizer_out.get_vocab() - - logging.info("Building permutations") - permutations = {} - for model in ( - pbar := tqdm.tqdm(referenced_models, desc="Building tokenizer permutations") - ): - if model in tokenizers: - model_vocab = tokenizers[model].get_vocab() - else: - model_vocab = tokenizers[base_model].get_vocab() - - vocab_size = get_vocab_size(model.model, trust_remote_code=trust_remote_code) - if vocab_size is None: - vocab_size = len(model_vocab) - - p = {} - for tok in vocab_out: - new_idx = vocab_out[tok] - if tok not in model_vocab: - p[new_idx] = -1 - continue - - orig_idx = model_vocab[tok] - if orig_idx >= vocab_size: - logging.warning( - f"{model} token {repr(tok)} has index {orig_idx}>{vocab_size-1} (padding?)" - ) - continue - - p[new_idx] = orig_idx - - permutations[model] = p - - del pbar - - return tokenizer_out, permutations - - -class TokenizerInfo(BaseModel, arbitrary_types_allowed=True): - tokenizer: transformers.PreTrainedTokenizerBase - permutations: Optional[Dict[ModelReference, Dict[int, int]]] - - -class BuildTokenizer(Task[TokenizerInfo]): - base_model: Optional[ModelReference] - referenced_models: Tuple[ModelReference, ...] - tokenizer_source: str - trust_remote_code: bool = False - - def arguments(self) -> Dict[str, Task]: - return {} - - def execute(self, **_kwargs) -> TokenizerInfo: - tokenizer, permutations = build_tokenizer( - self.base_model, - self.referenced_models, - self.tokenizer_source, - self.trust_remote_code, - ) - return TokenizerInfo(tokenizer=tokenizer, permutations=permutations)