Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / test / test_nllb.py
test_nllb.py226 lines · 8.9 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """test_nllb.py - unit test for `maml_convert`'s NLLB checkpoint path. |
| 3 | |
| 4 | Mirrors `test_small100.py`: `collect_nllb` is the one converter arm with no ONNX graph |
| 5 | behind it, so `check_checkpoint` is the whole guard and `collect_nllb`'s emission |
| 6 | *order* is the whole contract with `nets::nllb600`. Both are checked here against a |
| 7 | toy model of the same shape rather than the real 2.46 GB checkpoint, so this runs in |
| 8 | a second and needs no download. |
| 9 | |
| 10 | What each check is defending against (same four as small100, plus NLLB'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. `fc1` and `fc2` are the asymmetric |
| 14 | pair that makes it loud. |
| 15 | * **The order.** `nets::nllb600` walks the tensor table positionally. A layer emitted |
| 16 | out of order loads cleanly and infers nonsense. |
| 17 | * **The tied head appearing once.** Emitting the embedding twice would put 250 MiB |
| 18 | back into the download. |
| 19 | * **The int8 triple.** `Builder::conv_int8` reads kernel, then per-output-channel |
| 20 | scale, then bias. |
| 21 | * **The uneven head split.** 256,206 classes do not divide into 4 equal ranges; |
| 22 | `head_rows` must sum to vocab and tile the classes without gap or overlap. |
| 23 | |
| 24 | Run: |
| 25 | python3 scripts/ml/test/test_nllb.py |
| 26 | |
| 27 | Exit code 0 = all assertions passed. |
| 28 | """ |
| 29 | |
| 30 | from __future__ import annotations |
| 31 | |
| 32 | import os |
| 33 | import sys |
| 34 | |
| 35 | import numpy as np |
| 36 | |
| 37 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 38 | |
| 39 | import maml_convert # noqa: E402 (needs the path above) |
| 40 | |
| 41 | TOY = { |
| 42 | "d_model": 8, |
| 43 | "encoder_layers": 2, |
| 44 | "decoder_layers": 2, |
| 45 | "ffn": 16, |
| 46 | "vocab": 10, |
| 47 | "head_splits": 4, |
| 48 | "head_rows": [3, 3, 2, 2], |
| 49 | } |
| 50 | |
| 51 | passed = 0 |
| 52 | failed = 0 |
| 53 | |
| 54 | |
| 55 | def check(what: str, ok: bool) -> None: |
| 56 | global passed, failed |
| 57 | if ok: |
| 58 | passed += 1 |
| 59 | print(f" ok {what}") |
| 60 | else: |
| 61 | failed += 1 |
| 62 | print(f" FAIL {what}") |
| 63 | |
| 64 | |
| 65 | def toy_checkpoint(spec, transpose_projections: bool = False): |
| 66 | """`(get, shapes)` for a checkpoint of `spec`'s shape, filled with distinguishable values.""" |
| 67 | rng = np.random.default_rng(7) |
| 68 | held = {} |
| 69 | for name, shape in maml_convert.nllb_inventory(spec).items(): |
| 70 | if transpose_projections and name.endswith(".weight") and len(shape) == 2: |
| 71 | shape = list(reversed(shape)) |
| 72 | held[name] = rng.standard_normal(shape).astype(np.float32) |
| 73 | return held.__getitem__, {name: list(v.shape) for name, v in held.items()} |
| 74 | |
| 75 | |
| 76 | def test_the_inventory_is_the_real_architecture() -> None: |
| 77 | print("inventory:") |
| 78 | want = maml_convert.nllb_inventory(maml_convert.CHECKPOINTS["nllb600"]) |
| 79 | # 1 shared + 2 final norms + 12 enc * 16 names + 12 dec * 26 names: |
| 80 | # per encoder layer 2 norms*2 + 4 projs*2 + 2 + 2 = 16 names; per decoder layer |
| 81 | # 16 + cross norm*2 + 4 projs*2 = 26. The checkpoint holds 512 tensors (509 + the |
| 82 | # 3 extra tied copies); 1,402,138,624 params total. |
| 83 | check("509 parameters", len(want) == 509) |
| 84 | check("the embedding is [vocab, d_model]", want["model.shared.weight"] == [256_206, 1024]) |
| 85 | check("fc1 is [ffn, d_model]", want["model.encoder.layers.0.fc1.weight"] == [4096, 1024]) |
| 86 | check("fc2 is [d_model, ffn]", want["model.encoder.layers.0.fc2.weight"] == [1024, 4096]) |
| 87 | check( |
| 88 | "the decoder has cross-attention", |
| 89 | "model.decoder.layers.11.encoder_attn.q_proj.weight" in want, |
| 90 | ) |
| 91 | check( |
| 92 | "the encoder has none", |
| 93 | "model.encoder.layers.0.encoder_attn.q_proj.weight" not in want, |
| 94 | ) |
| 95 | check( |
| 96 | "the other three tied copies are absent", |
| 97 | "lm_head.weight" not in want |
| 98 | and "model.encoder.embed_tokens.weight" not in want |
| 99 | and "model.decoder.embed_tokens.weight" not in want, |
| 100 | ) |
| 101 | check( |
| 102 | "k_proj carries a bias (unlike whisper)", |
| 103 | "model.decoder.layers.0.self_attn.k_proj.bias" in want, |
| 104 | ) |
| 105 | total = sum(int(np.prod(shape)) for shape in want.values()) |
| 106 | # model.shared 256206*1024 + norms + 24 layers of (attn norms + 4/8 projs + ffn). |
| 107 | # Per encoder layer params: norms 3*2*1024 + projs 4*2*(1024*1024+1024)... computed below. |
| 108 | print(f" info inventory parameters: {total}") |
| 109 | |
| 110 | |
| 111 | def test_a_transposed_checkpoint_is_refused() -> None: |
| 112 | print("the transpose:") |
| 113 | real = maml_convert.nllb_inventory(maml_convert.CHECKPOINTS["nllb600"]) |
| 114 | flipped = { |
| 115 | name: (list(reversed(shape)) if name.endswith(".weight") and len(shape) == 2 else shape) |
| 116 | for name, shape in real.items() |
| 117 | } |
| 118 | try: |
| 119 | maml_convert.check_checkpoint(flipped, "nllb600") |
| 120 | caught = "" |
| 121 | except SystemExit as exit: |
| 122 | caught = str(exit) |
| 123 | check("a transposed checkpoint is refused", bool(caught)) |
| 124 | check("and fc1 is named in the message", "fc1" in caught) |
| 125 | maml_convert.check_checkpoint(real, "nllb600") |
| 126 | check("the real inventory is accepted", True) |
| 127 | |
| 128 | |
| 129 | def test_the_table_order_is_the_contract() -> None: |
| 130 | print("order:") |
| 131 | get, _ = toy_checkpoint(TOY) |
| 132 | layers, tensors = maml_convert.collect_nllb(get, TOY) |
| 133 | ops = [layer.op for layer in layers] |
| 134 | |
| 135 | heads = [i for i, op in enumerate(ops) if op == "Head"] |
| 136 | check("all four head splits come first", heads == [0, 1, 2, 3]) |
| 137 | |
| 138 | encoder = ops[4:4 + 8] |
| 139 | check( |
| 140 | "an encoder layer is norm, four projections, norm, fc1, fc2", |
| 141 | encoder == ["LayerNorm", "Linear8", "Linear8", "Linear8", "Linear8", |
| 142 | "LayerNorm", "Linear8", "Linear8"], |
| 143 | ) |
| 144 | per_encoder = 8 |
| 145 | at = 4 + TOY["encoder_layers"] * per_encoder |
| 146 | check("the encoder's final norm follows its layers", ops[at] == "LayerNorm") |
| 147 | decoder = ops[at + 1: at + 1 + 13] |
| 148 | check( |
| 149 | "a decoder layer has two attentions", |
| 150 | decoder == ["LayerNorm"] + ["Linear8"] * 4 + ["LayerNorm"] + ["Linear8"] * 4 |
| 151 | + ["LayerNorm", "Linear8", "Linear8"], |
| 152 | ) |
| 153 | check("the decoder's final norm is last", ops[-1] == "LayerNorm") |
| 154 | |
| 155 | names = [layer.name for layer in layers] |
| 156 | check( |
| 157 | "the layers are named after the checkpoint", |
| 158 | names[4] == "model.encoder.layers.0.self_attn_layer_norm", |
| 159 | ) |
| 160 | check("a head split names its class range", names[0].endswith("[0:3]")) |
| 161 | check("the last split ends at vocab", names[3].endswith(f"[8:{TOY['vocab']}]")) |
| 162 | |
| 163 | at_tensor = 0 |
| 164 | contiguous = True |
| 165 | for layer in layers: |
| 166 | contiguous = contiguous and layer.first_tensor == at_tensor |
| 167 | at_tensor += layer.tensor_count |
| 168 | check("layer tensor ranges tile the table", contiguous and at_tensor == len(tensors)) |
| 169 | |
| 170 | # 4 head layers of 3 + 2*8 enc + 1 + 2*13 dec + 1 layers. |
| 171 | want_layers = 4 + TOY["encoder_layers"] * 8 + 1 + TOY["decoder_layers"] * 13 + 1 |
| 172 | check(f"{want_layers} layers", len(layers) == want_layers) |
| 173 | want_tensors = 4 * 3 + TOY["encoder_layers"] * 22 + 2 + TOY["decoder_layers"] * 36 + 2 |
| 174 | check(f"{want_tensors} tensors", len(tensors) == want_tensors) |
| 175 | |
| 176 | |
| 177 | def test_an_int8_layer_is_kernel_then_scale_then_bias() -> None: |
| 178 | print("the int8 triple:") |
| 179 | get, _ = toy_checkpoint(TOY) |
| 180 | layers, tensors = maml_convert.collect_nllb(get, TOY) |
| 181 | |
| 182 | for index, rows in enumerate(TOY["head_rows"]): |
| 183 | head = layers[index] |
| 184 | kernel, scale, bias = tensors[head.first_tensor: head.first_tensor + 3] |
| 185 | check(f"split {index} kernel [{rows}, {TOY['d_model']}, 1, 1] int8", |
| 186 | kernel.dtype == np.int8 and list(kernel.shape) == [rows, TOY["d_model"], 1, 1]) |
| 187 | check(f"split {index} one scale per class", |
| 188 | scale.shape == (rows,) and scale.dtype != np.int8) |
| 189 | check(f"split {index} tied bias is zero", |
| 190 | bias.shape == (rows,) and not bias.any()) |
| 191 | |
| 192 | ffn = next(layer for layer in layers if layer.name.endswith("fc1")) |
| 193 | kernel, scale, bias = tensors[ffn.first_tensor: ffn.first_tensor + 3] |
| 194 | check( |
| 195 | f"fc1's kernel is [{TOY['ffn']}, {TOY['d_model']}, 1, 1]", |
| 196 | list(kernel.shape) == [TOY["ffn"], TOY["d_model"], 1, 1], |
| 197 | ) |
| 198 | check("with one scale per output channel", scale.shape == (TOY["ffn"],)) |
| 199 | check("and the checkpoint's own bias", bias.shape == (TOY["ffn"],) and bias.any()) |
| 200 | |
| 201 | |
| 202 | def test_the_digest_covers_the_order() -> None: |
| 203 | print("the digest:") |
| 204 | get, _ = toy_checkpoint(TOY) |
| 205 | layers, _ = maml_convert.collect_nllb(get, TOY) |
| 206 | before = maml_convert.layer_table_digest(layers) |
| 207 | q_proj = next(i for i, layer in enumerate(layers) if layer.name.endswith("q_proj")) |
| 208 | fc1 = next(i for i, layer in enumerate(layers) if layer.name.endswith("fc1")) |
| 209 | swapped = list(layers) |
| 210 | swapped[q_proj], swapped[fc1] = swapped[fc1], swapped[q_proj] |
| 211 | check("a reordered pair changes it", maml_convert.layer_table_digest(swapped) != before) |
| 212 | check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before) |
| 213 | |
| 214 | |
| 215 | def main() -> int: |
| 216 | test_the_inventory_is_the_real_architecture() |
| 217 | test_a_transposed_checkpoint_is_refused() |
| 218 | test_the_table_order_is_the_contract() |
| 219 | test_an_int8_layer_is_kernel_then_scale_then_bias() |
| 220 | test_the_digest_covers_the_order() |
| 221 | print(f"\n{passed} passed, {failed} failed") |
| 222 | return 1 if failed else 0 |
| 223 | |
| 224 | |
| 225 | if __name__ == "__main__": |
| 226 | raise SystemExit(main()) |