def create_model(source_model_id: str, source_revision: str, save_folder: str) -> str: import json from pathlib import Path import torch from huggingface_hub import hf_hub_download from transformers import AutoConfig, AutoModelForCausalLM, set_seed folder = Path(save_folder) folder.mkdir(parents=True, exist_ok=True) for name in ( "special_tokens_map.json", "tokenizer.model", "tokenizer_config.json", "tokenization_internlm2.py", "tokenization_internlm2_fast.py", "generation_config.json", "configuration_internlm2.py", "modeling_internlm2.py", ): (folder / name).write_bytes(Path(hf_hub_download(source_model_id, name, revision=source_revision)).read_bytes()) config = json.loads(Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text()) # InternLM2 is a LLaMA-family decoder with GQA 48/8 and RoPE base 1e6. Four # TP=4-legal heads cannot carry the 6:1 Q/KV ratio, so KV heads become 4. config.update( hidden_size=128, intermediate_size=352, num_hidden_layers=4, num_attention_heads=4, num_key_value_heads=4, max_position_embeddings=4096, # The shipped fast tokenizer carries six chat special tokens beyond the # 92,544-row source checkpoint vocabulary; pad to the tokenizer length # so template token ids stay in bounds (equivalent to resize after load). vocab_size=92550, bias=False, tie_word_embeddings=True, attn_implementation="eager", ) config["auto_map"] = { "AutoConfig": "configuration_internlm2.InternLM2Config", "AutoModel": "modeling_internlm2.InternLM2ForCausalLM", "AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM", } (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n") # The pinned remote code predates the Transformers 5.x tied-weight mapping. modeling = folder / "modeling_internlm2.py" text = modeling.read_text() old_ties = ' _tied_weights_keys = ["output.weight"]\n' if old_ties in text: text = text.replace(old_ties, ' _tied_weights_keys = {"output.weight": "model.tok_embeddings.weight"}\n') if " all_tied_weights_keys = {}" not in text: text = text.replace( "class InternLM2PreTrainedModel(PreTrainedModel):\n", "class InternLM2PreTrainedModel(PreTrainedModel):\n all_tied_weights_keys = {}\n", 1, ) # Transformers 5.x removed DynamicCache legacy tuple conversion; generation # always supplies a Cache instance. Plain forward() passes None. text = text.replace( " return_legacy_cache = False\n" " if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)\n" " return_legacy_cache = True\n" " past_key_values = DynamicCache.from_legacy_cache(past_key_values)\n", " if use_cache and not isinstance(past_key_values, Cache):\n" " past_key_values = DynamicCache()\n", ) text = text.replace( " if return_legacy_cache:\n" " next_cache = next_cache.to_legacy_cache()\n", "", ) # Transformers 5.x renamed get_max_cache_shape -> get_max_length (and a # dynamic cache reports -1, i.e. no fixed maximum). old_max = ( " max_cache_length = (\n" " torch.tensor(past_key_values.get_max_cache_shape(), device=input_ids.device)\n" " if past_key_values.get_max_cache_shape() is not None\n" " else None\n" " )\n" ) new_max = ( " _max_cache_shape = (\n" " past_key_values.get_max_length()\n" " if hasattr(past_key_values, 'get_max_length')\n" " else past_key_values.get_max_cache_shape()\n" " )\n" " max_cache_length = (\n" " torch.tensor(_max_cache_shape, device=input_ids.device)\n" " if _max_cache_shape is not None and _max_cache_shape > 0\n" " else None\n" " )\n" ) assert old_max in text text = text.replace(old_max, new_max) # Transformers 5.x passes full-length position_ids into prepare_inputs; the # pinned code only sliced positions it derived itself, leaving cache_position # unsliced on decode. Always slice by the already-trimmed input length. old_input_length = ( " input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]\n" ) new_input_length = ( " if position_ids is not None and past_key_values is not None:\n" " position_ids = position_ids[:, -input_ids.shape[1] :]\n" " input_length = input_ids.shape[-1]\n" ) assert old_input_length in text text = text.replace(old_input_length, new_input_length) modeling.write_text(text) set_seed(42) model = AutoModelForCausalLM.from_config( AutoConfig.from_pretrained(folder, trust_remote_code=True), dtype=torch.bfloat16, trust_remote_code=True, ) model.save_pretrained(folder) (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n") (folder / "generation_config.json").write_bytes( Path(hf_hub_download(source_model_id, "generation_config.json", revision=source_revision)).read_bytes() ) return str(model) if __name__ == "__main__": create_model( source_model_id="internlm/internlm2-chat-20b", source_revision="d606d418463ca058a8338e6ce4ba0f200aab15c1", save_folder="/tmp/internlm2", )