"""mktinygolden.py CKPTDIR OUT.h -- goldens for tests/engine_e2e_test.cpp: transformers' own forward pass, in float32, over the tiny checkpoints tests/tiny_model.h writes. CKPTDIR holds them as the test writes them: run `RAD_E2E_KEEP=1 build/tests/engine_e2e_test` and pass the directory it prints. For each family the header records the FNV-1a hash of model.safetensors (the test refuses a golden made from other weights), the prompt, and at every position the four most likely next tokens with their log-probabilities.""" import json, os, sys import torch from safetensors.torch import load_file ckpt_dir, out = sys.argv[1], sys.argv[2] torch.manual_seed(0) PROMPT = ("the quick red cat sat under the blue tree and the slow dog ran on the stone by the " "river, then the light went dark and the cat ran") ids = list(PROMPT.encode()) TOP = 4 def fnv(path): h = 0xcbf29ce484222325 for b in open(path, "rb").read(): h = ((h ^ b) * 0x100000001b3) & (2**64 - 1) return h def load(name, build, rename=lambda k: k): d = os.path.join(ckpt_dir, name) cfg = json.load(open(os.path.join(d, "config.json"))) model = build(cfg) sd = {rename(k): v.float() for k, v in load_file(os.path.join(d, "model.safetensors")).items()} missing, unexpected = model.load_state_dict(sd, strict=False) # A tied head is the embedding; anything else missing is a naming error. missing = [k for k in missing if k != "lm_head.weight"] if missing or unexpected: raise SystemExit(f"{name}: missing {missing}, unexpected {unexpected}") model = model.float().eval() with torch.no_grad(): logits = model(torch.tensor([ids])).logits[0].float() return fnv(os.path.join(d, "model.safetensors")), torch.log_softmax(logits, dim=-1) def text_cfg(cfg, drop=("architectures",)): return {k: v for k, v in cfg.items() if k not in drop} def qwen35(cfg): from transformers import Qwen3_5ForCausalLM, Qwen3_5TextConfig c = text_cfg(cfg) c.pop("model_type", None) return Qwen3_5ForCausalLM(Qwen3_5TextConfig(**c)) def lfm2(cfg): from transformers import Lfm2ForCausalLM, Lfm2Config c = text_cfg(cfg) c.pop("model_type", None) return Lfm2ForCausalLM(Lfm2Config(**c)) def gemma4(cfg): from transformers import Gemma4ForCausalLM, Gemma4TextConfig c = dict(cfg["text_config"]) c.pop("model_type", None) return Gemma4ForCausalLM(Gemma4TextConfig(**c)) strip_lm = lambda k: k.replace("model.language_model.", "model.") runs = [("qwen35", qwen35, strip_lm), ("lfm2", lfm2, lambda k: k), ("gemma4", gemma4, strip_lm)] import transformers L = ["/* tiny_golden.h -- GENERATED by mktinygolden.py from transformers " f"{transformers.__version__}; do not edit. */", "#pragma once", "#include ", "", f"static const char kTinyGoldPrompt[] = {json.dumps(PROMPT)};", f"enum {{ kTinyGoldTop = {TOP}, kTinyGoldPositions = {len(ids)} }};", "struct TinyGold {", " const char* family;", " uint64_t weights_fnv;", " int32_t id[kTinyGoldPositions][kTinyGoldTop];", " float logp[kTinyGoldPositions][kTinyGoldTop];", "};", "static const TinyGold kTinyGold[] = {"] def rows(t, fmt): return ", ".join("{ " + ", ".join(fmt(x) for x in row) + " }" for row in t) for name, build, rename in runs: h, lp = load(name, build, rename) v, i = torch.topk(lp, TOP, dim=-1) L.append(f" {{ \"{name}\", 0x{h:016x}ull,") L.append(" { " + rows(i, lambda x: str(int(x))) + " },") L.append(" { " + rows(v, lambda x: f"{float(x):.6g}f") + " } },") L.append("};") open(out, "w").write("\n".join(L) + "\n")