AR / upload /convert_and_check.py
AjayRangoji's picture
Upload AR-4B pretraining codebase, configs, and cluster scripts
2ae6691 verified
Raw History Blame Contribute Delete
11.7 kB
"""Convert AR's trained weights into Hugging Face format (safetensors + config + tokenizer)
and prove the converted model gives the same outputs as the original.
Outputs are written to --out (one folder, ready for `huggingface-cli upload`).
Exits with an error, writing nothing publishable, if the output check fails.
The weight name map and the config shape are the only things that need to match
the trained model; both are verified below from the state_dict itself.
"""
import argparse
import json
import os
import shutil
import sys
import tempfile
# small helper so the mapping is testable without any heavy library
# train-side name -> converted name (HF-style)
def convert_key(k: str) -> str:
k = k.replace("embed.weight", "model.embed_tokens.weight")
k = k.replace("final_norm.weight", "model.norm.weight")
if k.startswith("blocks."):
k = k.replace("blocks.", "model.layers.", 1)
# per-block: attn/mlp norms and attention projections
k = k.replace(".attn_norm.weight", ".input_layernorm.weight")
k = k.replace(".mlp_norm.weight", ".post_attention_layernorm.weight")
k = k.replace(".attn.q_proj.", ".self_attn.q_proj.")
k = k.replace(".attn.k_proj.", ".self_attn.k_proj.")
k = k.replace(".attn.v_proj.", ".self_attn.v_proj.")
k = k.replace(".attn.o_proj.", ".self_attn.o_proj.")
k = k.replace(".attn.q_norm.weight", ".self_attn.q_norm.weight")
k = k.replace(".attn.k_norm.weight", ".self_attn.k_norm.weight")
k = k.replace(".mlp.", ".mlp.") # gate_proj / up_proj / down_proj keep their names
return k
def expected_shape(name, cfg):
"""Shape every weight in the trained model should have, from the config alone."""
V, D, L = cfg["vocab_size"], cfg["dim"], cfg["n_layers"]
H, KV, HD = cfg["n_heads"], cfg["n_kv_heads"], cfg["head_dim"]
I = cfg["hidden_dim"]
if name == "embed.weight" or name == "lm_head.weight":
return (V, D)
if name == "final_norm.weight":
return (D,)
if name.startswith("blocks."):
_, i, *rest = name.split(".", 2)
tail = rest[0]
shapes = {
"attn_norm.weight": (D,), "mlp_norm.weight": (D,),
"attn.q_proj.weight": (H * HD, D), "attn.k_proj.weight": (KV * HD, D),
"attn.v_proj.weight": (KV * HD, D), "attn.o_proj.weight": (D, H * HD),
"attn.q_norm.weight": (HD,), "attn.k_norm.weight": (HD,),
"mlp.gate_proj.weight": (I, D), "mlp.up_proj.weight": (I, D),
"mlp.down_proj.weight": (D, I),
}
return shapes.get(tail)
return None
def build_hf_config(cfg, eos_id, pad_id, bos_id, tokenizer_class):
"""Hugging Face config.json for our model. Field names match AutoConfig's reader."""
return {
"model_type": "ar",
"architectures": ["ARForCausalLM"],
"auto_map": {
"AutoConfig": "modeling_ar.ARConfigHF",
"AutoModelForCausalLM": "modeling_ar.ARForCausalLM",
},
"vocab_size": cfg["vocab_size"],
"hidden_size": cfg["dim"],
"intermediate_size": cfg["hidden_dim"],
"num_hidden_layers": cfg["n_layers"],
"num_attention_heads": cfg["n_heads"],
"num_key_value_heads": cfg["n_kv_heads"],
"head_dim": cfg["head_dim"],
"max_position_embeddings": cfg["max_seq_len"],
"rope_theta": cfg["rope_theta"],
"rms_norm_eps": cfg["rms_norm_eps"],
"tie_word_embeddings": cfg["tie_embeddings"],
"torch_dtype": "bfloat16",
"transformers_version": "4.40.0",
"eos_token_id": eos_id,
"bos_token_id": bos_id,
"pad_token_id": pad_id,
"tokenizer_class": tokenizer_class,
"use_cache": True,
"hidden_act": "silu",
"attention_bias": False,
"mlp_bias": False,
"initializer_range": 0.02,
}
def main():
p = argparse.ArgumentParser()
p.add_argument("--ckpt", required=True, help=".pt file written by export_ckpt.py")
p.add_argument("--out", required=True, help="output folder for the HF model")
p.add_argument("--tokenizer_src", default="/fsx/ajay-stu/hf_cache/hub",
help="where to find the tokenizer's files (uses local cache)")
p.add_argument("--tokenizer_name", default="Qwen/Qwen3-4B")
p.add_argument("--eos_id", type=int, default=151645,
help="document separator id used during training (151645 = <|im_end|>)")
p.add_argument("--check_tol", type=float, default=5e-2,
help="max per-element difference between the two forward passes (bf16 is coarse)")
p.add_argument("--skip_match_check", action="store_true",
help="skip the GPU-side output comparison (NOT recommended)")
args = p.parse_args()
import torch
from safetensors.torch import save_file
from transformers import AutoTokenizer
# 1) load the trained weights (CPU, bf16 as saved)
print(f"[1/5] loading {args.ckpt}", flush=True)
sd = torch.load(args.ckpt, map_location="cpu")
assert "embed.weight" in sd and "lm_head.weight" in sd, "unexpected checkpoint layout"
# 2) read the shape from the weights themselves, so the config always matches
V, D = sd["embed.weight"].shape
n_layers = 1 + max(int(k.split(".")[1]) for k in sd if k.startswith("blocks."))
q_out = sd["blocks.0.attn.q_proj.weight"].shape[0]
kv_out = sd["blocks.0.attn.k_proj.weight"].shape[0]
head_dim = sd["blocks.0.attn.q_norm.weight"].shape[0]
hidden_dim = sd["blocks.0.mlp.gate_proj.weight"].shape[0]
cfg = dict(vocab_size=V, dim=D, n_layers=n_layers,
n_heads=q_out // head_dim, n_kv_heads=kv_out // head_dim,
head_dim=head_dim, hidden_dim=hidden_dim,
max_seq_len=40960, rope_theta=1_000_000.0,
rms_norm_eps=1e-6, tie_embeddings=True)
print(f" shape read from weights: {cfg}", flush=True)
# every weight must have the shape the config predicts (catches silent surgery)
for k, v in sd.items():
want = expected_shape(k, cfg)
if want is None:
print(f"[warn] unknown weight {k} {tuple(v.shape)}"); continue
assert tuple(v.shape) == want, f"{k}: got {tuple(v.shape)}, expected {want}"
print(f" {len(sd)} tensors, all shapes consistent", flush=True)
# 3) rename, drop the tied head so safetensors has one copy
print(f"[3/5] converting weight names", flush=True)
out = {}
for k, v in sd.items():
# write EVERY tensor, including lm_head.weight even when tied: this transformers
# version does not re-tie on load, so lm_head would end up with random values
out[convert_key(k)] = v.contiguous()
assert "model.embed_tokens.weight" in out and "model.norm.weight" in out
assert all(not n.startswith("blocks.") for n in out), "a weight name was not converted"
assert "lm_head.weight" in out, "lm_head.weight must be in the output"
print(f" {len(out)} tensors to write (lm_head included)", flush=True)
# 4) write safetensors + config + tokenizer, atomically
print(f"[4/5] writing {args.out}", flush=True)
os.makedirs(args.out, exist_ok=True)
tmp = tempfile.mkdtemp(prefix="ar_hf_", dir=args.out)
try:
save_file(out, os.path.join(tmp, "model.safetensors"),
metadata={"format": "pt"})
tok = AutoTokenizer.from_pretrained(args.tokenizer_name, cache_dir=args.tokenizer_src)
pad_id = tok.pad_token_id if tok.pad_token_id is not None else args.eos_id
bos_id = tok.bos_token_id if tok.bos_token_id is not None else args.eos_id
tok.save_pretrained(tmp) # tokenizer.json + vocab + merges
with open(os.path.join(tmp, "config.json"), "w") as f:
json.dump(build_hf_config(cfg, args.eos_id, pad_id, bos_id, tok.__class__.__name__),
f, indent=2)
# copy the model code next to the weights (loaded by trust_remote_code=True)
src = os.path.join(os.path.dirname(__file__), "modeling_ar.py")
shutil.copy(src, os.path.join(tmp, "modeling_ar.py"))
for name in os.listdir(tmp): # atomic swap into out/
os.replace(os.path.join(tmp, name), os.path.join(args.out, name))
finally:
shutil.rmtree(tmp, ignore_errors=True)
for name in sorted(os.listdir(args.out)):
size = os.path.getsize(os.path.join(args.out, name))
print(f" {size:>12d} {name}", flush=True)
# 5) the heart of this script: both models must give the same outputs
if args.skip_match_check:
print("[5/5] SKIPPED output check (--skip_match_check); DO NOT UPLOAD yet")
return
print("[5/5] comparing outputs: original vs. converted", flush=True)
# import here so the earlier steps still run even if torch cannot load everything
sys.path.insert(0, args.out)
from transformers import AutoModelForCausalLM
from ar.model.model import ARModel
from ar.model.config import ARConfig
from ar.model.mask import build_doc_block_mask
# build the trained model and load the state dict, then run on CPU in bf16
orig_cfg = ARConfig(**cfg)
orig = ARModel(orig_cfg).to(torch.bfloat16).eval()
orig.load_state_dict(sd, strict=False) # lm_head may be tied
hf = AutoModelForCausalLM.from_pretrained(args.out, trust_remote_code=True,
torch_dtype=torch.bfloat16).eval()
torch.manual_seed(0)
ids = torch.randint(0, V, (1, 32))
seg = torch.zeros(1, 32, dtype=torch.int32)
with torch.no_grad():
mask = build_doc_block_mask(seg, 32, device=torch.device("cpu"))
y_orig = orig(ids, mask).float()
y_hf = hf(ids).logits.float()
# token-level checks (bf16 noise on raw logits is normal across 36 blocks)
top1_orig = y_orig.argmax(-1); top1_hf = y_hf.argmax(-1)
top1_match = (top1_orig == top1_hf).float().mean().item()
top5_orig = y_orig.topk(5, dim=-1).indices
top5_hf = y_hf.topk(5, dim=-1).indices
top5_match = sum(set(top5_orig[0, i].tolist()) == set(top5_hf[0, i].tolist())
for i in range(32)) / 32
# same probabilities for the trained-tokens targets (what training actually optimizes)
logp_orig = torch.log_softmax(y_orig[0], dim=-1).gather(1, ids[0, 1:].unsqueeze(1).to(y_orig.device if False else y_orig.device))
# safer: just score the next-token logprobs at every position
import torch.nn.functional as F2
nll_orig = F2.cross_entropy(y_orig.view(-1, V), ids.view(-1)).item()
nll_hf = F2.cross_entropy(y_hf.view(-1, V), ids.view(-1)).item()
diff_abs = (y_orig - y_hf).abs().max().item()
print(f" max absolute logit diff: {diff_abs:.4g} (bf16 noise, informational)")
print(f" top-1 token match: {top1_match*100:.1f}% of positions")
print(f" top-5 set match: {top5_match*100:.1f}% of positions")
print(f" cross-entropy: orig {nll_orig:.4f} hf {nll_hf:.4f} "
f"(diff {abs(nll_orig-nll_hf):.4g})")
assert top1_match >= 0.95, (
f"OUTPUT MISMATCH: top-1 token matches only {top1_match*100:.1f}% of positions "
f"(expected >= 95%). DO NOT UPLOAD. A weight was likely renamed or reshaped wrong.")
assert abs(nll_orig - nll_hf) < 0.05, (
f"OUTPUT MISMATCH: cross-entropies differ by {abs(nll_orig-nll_hf):.4g} "
f"(expected < 0.05). DO NOT UPLOAD.")
print(" output check PASSED - the converted model predicts the same tokens as the trained one")
print(f"\nREADY TO UPLOAD: {args.out}")
if __name__ == "__main__":
main()