mamba2 / .meta /create_model.py
yujiepan's picture
Upload folder using huggingface_hub
3661070 verified
Raw History Blame Contribute Delete
2.05 kB
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.model",
"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())
# Mamba2 requires hidden*expand == num_heads*head_dim. Source keeps head_dim
# 64 and state 128, which are scan-kernel dimensions: 128*2 = 4 heads * 64.
# n_groups divides num_heads; dt rank (8) divides num_heads for the reshape.
config.update(
hidden_size=128,
intermediate_size=256,
num_hidden_layers=4,
num_heads=4,
head_dim=64,
n_groups=4,
state_size=128,
conv_kernel=4,
expand=2,
chunk_size=256,
time_step_rank=8,
tie_word_embeddings=False,
)
(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="mistralai/Mamba-Codestral-7B-v0.1",
source_revision="4f086c08c1e0f07bdc50ca25125dbbf7475d21da",
save_folder="/tmp/mamba2",
)