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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Export the trained model to HuggingFace-compatible format.
|
| 3 |
+
|
| 4 |
+
Creates:
|
| 5 |
+
- model.safetensors (weights)
|
| 6 |
+
- config.json (architecture config)
|
| 7 |
+
- generation_config.json
|
| 8 |
+
- tokenizer.json, tokenizer_config.json, special_tokens_map.json
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import json
|
| 14 |
+
import torch
|
| 15 |
+
from collections import OrderedDict
|
| 16 |
+
from safetensors.torch import save_file
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 19 |
+
from model.config import ModelConfig
|
| 20 |
+
from model.transformer import Transformer
|
| 21 |
+
from model.data import get_tokenizer
|
| 22 |
+
|
| 23 |
+
CHECKPOINT = "/jfs/deepak-kumar/checkpoints_dpo/dpo_final.pt"
|
| 24 |
+
OUTPUT_DIR = "/home/jovyan/training/hf_model"
|
| 25 |
+
|
| 26 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 27 |
+
|
| 28 |
+
print("=" * 60)
|
| 29 |
+
print(" EXPORTING MODEL TO HUGGING FACE FORMAT")
|
| 30 |
+
print("=" * 60)
|
| 31 |
+
|
| 32 |
+
# --- 1. Load model ---
|
| 33 |
+
print("\n[1/4] Loading checkpoint...")
|
| 34 |
+
tokenizer = get_tokenizer()
|
| 35 |
+
special_tokens = ["<|user|>", "<|assistant|>", "<|end|>"]
|
| 36 |
+
vocab = tokenizer.get_vocab()
|
| 37 |
+
new_tokens = [t for t in special_tokens if t not in vocab]
|
| 38 |
+
if new_tokens:
|
| 39 |
+
tokenizer.add_tokens(new_tokens, special_tokens=True)
|
| 40 |
+
|
| 41 |
+
model_config = ModelConfig()
|
| 42 |
+
model_config.vocab_size = len(tokenizer)
|
| 43 |
+
|
| 44 |
+
model = Transformer(model_config)
|
| 45 |
+
ckpt = torch.load(CHECKPOINT, map_location="cpu", weights_only=False)
|
| 46 |
+
model.load_state_dict(ckpt["model"])
|
| 47 |
+
step = ckpt.get("step", 0)
|
| 48 |
+
del ckpt
|
| 49 |
+
print(f" Loaded DPO model (step {step}, vocab {model_config.vocab_size})")
|
| 50 |
+
|
| 51 |
+
# --- 2. Convert state dict keys to HF-style naming ---
|
| 52 |
+
print("\n[2/4] Converting weights to safetensors...")
|
| 53 |
+
|
| 54 |
+
state_dict = model.state_dict()
|
| 55 |
+
hf_state = OrderedDict()
|
| 56 |
+
|
| 57 |
+
KEY_MAP = {
|
| 58 |
+
"tok_embeddings.weight": "model.embed_tokens.weight",
|
| 59 |
+
"norm.weight": "model.norm.weight",
|
| 60 |
+
"output.weight": "lm_head.weight",
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
for key, tensor in state_dict.items():
|
| 64 |
+
if key in KEY_MAP:
|
| 65 |
+
hf_state[KEY_MAP[key]] = tensor
|
| 66 |
+
continue
|
| 67 |
+
|
| 68 |
+
if key.startswith("layers."):
|
| 69 |
+
parts = key.split(".")
|
| 70 |
+
layer_idx = parts[1]
|
| 71 |
+
rest = ".".join(parts[2:])
|
| 72 |
+
|
| 73 |
+
layer_map = {
|
| 74 |
+
"attention_norm.weight": f"model.layers.{layer_idx}.input_layernorm.weight",
|
| 75 |
+
"ffn_norm.weight": f"model.layers.{layer_idx}.post_attention_layernorm.weight",
|
| 76 |
+
"attention.wq.weight": f"model.layers.{layer_idx}.self_attn.q_proj.weight",
|
| 77 |
+
"attention.wk.weight": f"model.layers.{layer_idx}.self_attn.k_proj.weight",
|
| 78 |
+
"attention.wv.weight": f"model.layers.{layer_idx}.self_attn.v_proj.weight",
|
| 79 |
+
"attention.wo.weight": f"model.layers.{layer_idx}.self_attn.o_proj.weight",
|
| 80 |
+
"ffn.w_gate.weight": f"model.layers.{layer_idx}.mlp.gate_proj.weight",
|
| 81 |
+
"ffn.w_up.weight": f"model.layers.{layer_idx}.mlp.up_proj.weight",
|
| 82 |
+
"ffn.w_down.weight": f"model.layers.{layer_idx}.mlp.down_proj.weight",
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
if rest in layer_map:
|
| 86 |
+
hf_state[layer_map[rest]] = tensor
|
| 87 |
+
else:
|
| 88 |
+
print(f" WARNING: unmapped key {key}")
|
| 89 |
+
hf_state[key] = tensor
|
| 90 |
+
elif key == "freqs_cis":
|
| 91 |
+
continue
|
| 92 |
+
else:
|
| 93 |
+
print(f" WARNING: unmapped key {key}")
|
| 94 |
+
hf_state[key] = tensor
|
| 95 |
+
|
| 96 |
+
# Convert all to bfloat16 for storage
|
| 97 |
+
for k in hf_state:
|
| 98 |
+
if hf_state[k].dtype == torch.float32:
|
| 99 |
+
hf_state[k] = hf_state[k].to(torch.bfloat16)
|
| 100 |
+
|
| 101 |
+
safetensors_path = os.path.join(OUTPUT_DIR, "model.safetensors")
|
| 102 |
+
save_file(hf_state, safetensors_path)
|
| 103 |
+
size_gb = os.path.getsize(safetensors_path) / 1e9
|
| 104 |
+
print(f" Saved {len(hf_state)} tensors -> {safetensors_path} ({size_gb:.2f} GB)")
|
| 105 |
+
|
| 106 |
+
# --- 3. Write config files ---
|
| 107 |
+
print("\n[3/4] Writing config files...")
|
| 108 |
+
|
| 109 |
+
config_json = {
|
| 110 |
+
"architectures": ["LlamaForCausalLM"],
|
| 111 |
+
"model_type": "llama",
|
| 112 |
+
"vocab_size": model_config.vocab_size,
|
| 113 |
+
"hidden_size": model_config.hidden_dim,
|
| 114 |
+
"intermediate_size": model_config.intermediate_dim,
|
| 115 |
+
"num_hidden_layers": model_config.num_layers,
|
| 116 |
+
"num_attention_heads": model_config.num_attention_heads,
|
| 117 |
+
"num_key_value_heads": model_config.num_kv_heads,
|
| 118 |
+
"max_position_embeddings": model_config.max_seq_len,
|
| 119 |
+
"rope_theta": model_config.rope_theta,
|
| 120 |
+
"rms_norm_eps": model_config.rms_norm_eps,
|
| 121 |
+
"hidden_act": "silu",
|
| 122 |
+
"initializer_range": 0.02,
|
| 123 |
+
"tie_word_embeddings": False,
|
| 124 |
+
"torch_dtype": "bfloat16",
|
| 125 |
+
"transformers_version": "4.40.0",
|
| 126 |
+
"use_cache": True,
|
| 127 |
+
"bos_token_id": tokenizer.bos_token_id,
|
| 128 |
+
"eos_token_id": tokenizer.eos_token_id,
|
| 129 |
+
"pad_token_id": tokenizer.pad_token_id,
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
with open(os.path.join(OUTPUT_DIR, "config.json"), "w") as f:
|
| 133 |
+
json.dump(config_json, f, indent=2)
|
| 134 |
+
print(" config.json")
|
| 135 |
+
|
| 136 |
+
gen_config = {
|
| 137 |
+
"bos_token_id": tokenizer.bos_token_id,
|
| 138 |
+
"eos_token_id": tokenizer.eos_token_id,
|
| 139 |
+
"pad_token_id": tokenizer.pad_token_id,
|
| 140 |
+
"do_sample": True,
|
| 141 |
+
"temperature": 0.7,
|
| 142 |
+
"top_k": 50,
|
| 143 |
+
"top_p": 0.9,
|
| 144 |
+
"repetition_penalty": 1.15,
|
| 145 |
+
"max_new_tokens": 512,
|
| 146 |
+
"transformers_version": "4.40.0",
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
with open(os.path.join(OUTPUT_DIR, "generation_config.json"), "w") as f:
|
| 150 |
+
json.dump(gen_config, f, indent=2)
|
| 151 |
+
print(" generation_config.json")
|
| 152 |
+
|
| 153 |
+
# --- 4. Export tokenizer ---
|
| 154 |
+
print("\n[4/4] Exporting tokenizer...")
|
| 155 |
+
tokenizer.save_pretrained(OUTPUT_DIR)
|
| 156 |
+
print(" Tokenizer files saved")
|
| 157 |
+
|
| 158 |
+
print("\n" + "=" * 60)
|
| 159 |
+
print(" EXPORT COMPLETE -> " + OUTPUT_DIR)
|
| 160 |
+
print("=" * 60)
|
| 161 |
+
print("\nFiles:")
|
| 162 |
+
for f in sorted(os.listdir(OUTPUT_DIR)):
|
| 163 |
+
size = os.path.getsize(os.path.join(OUTPUT_DIR, f))
|
| 164 |
+
if size > 1e6:
|
| 165 |
+
print(f" {f:40s} {size/1e6:.1f} MB")
|
| 166 |
+
else:
|
| 167 |
+
print(f" {f:40s} {size/1e3:.1f} KB")
|