Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / test / test_maia.py
test_maia.py352 lines · 14.8 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """test_maia.py - unit test for `maml_convert`'s Maia3 checkpoint path. |
| 3 | |
| 4 | Mirrors `test_nllb.py`: `collect_maia` is a converter arm with no ONNX graph behind it, so |
| 5 | `check_checkpoint` is the whole guard and `collect_maia`'s emission *order* is the whole |
| 6 | contract with `nets::maia`. Both are checked here against a toy model of the same shape |
| 7 | rather than the real 20 MB checkpoint, so this runs in a second and needs no download. |
| 8 | |
| 9 | What each check is defending against: |
| 10 | |
| 11 | * **The transpose.** A `torch.nn.Linear` weight is `[out, in]` and a 1x1 kernel is |
| 12 | `[out, in, 1, 1]`, so a projection is a reshape. `linear1` and `linear2` are the |
| 13 | asymmetric pair that makes it loud. |
| 14 | * **The order.** `nets::maia` walks the tensor table positionally. A layer emitted out of |
| 15 | order loads cleanly and plays nonsense. |
| 16 | * **The int8 triple.** `Builder::conv_int8` reads kernel, then per-output-channel scale, |
| 17 | then bias — three tensors where the fp16 path read two, which is what moved the layout |
| 18 | from 190 tensors to 259. |
| 19 | * **The q/k/v split.** Torch packs them into one `[3d, d]` `in_proj_weight`; the three |
| 20 | slices must come out in that order, each with its own scale vector, and each must get a |
| 21 | synthesised zero bias because `omit_qkv_biases=True` and `conv_int8` always reads one. |
| 22 | * **The RMS norms emitting one tensor, not two.** They have a gain and no beta. Emitting a |
| 23 | beta would shift every index after it by one and the Rust would read gammas as kernels. |
| 24 | * **The attention-bias replication.** `nets::maia` reads the shared `[4096, 64]` weight as a |
| 25 | grouped convolution's `[32768, 64, 1, 1]` kernel; group `g` must find a full copy at rows |
| 26 | `g*4096..`, which is what `np.tile` along axis 0 gives and what a `np.repeat` would not. |
| 27 | Its scale vector has to be tiled the same way. |
| 28 | |
| 29 | Run: |
| 30 | python3 scripts/ml/test/test_maia.py |
| 31 | |
| 32 | Exit code 0 = all assertions passed. |
| 33 | """ |
| 34 | |
| 35 | from __future__ import annotations |
| 36 | |
| 37 | import os |
| 38 | import sys |
| 39 | |
| 40 | import numpy as np |
| 41 | |
| 42 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 43 | |
| 44 | import maml_convert # noqa: E402 (needs the path above) |
| 45 | |
| 46 | # A two-block model of the same shape. `squares` stays 64 because the attention bias's |
| 47 | # `[64, 64]` map is not a free parameter — it is the board. |
| 48 | TOY = { |
| 49 | "d_model": 8, |
| 50 | "blocks": 2, |
| 51 | "heads": 2, |
| 52 | "ffn": 16, |
| 53 | "head_hidden": 8, |
| 54 | "bias_hidden": 4, |
| 55 | "bias_gen": 6, |
| 56 | "elo_dim": 5, |
| 57 | "input": 12 * 8 + 2 * 5, |
| 58 | "squares": 64, |
| 59 | "promotions": 4, |
| 60 | } |
| 61 | |
| 62 | passed = 0 |
| 63 | failed = 0 |
| 64 | |
| 65 | |
| 66 | def check(what: str, ok: bool) -> None: |
| 67 | global passed, failed |
| 68 | if ok: |
| 69 | passed += 1 |
| 70 | print(f" ok {what}") |
| 71 | else: |
| 72 | failed += 1 |
| 73 | print(f" FAIL {what}") |
| 74 | |
| 75 | |
| 76 | def toy_checkpoint(spec): |
| 77 | """`(get, shapes)` for a checkpoint of `spec`'s shape, filled with distinguishable values.""" |
| 78 | rng = np.random.default_rng(7) |
| 79 | held = {} |
| 80 | for name, shape in maml_convert.maia_inventory(spec).items(): |
| 81 | held[name] = rng.standard_normal(shape).astype(np.float32) |
| 82 | return held.__getitem__, {name: list(v.shape) for name, v in held.items()} |
| 83 | |
| 84 | |
| 85 | def test_the_inventory_is_the_real_architecture() -> None: |
| 86 | print("inventory:") |
| 87 | spec = maml_convert.CHECKPOINTS["maia"] |
| 88 | want = maml_convert.maia_inventory(spec) |
| 89 | # 5 top-level + 8 blocks * 16 names + 2 final norm + 3 policy + 10 value/ponder. |
| 90 | check("148 parameters", len(want) == 148) |
| 91 | check("token_projection is [256, 352]", want["token_projection.weight"] == [256, 352]) |
| 92 | check("the shared bias weight is [4096, 64]", want["smolgen_shared_weight"] == [4096, 64]) |
| 93 | check( |
| 94 | "linear1 is [ffn, d_model]", |
| 95 | want["transformer.layers.0.linear1.weight"] == [512, 256], |
| 96 | ) |
| 97 | check( |
| 98 | "linear2 is [d_model, ffn]", |
| 99 | want["transformer.layers.0.linear2.weight"] == [256, 512], |
| 100 | ) |
| 101 | check( |
| 102 | "in_proj is fused [3d, d]", |
| 103 | want["transformer.layers.0.self_attn.mha.in_proj_weight"] == [768, 256], |
| 104 | ) |
| 105 | check( |
| 106 | "there are no attention biases", |
| 107 | "transformer.layers.0.self_attn.mha.in_proj_bias" not in want |
| 108 | and "transformer.layers.0.self_attn.mha.out_proj.bias" not in want, |
| 109 | ) |
| 110 | check( |
| 111 | "the RMS norms have no beta", |
| 112 | "transformer.layers.0.norm1.weight" in want |
| 113 | and "transformer.layers.0.norm1.bias" not in want, |
| 114 | ) |
| 115 | check( |
| 116 | "the per-block copies of the shared weight are absent", |
| 117 | not any(name.endswith("self_attn.smolgen_weight") for name in want), |
| 118 | ) |
| 119 | check( |
| 120 | "the value and ponder heads are asserted but not emitted", |
| 121 | "fc_value.weight" in want and "fc_ponder.weight" in want, |
| 122 | ) |
| 123 | total = sum(int(np.prod(shape)) for shape in want.values()) |
| 124 | check(f"{total} parameters, matching fetch_maia's pin", total == 5_230_084) |
| 125 | |
| 126 | |
| 127 | def test_a_transposed_checkpoint_is_refused() -> None: |
| 128 | print("the transpose:") |
| 129 | real = maml_convert.maia_inventory(maml_convert.CHECKPOINTS["maia"]) |
| 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, "maia") |
| 136 | caught = "" |
| 137 | except SystemExit as exit: |
| 138 | caught = str(exit) |
| 139 | check("a wholly transposed checkpoint is refused", bool(caught)) |
| 140 | |
| 141 | # The message lists only the first few mismatches, so flip the asymmetric feed-forward |
| 142 | # pair on its own — that is the one this check exists for, and it has to be named. |
| 143 | one_layer = dict(real) |
| 144 | for name in ("transformer.layers.0.linear1.weight", "transformer.layers.0.linear2.weight"): |
| 145 | one_layer[name] = list(reversed(real[name])) |
| 146 | try: |
| 147 | maml_convert.check_checkpoint(one_layer, "maia") |
| 148 | caught = "" |
| 149 | except SystemExit as exit: |
| 150 | caught = str(exit) |
| 151 | check("a transposed feed-forward alone is refused", bool(caught)) |
| 152 | check("and linear1 is named in the message", "linear1" in caught) |
| 153 | |
| 154 | maml_convert.check_checkpoint(real, "maia") |
| 155 | check("the real inventory is accepted", True) |
| 156 | |
| 157 | |
| 158 | def test_the_table_order_is_the_contract() -> None: |
| 159 | print("order:") |
| 160 | get, _ = toy_checkpoint(TOY) |
| 161 | layers, tensors = maml_convert.collect_maia(get, TOY) |
| 162 | ops = [layer.op for layer in layers] |
| 163 | |
| 164 | check("the two elo tables come first", ops[:2] == ["Host", "Host"]) |
| 165 | check("then the token projection", ops[2] == "Linear8") |
| 166 | check("then the attention-bias kernel", ops[3] == "Smolgen8") |
| 167 | |
| 168 | block = ops[4:4 + 12] |
| 169 | check( |
| 170 | "a block is the bias generator, then attention, then the feed-forward", |
| 171 | block == ["Linear8", "LayerNorm", "Linear8", "LayerNorm"] |
| 172 | + ["Linear8"] * 4 |
| 173 | + ["RmsNorm", "Linear8", "Linear8", "RmsNorm"], |
| 174 | ) |
| 175 | at = 4 + TOY["blocks"] * 12 |
| 176 | check("the encoder's final norm follows the blocks", ops[at] == "LayerNorm") |
| 177 | check("then three policy projections", ops[at + 1:] == ["Linear8"] * 3) |
| 178 | |
| 179 | names = [layer.name for layer in layers] |
| 180 | check( |
| 181 | "q, k and v are named as separate projections", |
| 182 | names[8:11] |
| 183 | == [ |
| 184 | "transformer.layers.0.self_attn.q_proj", |
| 185 | "transformer.layers.0.self_attn.k_proj", |
| 186 | "transformer.layers.0.self_attn.v_proj", |
| 187 | ], |
| 188 | ) |
| 189 | check("the promotion head is last", names[-1] == "promo_bias_proj") |
| 190 | |
| 191 | at_tensor = 0 |
| 192 | contiguous = True |
| 193 | for layer in layers: |
| 194 | contiguous = contiguous and layer.first_tensor == at_tensor |
| 195 | at_tensor += layer.tensor_count |
| 196 | check("layer tensor ranges tile the table", contiguous and at_tensor == len(tensors)) |
| 197 | |
| 198 | want_layers = 2 + 1 + 1 + TOY["blocks"] * 12 + 1 + 3 |
| 199 | check(f"{want_layers} layers", len(layers) == want_layers) |
| 200 | # 2 host + 3 + 3 + blocks*30 + 2 + 3*3. |
| 201 | want_tensors = 2 + 3 + 3 + TOY["blocks"] * 30 + 2 + 9 |
| 202 | check(f"{want_tensors} tensors", len(tensors) == want_tensors) |
| 203 | |
| 204 | |
| 205 | def test_the_real_layout_matches_the_rust_constants() -> None: |
| 206 | print("the Rust layout:") |
| 207 | get, _ = toy_checkpoint(maml_convert.CHECKPOINTS["maia"]) |
| 208 | layers, tensors = maml_convert.collect_maia(get, maml_convert.CHECKPOINTS["maia"]) |
| 209 | # `nets::maia::TENSORS`, and the cursor constants it is built from. |
| 210 | check("259 tensors, which is nets::maia::TENSORS", len(tensors) == 259) |
| 211 | check("the first block starts at 8, which is BLOCK", True) |
| 212 | check("30 tensors per block, which is BLOCK_TENSORS", (259 - 8 - 11) // 8 == 30) |
| 213 | # `nets::maia::INT8_CONVS`. Kernels in the file, not dispatches: the bias kernel is one |
| 214 | # tensor that all eight blocks read. |
| 215 | kernels = sum(1 for layer in layers if layer.op in ("Linear8", "Smolgen8")) |
| 216 | check("69 int8 kernels, which is nets::maia::INT8_CONVS", kernels == 69) |
| 217 | |
| 218 | |
| 219 | def test_the_fused_projection_is_split_in_qkv_order() -> None: |
| 220 | print("the q/k/v split:") |
| 221 | d = TOY["d_model"] |
| 222 | get, _ = toy_checkpoint(TOY) |
| 223 | fused = get("transformer.layers.0.self_attn.mha.in_proj_weight") |
| 224 | layers, tensors = maml_convert.collect_maia(get, TOY) |
| 225 | |
| 226 | for part, projection in enumerate(("q_proj", "k_proj", "v_proj")): |
| 227 | layer = next(l for l in layers if l.name == f"transformer.layers.0.self_attn.{projection}") |
| 228 | kernel, scale, bias = tensors[layer.first_tensor: layer.first_tensor + 3] |
| 229 | check( |
| 230 | f"{projection}'s kernel is int8 [{d}, {d}, 1, 1]", |
| 231 | kernel.dtype == np.int8 and list(kernel.shape) == [d, d, 1, 1], |
| 232 | ) |
| 233 | check(f"{projection} has one scale per output channel", scale.shape == (d,)) |
| 234 | # Dequantised, the kernel must be the fused weight's slice back again — which is the |
| 235 | # check that the split happened before the quantisation and not after it. |
| 236 | back = kernel.astype(np.float32).reshape(d, d) * scale[:, None] |
| 237 | want = fused[part * d: (part + 1) * d] |
| 238 | check( |
| 239 | f"{projection} is slice {part} of the fused weight", |
| 240 | np.abs(back - want).max() < np.abs(want).max() / 100.0, |
| 241 | ) |
| 242 | check(f"{projection}'s bias is synthesised zeros", bias.shape == (d,) and not bias.any()) |
| 243 | |
| 244 | out = next(l for l in layers if l.name.endswith("mha.out_proj")) |
| 245 | check("out_proj's bias is synthesised too", not tensors[out.first_tensor + 2].any()) |
| 246 | ffn = next(l for l in layers if l.name.endswith("linear1")) |
| 247 | check("but the feed-forward keeps its own", tensors[ffn.first_tensor + 2].any()) |
| 248 | |
| 249 | |
| 250 | def test_an_int8_layer_is_kernel_then_scale_then_bias() -> None: |
| 251 | print("the int8 triple:") |
| 252 | get, _ = toy_checkpoint(TOY) |
| 253 | layers, tensors = maml_convert.collect_maia(get, TOY) |
| 254 | ffn = next(l for l in layers if l.name.endswith("linear1")) |
| 255 | kernel, scale, bias = tensors[ffn.first_tensor: ffn.first_tensor + 3] |
| 256 | check( |
| 257 | f"linear1's kernel is int8 [{TOY['ffn']}, {TOY['d_model']}, 1, 1]", |
| 258 | kernel.dtype == np.int8 and list(kernel.shape) == [TOY["ffn"], TOY["d_model"], 1, 1], |
| 259 | ) |
| 260 | check("with one scale per output channel", scale.shape == (TOY["ffn"],) and scale.dtype != np.int8) |
| 261 | check("and the checkpoint's own bias", bias.shape == (TOY["ffn"],) and bias.any()) |
| 262 | # Norms stay fp16: quantising a gain would be both pointless and wrong, since a layer |
| 263 | # norm's gamma has no output axis to carry a per-channel scale. |
| 264 | ln1 = next(l for l in layers if l.name.endswith("ln1")) |
| 265 | check("a layer norm is left fp16", tensors[ln1.first_tensor].dtype != np.int8) |
| 266 | norm1 = next(l for l in layers if l.name.endswith("norm1")) |
| 267 | check("and so is an RMS norm", tensors[norm1.first_tensor].dtype != np.int8) |
| 268 | |
| 269 | |
| 270 | def test_an_rms_norm_emits_one_tensor() -> None: |
| 271 | print("the RMS norms:") |
| 272 | get, _ = toy_checkpoint(TOY) |
| 273 | layers, tensors = maml_convert.collect_maia(get, TOY) |
| 274 | for name in ("norm1", "norm2"): |
| 275 | layer = next(l for l in layers if l.name == f"transformer.layers.0.{name}") |
| 276 | check(f"{name} emits one tensor", layer.tensor_count == 1) |
| 277 | check( |
| 278 | f"{name}'s gain is [d_model]", |
| 279 | tensors[layer.first_tensor].shape == (TOY["d_model"],), |
| 280 | ) |
| 281 | ln1 = next(l for l in layers if l.name.endswith("ln1")) |
| 282 | check("but a real layer norm still emits two", ln1.tensor_count == 2) |
| 283 | |
| 284 | |
| 285 | def test_the_bias_kernel_is_tiled_so_each_group_sees_the_whole_weight() -> None: |
| 286 | print("the replication:") |
| 287 | get, _ = toy_checkpoint(TOY) |
| 288 | shared = get("smolgen_shared_weight") |
| 289 | layers, tensors = maml_convert.collect_maia(get, TOY) |
| 290 | layer = next(l for l in layers if l.op == "Smolgen8") |
| 291 | kernel, scale, bias = tensors[layer.first_tensor: layer.first_tensor + 3] |
| 292 | |
| 293 | heads, gen = TOY["heads"], TOY["bias_gen"] |
| 294 | rows = heads * 64 * 64 |
| 295 | check(f"the kernel is int8 [{rows}, {gen}, 1, 1]", |
| 296 | kernel.dtype == np.int8 and list(kernel.shape) == [rows, gen, 1, 1]) |
| 297 | check("with one scale per output channel", scale.shape == (rows,)) |
| 298 | check("its bias is synthesised zeros", bias.shape == (rows,) and not bias.any()) |
| 299 | |
| 300 | flat = kernel.reshape(rows, gen) |
| 301 | for group in range(heads): |
| 302 | check( |
| 303 | f"group {group} reads a whole copy of the shared weight", |
| 304 | np.array_equal(flat[group * 4096: (group + 1) * 4096], flat[:4096]), |
| 305 | ) |
| 306 | check( |
| 307 | f"group {group}'s scales are tiled with it", |
| 308 | np.array_equal(scale[group * 4096: (group + 1) * 4096], scale[:4096]), |
| 309 | ) |
| 310 | # Dequantised, group 0 must be the shared weight back again. |
| 311 | back = flat[:4096].astype(np.float32) * scale[:4096, None] |
| 312 | check( |
| 313 | "and it dequantises to the shared weight", |
| 314 | np.abs(back - shared).max() < np.abs(shared).max() / 100.0, |
| 315 | ) |
| 316 | # `np.repeat` would interleave the rows instead, which is the plausible wrong answer: |
| 317 | # every group would then see 4096 copies of a handful of rows. |
| 318 | check( |
| 319 | "and it is a tile, not a repeat", |
| 320 | not np.array_equal(flat, np.repeat(flat[:4096], heads, axis=0)), |
| 321 | ) |
| 322 | |
| 323 | |
| 324 | def test_the_digest_covers_the_order() -> None: |
| 325 | print("the digest:") |
| 326 | get, _ = toy_checkpoint(TOY) |
| 327 | layers, _ = maml_convert.collect_maia(get, TOY) |
| 328 | before = maml_convert.layer_table_digest(layers) |
| 329 | q_proj = next(i for i, layer in enumerate(layers) if layer.name.endswith("q_proj")) |
| 330 | linear1 = next(i for i, layer in enumerate(layers) if layer.name.endswith("linear1")) |
| 331 | swapped = list(layers) |
| 332 | swapped[q_proj], swapped[linear1] = swapped[linear1], swapped[q_proj] |
| 333 | check("a reordered pair changes it", maml_convert.layer_table_digest(swapped) != before) |
| 334 | check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before) |
| 335 | |
| 336 | |
| 337 | def 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_the_real_layout_matches_the_rust_constants() |
| 342 | test_the_fused_projection_is_split_in_qkv_order() |
| 343 | test_an_int8_layer_is_kernel_then_scale_then_bias() |
| 344 | test_an_rms_norm_emits_one_tensor() |
| 345 | test_the_bias_kernel_is_tiled_so_each_group_sees_the_whole_weight() |
| 346 | test_the_digest_covers_the_order() |
| 347 | print(f"\n{passed} passed, {failed} failed") |
| 348 | return 1 if failed else 0 |
| 349 | |
| 350 | |
| 351 | if __name__ == "__main__": |
| 352 | raise SystemExit(main()) |