#!/usr/bin/env python3 """NLLB parity harness: transformers-torch greedy decode vs the converted weights. Mirrors the intent of `onnx_parity.py` for a checkpoint-sourced graph with no ONNX export: there is no onnxruntime side, so both sides are torch — the reference `M2M100ForConditionalGeneration` in fp32 against a NumPy re-implementation that reads the *converted* `.maml` tensors (int8 dequantised by per-channel scale + fp16 norms/biases, exactly as the Vulkan shaders will). What it checks, and what each check would catch: * **Encoder parity** (one sentence, `eng_Latn` -> `fra_Latn` + `deu_Latn`): the full encoder stack in fp32 vs dequantised-int8 must agree to ~1e-2 cosine-near-1. Catches a transposed projection, a wrong norm placement, a dropped `sqrt(d)` embedding scale, or a wrong sinusoid offset — any of which changes every output element. * **Greedy decode smoke** (transformers `generate`, 2 pairs): known-good token sequences rust-eng can validate the on-device decode loop against. Recorded in the output, not asserted (sampling-free greedy is deterministic for a fixed checkpoint). * **The quantisation report**: worst per-tensor cosine, same gate as conversion. Needs torch + transformers (CPU is fine, ~3 min). Run after `fetch_nllb600.py`: python scripts/ml/nllb_parity.py --hf DIR --maml build/nllb600/nllb600.maml Split-export fixtures (for `analysis/et-nllb/export_split.py`'s quant ladder): the encoder/decoder wrappers trace `model.model.encoder` / `model.model.decoder + lm_head`, so the fp32 torch reference they gate against must be pinned. Record once, check on every export: python scripts/ml/nllb_parity.py --hf DIR --record-split-ref analysis/et-nllb/split_ref python scripts/ml/nllb_parity.py --hf DIR --check-split-ref analysis/et-nllb/split_ref Gate: encoder-hidden + decoder-logits cosine >= 0.999 vs the recorded refs. """ import argparse import json import math import os import struct import sys import unicodedata import numpy as np SPLIT_REF_META = "meta.json" # Per-pair files: hidden_{i}.npy (encoder hidden) + logits_{i}.npy (decoder logits). # The two gate pairs the export ladder checks: eng->fra + eng->deu. SPLIT_REF_PAIRS = [ ("Hello, how are you?", "eng_Latn", "fra_Latn"), ("The cat sat on the mat.", "eng_Latn", "deu_Latn"), ] SPLIT_REF_GATE = 0.999 DECODER_START = 2 # ; fed-prefix start, step 0 forces the tgt token (never emitted) def read_maml(path): with open(path, "rb") as f: blob = f.read() assert blob[:4] == b"MAML" _ver, graph, count = struct.unpack("