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

Modern-Apps.git / scripts / ml / test / test_madlad.py

test_madlad.py350 lines · 14.8 KiBRaw
1#!/usr/bin/env python3
2"""test_madlad.py - unit test for `maml_convert`'s MADLAD checkpoint path.
3
4Mirrors `test_nllb.py`: `collect_madlad` is a converter arm with no ONNX graph
5behind it, so `check_checkpoint` is the whole guard and `collect_madlad`'s emission
6*order* is the whole contract with `nets::madlad`. Both are checked here against a
7toy model of the same shape rather than the real 12 GB checkpoint, so this runs in
8a second and needs no download.
9
10What each check is defending against (NLLB's five, plus MADLAD's own):
11
12* **The transpose.** A `torch.nn.Linear` weight is `[out, in]` and a 1x1 kernel is
13 `[out, in, 1, 1]`, so a projection is a reshape. `wi_0` and `wo` are the asymmetric
14 pair that makes it loud.
15* **The order.** `nets::madlad` walks the tensor table positionally. A layer emitted
16 out of order loads cleanly and infers nonsense.
17* **The untied head appearing twice.** The input table and the logits kernel differ
18 and both are emitted; emitting one twice would halve the head's fidelity report
19 and mistranslate.
20* **The int8 triple.** `Builder::conv_int8` reads kernel, then per-output-channel
21 scale, then bias — and T5 carries no biases, so every bias here is synthesised.
22* **The fused wi_01.** GEGLU needs `[gate | up]` rows in that order; concatenating
23 them backwards still builds and still produces text.
24* **The block-0-only tables.** Two `[32, 16]` relative tables at the very end, one
25 per side. A table emitted per layer would add 126 tensors of dead weight.
26
27Run:
28 python3 scripts/ml/test/test_madlad.py
29
30Exit code 0 = all assertions passed.
31"""
32
33from __future__ import annotations
34
35import os
36import sys
37
38import numpy as np
39
40sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
41
42import maml_convert # noqa: E402 (needs the path above)
43
44TOY = {
45 "d_model": 8,
46 "heads": 2,
47 "head_dim": 4,
48 "encoder_layers": 2,
49 "decoder_layers": 2,
50 "d_ff": 16,
51 "vocab": 16,
52 "head_splits": 4,
53 "head_rows": [4, 4, 4, 4],
54 "buckets": 8,
55}
56
57passed = 0
58failed = 0
59
60
61def check(what: str, ok: bool) -> None:
62 global passed, failed
63 if ok:
64 passed += 1
65 print(f" ok {what}")
66 else:
67 failed += 1
68 print(f" FAIL {what}")
69
70
71def toy_checkpoint(spec):
72 """`(get, shapes)` for a checkpoint of `spec`'s shape, filled with distinguishable values."""
73 rng = np.random.default_rng(7)
74 held = {}
75 for name, shape in maml_convert.madlad_inventory(spec).items():
76 held[name] = rng.standard_normal(shape).astype(np.float32)
77 return held.__getitem__, {name: list(v.shape) for name, v in held.items()}
78
79
80def test_the_inventory_is_the_real_architecture() -> None:
81 print("inventory:")
82 want = maml_convert.madlad_inventory(maml_convert.CHECKPOINTS["madlad400"])
83 # 2 tables + 32 enc * 9 names + 32 dec * 14 names + 2 final norms + 2 tables:
84 # per encoder layer self norm + 4 projs + ff norm + wi_0/wi_1/wo = 9 names;
85 # per decoder layer 9 + cross norm + 4 projs = 14. No biases anywhere.
86 check("742 parameters", len(want) == 742)
87 check("decoder.embed_tokens is [vocab, d_model]", want["decoder.embed_tokens.weight"] == [256_000, 1024])
88 check("lm_head is [vocab, d_model]", want["lm_head.weight"] == [256_000, 1024])
89 check("q is [inner, d_model]", want["encoder.block.0.layer.0.SelfAttention.q.weight"] == [2048, 1024])
90 check("o is [d_model, inner]", want["encoder.block.0.layer.0.SelfAttention.o.weight"] == [1024, 2048])
91 check("wi_0 is [d_ff, d_model]", want["encoder.block.0.layer.1.DenseReluDense.wi_0.weight"] == [8192, 1024])
92 check("wo is [d_model, d_ff]", want["encoder.block.0.layer.1.DenseReluDense.wo.weight"] == [1024, 8192])
93 check(
94 "the decoder has cross-attention",
95 "decoder.block.31.layer.1.EncDecAttention.q.weight" in want,
96 )
97 check(
98 "the encoder has none",
99 "encoder.block.0.layer.1.EncDecAttention.q.weight" not in want,
100 )
101 check(
102 "the ff moves to layer.2 in the decoder",
103 "decoder.block.0.layer.2.DenseReluDense.wi_0.weight" in want,
104 )
105 check(
106 "no projection carries a bias",
107 not any(n.endswith(".bias") for n in want if ".layer_norm" not in n and "final_layer_norm" not in n),
108 )
109 check(
110 "no norm carries a bias either",
111 not any("layer_norm.bias" in n for n in want),
112 )
113 check(
114 "block-0 holds both relative tables",
115 "encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight" in want
116 and "decoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight" in want,
117 )
118 check(
119 "block-1 holds neither",
120 "encoder.block.1.layer.0.SelfAttention.relative_attention_bias.weight" not in want
121 and "decoder.block.1.layer.0.SelfAttention.relative_attention_bias.weight" not in want,
122 )
123 total = sum(int(np.prod(shape)) for shape in want.values())
124 print(f" info inventory parameters: {total}")
125
126
127def test_a_transposed_checkpoint_is_refused() -> None:
128 print("the transpose:")
129 real = maml_convert.madlad_inventory(maml_convert.CHECKPOINTS["madlad400"])
130 flipped = {
131 name: (list(reversed(shape)) if name.endswith(".weight") and len(shape) == 2 else shape)
132 for name, shape in real.items()
133 }
134 try:
135 maml_convert.check_checkpoint(flipped, "madlad400")
136 caught = ""
137 except SystemExit as exit:
138 caught = str(exit)
139 check("a transposed checkpoint is refused", bool(caught))
140 # The message shows the first few mismatches alphabetically, which are the
141 # self-attention projections — so it names the offender, not just the count.
142 check("and a projection is named in the message", "SelfAttention.q.weight" in caught)
143 maml_convert.check_checkpoint(real, "madlad400")
144 check("the real inventory is accepted", True)
145
146
147def test_the_table_order_is_the_contract() -> None:
148 print("order:")
149 get, _ = toy_checkpoint(TOY)
150 layers, tensors = maml_convert.collect_madlad(get, TOY)
151 ops = [layer.op for layer in layers]
152
153 heads = [i for i, op in enumerate(ops) if op == "Head"]
154 check("all eight head splits come first", heads == list(range(8)))
155
156 encoder = ops[8 : 8 + 8]
157 check(
158 "an encoder layer is norm, four projections, norm, fused wi_01, wo",
159 encoder == ["RmsNorm", "Linear8", "Linear8", "Linear8", "Linear8",
160 "RmsNorm", "Linear8", "Linear8"],
161 )
162 per_encoder = 8
163 at = 8 + TOY["encoder_layers"] * per_encoder
164 check("the encoder's final norm follows its layers", ops[at] == "RmsNorm")
165 decoder = ops[at + 1 : at + 1 + 13]
166 check(
167 "a decoder layer has two attentions",
168 decoder == ["RmsNorm"] + ["Linear8"] * 4 + ["RmsNorm"] + ["Linear8"] * 4
169 + ["RmsNorm", "Linear8", "Linear8"],
170 )
171 check("the decoder's final norm is followed by the tables", ops[-3] == "RmsNorm")
172 check("the two relative tables are last", ops[-2:] == ["Relative", "Relative"])
173
174 names = [layer.name for layer in layers]
175 check(
176 "the layers are named after the checkpoint",
177 names[8] == "encoder.block.0.layer.0.layer_norm",
178 )
179 check("an input-table split names its class range", names[0].endswith("[0:4]"))
180 check("an lm_head split names its table", names[4].startswith("lm_head.weight["))
181 check("the last split ends at vocab", names[7].endswith(f"[12:{TOY['vocab']}]"))
182
183 at_tensor = 0
184 contiguous = True
185 for layer in layers:
186 contiguous = contiguous and layer.first_tensor == at_tensor
187 at_tensor += layer.tensor_count
188 check("layer tensor ranges tile the table", contiguous and at_tensor == len(tensors))
189
190 # 8 head layers + 2*8 enc + 1 + 2*13 dec + 1 + 2 tables.
191 want_layers = 8 + TOY["encoder_layers"] * 8 + 1 + TOY["decoder_layers"] * 13 + 1 + 2
192 check(f"{want_layers} layers", len(layers) == want_layers)
193 want_tensors = (
194 8 * 3
195 + TOY["encoder_layers"] * 20
196 + 1
197 + TOY["decoder_layers"] * 33
198 + 1
199 + 2
200 )
201 check(f"{want_tensors} tensors", len(tensors) == want_tensors)
202
203
204def test_an_int8_layer_is_kernel_then_scale_then_bias() -> None:
205 print("the int8 triple:")
206 get, _ = toy_checkpoint(TOY)
207 layers, tensors = maml_convert.collect_madlad(get, TOY)
208
209 for index, rows in enumerate(TOY["head_rows"]):
210 head = layers[index]
211 kernel, scale, bias = tensors[head.first_tensor : head.first_tensor + 3]
212 check(f"input-table split {index} kernel [{rows}, {TOY['d_model']}, 1, 1] int8",
213 kernel.dtype == np.int8 and list(kernel.shape) == [rows, TOY["d_model"], 1, 1])
214 check(f"input-table split {index} one scale per class",
215 scale.shape == (rows,) and scale.dtype != np.int8)
216 check(f"input-table split {index} bias is synthesised zero",
217 bias.shape == (rows,) and not bias.any())
218
219 fused = next(layer for layer in layers if layer.name.endswith("wi_01"))
220 kernel, scale, bias = tensors[fused.first_tensor : fused.first_tensor + 3]
221 check(
222 f"wi_01's kernel is [{2 * TOY['d_ff']}, {TOY['d_model']}, 1, 1]",
223 list(kernel.shape) == [2 * TOY["d_ff"], TOY["d_model"], 1, 1],
224 )
225 check("with one scale per fused row", scale.shape == (2 * TOY["d_ff"],))
226 check("and a synthesised zero bias", bias.shape == (2 * TOY["d_ff"],) and not bias.any())
227
228 wo = next(layer for layer in layers if layer.name.endswith(".wo"))
229 kernel, _, bias = tensors[wo.first_tensor : wo.first_tensor + 3]
230 check(
231 f"wo's kernel is [{TOY['d_model']}, {TOY['d_ff']}, 1, 1]",
232 list(kernel.shape) == [TOY["d_model"], TOY["d_ff"], 1, 1],
233 )
234 check("with a synthesised zero bias too", not bias.any())
235
236
237def test_the_fused_halves_are_gate_then_up() -> None:
238 print("the fused halves:")
239 get, _ = toy_checkpoint(TOY)
240 held = {name: get(name) for name in maml_convert.madlad_inventory(TOY)}
241 # No marking needed: the toy fill is already distinct randoms per tensor, and
242 # random matrices are near-orthogonal — so a swapped concatenation reads as
243 # near-zero cosine rather than a subtle error.
244 layers, tensors = maml_convert.collect_madlad(held.__getitem__, TOY)
245 fused = next(layer for layer in layers if layer.name == "encoder.block.0.layer.1.DenseReluDense.wi_01")
246 kernel = tensors[fused.first_tensor]
247 scale = tensors[fused.first_tensor + 1]
248 half = TOY["d_ff"]
249 # Dequantise each half and check it reconstructs its own source — and not the
250 # other's. Random matrices are near-orthogonal, so a swapped concatenation
251 # reads as near-zero cosine rather than a subtle error.
252 import numpy as _np
253
254 def cosine(a, b):
255 a, b = a.ravel().astype(_np.float64), b.ravel().astype(_np.float64)
256 return float(a @ b / max(_np.linalg.norm(a) * _np.linalg.norm(b), 1e-30))
257
258 wi_0 = held["encoder.block.0.layer.1.DenseReluDense.wi_0.weight"].reshape(half, -1)
259 wi_1 = held["encoder.block.0.layer.1.DenseReluDense.wi_1.weight"].reshape(half, -1)
260 gate_back = kernel[:half].astype(_np.float32).reshape(half, -1) * scale[:half, None]
261 up_back = kernel[half:].astype(_np.float32).reshape(half, -1) * scale[half:, None]
262 check("gate half reconstructs wi_0", cosine(gate_back, wi_0) > 0.99)
263 check("up half reconstructs wi_1", cosine(up_back, wi_1) > 0.99)
264 check("gate half is not wi_1", abs(cosine(gate_back, wi_1)) < 0.5)
265
266
267def test_the_digest_covers_the_order() -> None:
268 print("the digest:")
269 get, _ = toy_checkpoint(TOY)
270 layers, _ = maml_convert.collect_madlad(get, TOY)
271 before = maml_convert.layer_table_digest(layers)
272 q_proj = next(i for i, layer in enumerate(layers) if layer.name.endswith("SelfAttention.q"))
273 wi_01 = next(i for i, layer in enumerate(layers) if layer.name.endswith("wi_01"))
274 swapped = list(layers)
275 swapped[q_proj], swapped[wi_01] = swapped[wi_01], swapped[q_proj]
276 check("a reordered pair changes it", maml_convert.layer_table_digest(swapped) != before)
277 check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before)
278
279
280def test_q2k_block_transcription_is_candle_exact() -> None:
281 print("the Q2_K block:")
282 # A hand-built superblock: scales 0..15, quants 0..63, d=1.5, dmin=0.5 (fp16).
283 # Both transcriptions must agree bit-exactly — a lane/shift/scale slip changes values.
284 import struct
285
286 scales = bytes(range(16))
287 qs = bytes(range(64))
288 payload = scales + qs + struct.pack("<e", 1.5) + struct.pack("<e", 0.5)
289 assert len(payload) == 84
290 mine = maml_convert.q2k_to_float(payload, [1, 256], [1, 256])
291 indep = q2k_reference(payload, 1, 256)
292 check("converter and independent transcription agree", bool((mine == indep).all()))
293 # Spot values by hand: lane 0 (scales[0]=0: lo=0, hi=0) is all zeros;
294 # lane 1 (scales[1]=1: lo=1, hi=0): y = 2.25 * q, q = qs[l]>>2&3.
295 check("a zero-scale lane is zeros", bool((mine[16:32] == 0).all()))
296 # Orientation: out is [rows, taps] with torch flat == GGUF flat.
297 check("shape is [1, 256]", list(mine.shape) == [1, 256])
298
299
300def q2k_reference(payload, rows, taps):
301 """Independent Q2_K transcription (no shared code with `q2k_to_float`).
302
303 Written directly from candle's `BlockQ2K::to_float`; shares only the format constants.
304 """
305 import struct
306
307 out = np.empty((rows, taps), dtype=np.float32)
308 blocks = taps // maml_convert.Q2K_BLOCK
309 for r in range(rows):
310 for b in range(blocks):
311 blk = payload[(r * blocks + b) * 84 : (r * blocks + b + 1) * 84]
312 scales = list(blk[:16])
313 qs = list(blk[16:80])
314 d = struct.unpack("<e", bytes(blk[80:82]))[0]
315 dmin = struct.unpack("<e", bytes(blk[82:84]))[0]
316 is_ = 0
317 for half in range(2):
318 hq = qs[half * 32 : half * 32 + 32]
319 shift = 0
320 for lane in range(4):
321 lo, hi = scales[is_] & 0xF, scales[is_] >> 4
322 is_ += 1
323 for l in range(16):
324 out[r, b * 256 + half * 128 + lane * 32 + l] = (
325 d * (((hq[l] >> shift) & 3) * lo) - dmin * hi
326 )
327 lo, hi = scales[is_] & 0xF, scales[is_] >> 4
328 is_ += 1
329 for l in range(16):
330 out[r, b * 256 + half * 128 + lane * 32 + 16 + l] = (
331 d * (((hq[16 + l] >> shift) & 3) * lo) - dmin * hi
332 )
333 shift += 2
334 return out
335
336
337def main() -> int:
338 test_the_inventory_is_the_real_architecture()
339 test_a_transposed_checkpoint_is_refused()
340 test_the_table_order_is_the_contract()
341 test_an_int8_layer_is_kernel_then_scale_then_bias()
342 test_the_fused_halves_are_gate_then_up()
343 test_the_digest_covers_the_order()
344 test_q2k_block_transcription_is_candle_exact()
345 print(f"\n{passed} passed, {failed} failed")
346 return 1 if failed else 0
347
348
349if __name__ == "__main__":
350 raise SystemExit(main())