Modern Apps git

← Modern-Apps.git

speech: pin whisper-base upstream and convert it to .maml

Commit
291af7a9b7e568b11bb42d80da05a32dc810204b
Author
vayun-mathur <[email protected]>
When
2026-08-29 06:02 UTC (3 months ago)
Parents
b5fbe05

Diff

library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex ab458891c3..a13ea53a61 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -81,6 +81,12 @@ pub mod graph {     /// One graph rather than two because the towers share a file and a [`super::Weights`] upload,     /// even though they share no weights: `Mode::Image` and `Mode::Text` are two plans over one net.     pub const TINYCLIP: u32 = 16;+    /// whisper-base speech recognition, encoder and decoder in one file. See+    /// [`crate::nets::whisper`].+    ///+    /// One graph rather than two because the 51,865-row embedding is **tied**: it is the decoder's+    /// input table and the logits kernel, so two files would upload 26.6 MB of it twice.+    pub const WHISPER: u32 = 17; }  /// One tensor's entry in the table: where it is and what shape it is.
scripts/ml/fetch_whisper.py
diff --git a/scripts/ml/fetch_whisper.py b/scripts/ml/fetch_whisper.pynew file mode 100644index 0000000000..b7d3383af4--- /dev/null+++ b/scripts/ml/fetch_whisper.py@@ -0,0 +1,318 @@+#!/usr/bin/env python3+"""Fetch whisper-base's checkpoint and build the `whisper_base.maml` `:speech` bundles.++# Why this exists++It replaces `scripts/speech/fetch_whisper_onnx.sh`, which vendored two int8 ONNX exports from+`onnx-community/whisper-base` and pinned their digests. Those exports are gone with ONNX Runtime;+this reads the fp32 checkpoint they were quantised from and quantises it here instead.++# The fp32 checkpoint, not the int8 export++`onnx-community/whisper-base` is an ONNX Runtime **dynamic** int8 quantisation, and it quantises per+*tensor*. That is the same coarseness that moved SMaLL-100 onto `alirezamsh/small100`'s checkpoint+for a factor-of-four resolution gain on its embedding — see `CHECKPOINTS` in+`scripts/ml/maml_convert.py`. `maml_convert.quantise_per_channel` gives every kernel here a+per-output-channel scale, and the worst measured per-tensor correlation against fp32 is 0.99979.++`openai/whisper-base` is **Apache-2.0**. It is a build-host dependency only: 290 MB downloaded here,+nothing at run time.++# The pins, and what each one catches++* **File SHA-256**, below. Catches an upstream re-export at the same revision, or a truncated+  download.+* **`config.json`**, checked against [`ARCHITECTURE`] rather than trusted. `nets::whisper` hardcodes+  6 encoder layers, 6 decoder layers, `d_model` 512, 8 heads and a 2048-wide feed-forward.+* **`preprocessor_config.json`**, checked against [`FEATURES`]. `WhisperFeatures.kt` hardcodes the+  mel front end, and a wrong `n_fft` or `hop_length` produces fluent, confident nonsense rather than+  an error. The old shell script asserted the same constants; this keeps that.+* **`generation_config.json`**, checked against [`DECODING`]. The special-token ids and the+  suppression lists are what `post::whisper` is written against, and `<|notimestamps|>` in particular+  changes the output to timestamped text if it moves or is dropped.+* **The parameter inventory** `maml_convert.check_checkpoint` asserts — every name and every shape.+  It is also what catches the two absences the port depends on: no `k_proj.bias` anywhere, and no+  `proj_out` because the head is tied.+* **The layer table digest** `maml_convert.EXPECTED_DIGEST` pins, over the emitted order.++`vocab.json` and `generation_config.json` are **checked, not rewritten**. Both already ship beside+the model, vendored from `onnx-community/whisper-base` by the script this replaces, and both are+byte-for-byte what the runtime reads: `WhisperTokenizer` decodes with the vocabulary directly and+`post::whisper` reads the ids and suppression lists out of the generation config. Copying upstream's+copies over them would rewrite 50,000 lines of identically-meaning JSON, so instead this proves the+two mirrors **agree** — same token for every id below 50,257, same value for every decoding field —+which is a stronger statement than a copy and leaves the shipped bytes alone.++Usage:++    python scripts/ml/fetch_whisper.py                 # verify digests, write the assets+    python scripts/ml/fetch_whisper.py --work DIR      # keep the 290 MB checkpoint somewhere+    python scripts/ml/fetch_whisper.py --print-digests # after an intentional upstream bump+"""++import argparse+import hashlib+import json+import os+import subprocess+import sys+import tempfile++REPO = "openai/whisper-base"++# Pinned to a commit rather than to `main`, for the reason `fetch_and_convert.sh` gives: the digests+# below would catch a silent upstream change anyway, but a pinned revision tells you the upstream+# *revision* that moved rather than just that some bytes differ.+REVISION = "e37978b90ca9030d5170a5c07aadb050351a65bb"++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(os.path.dirname(HERE))++# A bundled asset directory, unlike `fetch_small100.py`'s runtime downloads.+OUT = os.path.join(ROOT, "speech", "src", "main", "assets", "whisper-base")++CHECKPOINT = "model.safetensors"+CONFIG = "config.json"+PREPROCESSOR = "preprocessor_config.json"+GENERATION = "generation_config.json"+VOCAB = "vocab.json"++# SHA-256 of every file this reads, at the pinned revision. Not the whole repo: `pytorch_model.bin`,+# `flax_model.msgpack` and `tf_model.h5` say the same thing as the checkpoint, so pinning them would+# pin something never downloaded.+DIGESTS = {+    CHECKPOINT: "07cadb9f25677c8d50df603e66a98fbd842cce45047139baeb16e6219a1e807b",+    CONFIG: "a153c53883a6799b6f056b4a8d1a515c9926d03994682ba88a7616618d7da0c1",+    PREPROCESSOR: "9b5cd03a36fbb8a627c64d98a5b5b126ead95a77720723944487311f0110b666",+    GENERATION: "444b3f636d2fff89dd9ecf549e2a085b61f7ff0fa0246d4628bac6a3b8cc9ba4",+    VOCAB: "8f680bba319e01a653d2e8a5dbc17a9157179e0576e6ce74ce0c06356c6e24f9",+}++# Transcribed from the pinned `config.json`, and asserted against it below rather than trusted.+# `nets::whisper` is written against these; `maml_convert.CHECKPOINTS` restates the subset the tensor+# table depends on.+ARCHITECTURE = {+    "d_model": 512,+    "encoder_layers": 6,+    "decoder_layers": 6,+    "encoder_attention_heads": 8,+    "decoder_attention_heads": 8,+    "encoder_ffn_dim": 2048,+    "decoder_ffn_dim": 2048,+    "vocab_size": 51_865,+    "max_source_positions": 1500,+    "max_target_positions": 448,+    "num_mel_bins": 80,+    "activation_function": "gelu",+    # No `sqrt(d_model)` on the embedding, unlike M2M-100. Asserted because the converter relies on+    # it: a checkpoint with `scale_embedding: true` would need the scale folded into the table.+    "scale_embedding": False,+}++# From the pinned `preprocessor_config.json`, and the constants `WhisperFeatures.kt` hardcodes. The+# old `fetch_whisper_onnx.sh` asserted these; a wrong mel is the one error in this pipeline that+# produces confident nonsense rather than a failure, so the check survives the port.+FEATURES = {+    "feature_size": 80,+    "n_fft": 400,+    "hop_length": 160,+    "sampling_rate": 16000,+    "n_samples": 480_000,+    "nb_max_frames": 3000,+    "chunk_length": 30,+}++# From the pinned `generation_config.json`, and the ids `post::whisper` is written against.+#+# `no_timestamps_token_id` is the one to watch: it is part of the step-0 prompt, and dropping it+# changes the output from plain text to `<|0.00|>`-style timestamped text. That is the same shape of+# hazard as SMaLL-100's "the language token goes on the source side".+DECODING = {+    "decoder_start_token_id": 50258,+    "eos_token_id": 50257,+    "pad_token_id": 50257,+    "no_timestamps_token_id": 50363,+    "max_length": 448,+    "is_multilingual": True,+}++# `task_to_id`, `lang_to_id` and the two suppression lists, checked by size and by spot value rather+# than transcribed in full: 99 languages and 88 suppressed ids would be a list checked against+# itself, but a list that changed *length* is a different model.+DECODING_SIZES = {+    "lang_to_id": 99,+    "suppress_tokens": 88,+    "begin_suppress_tokens": 2,+}++# Ids at or above this are special or timestamp tokens with no text form, and are not in+# `vocab.json`. The same constant as `WhisperTokenizer.FIRST_SPECIAL_ID`.+FIRST_SPECIAL_ID = 50_257+++def sha256(path):+    digest = hashlib.sha256()+    with open(path, "rb") as handle:+        for block in iter(lambda: handle.read(1 << 20), b""):+            digest.update(block)+    return digest.hexdigest()+++def convert(script, *args):+    """Run one of the sibling converters, letting its own output and exit code through.++    `check=True` matters: `maml_convert.py` exits non-zero when a layer table digest does not match,+    and that is the check that must stop an asset being written from the wrong checkpoint.+    """+    subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)+++def check_json(path, expected, label):+    """Fail if `path` does not hold every key of `expected` with that value."""+    held = json.load(open(path, encoding="utf-8"))+    wrong = {k: (held.get(k), v) for k, v in expected.items() if held.get(k) != v}+    if wrong:+        lines = "\n".join(f"  {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items())+        raise SystemExit(+            f"{path} is not the {label} the runtime hardcodes:\n{lines}\n"+            "Re-read it and check the Rust and Kotlin still match before re-pinning."+        )+    print(f"{os.path.basename(path)} matches {len(expected)} hardcoded {label} constants")+    return held+++def check_decoding(path):+    held = check_json(path, DECODING, "decoding")+    wrong = {}+    for key, count in DECODING_SIZES.items():+        got = len(held.get(key) or [])+        if got != count:+            wrong[key] = (got, count)+    # `transcribe` rather than `translate`: this is a recogniser, and the two ids are adjacent, so+    # reading one for the other is a one-digit mistake that produces English for every language.+    tasks = held.get("task_to_id") or {}+    if tasks.get("transcribe") != 50359:+        wrong["task_to_id.transcribe"] = (tasks.get("transcribe"), 50359)+    if wrong:+        lines = "\n".join(f"  {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items())+        raise SystemExit(f"{path}'s decoding tables moved:\n{lines}")+    print(f"generation_config.json has {DECODING_SIZES['lang_to_id']} languages and "+          f"{DECODING_SIZES['suppress_tokens']} suppressed ids")+    return held+++def check_bundled_vocabulary(upstream, bundled):+    """Fail unless the shipped `vocab.json` is the same token table as `upstream`'s.++    Not a digest comparison: the two mirrors serialise the same map differently — one key per line+    against compact — so the bytes differ and the meaning does not. What `WhisperTokenizer` reads is+    the token for each id below [`FIRST_SPECIAL_ID`], so that is what is compared.++    This is the only provenance the bundled table has ever had. The script this replaces pinned the+    digest of `onnx-community/whisper-base`'s copy, which said the bytes had not changed without+    saying they were right.+    """+    if not os.path.isfile(bundled):+        raise SystemExit(f"{bundled} is missing; it ships beside the model and is not rebuilt here")+    want = json.load(open(upstream, encoding="utf-8"))+    got = json.load(open(bundled, encoding="utf-8"))++    def table(mapping):+        out = [None] * FIRST_SPECIAL_ID+        for token, index in mapping.items():+            if 0 <= index < FIRST_SPECIAL_ID:+                out[index] = token+        return out++    a, b = table(want), table(got)+    differing = [index for index in range(FIRST_SPECIAL_ID) if a[index] != b[index]]+    missing = [index for index in range(FIRST_SPECIAL_ID) if b[index] is None]+    if differing or missing:+        raise SystemExit(+            f"{bundled} is not {REPO}'s token table:\n"+            f"  {len(differing)} ids differ, first {differing[:6]}\n"+            f"  {len(missing)} ids absent, first {missing[:6]}\n"+            "A wrong token table produces wrong text rather than an error."+        )+    print(f"the bundled vocab.json agrees with {REPO} on all {FIRST_SPECIAL_ID} text ids")+++def check_bundled_generation(upstream, bundled):+    """Fail unless the shipped `generation_config.json` decodes the same way as `upstream`'s.++    Every field `post::whisper` reads, plus the three tables, compared by value. The bundled copy also+    carries a `trust_remote_code` key upstream's does not, which nothing reads and which is therefore+    not compared.+    """+    if not os.path.isfile(bundled):+        raise SystemExit(f"{bundled} is missing; it ships beside the model and is not rebuilt here")+    want = json.load(open(upstream, encoding="utf-8"))+    got = json.load(open(bundled, encoding="utf-8"))+    keys = list(DECODING) + list(DECODING_SIZES) + ["task_to_id"]+    wrong = {k: (got.get(k), want.get(k)) for k in keys if got.get(k) != want.get(k)}+    if wrong:+        lines = "\n".join(f"  {k}: bundled {g!r} against upstream {w!r}" for k, (g, w) in wrong.items())+        raise SystemExit(f"{bundled} is not {REPO}'s generation config:\n{lines}")+    print(f"the bundled generation_config.json agrees with {REPO} on all {len(keys)} decoding fields")+++def main():+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+    parser.add_argument("--work", help="where to keep the checkpoint (default: a temp directory)")+    parser.add_argument("-o", "--out", default=OUT, help="where to write the assets")+    parser.add_argument(+        "--print-digests",+        action="store_true",+        help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",+    )+    args = parser.parse_args()++    try:+        from huggingface_hub import snapshot_download+    except ImportError:+        raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")++    work = args.work or os.path.join(tempfile.gettempdir(), "whisper")+    local = snapshot_download(+        repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work+    )+    print(f"{REPO}@{REVISION[:12]} in {local}")++    if args.print_digests:+        for name in DIGESTS:+            print(f'    {name}: "{sha256(os.path.join(local, name))}",')+        return 0++    for name, expected in DIGESTS.items():+        got = sha256(os.path.join(local, name))+        if got != expected:+            raise SystemExit(+                f"{name}\n  sha256 {got}\n  pinned {expected}\n"+                "The upstream checkpoint changed. Re-read it, check the Rust forward pass still\n"+                "matches, then re-pin with --print-digests."+            )+    print(f"{len(DIGESTS)} upstream digests match")+    check_json(os.path.join(local, CONFIG), ARCHITECTURE, "architecture")+    check_json(os.path.join(local, PREPROCESSOR), FEATURES, "mel front end")+    check_decoding(os.path.join(local, GENERATION))++    os.makedirs(args.out, exist_ok=True)+    graph = os.path.join(args.out, "whisper_base.maml")+    convert("maml_convert.py", os.path.join(local, CHECKPOINT), "--graph", "whisper", "-o", graph)+    # Checked rather than rewritten. See the module docstring.+    check_bundled_vocabulary(os.path.join(local, VOCAB), os.path.join(args.out, VOCAB))+    check_bundled_generation(+        os.path.join(local, GENERATION), os.path.join(args.out, GENERATION)+    )++    print(f"\n{args.out}")+    for name in sorted(os.listdir(args.out)):+        path = os.path.join(args.out, name)+        if os.path.isfile(path):+            size = os.path.getsize(path)+            print(f"  {name}: {size} bytes ({size / (1 << 20):.1f} MiB) {sha256(path)}")+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex 78b8e6c3b9..f6ca1b19a3 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -135,6 +135,8 @@ GRAPHS = {     "small100": 15,     # An ONNX graph read by name rather than walked; see [`ARCHITECTURES`].     "tinyclip": 16,+    # Read from a PyTorch checkpoint rather than an ONNX graph; see [`CHECKPOINTS`].+    "whisper": 17, }  # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -152,6 +154,7 @@ EXPECTED_DIGEST = {     "supertonic_ve": "48ab5789e8839507ff93e099dc0f61940f25da9ba6201651784f6e68598199e2",     "small100": "c9f05f2fb686aa53137ca06b521baf6d7a00f32cfb4ea42bd14a5c3e7cf6c086",     "tinyclip": "7557b2725b52ea04bd18b12e089320b9dd419cd3f7344c0e3d32888d61c24fa7",+    "whisper": "9e2830c5ea5d443fc31eb5c4eb80fa9a3b9bbcccd3c07963256ade50963c72a2", }  # Graphs that are one **module** of a larger export, keyed by the node-name prefix that@@ -315,6 +318,36 @@ CHECKPOINTS = {         # free; 128,112 is 2 x 64,056, so the halves are equal and no range is padded.         "head_splits": 2,     },+    # whisper-base, from `openai/whisper-base`. A checkpoint for the same reason SMaLL-100 is one:+    # the ONNX exports that exist are already int8 and quantised per **tensor**, which is the+    # coarseness that cost SMaLL-100's embedding a factor of four.+    #+    # Two things about this architecture are unlike anything else here, and both are asserted rather+    # than assumed by [`whisper_inventory`]:+    #+    # * **No `k_proj.bias`.** Only `q_proj`, `v_proj` and `out_proj` carry one, in all 18 attentions.+    #   `Builder::conv_int8` always reads a bias after the scale, so the converter synthesises a+    #   zero and records it in the digest key — a checkpoint that grows one must not be read as this+    #   table.+    # * **A convolution stem.** `conv1` is `[512, 80, 3]` stride 1 and `conv2` is `[512, 512, 3]`+    #   **stride 2**, which is what turns 3000 mel frames into 1500 encoder positions. Both are+    #   rank-3, so they are lifted to the `1 x k` rank-4 kernel this runtime indexes.+    #+    # The head is **tied** to `embed_tokens`, as SMaLL-100's is, but at 51,865 x 512 it is 26.6 MB+    # and fits one binding — so unlike SMaLL-100 it needs no class split.+    "whisper": {+        "d_model": 512,+        "encoder_layers": 6,+        "decoder_layers": 6,+        "ffn": 2048,+        "vocab": 51_865,+        "mels": 80,+        # `max_source_positions` and `max_target_positions`. The first is 3000 mel frames after+        # `conv2`'s stride 2; the second is the decoder's learned position table.+        "source_positions": 1500,+        "target_positions": 448,+        "conv_kernel": 3,+    }, }  @@ -729,6 +762,65 @@ def small100_inventory(spec):     return want  +def whisper_inventory(spec):+    """`{name: shape}` whisper-base's checkpoint must hold exactly, derived from [`CHECKPOINTS`].++    Derived rather than transcribed: a list of 245 names would be checked against itself.++    Two absences are as load-bearing as the presences, so both are stated by *not* appearing:++    * **`k_proj.bias` is not here**, in any of the 18 attentions. A checkpoint that grows one would+      have 18 unexpected names and fail, rather than being read as this table with the bias ignored.+    * **There is no `proj_out`.** The head is tied to `model.decoder.embed_tokens.weight`, which+      therefore appears once and is emitted once.++    The shapes are `torch.nn.Linear`'s **`[out, in]`**, which is a `[out, in, 1, 1]` kernel and so a+    reshape rather than a transpose. `fc1` at `[2048, 512]` and `fc2` at `[512, 2048]` are the+    asymmetric pair that makes a transposed checkpoint fail here rather than on the device.+    """+    d, ffn = spec["d_model"], spec["ffn"]+    kernel = spec["conv_kernel"]+    want = {+        "model.encoder.conv1.weight": [d, spec["mels"], kernel],+        "model.encoder.conv1.bias": [d],+        "model.encoder.conv2.weight": [d, d, kernel],+        "model.encoder.conv2.bias": [d],+        # A real tensor, not computed sinusoids: whisper freezes them into the checkpoint.+        "model.encoder.embed_positions.weight": [spec["source_positions"], d],+        "model.decoder.embed_tokens.weight": [spec["vocab"], d],+        # Learned, unlike the encoder's.+        "model.decoder.embed_positions.weight": [spec["target_positions"], d],+    }+    for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):+        want[f"model.{side}.layer_norm.weight"] = [d]+        want[f"model.{side}.layer_norm.bias"] = [d]+        for index in range(count):+            at = f"model.{side}.layers.{index}"+            attentions = ["self_attn"] + (["encoder_attn"] if side == "decoder" else [])+            for attention in attentions:+                want[f"{at}.{attention}_layer_norm.weight"] = [d]+                want[f"{at}.{attention}_layer_norm.bias"] = [d]+                for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):+                    want[f"{at}.{attention}.{projection}.weight"] = [d, d]+                    # Every projection but the key has a bias. See the docstring.+                    if projection != "k_proj":+                        want[f"{at}.{attention}.{projection}.bias"] = [d]+            want[f"{at}.final_layer_norm.weight"] = [d]+            want[f"{at}.final_layer_norm.bias"] = [d]+            want[f"{at}.fc1.weight"] = [ffn, d]+            want[f"{at}.fc1.bias"] = [ffn]+            want[f"{at}.fc2.weight"] = [d, ffn]+            want[f"{at}.fc2.bias"] = [d]+    return want+++# The inventory each checkpoint-sourced graph is checked against, and the collector that emits it.+#+# Two dicts rather than a key inside [`CHECKPOINTS`] because both hold functions defined below it.+INVENTORIES = {}+COLLECTORS = {}++ def check_checkpoint(shapes, graph_id_name):     """Refuse a checkpoint that is not the architecture the Rust forward pass hardcodes. @@ -744,7 +836,7 @@ def check_checkpoint(shapes, graph_id_name):     that mistake loud: a transposed checkpoint fails on those four numbers before anything is     written. That is the whole reason this asserts shapes rather than just names.     """-    want = small100_inventory(CHECKPOINTS[graph_id_name])+    want = INVENTORIES[graph_id_name](CHECKPOINTS[graph_id_name])     missing = sorted(set(want) - set(shapes))     extra = sorted(set(shapes) - set(want))     shared = sorted(set(want) & set(shapes))@@ -910,6 +1002,160 @@ def collect_small100(get, spec):     return layers, tensors  +def collect_whisper(get, spec):+    """whisper-base's checkpoint as the ordered tensor table `nets::whisper` indexes.++    Order is the contract, and it is forward order per stack, encoder first:++        `conv1`, `conv2`, the encoder position table, each encoder layer, the encoder's norm+        the tied head, the decoder position table, each decoder layer, the decoder's norm++    # The two convolutions++    Both are rank-3 in the checkpoint and are emitted as the `1 x k` rank-4 kernel this runtime+    indexes, which is a reshape of the same bytes. Their geometry is in the digest key rather than in+    the Rust alone, because `conv2`'s **stride 2** is what turns 3000 mel frames into 1500 encoder+    positions and a wrong stride gives the right rank and the wrong length.++    # The absent key bias++    No `k_proj` in any of the 18 attentions has one. `Builder::conv_int8` reads a bias after the+    scale, so each gets zeros — exact, and recorded in the digest key as `b0=synthesised` so a+    checkpoint that grows one is not silently read as this table.++    # The tied head++    `model.decoder.embed_tokens.weight` is emitted **once** and has two roles, as SMaLL-100's does:+    `nets::whisper` gathers a row of it on the host to build a decode step's input, and binds the+    same tensor as the kernel of the logits projection. At 51,865 x 512 it is 26.6 MB of int8, well+    inside `maxStorageBufferRange`'s guaranteed 128 MiB, so unlike SMaLL-100 it needs no class split.++    # What is not folded++    * The attention query scale. Whisper scales the query by `head_dim ** -0.5` and `head_dim` is 64,+      which is the `1 / sqrt(head_dim)` `attn_scores` already applies. Folding it would apply it+      twice.+    * `sqrt(d_model)` on the embedding. `config.json` has `scale_embedding: false`, so there is none.+    * Both **position tables** are real tensors, and they go opposite ways. The **encoder's** is+      added to the conv stem's output, which is a device tensor, so it is transposed to+      `[width, 1, positions]` and emitted as a `Kind::Constant`. The **decoder's** is added to a+      gathered embedding row on the *host*, in f32, exactly as `nets::small100::embed_positions`+      does, so it stays `[positions, width]` and never reaches a shader.+    """+    layers = []+    tensors = []+    fidelity = Fidelity()++    def emit(op, name, key, added):+        layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))++    def convolution(name, stride):+        """A rank-3 `[out, in, k]` kernel as the `1 x k` int8 one, its scale and its bias."""+        weight = get(f"{name}.weight")+        bias = get(f"{name}.bias")+        outputs, inputs, width = weight.shape+        lifted = weight.reshape(outputs, inputs, 1, width)+        kernel, scale = fidelity.quantise(name, lifted)+        tensors.extend([kernel, scale, bias])+        # ONNX orders pads as all the begins then all the ends, so a 1-D `[1, 1]` is `[0, 1, 0, 1]`.+        # `same` padding on a kernel of 3, which is what holds the length at stride 1 and halves it+        # at stride 2.+        emit(+            "Conv8",+            name,+            f"Conv8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "+            f"k={[1, width]} s={[1, stride]} p={[0, 1, 0, 1]} zp=0 dtype=int8",+            3,+        )++    def linear(name, biased=True):+        """An int8 kernel as `[out, in, 1, 1]`, its per-output-channel scale, and its bias."""+        weight = get(f"{name}.weight")+        outputs, inputs = weight.shape+        kernel, scale = fidelity.quantise(name, weight.reshape(outputs, inputs, 1, 1))+        if biased:+            bias = get(f"{name}.bias")+            suffix = ""+        else:+            bias = np.zeros(outputs, dtype=np.float32)+            suffix = " b0=synthesised"+        tensors.extend([kernel, scale, bias])+        emit(+            "Linear8",+            name,+            f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "+            f"zp=0 dtype=int8{suffix}",+            3,+        )++    def layer_norm(name):+        gamma = get(f"{name}.weight")+        beta = get(f"{name}.bias")+        tensors.extend([gamma, beta])+        emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)++    def table(name):+        values = get(f"{name}.weight")+        tensors.append(values)+        emit("Table", name, f"Table t={list(values.shape)}", 1)++    def constant(name):+        """A `[positions, width]` table as the `[width, 1, positions]` a `Kind::Constant` wants."""+        values = get(f"{name}.weight")+        positions, width = values.shape+        transposed = values.T.reshape(width, 1, positions).copy()+        tensors.append(transposed)+        emit("Constant", name, f"Constant t={list(transposed.shape)}", 1)++    def stack(side, count):+        for index in range(count):+            at = f"model.{side}.layers.{index}"+            # Pre-norm, as `WhisperEncoderLayer` and `WhisperDecoderLayer` are: the norm comes before+            # the sublayer it feeds and the residual skips both.+            attentions = ["self_attn"] + (["encoder_attn"] if side == "decoder" else [])+            for attention in attentions:+                layer_norm(f"{at}.{attention}_layer_norm")+                for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):+                    linear(f"{at}.{attention}.{projection}", biased=projection != "k_proj")+            layer_norm(f"{at}.final_layer_norm")+            linear(f"{at}.fc1")+            linear(f"{at}.fc2")+        layer_norm(f"model.{side}.layer_norm")++    # --- the encoder ---+    convolution("model.encoder.conv1", stride=1)+    # Stride 2: 3000 mel frames become the 1500 positions the decoder cross-attends over.+    convolution("model.encoder.conv2", stride=2)+    # Transposed and device-resident: it is added to the conv stem's output. The decoder's table+    # below is not, because the host adds that one.+    constant("model.encoder.embed_positions")+    stack("encoder", spec["encoder_layers"])++    # --- the decoder ---+    head = "model.decoder.embed_tokens"+    rows = get(f"{head}.weight")+    classes, width = rows.shape+    kernel, scale = fidelity.quantise(head, rows.reshape(classes, width, 1, 1))+    # `Builder::conv_int8` reads a bias after the scale, and a tied head has none.+    tensors.extend([kernel, scale, np.zeros(classes, dtype=np.float32)])+    emit(+        "Head",+        head,+        f"Head w={list(kernel.shape)} scale={[classes]} b={[classes]} tied=embed_tokens "+        "zp=0 dtype=int8 b0=synthesised",+        3,+    )+    table("model.decoder.embed_positions")+    stack("decoder", spec["decoder_layers"])++    fidelity.report()+    return layers, tensors+++INVENTORIES.update({"small100": small100_inventory, "whisper": whisper_inventory})+COLLECTORS.update({"small100": collect_small100, "whisper": collect_whisper})++ # The vision position table, after TinyCLIP's export constant-folds it: `position_ids` is a # constant, so the `Gather` that reads the table folds away and its `[1, 197, 256]` result is the # initializer. There is no `vision_model.embeddings.position_embedding.weight` to read.@@ -1280,7 +1526,7 @@ def main():     if args.graph in CHECKPOINTS:         get, shapes = open_checkpoint(args.model)         check_checkpoint(shapes, args.graph)-        layers, tensors = collect_small100(get, CHECKPOINTS[args.graph])+        layers, tensors = COLLECTORS[args.graph](get, CHECKPOINTS[args.graph])     elif args.graph in ARCHITECTURES:         model = onnx.load(args.model)         check_graph(model, args.graph)
scripts/ml/test/test_whisper.py
diff --git a/scripts/ml/test/test_whisper.py b/scripts/ml/test/test_whisper.pynew file mode 100644index 0000000000..217c416637--- /dev/null+++ b/scripts/ml/test/test_whisper.py@@ -0,0 +1,340 @@+#!/usr/bin/env python3+"""test_whisper.py - unit test for `maml_convert`'s whisper-base checkpoint path.++The sibling of `test_small100.py`, and the same argument: `collect_whisper` reads a checkpoint, so+nothing about its input records the architecture. `check_checkpoint` against `whisper_inventory` is+the whole shape guard, and `collect_whisper`'s emission *order* is the whole contract with+`nets::whisper`. Both are checked against a toy model of the same shape rather than the real 290 MB+checkpoint, so this runs in a second and needs no download.++What each check is defending against, beyond what the SMaLL-100 test already covers:++* **The absent `k_proj.bias`.** No key projection in any of whisper's 18 attentions has one, and+  `Builder::conv_int8` always reads a bias after the scale. The converter synthesises zeros; this+  asserts that a checkpoint which *grows* one is refused rather than read as this table with the+  bias ignored, and that the synthesis is recorded in the digest key.+* **The conv stem's stride.** `conv2` is stride 2, which is what turns 3000 mel frames into 1500+  encoder positions. A wrong stride gives the right rank and the wrong length, and the encoder's+  output length is not checked against anything downstream.+* **The rank-3 lift.** Both convolutions are `[out, in, k]` in the checkpoint and `[out, in, 1, k]`+  in the file. That is a reshape of the same bytes, and it must not be a transpose.+* **The tied head appearing once, and not being split.** SMaLL-100's is emitted as two class ranges+  because 128,112 x 1024 is 125 MiB against a guaranteed 128 MiB binding; whisper's 51,865 x 512 is+  26.6 MB and must be one tensor, or `nets::whisper` reads the wrong index for every layer after it.+* **The position tables going opposite ways.** The encoder's is added to the conv stem's output on+  the device, so it is transposed to `[width, 1, positions]` and emitted as a `Constant`; the+  decoder's is added to a gathered embedding row on the *host*, so it is left `[positions, width]`.+  Swapping them is silent.++Run:++    python3 scripts/ml/test/test_whisper.py++Exit code 0 = all assertions passed.+"""++from __future__ import annotations++import os+import sys++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import maml_convert  # noqa: E402  (needs the path above)++# The real architecture with every dimension shrunk, so the table has the same *structure* — two+# convolutions, two position tables, an encoder stack, a tied head, a decoder stack, two trailing+# norms — at a size that fits in memory. `conv_kernel` stays 3 because that is what the Rust reads.+TOY = {+    "d_model": 8,+    "encoder_layers": 2,+    "decoder_layers": 1,+    "ffn": 16,+    "vocab": 6,+    "mels": 4,+    "source_positions": 10,+    "target_positions": 5,+    "conv_kernel": 3,+}++passed = 0+failed = 0+++def check(what: str, ok: bool) -> None:+    global passed, failed+    if ok:+        passed += 1+        print(f"  ok    {what}")+    else:+        failed += 1+        print(f"  FAIL  {what}")+++def toy_checkpoint(spec, transpose_projections: bool = False, key_bias: bool = False):+    """`(get, shapes)` for a checkpoint of `spec`'s shape, filled with distinguishable values."""+    rng = np.random.default_rng(13)+    held = {}+    for name, shape in maml_convert.whisper_inventory(spec).items():+        if transpose_projections and name.endswith(".weight") and len(shape) == 2:+            shape = list(reversed(shape))+        held[name] = rng.standard_normal(shape).astype(np.float32)+    if key_bias:+        # The absence this port depends on, deliberately filled in.+        for name in [n for n in list(held) if n.endswith("k_proj.weight")]:+            held[name.replace(".weight", ".bias")] = np.zeros(spec["d_model"], dtype=np.float32)+    return held.__getitem__, {name: list(v.shape) for name, v in held.items()}+++def test_the_inventory_is_the_real_architecture() -> None:+    print("inventory:")+    want = maml_convert.whisper_inventory(maml_convert.CHECKPOINTS["whisper"])+    # 245 is what `openai/whisper-base` holds; a derived list that disagrees is derived wrong.+    check(f"245 parameters, got {len(want)}", len(want) == 245)+    check("the tied embedding is [vocab, d_model]", want["model.decoder.embed_tokens.weight"] == [51_865, 512])+    check("there is no proj_out, because the head is tied", "proj_out.weight" not in want)+    # The two convolutions, rank-3 in the checkpoint.+    check("conv1 is [d_model, mels, 3]", want["model.encoder.conv1.weight"] == [512, 80, 3])+    check("conv2 is [d_model, d_model, 3]", want["model.encoder.conv2.weight"] == [512, 512, 3])+    # The encoder's positions are a real frozen tensor, not computed sinusoids.+    check(+        "the encoder has a 1500-position table",+        want["model.encoder.embed_positions.weight"] == [1500, 512],+    )+    check(+        "and the decoder a learned 448-position one",+        want["model.decoder.embed_positions.weight"] == [448, 512],+    )+    # The pair a transpose would swap.+    check("fc1 is [ffn, d_model]", want["model.encoder.layers.0.fc1.weight"] == [2048, 512])+    check("fc2 is [d_model, ffn]", want["model.encoder.layers.0.fc2.weight"] == [512, 2048])+    # The absence, stated as an absence.+    keys = [n for n in want if n.endswith("k_proj.weight")]+    biases = [n for n in want if n.endswith("k_proj.bias")]+    check(f"18 key projections, got {len(keys)}", len(keys) == 18)+    check("and not one of them has a bias", not biases)+    check(+        "while q, v and out all do",+        all(+            f"model.encoder.layers.0.self_attn.{p}.bias" in want+            for p in ("q_proj", "v_proj", "out_proj")+        ),+    )+    check(+        "the decoder has cross-attention",+        "model.decoder.layers.0.encoder_attn.q_proj.weight" in want,+    )+    check(+        "the encoder has none",+        "model.encoder.layers.0.encoder_attn.q_proj.weight" not in want,+    )+    total = sum(int(np.prod(shape)) for shape in want.values())+    check(f"72,593,920 parameters, got {total}", total == 72_593_920)+++def test_a_transposed_or_bias_grown_checkpoint_is_refused() -> None:+    print("the two refusals:")+    real = maml_convert.whisper_inventory(maml_convert.CHECKPOINTS["whisper"])+    maml_convert.check_checkpoint(real, "whisper")+    check("the real inventory is accepted", True)++    flipped = {+        name: (list(reversed(shape)) if name.endswith(".weight") and len(shape) == 2 else shape)+        for name, shape in real.items()+    }+    try:+        maml_convert.check_checkpoint(flipped, "whisper")+        caught = ""+    except SystemExit as exit:+        caught = str(exit)+    check("a transposed checkpoint is refused", bool(caught))+    check("and fc1 is named in the message", "fc1" in caught)++    # A checkpoint that grew the bias the converter synthesises. It must fail, not be read as this+    # table: the emitted bias would be zeros while the real one is not, which is silent.+    grown = dict(real)+    grown["model.encoder.layers.0.self_attn.k_proj.bias"] = [512]+    try:+        maml_convert.check_checkpoint(grown, "whisper")+        caught = ""+    except SystemExit as exit:+        caught = str(exit)+    check("a checkpoint that grew a k_proj bias is refused", bool(caught))+    check("and it is named as unexpected", "k_proj.bias" in caught)+++def test_the_table_order_is_the_contract() -> None:+    print("order:")+    get, _ = toy_checkpoint(TOY)+    layers, tensors = maml_convert.collect_whisper(get, TOY)+    ops = [layer.op for layer in layers]+    encoder_layer = ["LayerNorm"] + ["Linear8"] * 4 + ["LayerNorm", "Linear8", "Linear8"]+    decoder_layer = (+        ["LayerNorm"] + ["Linear8"] * 4+        + ["LayerNorm"] + ["Linear8"] * 4+        + ["LayerNorm", "Linear8", "Linear8"]+    )+    expected = (+        ["Conv8", "Conv8", "Constant"]+        + encoder_layer * TOY["encoder_layers"]+        + ["LayerNorm"]+        + ["Head", "Table"]+        + decoder_layer * TOY["decoder_layers"]+        + ["LayerNorm"]+    )+    check("the whole table is encoder then decoder, in forward order", ops == expected)+    names = [layer.name for layer in layers]+    check("conv1 comes first", names[0].endswith("conv1"))+    check("then conv2", names[1].endswith("conv2"))+    check("then the encoder positions", names[2].endswith("encoder.embed_positions"))+    check("the tied head opens the decoder", names.count("model.decoder.embed_tokens") == 1)+    check("and is emitted once, unsplit", ops.count("Head") == 1)+    check("the decoder's norm is last", names[-1] == "model.decoder.layer_norm")+    # The stacks are contiguous.+    encoder = [i for i, name in enumerate(names) if ".encoder." in name]+    decoder = [i for i, name in enumerate(names) if ".decoder." in name]+    check("no decoder layer sits inside the encoder", max(encoder) < min(decoder))+    # Every layer's tensors are contiguous and in order, which is how the Rust indexes them.+    at = 0+    contiguous = True+    for layer in layers:+        contiguous = contiguous and layer.first_tensor == at+        at += layer.tensor_count+    check("layer tensor ranges tile the table", contiguous and at == len(tensors))+++def test_the_conv_stem_is_lifted_and_strided() -> None:+    print("the conv stem:")+    get, _ = toy_checkpoint(TOY)+    layers, tensors = maml_convert.collect_whisper(get, TOY)++    conv1, conv2 = layers[0], layers[1]+    for layer, inputs, stride in ((conv1, TOY["mels"], 1), (conv2, TOY["d_model"], 2)):+        kernel, scale, bias = tensors[layer.first_tensor: layer.first_tensor + 3]+        check(+            f"{layer.name.rsplit('.', 1)[-1]} is [{TOY['d_model']}, {inputs}, 1, 3] int8",+            list(kernel.shape) == [TOY["d_model"], inputs, 1, TOY["conv_kernel"]]+            and kernel.dtype == np.int8,+        )+        check("with one scale per output channel", scale.shape == (TOY["d_model"],))+        check("and the checkpoint's own bias", bias.shape == (TOY["d_model"],) and bias.any())+        check(f"and stride {stride} in its key", f"s={[1, stride]}" in layer.key())+    # The lift is a reshape, not a transpose: element order is unchanged.+    original = get("model.encoder.conv1.weight")+    kernel, scale, _ = tensors[conv1.first_tensor: conv1.first_tensor + 3]+    back = kernel.astype(np.float32).reshape(TOY["d_model"], -1) * scale[:, None]+    check(+        "the lift preserves element order",+        np.allclose(back.reshape(original.shape), original, atol=0.05),+    )+++def test_a_key_projection_gets_a_synthesised_zero_bias() -> None:+    print("the absent key bias:")+    get, _ = toy_checkpoint(TOY)+    layers, tensors = maml_convert.collect_whisper(get, TOY)+    keys = [layer for layer in layers if layer.name.endswith("k_proj")]+    check(f"{TOY['encoder_layers'] + TOY['decoder_layers'] * 2} key projections", len(keys) == 4)+    for layer in keys:+        kernel, scale, bias = tensors[layer.first_tensor: layer.first_tensor + 3]+        check(f"{layer.name.split('.layers.')[-1]}: still an int8 triple", layer.tensor_count == 3)+        check("with a zero bias", bias.shape == (TOY["d_model"],) and not bias.any())+        check("recorded in the key", "b0=synthesised" in layer.key())+        check("and a real kernel", kernel.dtype == np.int8 and scale.any())+    # And no other projection has one, which is what says the synthesis is targeted.+    others = [+        layer+        for layer in layers+        if layer.op == "Linear8" and not layer.name.endswith("k_proj")+    ]+    check(+        "no other projection is synthesised",+        all("b0=synthesised" not in layer.key() for layer in others),+    )+++def test_the_position_tables_go_opposite_ways() -> None:+    print("the head and the tables:")+    get, _ = toy_checkpoint(TOY)+    layers, tensors = maml_convert.collect_whisper(get, TOY)++    head = next(layer for layer in layers if layer.op == "Head")+    kernel, scale, bias = tensors[head.first_tensor: head.first_tensor + 3]+    check(+        f"[{TOY['vocab']}, {TOY['d_model']}, 1, 1] int8",+        list(kernel.shape) == [TOY["vocab"], TOY["d_model"], 1, 1] and kernel.dtype == np.int8,+    )+    check("one scale per class", scale.shape == (TOY["vocab"],))+    check("a tied head's bias is zero", bias.shape == (TOY["vocab"],) and not bias.any())+    check("and the tie is recorded in the key", "tied=embed_tokens" in head.key())++    # The encoder's table is added to the conv stem's output, which is a device tensor, so it is+    # transposed to `[width, 1, positions]` and emitted as a `Constant`.+    encoder = next(layer for layer in layers if layer.op == "Constant")+    values = tensors[encoder.first_tensor]+    check("the encoder's table is a Constant", encoder.name.endswith("encoder.embed_positions"))+    check(+        f"transposed to [{TOY['d_model']}, 1, {TOY['source_positions']}]",+        list(values.shape) == [TOY["d_model"], 1, TOY["source_positions"]],+    )+    original = get("model.encoder.embed_positions.weight")+    check(+        "so channel c of position p is table[c][0][p]",+        np.allclose(values.reshape(TOY["d_model"], TOY["source_positions"]), original.T),+    )++    # The decoder's is added to a gathered embedding row on the host, so it is left alone.+    decoder = next(layer for layer in layers if layer.op == "Table")+    values = tensors[decoder.first_tensor]+    check("the decoder's table is a host Table", decoder.name.endswith("decoder.embed_positions"))+    check(+        f"left [{TOY['target_positions']}, {TOY['d_model']}]",+        list(values.shape) == [TOY["target_positions"], TOY["d_model"]],+    )+    check(+        "unchanged, because the host reads it",+        np.allclose(values, get("model.decoder.embed_positions.weight")),+    )+++def test_the_digest_covers_the_order() -> None:+    print("the digest:")+    get, _ = toy_checkpoint(TOY)+    layers, _ = maml_convert.collect_whisper(get, TOY)+    before = maml_convert.layer_table_digest(layers)+    # A key is what the Rust hardcodes about a layer, not its name, so the pair swapped here has to+    # differ in shape. The two convolutions differ in their stride as well as their input width.+    swapped = list(layers)+    swapped[0], swapped[1] = swapped[1], swapped[0]+    check("swapping the two convolutions changes it", maml_convert.layer_table_digest(swapped) != before)+    q = next(i for i, layer in enumerate(layers) if layer.name.endswith("q_proj"))+    fc1 = next(i for i, layer in enumerate(layers) if layer.name.endswith("fc1"))+    swapped = list(layers)+    swapped[q], swapped[fc1] = swapped[fc1], swapped[q]+    check("and so does a reordered projection pair", maml_convert.layer_table_digest(swapped) != before)+    check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before)+    # A key projection and a query projection are the same shape, so `b0=synthesised` is the only+    # thing distinguishing them in the digest — which is exactly why it is in the key.+    keys = "\n".join(layer.key() for layer in layers)+    check(+        "every key projection is marked synthesised",+        keys.count("b0=synthesised") == 4 + 1,  # four k_proj, plus the tied head+    )+++def main() -> int:+    test_the_inventory_is_the_real_architecture()+    test_a_transposed_or_bias_grown_checkpoint_is_refused()+    test_the_table_order_is_the_contract()+    test_the_conv_stem_is_lifted_and_strided()+    test_a_key_projection_gets_a_synthesised_zero_bias()+    test_the_position_tables_go_opposite_ways()+    test_the_digest_covers_the_order()+    print(f"\n{passed} passed, {failed} failed")+    return 1 if failed else 0+++if __name__ == "__main__":+    raise SystemExit(main())
speech/src/main/assets/whisper-base/whisper_base.maml
diff --git a/speech/src/main/assets/whisper-base/whisper_base.maml b/speech/src/main/assets/whisper-base/whisper_base.mamlnew file mode 100644index 0000000000..fe7b539718Binary files /dev/null and b/speech/src/main/assets/whisper-base/whisper_base.maml differ