dbrx / .meta /create_model.py
yujiepan's picture
Upload folder using huggingface_hub
3fd45a1 verified
Raw History Blame Contribute Delete
2.25 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)
# The tiktoken-based tokenizer loads through the pinned tiktoken.py helper.
for name in (
"special_tokens_map.json",
"tokenizer_config.json",
"added_tokens.json",
"tiktoken.py",
"generation_config.json",
"LICENSE.txt",
"NOTICE.txt",
):
(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())
# DBRX is MoE in every layer: keep 16 experts and top-4 routing. The source
# GQA ratio is 6:1 (48/8); four TP=4-legal heads cannot carry that, so KV
# heads drop to 4. Per-expert FFN keeps the source 1.75x ratio (10752/6144).
config.update(
d_model=128,
n_layers=4,
n_heads=4,
max_seq_len=4096,
)
config["attn_config"]["kv_n_heads"] = 4
config["ffn_config"]["ffn_hidden_size"] = 224
config["ffn_config"]["moe_num_experts"] = 16
config["ffn_config"]["moe_top_k"] = 4
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, 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="alpindale/dbrx-instruct",
source_revision="8007650525bf3b67d6a4763caf02230061452d45",
save_folder="/tmp/dbrx",
)