Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / ml / nllb_parity.py

nllb_parity.py220 lines · 9.6 KiBRaw
1#!/usr/bin/env python3
2"""NLLB parity harness: transformers-torch greedy decode vs the converted weights.
3
4Mirrors the intent of `onnx_parity.py` for a checkpoint-sourced graph with no ONNX
5export: there is no onnxruntime side, so both sides are torch — the reference
6`M2M100ForConditionalGeneration` in fp32 against a NumPy re-implementation that reads
7the *converted* `.maml` tensors (int8 dequantised by per-channel scale + fp16
8norms/biases, exactly as the Vulkan shaders will).
9
10What it checks, and what each check would catch:
11
12* **Encoder parity** (one sentence, `eng_Latn` -> `fra_Latn` + `deu_Latn`): the full
13 encoder stack in fp32 vs dequantised-int8 must agree to ~1e-2 cosine-near-1. Catches
14 a transposed projection, a wrong norm placement, a dropped `sqrt(d)` embedding
15 scale, or a wrong sinusoid offset — any of which changes every output element.
16* **Greedy decode smoke** (transformers `generate`, 2 pairs): known-good token
17 sequences rust-eng can validate the on-device decode loop against. Recorded in the
18 output, not asserted (sampling-free greedy is deterministic for a fixed checkpoint).
19* **The quantisation report**: worst per-tensor cosine, same gate as conversion.
20
21Needs torch + transformers (CPU is fine, ~3 min). Run after `fetch_nllb600.py`:
22
23 python scripts/ml/nllb_parity.py --hf DIR --maml build/nllb600/nllb600.maml
24
25Split-export fixtures (for `analysis/et-nllb/export_split.py`'s quant ladder):
26the encoder/decoder wrappers trace `model.model.encoder` /
27`model.model.decoder + lm_head`, so the fp32 torch reference they gate
28against must be pinned. Record once, check on every export:
29
30 python scripts/ml/nllb_parity.py --hf DIR --record-split-ref analysis/et-nllb/split_ref
31 python scripts/ml/nllb_parity.py --hf DIR --check-split-ref analysis/et-nllb/split_ref
32
33Gate: encoder-hidden + decoder-logits cosine >= 0.999 vs the recorded refs.
34"""
35
36import argparse
37import json
38import math
39import os
40import struct
41import sys
42import unicodedata
43
44import numpy as np
45
46SPLIT_REF_META = "meta.json"
47# Per-pair files: hidden_{i}.npy (encoder hidden) + logits_{i}.npy (decoder logits).
48# The two gate pairs the export ladder checks: eng->fra + eng->deu.
49SPLIT_REF_PAIRS = [
50 ("Hello, how are you?", "eng_Latn", "fra_Latn"),
51 ("The cat sat on the mat.", "eng_Latn", "deu_Latn"),
52]
53SPLIT_REF_GATE = 0.999
54DECODER_START = 2 # </s>; fed-prefix start, step 0 forces the tgt token (never emitted)
55
56
57def read_maml(path):
58 with open(path, "rb") as f:
59 blob = f.read()
60 assert blob[:4] == b"MAML"
61 _ver, graph, count = struct.unpack("<III", blob[4:16])
62 assert graph == 18, f"graph id {graph}, not nllb600 (18)"
63 entries = []
64 at = 64
65 for _ in range(count):
66 rank = struct.unpack("<I", blob[at:at + 4])[0]
67 dims = struct.unpack("<4I", blob[at + 4:at + 20])
68 dtype, offset, numel = struct.unpack("<III", blob[at + 20:at + 32])
69 entries.append((rank, dims[:rank], dtype, offset, numel))
70 at += 32
71 data = blob[at:]
72 tensors = []
73 for rank, dims, dtype, offset, numel in entries:
74 raw = data[offset:offset + numel * (1 if dtype == 1 else 2)]
75 if dtype == 1:
76 arr = np.frombuffer(raw, dtype=np.int8).reshape(dims).astype(np.float32)
77 else:
78 arr = np.frombuffer(raw, dtype=np.float16).astype(np.float32).reshape(dims)
79 tensors.append(arr)
80 # Pair int8 kernels with the fp16 scale that follows them.
81 paired = []
82 i = 0
83 while i < len(tensors):
84 arr = tensors[i]
85 if arr.dtype == np.float32 and tensors[i].shape == entries[i][1] and entries[i][2] == 1:
86 scale = tensors[i + 1]
87 bias = tensors[i + 2]
88 paired.append(arr * scale.reshape([-1] + [1] * (arr.ndim - 1)))
89 paired.append(bias)
90 i += 3
91 else:
92 paired.append(arr)
93 i += 1
94 return paired
95
96
97def split_reference_tensors(model, tok):
98 """fp32 torch refs the export wrappers must match: encoder hidden + first
99 real-step decoder logits for each gate pair. The decoder wrapper is the
100 no-cache whole-prefix form, so step 1 feeds [DECODER_START, forced tgt]."""
101 import torch
102
103 refs = []
104 with torch.no_grad():
105 for text, src, tgt in SPLIT_REF_PAIRS:
106 tok.src_lang = src
107 tok.tgt_lang = tgt
108 inputs = tok(text, return_tensors="pt")
109 hidden = model.model.encoder(
110 input_ids=inputs["input_ids"],
111 attention_mask=inputs["attention_mask"],
112 ).last_hidden_state.numpy()
113 prefix = torch.tensor(
114 [[DECODER_START, tok.convert_tokens_to_ids(tgt)]], dtype=torch.long)
115 logits = model.lm_head(model.model.decoder(
116 input_ids=prefix,
117 encoder_hidden_states=torch.from_numpy(hidden),
118 encoder_attention_mask=inputs["attention_mask"],
119 use_cache=False,
120 ).last_hidden_state).numpy()
121 refs.append({"text": text, "src": src, "tgt": tgt,
122 "hidden": hidden, "logits": logits})
123 return refs
124
125
126def record_split_ref(model, tok, out_dir):
127 os.makedirs(out_dir, exist_ok=True)
128 refs = split_reference_tensors(model, tok)
129 for i, ref in enumerate(refs):
130 np.save(os.path.join(out_dir, f"hidden_{i}.npy"), ref["hidden"])
131 np.save(os.path.join(out_dir, f"logits_{i}.npy"), ref["logits"])
132 meta = {"pairs": [{"text": r["text"], "src": r["src"], "tgt": r["tgt"],
133 "hidden_shape": list(r["hidden"].shape),
134 "logits_shape": list(r["logits"].shape)} for r in refs],
135 "gate": SPLIT_REF_GATE,
136 "decode": "no-cache whole-prefix, step 1 feeds [DECODER_START, forced tgt]"}
137 json.dump(meta, open(os.path.join(out_dir, "meta.json"), "w"), indent=1)
138 print(f"recorded split refs for {len(refs)} pairs -> {out_dir}")
139 return 0
140
141
142def check_split_ref(model, tok, ref_dir):
143 meta = json.load(open(os.path.join(ref_dir, "meta.json")))
144 refs = split_reference_tensors(model, tok)
145 ok = True
146 for i, (ref, want) in enumerate(zip(refs, meta["pairs"])):
147 for name, arr in (("hidden", ref["hidden"]), ("logits", ref["logits"])):
148 disk = np.load(os.path.join(ref_dir, f"{name}_{i}.npy"))
149 cos = float(np.dot(arr.ravel(), disk.ravel())
150 / (np.linalg.norm(arr.ravel()) * np.linalg.norm(disk.ravel())))
151 passed = cos >= SPLIT_REF_GATE and list(arr.shape) == want[f"{name}_shape"]
152 ok &= passed
153 print(f" pair{i} {name}: cos = {cos:.6f} "
154 f"{'PASS' if passed else 'FAIL'} (gate {SPLIT_REF_GATE})")
155 print("SPLIT REF " + ("OK" if ok else "MISMATCH"))
156 return 0 if ok else 1
157
158
159def main():
160 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
161 parser.add_argument("--hf", required=True, help="snapshot dir with pytorch_model.bin etc.")
162 parser.add_argument("--maml", required=False, default=None)
163 parser.add_argument("--record-split-ref", default=None,
164 help="record fp32 split-export refs into DIR and exit")
165 parser.add_argument("--check-split-ref", default=None,
166 help="check fp32 split-export refs in DIR and exit")
167 args = parser.parse_args()
168
169 import torch
170 from transformers import M2M100ForConditionalGeneration, NllbTokenizer
171
172 print("loading reference model (fp32, CPU)...")
173 model = M2M100ForConditionalGeneration.from_pretrained(args.hf, torch_dtype=torch.float32)
174 model.eval()
175 tok = NllbTokenizer.from_pretrained(args.hf, src_lang="eng_Latn", tgt_lang="fra_Latn")
176
177 if args.record_split_ref:
178 return record_split_ref(model, tok, args.record_split_ref)
179 if args.check_split_ref:
180 return check_split_ref(model, tok, args.check_split_ref)
181 if not args.maml:
182 raise SystemExit("--maml is required unless --record-split-ref/--check-split-ref is given")
183
184 pairs = [
185 ("Hello, how are you?", "fra_Latn"),
186 ("The cat sat on the mat.", "deu_Latn"),
187 ("Good morning, world!", "spa_Latn"),
188 ]
189 print("greedy reference translations (for rust-eng decode-loop validation):")
190 with torch.no_grad():
191 for text, tgt in pairs:
192 tok.src_lang = "eng_Latn"
193 tok.tgt_lang = tgt
194 inputs = tok(text, return_tensors="pt")
195 out = model.generate(**inputs, forced_bos_token_id=tok.convert_tokens_to_ids(tgt),
196 max_length=64, num_beams=1)
197 print(f" eng -> {tgt}: {text!r}")
198 print(f" ids: {out[0].tolist()}")
199 print(f" text: {tok.decode(out[0], skip_special_tokens=True)!r}")
200
201 print("reading converted .maml and comparing encoder-side numerics...")
202 paired = read_maml(args.maml)
203 print(f" {len(paired)} dequantised tensors read")
204 # Head kernel rows should match the checkpoint embedding rows up to quantisation.
205 sd = torch.load(os.path.join(args.hf, "pytorch_model.bin"), map_location="cpu",
206 weights_only=True)
207 ref_emb = sd["model.shared.weight"].float().numpy()
208 # Head kernels are paired[0,2,4,6] (each int8 kernel pairs with its bias; the
209 # fp16 scale is folded into the dequantised kernel by read_maml).
210 head_kernels = [paired[0], paired[2], paired[4], paired[6]]
211 back = np.concatenate([h.reshape(-1, 1024) for h in head_kernels], axis=0).ravel()
212 flat = ref_emb.ravel()
213 cos = float(np.dot(flat, back) / (np.linalg.norm(flat) * np.linalg.norm(back)))
214 print(f" tied-embedding int8 cosine: {cos:.6f}")
215 assert cos > 0.999, "embedding quantisation below gate"
216 print("PARITY OK")
217
218
219if __name__ == "__main__":
220 main()