Delete mergekit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- mergekit/__init__.pyDeleted
- mergekit/_data/__init__.pyDeleted
- mergekit/_data/architectures/__init__.pyDeleted
- mergekit/_data/architectures/baichuan.jsonDeleted-47
- mergekit/_data/architectures/bert-masked-lm.jsonDeleted-118
- mergekit/_data/architectures/bert-sequence-classification.jsonDeleted-118
- mergekit/_data/architectures/bert.jsonDeleted-175
- mergekit/_data/architectures/chatglm.jsonDeleted-50
- mergekit/_data/architectures/cohere.jsonDeleted-53
- mergekit/_data/architectures/distilbert-masked-lm.jsonDeleted-104
- mergekit/_data/architectures/distilbert-sequence-classification.jsonDeleted-94
- mergekit/_data/architectures/distilbert-token-classification.jsonDeleted-88
- mergekit/_data/architectures/distilbert.jsonDeleted-81
- mergekit/_data/architectures/falcon.jsonDeleted-53
- mergekit/_data/architectures/gemma.jsonDeleted-85
- mergekit/_data/architectures/gemma2.jsonDeleted-62
- mergekit/_data/architectures/gpt-neox.jsonDeleted-74
- mergekit/_data/architectures/gpt2-sequence-classification.jsonDeleted-66
- mergekit/_data/architectures/gpt2.jsonDeleted-64
- mergekit/_data/architectures/gptbigcode.jsonDeleted-70
- mergekit/_data/architectures/jais.jsonDeleted-70
- mergekit/_data/architectures/llama.jsonDeleted-91
- mergekit/_data/architectures/mamba.jsonDeleted-57
- mergekit/_data/architectures/mistral.jsonDeleted-90
- mergekit/_data/architectures/phi-1.jsonDeleted-66
- mergekit/_data/architectures/phi2-old.jsonDeleted-62
- mergekit/_data/architectures/phi2.jsonDeleted-74
- mergekit/_data/architectures/phi3.jsonDeleted-50
- mergekit/_data/architectures/qwen.jsonDeleted-50
- mergekit/_data/architectures/qwen2.jsonDeleted-65
- mergekit/_data/architectures/roberta-masked-lm.jsonDeleted-104
- mergekit/_data/architectures/roberta-sequence-classification.jsonDeleted-95
- mergekit/_data/architectures/roberta-token-classification.jsonDeleted-89
- mergekit/_data/architectures/roberta.jsonDeleted-89
- mergekit/_data/architectures/stablelm.jsonDeleted-98
- mergekit/_data/architectures/stablelm2.jsonDeleted-74
- mergekit/_data/architectures/starcoder2.jsonDeleted-78
- mergekit/architecture.pyDeleted-378
- mergekit/card.pyDeleted-239
- mergekit/common.pyDeleted-290
- mergekit/config.pyDeleted-210
- mergekit/evo/__init__.pyDeleted
- mergekit/evo/actors.pyDeleted-324
- mergekit/evo/config.pyDeleted-95
- mergekit/evo/genome.pyDeleted-383
- mergekit/evo/helpers.pyDeleted-126
- mergekit/evo/monkeypatch.pyDeleted-140
- mergekit/evo/strategy.pyDeleted-301
- mergekit/graph.pyDeleted-272
- mergekit/io/__init__.pyDeleted-28
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118{
"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"
]
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118{
"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"
]
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175{
"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"
]
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104{
"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"
}
]
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394{
"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"
}
]
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{
"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"
}
]
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485{
"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}"
}
]
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162{
"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"
]
}
]
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{
"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"
}
]
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{
"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"
}
]
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970{
"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"
}
]
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970{
"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"
}
]
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091{
"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
}
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990{
"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
}
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{
"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"
}
]
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950{
"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
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{
"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"
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798{
"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
}
]
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778{
"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"
}
]
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378# 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}"
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# 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,
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290# 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: '<MODEL_PATH>(+<LORA_PATH>)?'"""
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_cls123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210# 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324# 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383# 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 x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140# 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 = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301# 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]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272# 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_dependencies12345678910111213141516171819202122232425262728# 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",
]mergekit/__init__.pyDeleted
mergekit/_data/__init__.pyDeleted
mergekit/_data/architectures/__init__.pyDeleted
mergekit/_data/architectures/baichuan.jsonDeleted-47
mergekit/_data/architectures/bert-masked-lm.jsonDeleted-118
mergekit/_data/architectures/bert-sequence-classification.jsonDeleted-118
mergekit/_data/architectures/bert.jsonDeleted-175
mergekit/_data/architectures/chatglm.jsonDeleted-50
mergekit/_data/architectures/cohere.jsonDeleted-53
mergekit/_data/architectures/distilbert-masked-lm.jsonDeleted-104
mergekit/_data/architectures/distilbert-sequence-classification.jsonDeleted-94
mergekit/_data/architectures/distilbert-token-classification.jsonDeleted-88
mergekit/_data/architectures/distilbert.jsonDeleted-81
mergekit/_data/architectures/falcon.jsonDeleted-53
mergekit/_data/architectures/gemma.jsonDeleted-85
mergekit/_data/architectures/gemma2.jsonDeleted-62
mergekit/_data/architectures/gpt-neox.jsonDeleted-74
mergekit/_data/architectures/gpt2-sequence-classification.jsonDeleted-66
mergekit/_data/architectures/gpt2.jsonDeleted-64
mergekit/_data/architectures/gptbigcode.jsonDeleted-70
mergekit/_data/architectures/jais.jsonDeleted-70
mergekit/_data/architectures/llama.jsonDeleted-91
mergekit/_data/architectures/mamba.jsonDeleted-57
mergekit/_data/architectures/mistral.jsonDeleted-90
mergekit/_data/architectures/phi-1.jsonDeleted-66
mergekit/_data/architectures/phi2-old.jsonDeleted-62
mergekit/_data/architectures/phi2.jsonDeleted-74
mergekit/_data/architectures/phi3.jsonDeleted-50
mergekit/_data/architectures/qwen.jsonDeleted-50
mergekit/_data/architectures/qwen2.jsonDeleted-65
mergekit/_data/architectures/roberta-masked-lm.jsonDeleted-104
mergekit/_data/architectures/roberta-sequence-classification.jsonDeleted-95
mergekit/_data/architectures/roberta-token-classification.jsonDeleted-89
mergekit/_data/architectures/roberta.jsonDeleted-89
mergekit/_data/architectures/stablelm.jsonDeleted-98
mergekit/_data/architectures/stablelm2.jsonDeleted-74
mergekit/_data/architectures/starcoder2.jsonDeleted-78
mergekit/architecture.pyDeleted-378
mergekit/card.pyDeleted-239
mergekit/common.pyDeleted-290
mergekit/config.pyDeleted-210
mergekit/evo/__init__.pyDeleted
mergekit/evo/actors.pyDeleted-324
mergekit/evo/config.pyDeleted-95
mergekit/evo/genome.pyDeleted-383
mergekit/evo/helpers.pyDeleted-126
mergekit/evo/monkeypatch.pyDeleted-140
mergekit/evo/strategy.pyDeleted-301
mergekit/graph.pyDeleted-272
mergekit/io/__init__.pyDeleted-28