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.json", "tokenizer_config.json", "generation_config.json", ): (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()) # Falcon modeling requires head_dim * num_heads == hidden_size, so head_dim 32 # fixes hidden at 4 heads. The 40B uses 8 KV heads (16:1 GQA); the smallest # TP=4-legal layout keeps four heads and four KV heads. Structural flags of # the 40B (new decoder arch, parallel attention, no biases, rotary) stay. config.update( hidden_size=128, num_hidden_layers=4, num_attention_heads=4, num_kv_heads=4, tie_word_embeddings=True, ) config.pop("auto_map", None) (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n") set_seed(42) model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(folder), dtype=torch.bfloat16) 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="tiiuae/falcon-40b", source_revision="05ab2ee8d6b593bdbab17d728de5c028a7a94d83", save_folder="/tmp/falcon", )