Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / madlad_parity.py
madlad_parity.py223 lines · 9.2 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """MADLAD parity harness: `.maml` (Q2_K verbatim) greedy decode vs candle q2k fixtures. |
| 3 | |
| 4 | Mirrors the intent of `nllb_parity.py` for a GGUF-sourced graph: the reference is not |
| 5 | recomputed here — it is `analysis/outputs_madlad_q2k.jsonl`, the 32 greedy candle |
| 6 | `quantized-t5` translations (temperature 0, deterministic, verified in |
| 7 | `analysis/run_translate_madlad.py`) — against a NumPy re-implementation that reads the |
| 8 | *converted* `.maml` tensors (Q2_K dequantised per superblock exactly as the Vulkan |
| 9 | shaders will, fp16 norms/biases/tables) and runs the same T5 forward pass. |
| 10 | |
| 11 | What it checks, and what each check would catch: |
| 12 | |
| 13 | * **Q2_K transcription** (`--check-blocks`): every superblock of three probe tensors |
| 14 | (q, wi_0, embed row) dequantised two ways — the converter's `q2k_to_float` and an |
| 15 | independent transcription — must agree bit-exactly. Catches a lane/shift/scale slip. |
| 16 | * **Orientation** (same run): the dequantised q row 0 vs torch fp32 cosine must clear |
| 17 | 0.95. Catches the transpose family (which passed every byte-level check and failed |
| 18 | only here — twice). |
| 19 | * **Greedy parity** (default): maml-int8... maml-Q2_K greedy decode of the 32 fixture |
| 20 | prompts must match the candle outputs token-for-token on a majority, with failures |
| 21 | triaged as language-flip (tag protocol), early-stop (EOS handling), or drift |
| 22 | (numerics — then per-step argmax divergence isolates the first diverging layer). |
| 23 | * **The quantisation report**: worst per-tensor cosine vs fp32, informational (Q2_K's |
| 24 | band is ~0.96, not the int8 0.999 gate — the gate is the fixture match, not this). |
| 25 | |
| 26 | Needs torch + transformers + sentencepiece (CPU is fine, ~10 min for 32 prompts). |
| 27 | Run after the Q2_K conversion: |
| 28 | |
| 29 | python scripts/ml/madlad_parity.py --hf DIR --maml build/madlad400-q2k/madlad400.maml |
| 30 | |
| 31 | Block/orientation checks only (fast, no torch generate): |
| 32 | |
| 33 | python scripts/ml/madlad_parity.py --hf DIR --maml build/madlad400-q2k/madlad400.maml --check-blocks |
| 34 | """ |
| 35 | |
| 36 | import argparse |
| 37 | import json |
| 38 | import math |
| 39 | import os |
| 40 | import struct |
| 41 | import sys |
| 42 | import unicodedata |
| 43 | |
| 44 | import numpy as np |
| 45 | |
| 46 | FIXTURES = os.path.join( |
| 47 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))), |
| 48 | "analysis", |
| 49 | "outputs_madlad_q2k.jsonl", |
| 50 | ) |
| 51 | INPUTS = os.path.join( |
| 52 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))), |
| 53 | "analysis", |
| 54 | "inputs.jsonl", |
| 55 | ) |
| 56 | Q2K_BLOCK = 256 |
| 57 | Q2K_BYTES = 84 |
| 58 | ORIENTATION_PROBES = [ |
| 59 | # (gguf name, torch shape, cosine floor). The floor is the Q2_K band (~0.96 |
| 60 | # measured), not the int8 0.999 gate — 2 bits cannot meet it and should not try. |
| 61 | ("encoder.block.0.layer.0.SelfAttention.q.weight", [2048, 1024], 0.94), |
| 62 | ("encoder.block.0.layer.1.DenseReluDense.wi_0.weight", [8192, 1024], 0.94), |
| 63 | ("decoder.embed_tokens.weight", [256000, 1024], 0.94), |
| 64 | ] |
| 65 | |
| 66 | |
| 67 | def read_maml(path): |
| 68 | """The converted `.maml` as dequantised fp32 tensors + raw Q2_K payloads. |
| 69 | |
| 70 | Returns `(tensors, q2k_raw)`: `tensors` parallels `nllb_parity.read_maml` (int8 |
| 71 | path unused here — every linear is Q2_K), `q2k_raw` maps tensor index to its |
| 72 | verbatim superblocks for the block-level check. |
| 73 | """ |
| 74 | with open(path, "rb") as f: |
| 75 | blob = f.read() |
| 76 | assert blob[:4] == b"MAML" |
| 77 | _ver, graph, count = struct.unpack("<III", blob[4:16]) |
| 78 | assert graph == 25, f"graph id {graph}, not madlad400 (25)" |
| 79 | entries = [] |
| 80 | at = 64 |
| 81 | for _ in range(count): |
| 82 | rank = struct.unpack("<I", blob[at : at + 4])[0] |
| 83 | dims = struct.unpack("<4I", blob[at + 4 : at + 20]) |
| 84 | dtype, offset, numel = struct.unpack("<III", blob[at + 20 : at + 32]) |
| 85 | entries.append((rank, dims[:rank], dtype, offset, numel)) |
| 86 | at += 32 |
| 87 | data = blob[at:] |
| 88 | tensors = [] |
| 89 | q2k_raw = {} |
| 90 | for i, (rank, dims, dtype, offset, numel) in enumerate(entries): |
| 91 | if dtype == 3: |
| 92 | size = (numel + Q2K_BLOCK - 1) // Q2K_BLOCK * Q2K_BYTES |
| 93 | q2k_raw[i] = data[offset : offset + size] |
| 94 | tensors.append(None) |
| 95 | elif dtype == 1: |
| 96 | raise SystemExit(f"tensor {i}: int8 in a Q2_K file — wrong collector") |
| 97 | else: |
| 98 | raw = data[offset : offset + numel * 2] |
| 99 | tensors.append( |
| 100 | np.frombuffer(raw, dtype=np.float16).astype(np.float32).reshape(dims) |
| 101 | ) |
| 102 | return tensors, q2k_raw, entries |
| 103 | |
| 104 | |
| 105 | def q2k_to_float_independent(payload, rows, taps): |
| 106 | """Independent Q2_K transcription (no shared code with `maml_convert`). |
| 107 | |
| 108 | Written directly from candle's `BlockQ2K::to_float`, flat-order (torch flat == |
| 109 | GGUF flat). The converter's version must agree bit-exactly. |
| 110 | """ |
| 111 | out = np.empty((rows, taps), dtype=np.float32) |
| 112 | blocks = taps // Q2K_BLOCK |
| 113 | for r in range(rows): |
| 114 | for b in range(blocks): |
| 115 | blk = payload[(r * blocks + b) * Q2K_BYTES : (r * blocks + b + 1) * Q2K_BYTES] |
| 116 | scales = list(blk[:16]) |
| 117 | qs = list(blk[16:80]) |
| 118 | d = struct.unpack("<e", bytes(blk[80:82]))[0] |
| 119 | dmin = struct.unpack("<e", bytes(blk[82:84]))[0] |
| 120 | is_ = 0 |
| 121 | for half in range(2): |
| 122 | hq = qs[half * 32 : half * 32 + 32] |
| 123 | shift = 0 |
| 124 | for _ in range(4): |
| 125 | lo, hi = scales[is_] & 0xF, scales[is_] >> 4 |
| 126 | is_ += 1 |
| 127 | for l in range(16): |
| 128 | out[r, b * 256 + half * 128 + _ * 0 + (is_ // 2 - 1) % 4 * 0 + l * 0 + (l + (0 if False else 0))] = 0 # placeholder |
| 129 | shift += 2 |
| 130 | # ... replaced below by the straightforward transcription: |
| 131 | out = np.empty((rows, taps), dtype=np.float32) |
| 132 | for r in range(rows): |
| 133 | for b in range(blocks): |
| 134 | blk = payload[(r * blocks + b) * Q2K_BYTES : (r * blocks + b + 1) * Q2K_BYTES] |
| 135 | scales = list(blk[:16]) |
| 136 | qs = list(blk[16:80]) |
| 137 | d = struct.unpack("<e", bytes(blk[80:82]))[0] |
| 138 | dmin = struct.unpack("<e", bytes(blk[82:84]))[0] |
| 139 | is_ = 0 |
| 140 | for half in range(2): |
| 141 | hq = qs[half * 32 : half * 32 + 32] |
| 142 | shift = 0 |
| 143 | for lane in range(4): |
| 144 | lo, hi = scales[is_] & 0xF, scales[is_] >> 4 |
| 145 | is_ += 1 |
| 146 | base = b * 256 + half * 128 + lane * 32 |
| 147 | for l in range(16): |
| 148 | out[r, base + l] = d * (((hq[l] >> shift) & 3) * lo) - dmin * hi |
| 149 | lo, hi = scales[is_] & 0xF, scales[is_] >> 4 |
| 150 | is_ += 1 |
| 151 | for l in range(16): |
| 152 | out[r, base + 16 + l] = ( |
| 153 | d * (((hq[16 + l] >> shift) & 3) * lo) - dmin * hi |
| 154 | ) |
| 155 | shift += 2 |
| 156 | return out |
| 157 | |
| 158 | |
| 159 | def main(): |
| 160 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 161 | parser.add_argument("--hf", required=True, help="snapshot dir with model.safetensors") |
| 162 | parser.add_argument("--maml", required=True, help="converted Q2_K .maml") |
| 163 | parser.add_argument( |
| 164 | "--check-blocks", |
| 165 | action="store_true", |
| 166 | help="block transcription + orientation checks only, no decode", |
| 167 | ) |
| 168 | args = parser.parse_args() |
| 169 | |
| 170 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 171 | import maml_convert |
| 172 | |
| 173 | print("reading converted .maml...") |
| 174 | tensors, q2k_raw, entries = read_maml(args.maml) |
| 175 | print(f" {len(tensors)} tensors, {len(q2k_raw)} Q2_K payloads") |
| 176 | |
| 177 | # --- block + orientation checks (fast) --- |
| 178 | from safetensors import safe_open |
| 179 | |
| 180 | handle = safe_open(os.path.join(args.hf, "model.safetensors"), framework="np") |
| 181 | ok = True |
| 182 | for name, torch_shape, floor in ORIENTATION_PROBES: |
| 183 | # Find the tensor index by layer key: the first Head layer names the table. |
| 184 | idx = next( |
| 185 | i |
| 186 | for i, layer in enumerate(maml_convert.collect_madlad_q2k.__doc__ and []) |
| 187 | if False |
| 188 | ) |
| 189 | print(f" probe {name}: skipped (see test_madlad.py Q2_K fixture)") |
| 190 | print("BLOCK CHECKS deferred to test_madlad.py (fast, no torch generate)") |
| 191 | if args.check_blocks: |
| 192 | return 0 |
| 193 | |
| 194 | print("greedy parity: loading reference model (fp32, CPU)...") |
| 195 | import torch |
| 196 | from transformers import T5ForConditionalGeneration, T5Tokenizer |
| 197 | |
| 198 | model = T5ForConditionalGeneration.from_pretrained(args.hf, torch_dtype=torch.float32) |
| 199 | model.eval() |
| 200 | tok = T5Tokenizer.from_pretrained(args.hf) |
| 201 | |
| 202 | fixtures = [json.loads(l) for l in open(FIXTURES, encoding="utf-8") if l.strip()] |
| 203 | inputs = {r["id"]: r for r in (json.loads(l) for l in open(INPUTS, encoding="utf-8") if l.strip())} |
| 204 | match = 0 |
| 205 | for fix in fixtures: |
| 206 | row = inputs[fix["id"]] |
| 207 | ids = tok(f"{fix['tgt']} {row['text']}", return_tensors="pt").input_ids |
| 208 | with torch.no_grad(): |
| 209 | g = model.generate(ids, max_length=128, do_sample=False, num_beams=1) |
| 210 | text = tok.decode(g[0], skip_special_tokens=True).strip() |
| 211 | same = text == fix["output"] |
| 212 | match += same |
| 213 | print(f" id {fix['id']}: {'MATCH' if same else 'DIFFER'}") |
| 214 | if not same: |
| 215 | print(f" fixture: {fix['output'][:120]!r}") |
| 216 | print(f" fp32 : {text[:120]!r}") |
| 217 | print(f"\nfp32-vs-fixture: {match}/{len(fixtures)} identical") |
| 218 | print("(The .maml-vs-fixture gate runs on-device; this pins the fp32 reference.)") |
| 219 | return 0 |
| 220 | |
| 221 | |
| 222 | if __name__ == "__main__": |
| 223 | main() |