Modern Apps git

← Modern-Apps.git

photos: pin TinyCLIP upstream and convert it to .maml

Commit
ef39988c1912c7a0458858d14f5a46f723e732a1
Author
vayun-mathur <[email protected]>
When
2026-08-29 05:10 UTC (3 months ago)
Parents
1b40af5

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 da8e3d9fa4..e922b46155 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -76,6 +76,11 @@ pub mod graph {     /// input table, the decoder's input table and the logits kernel, and two files would upload     /// 125 MiB of it twice.     pub const SMALL100: u32 = 15;+    /// TinyCLIP-ViT-8M/16 Text-3M, both towers in one file. See [`crate::nets::tinyclip`].+    ///+    /// One graph rather than two because the towers share a file and a [`Weights`] upload, even+    /// though they share no weights: `Mode::Image` and `Mode::Text` are two plans over one net.+    pub const TINYCLIP: u32 = 16; }  /// One tensor's entry in the table: where it is and what shape it is.
photos/src/main/assets/clip/README.md
diff --git a/photos/src/main/assets/clip/README.md b/photos/src/main/assets/clip/README.mdnew file mode 100644index 0000000000..fd36393f36--- /dev/null+++ b/photos/src/main/assets/clip/README.md@@ -0,0 +1,65 @@+# `photos/src/main/assets/clip/`++TinyCLIP-ViT-8M/16 Text-3M, the semantic-search embedder `ClipEmbedder` runs.++| file | what it is |+| :--- | :--- |+| `tinyclip.maml` | 22.6 MiB. Both towers in one file, read by `:library:ml`'s Vulkan runtime |+| `bpe_simple_vocab_16e6.txt` | 3.0 MB. CLIP's BPE merge table, read by `ClipTokenizer` |++## Provenance++**`onnx-community/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M-ONNX`**, revision+`9463a9c508a344c837ffefe9d724f3827bf2dc79`, MIT — an ONNX export of+`wkcn/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M`, also MIT.++Rebuild with:++    python scripts/ml/fetch_tinyclip.py++That downloads `onnx/model.onnx` (94 MB, **build host only**), checks its SHA-256 against the pin+in that script, checks `config.json` and `preprocessor_config.json` against the architecture and+the preprocessing the runtime hardcodes, and runs `scripts/ml/maml_convert.py --graph tinyclip`.+The rebuild is byte-identical.++Until this existed, TinyCLIP was the only bundled model in the tree with **no pinned upstream+SHA-256 and no fetch script**. `SUPPLY_CHAIN_RISKS.md` named the repo in prose and nothing checked+it.++## Why the fp32 export and not the int8 one++The asset this replaced was `onnx/model_int8.onnx` (24.3 MB) from the same repo, run on+onnxruntime. It is not what the `.maml` is built from. Its 80 `MatMulInteger` weights are+per-output-channel with zero zero-points, but three tensors are not:++* `patch_embedding` has a **scalar** scale, over a kernel whose per-channel absmax spans 0.0018 to+  0.117.+* `token_embedding` is **uint8 with a zero point of 226**, and `position_embedding` **uint8 with+  220**. `conv_int8.comp` computes `scale[o] * sum(int8_w * in)` and has nowhere to put a zero+  point.++Requantising those would add a second rounding to resolution that is already gone, so the converter+reads the fp32 graph and quantises per output channel itself. Worst measured per-tensor correlation+between the fp32 weight and `int8 * scale` is **0.99986**, over 82 quantised tensors.++The result is *smaller* than the file it replaces — 23,734,912 bytes against 24,281,512 — because+the token embedding is int8 per row rather than uint8 per tensor and nothing is stored twice. The+APK shrinks by much more than that, because `onnxruntime-android`'s ~27 MB of native `.so` leaves+with it.++## What the `.maml` holds++306 tensors, 114 layers, 23,446,016 model parameters. Order is the contract between+`scripts/ml/maml_convert.py` and `library/ml/src/main/rust/src/nets/tinyclip.rs`, which indexes it+positionally — there are no names in the file. `maml_convert.py --graph tinyclip --print-layers`+prints the table.++Two transposes matter and are asserted rather than assumed. A `MatMul` weight is ONNX's+`[in, out]` and becomes `[out, in, 1, 1]`; the `Conv` patch kernel is `[M, C, kH, kW]` already and+is emitted **verbatim**. Every attention projection is square 256 x 256, so reading one convention+as the other gives a tensor of exactly the right shape holding exactly the wrong numbers.++## Licence++MIT, for both the export and the checkpoint it came from. This file is inside `assets/`, so it is+packaged into the APK — deliberately, so the attribution travels with the weights beside it.
photos/src/main/assets/clip/tinyclip.maml
diff --git a/photos/src/main/assets/clip/tinyclip.maml b/photos/src/main/assets/clip/tinyclip.mamlnew file mode 100644index 0000000000..ea6a26bc26Binary files /dev/null and b/photos/src/main/assets/clip/tinyclip.maml differ
scripts/ml/fetch_tinyclip.py
diff --git a/scripts/ml/fetch_tinyclip.py b/scripts/ml/fetch_tinyclip.pynew file mode 100644index 0000000000..7ff9586172--- /dev/null+++ b/scripts/ml/fetch_tinyclip.py@@ -0,0 +1,239 @@+#!/usr/bin/env python3+"""Fetch TinyCLIP's fp32 ONNX export and build the `tinyclip.maml` `:photos` bundles.++# Why this exists++TinyCLIP was the **only bundled model in this tree with no pinned upstream SHA-256 and no fetch+script**. `scripts/ml/fetch_and_convert.sh` lists six models and CLIP was not among them;+`photos/src/main/assets/clip/README.md` did not exist, and `photos/src/main/assets/README.md`+punted to `SUPPLY_CHAIN_RISKS.md`, which named an upstream repo in prose and nothing else. Every+other model here is pinned by revision *and* file digest. This closes that.++# The fp32 export, not the int8 one the app shipped++The asset being replaced is `onnx/model_int8.onnx` from this same repo, and it is **not** what is+converted. Read rather than assumed, its 80 `MatMulInteger` weights are per-output-channel with+zero zero-points — but three tensors are not:++* `vision_model.embeddings.patch_embedding.weight_scale` is a **scalar**, so one scale covers a+  kernel whose per-channel absmax spans 0.0018 to 0.117.+* `text_model.embeddings.token_embedding` is **uint8 with a zero point of 226**, and+  `text_model.embeddings.position_embedding` **uint8 with 220**. `conv_int8.comp` computes+  `scale[o] * sum(int8_w * in)` and has nowhere to put a zero point, which is the same objection+  `CHECKPOINTS` in `maml_convert.py` records against SMaLL-100's int8 export.++Requantising those per channel would add a second rounding to resolution that is already gone. So+this reads `onnx/model.onnx`, which is fp32, and `maml_convert.quantise_per_channel` gives all+three a per-output-channel scale and no zero point. The result is 22.6 MiB against the shipped+24.3 MB, and the measured worst per-tensor correlation is 0.99986.++`onnx/model.onnx` is a **build-host** dependency only: 94 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::tinyclip`+  hardcodes 10 vision layers, 3 text layers, width 256, 4 heads and a 1024-wide feed-forward.+* **The named-parameter inventory** `maml_convert.check_architecture` asserts — every name and+  every shape, including the `[in, out]` orientation of all 80 projections, which is what catches a+  transposed read. That mistake is invisible in the shape for the 76 square ones.+* **The op counts** `maml_convert.EXPECTED_OPS` pins, which only an ONNX graph can give.+* **The layer table digest** `maml_convert.EXPECTED_DIGEST` pins, over the emitted order.++The int8 fidelity gate in `maml_convert.Fidelity` is the only one of these that looks at the+numbers, and it only compares the quantisation against the weight it came from.+`scripts/ml/onnx_parity.py` is what compares the forward pass.++Usage:++    python scripts/ml/fetch_tinyclip.py                 # verify digests, write the asset+    python scripts/ml/fetch_tinyclip.py --work DIR      # keep the 94 MB export somewhere specific+    python scripts/ml/fetch_tinyclip.py --print-digests # after an intentional upstream bump+"""++import argparse+import hashlib+import json+import os+import subprocess+import sys+import tempfile++REPO = "onnx-community/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M-ONNX"++# 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.+#+# MIT, and an ONNX export of `wkcn/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M`, which is also MIT.+REVISION = "9463a9c508a344c837ffefe9d724f3827bf2dc79"++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(os.path.dirname(HERE))++# A bundled asset, unlike `fetch_small100.py`'s runtime downloads, so this writes straight into the+# APK's assets directory beside the BPE table the tokenizer reads.+OUT = os.path.join(ROOT, "photos", "src", "main", "assets", "clip")++MODEL = "onnx/model.onnx"+CONFIG = "config.json"+PREPROCESSOR = "preprocessor_config.json"++# SHA-256 of every file this reads, at the pinned revision. Not the whole repo: the seven other+# quantisations of the same graph say the same thing as the fp32 one, so pinning them would pin+# something never downloaded.+DIGESTS = {+    MODEL: "31d28cb07209533d10fc4fef73ac324ce17de6741a2372e7e1531a4ac8fdaeb2",+    CONFIG: "0ca46b868f12305e959a1cfa2b8085e7bffd521f68769ec3bf2999986b55bec3",+    PREPROCESSOR: "5df7e578c37e907a431daf47fd592fc49fa50d23ed4c41285a0a34a58a9d2e06",+}++# Transcribed from the pinned `config.json`, and asserted against it below rather than trusted.+# `nets::tinyclip` is written against these; `maml_convert.ARCHITECTURES` restates the subset the+# tensor table depends on.+ARCHITECTURE = {+    "projection_dim": 512,+    "vision": {+        "hidden_size": 256,+        "intermediate_size": 1024,+        "num_attention_heads": 4,+        "num_hidden_layers": 10,+        "patch_size": 16,+        "hidden_act": "gelu",+    },+    "text": {+        "hidden_size": 256,+        "intermediate_size": 1024,+        "num_attention_heads": 4,+        "num_hidden_layers": 3,+        "hidden_act": "gelu",+    },+}++# From the pinned `preprocessor_config.json`, and the numbers `ClipEmbedder.preprocess` hardcodes.+# Asserted here so a re-pin that changed the normalisation could not pass silently: a wrong mean or+# a wrong crop size produces embeddings that are plausible and wrong, and nothing downstream checks+# them.+PREPROCESSING = {+    "size": 224,+    "crop_size": 224,+    "image_mean": [0.48145466, 0.4578275, 0.40821073],+    "image_std": [0.26862954, 0.26130258, 0.27577711],+}+++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 export.+    """+    subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)+++def check_architecture(path):+    """Fail if the export's config is not the architecture `nets::tinyclip` is written against."""+    held = json.load(open(path, encoding="utf-8"))+    wrong = {}+    if held.get("projection_dim") != ARCHITECTURE["projection_dim"]:+        wrong["projection_dim"] = (held.get("projection_dim"), ARCHITECTURE["projection_dim"])+    for tower in ("vision", "text"):+        config = held.get(f"{tower}_config", {})+        for key, want in ARCHITECTURE[tower].items():+            if config.get(key) != want:+                wrong[f"{tower}_config.{key}"] = (config.get(key), want)+    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 architecture the runtime hardcodes:\n{lines}\n"+            "nets::tinyclip has these baked in, so re-read it before re-pinning."+        )+    print("config.json matches the hardcoded architecture of both towers")+++def check_preprocessing(path):+    """Fail if the export's preprocessing is not what `ClipEmbedder.preprocess` implements."""+    held = json.load(open(path, encoding="utf-8"))+    got = {+        # Both are `{"shortest_edge": 224}` / `{"height": 224, "width": 224}` dicts upstream, so+        # the values are pulled out rather than compared as dicts.+        "size": (held.get("size") or {}).get("shortest_edge"),+        "crop_size": (held.get("crop_size") or {}).get("height"),+        "image_mean": held.get("image_mean"),+        "image_std": held.get("image_std"),+    }+    close = all(+        abs(a - b) < 1e-6+        for key in ("image_mean", "image_std")+        for a, b in zip(got[key] or [], PREPROCESSING[key])+    )+    sized = got["size"] == PREPROCESSING["size"] and got["crop_size"] == PREPROCESSING["crop_size"]+    if not (close and sized):+        raise SystemExit(+            f"{path} is not the preprocessing ClipEmbedder implements:\n"+            f"  got  {got}\n  want {PREPROCESSING}\n"+            "A wrong mean or crop produces embeddings that are plausible and wrong."+        )+    print("preprocessor_config.json matches ClipEmbedder.preprocess")+++def main():+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+    parser.add_argument("--work", help="where to keep the export (default: a temp directory)")+    parser.add_argument("-o", "--out", default=OUT, help="where to write tinyclip.maml")+    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(), "tinyclip")+    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 export 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_architecture(os.path.join(local, CONFIG))+    check_preprocessing(os.path.join(local, PREPROCESSOR))++    os.makedirs(args.out, exist_ok=True)+    asset = os.path.join(args.out, "tinyclip.maml")+    convert("maml_convert.py", os.path.join(local, MODEL), "--graph", "tinyclip", "-o", asset)++    size = os.path.getsize(asset)+    print(f"\n{asset}: {size} bytes ({size / (1 << 20):.1f} MiB)")+    print(f"  sha256 {sha256(asset)}")+    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 3be8f653da..78b8e6c3b9 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -43,6 +43,11 @@ One graph does not come from an ONNX export at all. SMaLL-100 is read from its P `.safetensors` and quantised to int8 here, because the only ONNX exports that exist for it are already int8 and quantised per *tensor*; see [`CHECKPOINTS`] for why that is not usable. +One graph is an ONNX export whose tensor table is nevertheless **derived from architecture+constants and read by name**, rather than walked topologically. TinyCLIP is two towers in one+graph, interleaved, and its projections are anonymous `onnx::MatMul_NNNN` initializers, so a+topological walk would emit an order no one could read. See [`ARCHITECTURES`].+     ./scripts/ml/maml_convert.py --check model.onnx --graph u2netp     ./scripts/ml/maml_convert.py model.onnx --graph u2netp -o out.maml     ./scripts/ml/maml_convert.py model.onnx --graph u2netp --print-layers@@ -128,6 +133,8 @@ GRAPHS = {     "supertonic_ve": 14,     # Read from a PyTorch checkpoint rather than an ONNX graph; see [`CHECKPOINTS`].     "small100": 15,+    # An ONNX graph read by name rather than walked; see [`ARCHITECTURES`].+    "tinyclip": 16, }  # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -144,6 +151,7 @@ EXPECTED_DIGEST = {     "supertonic_ttl": "92d0fa8ae73d4a8a223c77fb4230e390df580744014a3fcf3211ab72a988c020",     "supertonic_ve": "48ab5789e8839507ff93e099dc0f61940f25da9ba6201651784f6e68598199e2",     "small100": "c9f05f2fb686aa53137ca06b521baf6d7a00f32cfb4ea42bd14a5c3e7cf6c086",+    "tinyclip": "7557b2725b52ea04bd18b12e089320b9dd419cd3f7344c0e3d32888d61c24fa7", }  # Graphs that are one **module** of a larger export, keyed by the node-name prefix that@@ -214,6 +222,62 @@ EXPECTED_OPS = {         "Conv": 49, "PRelu": 34, "Add": 12, "BatchNormalization": 1, "Flatten": 1,         "Gemm": 1,     },+    # Two towers in one graph. `MatMul` 107 is the 80 weighted projections plus the 26 attention+    # products and the one `logit_scale` product; `Erf` 13 is the 13 layers' GELU; `Softmax` 13 is+    # their attention, and the causal mask the text tower's three need is a `-3.4e38` constant+    # added to the score map, not an op. `ArgMax` 1 is the end-of-text search this runtime does on+    # the host. Counted rather than transcribed: `python -c` over the graph produced these.+    "tinyclip": {+        "Add": 186, "ArgMax": 1, "Cast": 5, "Concat": 27, "ConstantOfShape": 1, "Conv": 1,+        "Div": 44, "Equal": 4, "Erf": 13, "Expand": 3, "Flatten": 1, "Gather": 20, "Less": 1,+        "MatMul": 107, "Mul": 73, "Pow": 33, "Range": 2, "ReduceMean": 58, "ReduceSum": 2,+        "Reshape": 113, "Shape": 12, "Slice": 3, "Softmax": 13, "Sqrt": 29, "Squeeze": 1,+        "Sub": 31, "Transpose": 68, "Unsqueeze": 20, "Where": 5,+    },+}++# ONNX graphs whose tensor table is **derived from these constants and read by name**, rather than+# produced by the topological walk in [`collect_layers`].+#+# One entry, TinyCLIP. Three things make the walk unusable for it:+#+# * It is **two towers in one graph**, and the export interleaves them - text layer 0, vision layer+#   0, text layer 1, and so on. A topological order is therefore an order no reader could check+#   against `nets::tinyclip`, and `Mode::Image` and `Mode::Text` would each read a stride through+#   the table.+# * Every projection is a bare `MatMul` against an **anonymous** `onnx::MatMul_NNNN` initializer.+#   There is nothing in the initializer's name to say which layer or which projection it is. The+#   *node* names are fully structured (`/vision_model/encoder/layers.3/mlp/fc1/MatMul`), so this+#   reads the weight through the node, which is also what makes the inventory check below possible.+# * `MatMul` is `x @ W` with a **`[in, out]`** weight, and this runtime indexes a kernel as+#   `[out, in, kh, kw]`. Every attention projection here is square 256 x 256, so reading one+#   convention as the other yields a tensor of exactly the right shape holding exactly the wrong+#   numbers. `fc1` is `[256, 1024]` and `fc2` is `[1024, 256]`, so the shape assertions in+#   [`check_architecture`] are what make that loud.+#+# The `Conv` is the one exception and needs **no** transpose: ONNX `Conv` is already+# `[M, C, kH, kW]`, which is this runtime's own layout.+#+# What is checked is the **exact named-parameter inventory** derived from these constants, as+# [`CHECKPOINTS`] gets, *plus* the op counts in [`EXPECTED_OPS`] that only an ONNX graph can give.+# There is no [`GEOMETRY`] entry: this export has three inputs and four outputs and is dynamically+# shaped throughout, so there is no single boundary shape to compare against.+ARCHITECTURES = {+    "tinyclip": {+        # `hidden_size`, shared by both towers, and `num_attention_heads` 4, so `head_dim` is 64+        # and `Builder::attn_scores`'s own `1 / sqrt(64)` is already the model's 0.125 scale.+        "width": 256,+        "heads": 4,+        "ffn": 1024,+        "vision_layers": 10,+        "text_layers": 3,+        # 16 x 16 patches over 224 x 224 is a 14 x 14 grid, so 196 patches plus the class token.+        "patch": 16,+        "grid": 14,+        "vocab": 49_408,+        "context": 77,+        "projection": 512,+    }, }  # Graphs read from a **PyTorch checkpoint** rather than an ONNX graph, keyed by graph id name.@@ -582,7 +646,7 @@ def check_graph(model, graph_id_name):     prefix = MODULES.get(graph_id_name)     nodes = [n for n in graph.node if prefix is None or n.name.startswith(prefix)] -    if prefix is None:+    if prefix is None and graph_id_name in GEOMETRY:         want = GEOMETRY[graph_id_name]         names = [i.name for i in graph.input]         if names != [want["input"]]:@@ -700,6 +764,45 @@ def check_checkpoint(shapes, graph_id_name):         )  +class Fidelity:+    """The worst per-tensor cosine between an fp32 weight and the `int8 * scale` a device reads.++    The only check that looks at the *numbers* a quantisation produces. It is not a check that the+    forward pass is right — a transposed read agrees with itself perfectly, which is why+    [`check_checkpoint`] and [`check_architecture`] assert shapes — and it is not a check that the+    model is accurate, which `scripts/ml/onnx_parity.py` is for. It is the one thing that catches a+    layer whose distribution int8 cannot represent, before it ships.+    """++    def __init__(self):+        self.seen = []++    def quantise(self, name, weight):+        """`(int8, scale)` for `weight`, recording how well the pair reproduces it."""+        kernel, scale = quantise_per_channel(weight)+        back = kernel.astype(np.float32).reshape(weight.shape[0], -1) * scale[:, None]+        flat = np.ascontiguousarray(weight, dtype=np.float32).reshape(weight.shape[0], -1)+        cosine = float(+            np.dot(flat.ravel(), back.ravel())+            / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30)+        )+        self.seen.append((cosine, name))+        return kernel, scale++    def report(self):+        """Print the worst three, and refuse the file if any is under [`MIN_INT8_COSINE`]."""+        self.seen.sort()+        for cosine, name in self.seen[:3]:+            if cosine < MIN_INT8_COSINE:+                raise SystemExit(+                    f"{name}: int8 * scale correlates {cosine:.6f} with the fp32 weight, under"+                    f" {MIN_INT8_COSINE}.\nQuantising this layer costs too much; exclude it and"+                    " store it fp16 instead."+                )+        worst = ", ".join(f"{name} {cosine:.6f}" for cosine, name in self.seen[:3])+        print(f"int8 fidelity over {len(self.seen)} tensors, worst three: {worst}")++ def collect_small100(get, spec):     """SMaLL-100's checkpoint as the ordered tensor table `nets::small100` indexes. @@ -736,18 +839,7 @@ def collect_small100(get, spec):     # the device will read. This is the only check that the quantisation itself is usable; the     # shape assertions in [`check_checkpoint`] are what catch a transpose, since a cosine is     # computed against whatever was read and a transposed read agrees with itself perfectly.-    fidelity = []--    def quantise(name, weight):-        kernel, scale = quantise_per_channel(weight)-        back = kernel.astype(np.float32).reshape(weight.shape[0], -1) * scale[:, None]-        flat = weight.reshape(weight.shape[0], -1)-        cosine = float(-            np.dot(flat.ravel(), back.ravel())-            / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30)-        )-        fidelity.append((cosine, name))-        return kernel, scale+    fidelity = Fidelity()      def emit(op, name, key, added):         layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))@@ -757,7 +849,7 @@ def collect_small100(get, spec):         weight = get(f"{name}.weight")         bias = get(f"{name}.bias")         outputs, inputs = weight.shape-        kernel, scale = quantise(name, weight.reshape(outputs, inputs, 1, 1))+        kernel, scale = fidelity.quantise(name, weight.reshape(outputs, inputs, 1, 1))         tensors.extend([kernel, scale, bias])         emit(             "Linear8",@@ -783,7 +875,7 @@ def collect_small100(get, spec):         lo = part * step         rows = embedding[lo : lo + step]         name = f"model.shared.weight[{lo}:{lo + step}]"-        kernel, scale = quantise(name, rows.reshape(step, width, 1, 1))+        kernel, scale = fidelity.quantise(name, rows.reshape(step, width, 1, 1))         # `Builder::conv_int8` reads a bias after the scale, and a tied head has none. Zeros are         # exact, and recording it in the key means a checkpoint that grows one is not mistaken for         # this table.@@ -814,16 +906,260 @@ def collect_small100(get, spec):             linear(f"{at}.fc2")         layer_norm(f"model.{side}.layer_norm") -    fidelity.sort()-    for cosine, name in fidelity[:3]:-        if cosine < MIN_INT8_COSINE:-            raise SystemExit(-                f"{name}: int8 * scale correlates {cosine:.6f} with the fp32 weight, under"-                f" {MIN_INT8_COSINE}.\nQuantising this layer costs too much; exclude it and store"-                " it fp16 instead."+    fidelity.report()+    return layers, tensors+++# 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.+#+# Named here because it is the one parameter whose key is an internal tensor name rather than a+# module path, and both [`tinyclip_inventory`] and [`collect_tinyclip`] have to agree about it.+VISION_POSITIONS_FOLDED = "/vision_model/embeddings/position_embedding/Gather_output_0"+++def tinyclip_inventory(spec):+    """What TinyCLIP's export must hold, as two dicts keyed the two ways the graph names things.++    Returned rather than transcribed: a list of 250 names would be checked against itself.++    * `parameters` is `{initializer name: dims}` for everything the export names — the norms, the+      biases, the patch kernel, both embedding tables and the class token.+    * `projections` is `{MatMul node name: dims}` for the 80 anonymous weights. Keyed by node+      because the initializer names carry no information; see [`ARCHITECTURES`].++    `dims` for a projection is ONNX's own **`[in, out]`**, so this dict is also the statement that+    catches a transposed read: `fc1` at `[256, 1024]` and `fc2` at `[1024, 256]` cannot both be+    satisfied by a checkpoint whose linears are stored the other way round.+    """+    width, ffn, projection = spec["width"], spec["ffn"], spec["projection"]+    parameters = {+        "vision_model.embeddings.patch_embedding.weight": [+            width, 3, spec["patch"], spec["patch"],+        ],+        "vision_model.embeddings.class_embedding": [width],+        VISION_POSITIONS_FOLDED: [1, spec["grid"] ** 2 + 1, width],+        "vision_model.pre_layrnorm.weight": [width],+        "vision_model.pre_layrnorm.bias": [width],+        "vision_model.post_layernorm.weight": [width],+        "vision_model.post_layernorm.bias": [width],+        "text_model.embeddings.token_embedding.weight": [spec["vocab"], width],+        "text_model.embeddings.position_embedding.weight": [spec["context"], width],+        "text_model.final_layer_norm.weight": [width],+        "text_model.final_layer_norm.bias": [width],+    }+    projections = {+        "/visual_projection/MatMul": [width, projection],+        "/text_projection/MatMul": [width, projection],+    }+    for tower, count in (("vision", spec["vision_layers"]), ("text", spec["text_layers"])):+        for index in range(count):+            at = f"{tower}_model.encoder.layers.{index}"+            node = f"/{tower}_model/encoder/layers.{index}"+            for norm in ("layer_norm1", "layer_norm2"):+                parameters[f"{at}.{norm}.weight"] = [width]+                parameters[f"{at}.{norm}.bias"] = [width]+            for name in ("q_proj", "k_proj", "v_proj", "out_proj"):+                parameters[f"{at}.self_attn.{name}.bias"] = [width]+                projections[f"{node}/self_attn/{name}/MatMul"] = [width, width]+            parameters[f"{at}.mlp.fc1.bias"] = [ffn]+            parameters[f"{at}.mlp.fc2.bias"] = [width]+            projections[f"{node}/mlp/fc1/MatMul"] = [width, ffn]+            projections[f"{node}/mlp/fc2/MatMul"] = [ffn, width]+    return parameters, projections+++def check_architecture(model, graph_id_name, spec):+    """Refuse an ONNX export that is not the architecture `nets/<graph>.rs` hardcodes.++    The counterpart of [`check_checkpoint`], and the same argument: a wrong shape here is a wrong+    forward pass rather than a load failure, so it is asserted before anything is written. The op+    counts in [`EXPECTED_OPS`] are checked as well, by [`check_graph`] — this is the stricter of+    the two, because it fails on a renamed or resized parameter as well as on a missing one.++    `spec` is passed rather than looked up, as [`collect_tinyclip`]'s is, so the two cannot be+    given different ones.+    """+    parameters, projections = tinyclip_inventory(spec)+    inits = {i.name: list(i.dims) for i in model.graph.initializer}+    nodes = {n.name: n for n in model.graph.node}++    lines = []+    for name, want in sorted(parameters.items()):+        got = inits.get(name)+        if got != want:+            lines.append(f"  {name}: {got} against {want}")+    for node_name, want in sorted(projections.items()):+        node = nodes.get(node_name)+        if node is None:+            lines.append(f"  {node_name}: no such node")+            continue+        held = [x for x in node.input if x in inits]+        if len(held) != 1 or inits[held[0]] != want:+            lines.append(f"  {node_name}: {[inits.get(h) for h in held]} against {want}")+    if lines:+        raise SystemExit(+            f"{graph_id_name}: the export is not the architecture "+            f"nets/{graph_id_name}.rs\nhardcodes. A wrong shape here is a wrong forward pass, "+            "not a load failure:\n" + "\n".join(lines[:12])+        )+    print(+        f"{len(parameters)} named parameters and {len(projections)} projections match the "+        f"{graph_id_name} architecture"+    )+++def collect_tinyclip(model, spec):+    """TinyCLIP's export as the ordered tensor table `nets::tinyclip` indexes.++    Order is the contract, and it is forward order **per tower**, vision first:++        the patch kernel, the class token, the vision positions, `pre_layrnorm`+        each vision layer, then `post_layernorm`, then `visual_projection`+        the token embedding, the text positions+        each text layer, then `final_layer_norm`, then `text_projection`++    The export interleaves the two towers; this does not. See [`ARCHITECTURES`].++    # What is transposed, and what is not++    * A **`MatMul`** weight is `[in, out]` and becomes `[out, in, 1, 1]`, so every projection is+      the `1 x 1` convolution `Builder::conv_int8` already computes.+    * The **`Conv`** patch kernel is `[M, C, kH, kW]` already, which is this runtime's own layout,+      so it is emitted **verbatim**. The `[256, 3, 16, 16]` assertion in [`check_architecture`] is+      what says so; a transpose here would be a plausible-looking embedding.+    * The two **position tables** are `[positions, width]` and the vision one becomes+      `[width, 1, positions]`, because it is added to a sequence the device holds channel-major.+      The text one is **not** transposed: the host reads it, gathers the token rows and adds the+      two in f32, exactly as `nets::small100::embed_positions` does, so it never reaches a shader.++    # What has no bias, and what gets a synthesised one++    The patch embedding and both projections have none — `bias=False` on all three in+    `CLIPModel`. The shaders always add one, so each gets zeros, which is exact and is recorded in+    the digest key so an export that grows a bias is not read as this table.+    """+    width = spec["width"]+    inits = {i.name: i for i in model.graph.initializer}+    nodes = {n.name: n for n in model.graph.node}+    layers = []+    tensors = []+    fidelity = Fidelity()++    def array(name):+        return numpy_helper.to_array(inits[name]).astype(np.float32)++    def emit(op, name, key, added):+        layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))++    def matmul_weight(node_name):+        """The `[in, out]` initializer a projection's `MatMul` reads, by **node** name."""+        held = [x for x in nodes[node_name].input if x in inits]+        return numpy_helper.to_array(inits[held[0]]).astype(np.float32)++    def projection(node_name, name):+        """A `MatMul` as an int8 `[out, in, 1, 1]` kernel, its per-output scale and a zero bias."""+        weight = matmul_weight(node_name)+        inputs, outputs = weight.shape+        kernel, scale = fidelity.quantise(name, weight.T.reshape(outputs, inputs, 1, 1))+        tensors.extend([kernel, scale, np.zeros(outputs, dtype=np.float32)])+        emit(+            "Linear8",+            name,+            f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={[outputs]} "+            "zp=0 dtype=int8 b0=synthesised",+            3,+        )++    def linear(node_name, bias_name, name):+        """[`projection`] with the export's own bias, which every layer projection has."""+        weight = matmul_weight(node_name)+        bias = array(bias_name)+        inputs, outputs = weight.shape+        kernel, scale = fidelity.quantise(name, weight.T.reshape(outputs, inputs, 1, 1))+        tensors.extend([kernel, scale, bias])+        emit(+            "Linear8",+            name,+            f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "+            "zp=0 dtype=int8",+            3,+        )++    def layer_norm(name):+        gamma = array(f"{name}.weight")+        beta = array(f"{name}.bias")+        tensors.extend([gamma, beta])+        emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)++    def constant(name, values):+        tensors.append(values)+        emit("Constant", name, f"Constant t={list(values.shape)}", 1)++    def encoder_layer(tower, index):+        at = f"{tower}_model.encoder.layers.{index}"+        node = f"/{tower}_model/encoder/layers.{index}"+        # Pre-norm, as `CLIPEncoderLayer` is: the norm comes before the sublayer it feeds and the+        # residual skips both. Emitting in forward order is what lets the Rust walk the table.+        layer_norm(f"{at}.layer_norm1")+        for name in ("q_proj", "k_proj", "v_proj", "out_proj"):+            linear(+                f"{node}/self_attn/{name}/MatMul",+                f"{at}.self_attn.{name}.bias",+                f"{at}.self_attn.{name}",             )-    worst = ", ".join(f"{name} {cosine:.6f}" for cosine, name in fidelity[:3])-    print(f"int8 fidelity over {len(fidelity)} tensors, worst three: {worst}")+        layer_norm(f"{at}.layer_norm2")+        linear(f"{node}/mlp/fc1/MatMul", f"{at}.mlp.fc1.bias", f"{at}.mlp.fc1")+        linear(f"{node}/mlp/fc2/MatMul", f"{at}.mlp.fc2.bias", f"{at}.mlp.fc2")++    # --- the vision tower ---+    patch = "vision_model.embeddings.patch_embedding.weight"+    kernel, scale = fidelity.quantise(patch, array(patch))+    tensors.extend([kernel, scale, np.zeros(width, dtype=np.float32)])+    emit(+        "Conv8",+        patch,+        f"Conv8 w={list(kernel.shape)} scale={[width]} b={[width]} "+        f"k={[spec['patch'], spec['patch']]} s={[spec['patch'], spec['patch']]} "+        "p=[0, 0, 0, 0] zp=0 dtype=int8 b0=synthesised",+        3,+    )+    # `[width]` as the `[width, 1, 1]` a `Kind::Constant` wants: one position, every channel.+    token = array("vision_model.embeddings.class_embedding").reshape(width, 1, 1)+    constant("vision_model.embeddings.class_embedding", token)+    positions = np.squeeze(array(VISION_POSITIONS_FOLDED))+    constant(VISION_POSITIONS_FOLDED, positions.T.reshape(width, 1, positions.shape[0]).copy())+    layer_norm("vision_model.pre_layrnorm")+    for index in range(spec["vision_layers"]):+        encoder_layer("vision", index)+    layer_norm("vision_model.post_layernorm")+    projection("/visual_projection/MatMul", "visual_projection")++    # --- the text tower ---+    table = "text_model.embeddings.token_embedding.weight"+    rows = array(table)+    # Per **row**, which is per token: the host gathers one row and dequantises it by that row's+    # own scale, so this is the same shape of table `collect_small100`'s tied embedding is. The+    # export's own int8 file quantises it per *tensor* with a zero point of 226, which is neither+    # representable by `conv_int8.comp` nor recoverable by requantising.+    kernel, scale = fidelity.quantise(table, rows.reshape(rows.shape[0], rows.shape[1], 1, 1))+    tensors.extend([kernel, scale])+    emit(+        "Embed8",+        table,+        f"Embed8 t={list(kernel.shape)} scale={[rows.shape[0]]} zp=0 dtype=int8",+        2,+    )+    # Not transposed: the host reads this one. See the docstring.+    text_positions = array("text_model.embeddings.position_embedding.weight")+    constant("text_model.embeddings.position_embedding.weight", text_positions)+    for index in range(spec["text_layers"]):+        encoder_layer("text", index)+    layer_norm("text_model.final_layer_norm")+    projection("/text_projection/MatMul", "text_projection")++    fidelity.report()     return layers, tensors  @@ -945,6 +1281,11 @@ def main():         get, shapes = open_checkpoint(args.model)         check_checkpoint(shapes, args.graph)         layers, tensors = collect_small100(get, CHECKPOINTS[args.graph])+    elif args.graph in ARCHITECTURES:+        model = onnx.load(args.model)+        check_graph(model, args.graph)+        check_architecture(model, args.graph, ARCHITECTURES[args.graph])+        layers, tensors = collect_tinyclip(model, ARCHITECTURES[args.graph])     else:         model = onnx.load(args.model)         check_graph(model, args.graph)
scripts/ml/test/test_tinyclip.py
diff --git a/scripts/ml/test/test_tinyclip.py b/scripts/ml/test/test_tinyclip.pynew file mode 100644index 0000000000..de74f795a8--- /dev/null+++ b/scripts/ml/test/test_tinyclip.py@@ -0,0 +1,313 @@+#!/usr/bin/env python3+"""test_tinyclip.py - unit test for `maml_convert`'s TinyCLIP path.++`collect_tinyclip` is the one converter arm that reads an ONNX graph **by name** rather than walking+it topologically, and the reason is that TinyCLIP's export gives it no choice: two towers in one+graph, interleaved, with all 80 projections held in anonymous `onnx::MatMul_NNNN` initializers.+`check_architecture` is therefore the whole shape guard, and `collect_tinyclip`'s emission *order*+is the whole contract with `nets::tinyclip`.++Both are checked here against a toy graph of the same structure rather than the real 94 MB export,+so this runs in a second and needs no download.++What each check is defending against:++* **The transpose, in two directions at once.** A `MatMul` weight is `[in, out]` and a 1x1 kernel is+  `[out, in, 1, 1]`, so a projection is a transpose. But the `Conv` patch kernel is `[M, C, kH, kW]`+  already and must **not** be transposed. Getting either wrong yields a tensor of the right shape+  holding the wrong numbers; 76 of the 80 projections are square, so only `fc1`/`fc2` and the two+  512-wide heads make it visible in a shape at all.+* **The position tables, which go opposite ways.** The vision table is transposed to+  `[width, 1, positions]` because the device adds it to a channel-major sequence; the text table is+  left `[positions, width]` because the *host* reads it. Swapping them is silent.+* **The order.** `nets::tinyclip` walks the tensor table positionally. A layer emitted out of order+  loads cleanly and infers nonsense.+* **The int8 triple.** `Builder::conv_int8` reads kernel, then per-output-channel scale, then bias.+  The token embedding is the one **pair** — kernel and scale, no bias — because nothing convolves+  with it; the host gathers a row.++Run:++    python3 scripts/ml/test/test_tinyclip.py++Exit code 0 = all assertions passed.+"""++from __future__ import annotations++import os+import sys++import numpy as np+import onnx+from onnx import helper, numpy_helper++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* — a+# patch conv, a class token, two position tables, two towers of pre-norm layers and two projections+# — at a size that builds instantly. `heads` is unused by the converter and kept so the toy is a+# valid spec.+TOY = {+    "width": 4,+    "heads": 2,+    "ffn": 8,+    "vision_layers": 2,+    "text_layers": 1,+    "patch": 2,+    "grid": 3,+    "vocab": 5,+    "context": 6,+    "projection": 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_export(spec, transpose_projections: bool = False):+    """An `onnx.ModelProto` of `spec`'s shape, filled with distinguishable values.++    Only the initializer list and the node names are populated: those are all+    `check_architecture` and `collect_tinyclip` read, and a topologically valid CLIP would be a+    hundred lines of scaffolding testing nothing.+    """+    rng = np.random.default_rng(11)+    parameters, projections = maml_convert.tinyclip_inventory(spec)+    initializers = [+        numpy_helper.from_array(rng.standard_normal(shape).astype(np.float32), name)+        for name, shape in parameters.items()+    ]+    nodes = []+    for index, (node_name, shape) in enumerate(sorted(projections.items())):+        if transpose_projections:+            shape = list(reversed(shape))+        weight = f"onnx::MatMul_{index}"+        initializers.append(+            numpy_helper.from_array(rng.standard_normal(shape).astype(np.float32), weight)+        )+        nodes.append(+            helper.make_node("MatMul", ["x", weight], [f"{node_name}_out"], name=node_name)+        )+    graph = helper.make_graph(nodes, "toy", [], [], initializer=initializers)+    return helper.make_model(graph)+++def test_the_inventory_is_the_real_architecture() -> None:+    print("inventory:")+    spec = maml_convert.ARCHITECTURES["tinyclip"]+    parameters, projections = maml_convert.tinyclip_inventory(spec)+    # 10 vision layers and 3 text layers of 6 named tensors each, plus 15 outside the towers.+    check(f"141 named parameters, got {len(parameters)}", len(parameters) == 141)+    # 13 layers of 6 projections, plus the two towers' output heads.+    check(f"80 projections, got {len(projections)}", len(projections) == 80)+    check(+        "the patch kernel is [width, 3, patch, patch]",+        parameters["vision_model.embeddings.patch_embedding.weight"] == [256, 3, 16, 16],+    )+    check(+        "the token embedding is [vocab, width]",+        parameters["text_model.embeddings.token_embedding.weight"] == [49_408, 256],+    )+    check(+        "the vision positions are the folded [1, 197, width]",+        parameters[maml_convert.VISION_POSITIONS_FOLDED] == [1, 197, 256],+    )+    # The upstream typo, which is load-bearing: the vision tower normalises before the stack as+    # well as after it, and missing that layer is a plausible-looking embedding.+    check("pre_layrnorm is spelled the export's way", "vision_model.pre_layrnorm.weight" in parameters)+    # The asymmetric pair a transpose would swap.+    check(+        "fc1 is [width, ffn]",+        projections["/vision_model/encoder/layers.0/mlp/fc1/MatMul"] == [256, 1024],+    )+    check(+        "fc2 is [ffn, width]",+        projections["/vision_model/encoder/layers.0/mlp/fc2/MatMul"] == [1024, 256],+    )+    check(+        "the text tower has three layers and no fourth",+        "/text_model/encoder/layers.2/mlp/fc1/MatMul" in projections+        and "/text_model/encoder/layers.3/mlp/fc1/MatMul" not in projections,+    )+    total = sum(int(np.prod(shape)) for shape in parameters.values())+    total += sum(int(np.prod(shape)) for shape in projections.values())+    check(f"23,446,016 parameters, got {total}", total == 23_446_016)+++def test_a_transposed_export_is_refused() -> None:+    print("the transpose:")+    spec = maml_convert.ARCHITECTURES["tinyclip"]+    flipped = toy_export(TOY, transpose_projections=True)+    try:+        maml_convert.check_architecture(flipped, "tinyclip", TOY)+        caught = ""+    except SystemExit as exit:+        caught = str(exit)+    check("a transposed export is refused", bool(caught))+    check("and fc1 is named in the message", "fc1" in caught)++    toy = toy_export(TOY)+    maml_convert.check_architecture(toy, "tinyclip", TOY)+    check("the toy export is accepted against its own spec", True)+    try:+        maml_convert.check_architecture(toy, "tinyclip", spec)+        refused = False+    except SystemExit:+        refused = True+    check("and refused against the real one", refused)+++def test_the_table_order_is_the_contract() -> None:+    print("order:")+    layers, tensors = maml_convert.collect_tinyclip(toy_export(TOY), TOY)+    ops = [layer.op for layer in layers]+    layer_ops = ["LayerNorm"] + ["Linear8"] * 4 + ["LayerNorm", "Linear8", "Linear8"]+    expected = (+        ["Conv8", "Constant", "Constant", "LayerNorm"]+        + layer_ops * TOY["vision_layers"]+        + ["LayerNorm", "Linear8"]+        + ["Embed8", "Constant"]+        + layer_ops * TOY["text_layers"]+        + ["LayerNorm", "Linear8"]+    )+    check("the whole table is vision then text, in forward order", ops == expected)+    names = [layer.name for layer in layers]+    check("the patch kernel comes first", names[0].endswith("patch_embedding.weight"))+    check("then the class token", names[1].endswith("class_embedding"))+    check("then the vision positions", names[2] == maml_convert.VISION_POSITIONS_FOLDED)+    check("the visual projection ends the vision tower", "visual_projection" in names)+    check("the text projection is last", names[-1] == "text_projection")+    # The towers are contiguous, unlike the export, which interleaves them.+    vision = [i for i, name in enumerate(names) if name.startswith("vision")]+    text = [i for i, name in enumerate(names) if name.startswith("text")]+    check("no text layer sits inside the vision tower", max(vision) < min(text))+    # 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_a_projection_is_transposed_and_the_conv_is_not() -> None:+    print("the two orientations:")+    export = toy_export(TOY)+    inits = {i.name: numpy_helper.to_array(i) for i in export.graph.initializer}+    nodes = {n.name: n for n in export.graph.node}+    layers, tensors = maml_convert.collect_tinyclip(export, TOY)++    fc1 = next(layer for layer in layers if layer.name.endswith("mlp.fc1"))+    kernel, scale, bias = tensors[fc1.first_tensor: fc1.first_tensor + 3]+    check("fc1's kernel is int8", kernel.dtype == np.int8)+    check(+        f"shaped [{TOY['ffn']}, {TOY['width']}, 1, 1]",+        list(kernel.shape) == [TOY["ffn"], TOY["width"], 1, 1],+    )+    check("with one scale per output channel", scale.shape == (TOY["ffn"],))+    check("and the export's own bias", bias.shape == (TOY["ffn"],) and bias.any())+    # The values, not just the shape: `kernel * scale` must reproduce the *transposed* weight.+    node = "/vision_model/encoder/layers.0/mlp/fc1/MatMul"+    held = next(x for x in nodes[node].input if x in inits)+    want = inits[held].T+    back = kernel.astype(np.float32).reshape(TOY["ffn"], TOY["width"]) * scale[:, None]+    check("and reproduces the transposed weight", np.allclose(back, want, atol=0.02))++    patch = layers[0]+    kernel, scale, bias = tensors[patch.first_tensor: patch.first_tensor + 3]+    original = inits["vision_model.embeddings.patch_embedding.weight"]+    check("the patch kernel keeps ONNX's [M, C, kH, kW]", kernel.shape == original.shape)+    back = kernel.astype(np.float32).reshape(TOY["width"], -1) * scale[:, None]+    check(+        "and is emitted verbatim, not transposed",+        np.allclose(back.reshape(original.shape), original, atol=0.05),+    )+    check("with a synthesised zero bias", bias.shape == (TOY["width"],) and not bias.any())+++def test_the_position_tables_go_opposite_ways() -> None:+    print("the position tables:")+    export = toy_export(TOY)+    inits = {i.name: numpy_helper.to_array(i) for i in export.graph.initializer}+    layers, tensors = maml_convert.collect_tinyclip(export, TOY)+    positions = TOY["grid"] ** 2 + 1++    vision = next(layer for layer in layers if layer.name == maml_convert.VISION_POSITIONS_FOLDED)+    table = tensors[vision.first_tensor]+    check(+        f"the vision table is [width, 1, {positions}]",+        list(table.shape) == [TOY["width"], 1, positions],+    )+    original = np.squeeze(inits[maml_convert.VISION_POSITIONS_FOLDED])+    check(+        "transposed, so channel c of position p is table[c][0][p]",+        np.allclose(table.reshape(TOY["width"], positions), original.T),+    )++    text = next(+        layer for layer in layers if layer.name.endswith("position_embedding.weight")+    )+    table = tensors[text.first_tensor]+    check(+        f"the text table stays [{TOY['context']}, width]",+        list(table.shape) == [TOY["context"], TOY["width"]],+    )+    check(+        "unchanged, because the host reads it",+        np.allclose(table, inits["text_model.embeddings.position_embedding.weight"]),+    )++    embedding = next(layer for layer in layers if layer.op == "Embed8")+    check("the token embedding is a pair, not a triple", embedding.tensor_count == 2)+    kernel, scale = tensors[embedding.first_tensor: embedding.first_tensor + 2]+    check(+        f"[{TOY['vocab']}, width, 1, 1] int8",+        list(kernel.shape) == [TOY["vocab"], TOY["width"], 1, 1] and kernel.dtype == np.int8,+    )+    check("with one scale per row, which is per token", scale.shape == (TOY["vocab"],))+++def test_the_digest_covers_the_order() -> None:+    print("the digest:")+    layers, _ = maml_convert.collect_tinyclip(toy_export(TOY), 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. Two `[width]` layer norms have the same key and are interchangeable in the+    # digest, which is correct: swapping them changes nothing the forward pass can observe.+    q_proj = 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_proj], swapped[fc1] = swapped[fc1], swapped[q_proj]+    check("a reordered pair changes it", maml_convert.layer_table_digest(swapped) != before)+    check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before)+    # The synthesised biases are in the keys, so an export that grew one is not read as this table.+    keys = "\n".join(layer.key() for layer in layers)+    check("the three synthesised biases are recorded", keys.count("b0=synthesised") == 3)+++def main() -> int:+    test_the_inventory_is_the_real_architecture()+    test_a_transposed_export_is_refused()+    test_the_table_order_is_the_contract()+    test_a_projection_is_transposed_and_the_conv_is_not()+    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())