Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / test / test_whisper.py
test_whisper.py340 lines · 15.4 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """test_whisper.py - unit test for `maml_convert`'s whisper-base checkpoint path. |
| 3 | |
| 4 | The sibling of `test_small100.py`, and the same argument: `collect_whisper` reads a checkpoint, so |
| 5 | nothing about its input records the architecture. `check_checkpoint` against `whisper_inventory` is |
| 6 | the whole shape guard, and `collect_whisper`'s emission *order* is the whole contract with |
| 7 | `nets::whisper`. Both are checked against a toy model of the same shape rather than the real 290 MB |
| 8 | checkpoint, so this runs in a second and needs no download. |
| 9 | |
| 10 | What each check is defending against, beyond what the SMaLL-100 test already covers: |
| 11 | |
| 12 | * **The absent `k_proj.bias`.** No key projection in any of whisper's 18 attentions has one, and |
| 13 | `Builder::conv_int8` always reads a bias after the scale. The converter synthesises zeros; this |
| 14 | asserts that a checkpoint which *grows* one is refused rather than read as this table with the |
| 15 | bias ignored, and that the synthesis is recorded in the digest key. |
| 16 | * **The conv stem's stride.** `conv2` is stride 2, which is what turns 3000 mel frames into 1500 |
| 17 | encoder positions. A wrong stride gives the right rank and the wrong length, and the encoder's |
| 18 | output length is not checked against anything downstream. |
| 19 | * **The rank-3 lift.** Both convolutions are `[out, in, k]` in the checkpoint and `[out, in, 1, k]` |
| 20 | in the file. That is a reshape of the same bytes, and it must not be a transpose. |
| 21 | * **The tied head appearing once, and not being split.** SMaLL-100's is emitted as two class ranges |
| 22 | because 128,112 x 1024 is 125 MiB against a guaranteed 128 MiB binding; whisper's 51,865 x 512 is |
| 23 | 26.6 MB and must be one tensor, or `nets::whisper` reads the wrong index for every layer after it. |
| 24 | * **The position tables going opposite ways.** The encoder's is added to the conv stem's output on |
| 25 | the device, so it is transposed to `[width, 1, positions]` and emitted as a `Constant`; the |
| 26 | decoder's is added to a gathered embedding row on the *host*, so it is left `[positions, width]`. |
| 27 | Swapping them is silent. |
| 28 | |
| 29 | Run: |
| 30 | |
| 31 | python3 scripts/ml/test/test_whisper.py |
| 32 | |
| 33 | Exit code 0 = all assertions passed. |
| 34 | """ |
| 35 | |
| 36 | from __future__ import annotations |
| 37 | |
| 38 | import os |
| 39 | import sys |
| 40 | |
| 41 | import numpy as np |
| 42 | |
| 43 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 44 | |
| 45 | import maml_convert # noqa: E402 (needs the path above) |
| 46 | |
| 47 | # The real architecture with every dimension shrunk, so the table has the same *structure* — two |
| 48 | # convolutions, two position tables, an encoder stack, a tied head, a decoder stack, two trailing |
| 49 | # norms — at a size that fits in memory. `conv_kernel` stays 3 because that is what the Rust reads. |
| 50 | TOY = { |
| 51 | "d_model": 8, |
| 52 | "encoder_layers": 2, |
| 53 | "decoder_layers": 1, |
| 54 | "ffn": 16, |
| 55 | "vocab": 6, |
| 56 | "mels": 4, |
| 57 | "source_positions": 10, |
| 58 | "target_positions": 5, |
| 59 | "conv_kernel": 3, |
| 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, transpose_projections: bool = False, key_bias: bool = False): |
| 77 | """`(get, shapes)` for a checkpoint of `spec`'s shape, filled with distinguishable values.""" |
| 78 | rng = np.random.default_rng(13) |
| 79 | held = {} |
| 80 | for name, shape in maml_convert.whisper_inventory(spec).items(): |
| 81 | if transpose_projections and name.endswith(".weight") and len(shape) == 2: |
| 82 | shape = list(reversed(shape)) |
| 83 | held[name] = rng.standard_normal(shape).astype(np.float32) |
| 84 | if key_bias: |
| 85 | # The absence this port depends on, deliberately filled in. |
| 86 | for name in [n for n in list(held) if n.endswith("k_proj.weight")]: |
| 87 | held[name.replace(".weight", ".bias")] = np.zeros(spec["d_model"], dtype=np.float32) |
| 88 | return held.__getitem__, {name: list(v.shape) for name, v in held.items()} |
| 89 | |
| 90 | |
| 91 | def test_the_inventory_is_the_real_architecture() -> None: |
| 92 | print("inventory:") |
| 93 | want = maml_convert.whisper_inventory(maml_convert.CHECKPOINTS["whisper"]) |
| 94 | # 245 is what `openai/whisper-base` holds; a derived list that disagrees is derived wrong. |
| 95 | check(f"245 parameters, got {len(want)}", len(want) == 245) |
| 96 | check("the tied embedding is [vocab, d_model]", want["model.decoder.embed_tokens.weight"] == [51_865, 512]) |
| 97 | check("there is no proj_out, because the head is tied", "proj_out.weight" not in want) |
| 98 | # The two convolutions, rank-3 in the checkpoint. |
| 99 | check("conv1 is [d_model, mels, 3]", want["model.encoder.conv1.weight"] == [512, 80, 3]) |
| 100 | check("conv2 is [d_model, d_model, 3]", want["model.encoder.conv2.weight"] == [512, 512, 3]) |
| 101 | # The encoder's positions are a real frozen tensor, not computed sinusoids. |
| 102 | check( |
| 103 | "the encoder has a 1500-position table", |
| 104 | want["model.encoder.embed_positions.weight"] == [1500, 512], |
| 105 | ) |
| 106 | check( |
| 107 | "and the decoder a learned 448-position one", |
| 108 | want["model.decoder.embed_positions.weight"] == [448, 512], |
| 109 | ) |
| 110 | # The pair a transpose would swap. |
| 111 | check("fc1 is [ffn, d_model]", want["model.encoder.layers.0.fc1.weight"] == [2048, 512]) |
| 112 | check("fc2 is [d_model, ffn]", want["model.encoder.layers.0.fc2.weight"] == [512, 2048]) |
| 113 | # The absence, stated as an absence. |
| 114 | keys = [n for n in want if n.endswith("k_proj.weight")] |
| 115 | biases = [n for n in want if n.endswith("k_proj.bias")] |
| 116 | check(f"18 key projections, got {len(keys)}", len(keys) == 18) |
| 117 | check("and not one of them has a bias", not biases) |
| 118 | check( |
| 119 | "while q, v and out all do", |
| 120 | all( |
| 121 | f"model.encoder.layers.0.self_attn.{p}.bias" in want |
| 122 | for p in ("q_proj", "v_proj", "out_proj") |
| 123 | ), |
| 124 | ) |
| 125 | check( |
| 126 | "the decoder has cross-attention", |
| 127 | "model.decoder.layers.0.encoder_attn.q_proj.weight" in want, |
| 128 | ) |
| 129 | check( |
| 130 | "the encoder has none", |
| 131 | "model.encoder.layers.0.encoder_attn.q_proj.weight" not in want, |
| 132 | ) |
| 133 | total = sum(int(np.prod(shape)) for shape in want.values()) |
| 134 | check(f"72,593,920 parameters, got {total}", total == 72_593_920) |
| 135 | |
| 136 | |
| 137 | def test_a_transposed_or_bias_grown_checkpoint_is_refused() -> None: |
| 138 | print("the two refusals:") |
| 139 | real = maml_convert.whisper_inventory(maml_convert.CHECKPOINTS["whisper"]) |
| 140 | maml_convert.check_checkpoint(real, "whisper") |
| 141 | check("the real inventory is accepted", True) |
| 142 | |
| 143 | flipped = { |
| 144 | name: (list(reversed(shape)) if name.endswith(".weight") and len(shape) == 2 else shape) |
| 145 | for name, shape in real.items() |
| 146 | } |
| 147 | try: |
| 148 | maml_convert.check_checkpoint(flipped, "whisper") |
| 149 | caught = "" |
| 150 | except SystemExit as exit: |
| 151 | caught = str(exit) |
| 152 | check("a transposed checkpoint is refused", bool(caught)) |
| 153 | check("and fc1 is named in the message", "fc1" in caught) |
| 154 | |
| 155 | # A checkpoint that grew the bias the converter synthesises. It must fail, not be read as this |
| 156 | # table: the emitted bias would be zeros while the real one is not, which is silent. |
| 157 | grown = dict(real) |
| 158 | grown["model.encoder.layers.0.self_attn.k_proj.bias"] = [512] |
| 159 | try: |
| 160 | maml_convert.check_checkpoint(grown, "whisper") |
| 161 | caught = "" |
| 162 | except SystemExit as exit: |
| 163 | caught = str(exit) |
| 164 | check("a checkpoint that grew a k_proj bias is refused", bool(caught)) |
| 165 | check("and it is named as unexpected", "k_proj.bias" in caught) |
| 166 | |
| 167 | |
| 168 | def test_the_table_order_is_the_contract() -> None: |
| 169 | print("order:") |
| 170 | get, _ = toy_checkpoint(TOY) |
| 171 | layers, tensors = maml_convert.collect_whisper(get, TOY) |
| 172 | ops = [layer.op for layer in layers] |
| 173 | encoder_layer = ["LayerNorm"] + ["Linear8"] * 4 + ["LayerNorm", "Linear8", "Linear8"] |
| 174 | decoder_layer = ( |
| 175 | ["LayerNorm"] + ["Linear8"] * 4 |
| 176 | + ["LayerNorm"] + ["Linear8"] * 4 |
| 177 | + ["LayerNorm", "Linear8", "Linear8"] |
| 178 | ) |
| 179 | expected = ( |
| 180 | ["Conv8", "Conv8", "Constant"] |
| 181 | + encoder_layer * TOY["encoder_layers"] |
| 182 | + ["LayerNorm"] |
| 183 | + ["Head", "Table"] |
| 184 | + decoder_layer * TOY["decoder_layers"] |
| 185 | + ["LayerNorm"] |
| 186 | ) |
| 187 | check("the whole table is encoder then decoder, in forward order", ops == expected) |
| 188 | names = [layer.name for layer in layers] |
| 189 | check("conv1 comes first", names[0].endswith("conv1")) |
| 190 | check("then conv2", names[1].endswith("conv2")) |
| 191 | check("then the encoder positions", names[2].endswith("encoder.embed_positions")) |
| 192 | check("the tied head opens the decoder", names.count("model.decoder.embed_tokens") == 1) |
| 193 | check("and is emitted once, unsplit", ops.count("Head") == 1) |
| 194 | check("the decoder's norm is last", names[-1] == "model.decoder.layer_norm") |
| 195 | # The stacks are contiguous. |
| 196 | encoder = [i for i, name in enumerate(names) if ".encoder." in name] |
| 197 | decoder = [i for i, name in enumerate(names) if ".decoder." in name] |
| 198 | check("no decoder layer sits inside the encoder", max(encoder) < min(decoder)) |
| 199 | # Every layer's tensors are contiguous and in order, which is how the Rust indexes them. |
| 200 | at = 0 |
| 201 | contiguous = True |
| 202 | for layer in layers: |
| 203 | contiguous = contiguous and layer.first_tensor == at |
| 204 | at += layer.tensor_count |
| 205 | check("layer tensor ranges tile the table", contiguous and at == len(tensors)) |
| 206 | |
| 207 | |
| 208 | def test_the_conv_stem_is_lifted_and_strided() -> None: |
| 209 | print("the conv stem:") |
| 210 | get, _ = toy_checkpoint(TOY) |
| 211 | layers, tensors = maml_convert.collect_whisper(get, TOY) |
| 212 | |
| 213 | conv1, conv2 = layers[0], layers[1] |
| 214 | for layer, inputs, stride in ((conv1, TOY["mels"], 1), (conv2, TOY["d_model"], 2)): |
| 215 | kernel, scale, bias = tensors[layer.first_tensor: layer.first_tensor + 3] |
| 216 | check( |
| 217 | f"{layer.name.rsplit('.', 1)[-1]} is [{TOY['d_model']}, {inputs}, 1, 3] int8", |
| 218 | list(kernel.shape) == [TOY["d_model"], inputs, 1, TOY["conv_kernel"]] |
| 219 | and kernel.dtype == np.int8, |
| 220 | ) |
| 221 | check("with one scale per output channel", scale.shape == (TOY["d_model"],)) |
| 222 | check("and the checkpoint's own bias", bias.shape == (TOY["d_model"],) and bias.any()) |
| 223 | check(f"and stride {stride} in its key", f"s={[1, stride]}" in layer.key()) |
| 224 | # The lift is a reshape, not a transpose: element order is unchanged. |
| 225 | original = get("model.encoder.conv1.weight") |
| 226 | kernel, scale, _ = tensors[conv1.first_tensor: conv1.first_tensor + 3] |
| 227 | back = kernel.astype(np.float32).reshape(TOY["d_model"], -1) * scale[:, None] |
| 228 | check( |
| 229 | "the lift preserves element order", |
| 230 | np.allclose(back.reshape(original.shape), original, atol=0.05), |
| 231 | ) |
| 232 | |
| 233 | |
| 234 | def test_a_key_projection_gets_a_synthesised_zero_bias() -> None: |
| 235 | print("the absent key bias:") |
| 236 | get, _ = toy_checkpoint(TOY) |
| 237 | layers, tensors = maml_convert.collect_whisper(get, TOY) |
| 238 | keys = [layer for layer in layers if layer.name.endswith("k_proj")] |
| 239 | check(f"{TOY['encoder_layers'] + TOY['decoder_layers'] * 2} key projections", len(keys) == 4) |
| 240 | for layer in keys: |
| 241 | kernel, scale, bias = tensors[layer.first_tensor: layer.first_tensor + 3] |
| 242 | check(f"{layer.name.split('.layers.')[-1]}: still an int8 triple", layer.tensor_count == 3) |
| 243 | check("with a zero bias", bias.shape == (TOY["d_model"],) and not bias.any()) |
| 244 | check("recorded in the key", "b0=synthesised" in layer.key()) |
| 245 | check("and a real kernel", kernel.dtype == np.int8 and scale.any()) |
| 246 | # And no other projection has one, which is what says the synthesis is targeted. |
| 247 | others = [ |
| 248 | layer |
| 249 | for layer in layers |
| 250 | if layer.op == "Linear8" and not layer.name.endswith("k_proj") |
| 251 | ] |
| 252 | check( |
| 253 | "no other projection is synthesised", |
| 254 | all("b0=synthesised" not in layer.key() for layer in others), |
| 255 | ) |
| 256 | |
| 257 | |
| 258 | def test_the_position_tables_go_opposite_ways() -> None: |
| 259 | print("the head and the tables:") |
| 260 | get, _ = toy_checkpoint(TOY) |
| 261 | layers, tensors = maml_convert.collect_whisper(get, TOY) |
| 262 | |
| 263 | head = next(layer for layer in layers if layer.op == "Head") |
| 264 | kernel, scale, bias = tensors[head.first_tensor: head.first_tensor + 3] |
| 265 | check( |
| 266 | f"[{TOY['vocab']}, {TOY['d_model']}, 1, 1] int8", |
| 267 | list(kernel.shape) == [TOY["vocab"], TOY["d_model"], 1, 1] and kernel.dtype == np.int8, |
| 268 | ) |
| 269 | check("one scale per class", scale.shape == (TOY["vocab"],)) |
| 270 | check("a tied head's bias is zero", bias.shape == (TOY["vocab"],) and not bias.any()) |
| 271 | check("and the tie is recorded in the key", "tied=embed_tokens" in head.key()) |
| 272 | |
| 273 | # The encoder's table is added to the conv stem's output, which is a device tensor, so it is |
| 274 | # transposed to `[width, 1, positions]` and emitted as a `Constant`. |
| 275 | encoder = next(layer for layer in layers if layer.op == "Constant") |
| 276 | values = tensors[encoder.first_tensor] |
| 277 | check("the encoder's table is a Constant", encoder.name.endswith("encoder.embed_positions")) |
| 278 | check( |
| 279 | f"transposed to [{TOY['d_model']}, 1, {TOY['source_positions']}]", |
| 280 | list(values.shape) == [TOY["d_model"], 1, TOY["source_positions"]], |
| 281 | ) |
| 282 | original = get("model.encoder.embed_positions.weight") |
| 283 | check( |
| 284 | "so channel c of position p is table[c][0][p]", |
| 285 | np.allclose(values.reshape(TOY["d_model"], TOY["source_positions"]), original.T), |
| 286 | ) |
| 287 | |
| 288 | # The decoder's is added to a gathered embedding row on the host, so it is left alone. |
| 289 | decoder = next(layer for layer in layers if layer.op == "Table") |
| 290 | values = tensors[decoder.first_tensor] |
| 291 | check("the decoder's table is a host Table", decoder.name.endswith("decoder.embed_positions")) |
| 292 | check( |
| 293 | f"left [{TOY['target_positions']}, {TOY['d_model']}]", |
| 294 | list(values.shape) == [TOY["target_positions"], TOY["d_model"]], |
| 295 | ) |
| 296 | check( |
| 297 | "unchanged, because the host reads it", |
| 298 | np.allclose(values, get("model.decoder.embed_positions.weight")), |
| 299 | ) |
| 300 | |
| 301 | |
| 302 | def test_the_digest_covers_the_order() -> None: |
| 303 | print("the digest:") |
| 304 | get, _ = toy_checkpoint(TOY) |
| 305 | layers, _ = maml_convert.collect_whisper(get, TOY) |
| 306 | before = maml_convert.layer_table_digest(layers) |
| 307 | # A key is what the Rust hardcodes about a layer, not its name, so the pair swapped here has to |
| 308 | # differ in shape. The two convolutions differ in their stride as well as their input width. |
| 309 | swapped = list(layers) |
| 310 | swapped[0], swapped[1] = swapped[1], swapped[0] |
| 311 | check("swapping the two convolutions changes it", maml_convert.layer_table_digest(swapped) != before) |
| 312 | q = next(i for i, layer in enumerate(layers) if layer.name.endswith("q_proj")) |
| 313 | fc1 = next(i for i, layer in enumerate(layers) if layer.name.endswith("fc1")) |
| 314 | swapped = list(layers) |
| 315 | swapped[q], swapped[fc1] = swapped[fc1], swapped[q] |
| 316 | check("and so does a reordered projection pair", maml_convert.layer_table_digest(swapped) != before) |
| 317 | check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before) |
| 318 | # A key projection and a query projection are the same shape, so `b0=synthesised` is the only |
| 319 | # thing distinguishing them in the digest — which is exactly why it is in the key. |
| 320 | keys = "\n".join(layer.key() for layer in layers) |
| 321 | check( |
| 322 | "every key projection is marked synthesised", |
| 323 | keys.count("b0=synthesised") == 4 + 1, # four k_proj, plus the tied head |
| 324 | ) |
| 325 | |
| 326 | |
| 327 | def main() -> int: |
| 328 | test_the_inventory_is_the_real_architecture() |
| 329 | test_a_transposed_or_bias_grown_checkpoint_is_refused() |
| 330 | test_the_table_order_is_the_contract() |
| 331 | test_the_conv_stem_is_lifted_and_strided() |
| 332 | test_a_key_projection_gets_a_synthesised_zero_bias() |
| 333 | test_the_position_tables_go_opposite_ways() |
| 334 | test_the_digest_covers_the_order() |
| 335 | print(f"\n{passed} passed, {failed} failed") |
| 336 | return 1 if failed else 0 |
| 337 | |
| 338 | |
| 339 | if __name__ == "__main__": |
| 340 | raise SystemExit(main()) |