Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / ml / maml_convert.py

maml_convert.py4749 lines · 230.6 KiBRaw
1#!/usr/bin/env python3
2"""ONNX to `.maml`, the weights container `:library:ml` reads.
3
4`:library:ml` is not a graph interpreter: each network's forward pass is hardcoded
5Rust in `library/ml/src/main/rust/src/nets/`. So a `.maml` file carries **only
6ordered tensors** — no operators, no topology, no names. The Rust net module
7indexes the tensor table positionally.
8
9That makes tensor *order* the entire contract between this script and the Rust,
10and a reordering would be silently wrong rather than a load failure. So the order
11is defined mechanically and pinned:
12
13* Order is the weighted nodes in ONNX **topological order** — `Conv`/`ConvTranspose`
14 weight then bias, `PRelu` slope, `Gemm` weight then bias. Nothing else is emitted:
15 every other initializer in these graphs is shape-computation scaffolding that folds
16 away at a fixed input size.
17
18 Topological rather than initializer order matters for the nets with `PRelu`: the Rust
19 reads a layer as `weight = i, bias = i + 1, slope = i + 2`, which only lines up if a
20 slope is emitted immediately after the convolution it follows.
21* `--check` hashes the whole ordered layer table (shapes *and* the attributes the
22 Rust hardcodes: dilation, pads, strides, group) into one SHA-256 pinned below.
23 Any upstream re-export that renames, reorders, retunes or re-pads a single layer
24 changes that hash and fails, instead of producing a file that loads and infers
25 nonsense.
26
27Two nodes are rewritten rather than emitted verbatim, because doing it here means the
28runtime needs no shader for either:
29
30* A **`Gemm`** over a flattened NCHW map is a convolution whose kernel covers the whole
31 spatial extent. MobileFaceNet's `[512, 3136]` becomes `[512, 64, 7, 7]` and the
32 existing `conv.comp` computes it, so there is no `InnerProduct` pipeline.
33* A trailing **`BatchNormalization`** is folded into the `Gemm` before it. At inference a
34 batch norm is a per-channel affine, so `W' = W * gamma / sqrt(var + eps)` and
35 `b' = (b - mean) * gamma / sqrt(var + eps) + beta` is exact, not an approximation.
36
37Weights are stored fp16 with fp32 accumulation in-shader (see `SPEC` below for the
38byte layout). ONNX tensor layout is preserved verbatim — `[M, C/group, kH, kW]` for
39`Conv`, `[C, M/group, kH, kW]` for `ConvTranspose` — so nothing here has to agree
40with the shaders about a transpose.
41
42One graph does not come from an ONNX export at all. SMaLL-100 is read from its PyTorch
43`.safetensors` and quantised to int8 here, because the only ONNX exports that exist for it are
44already int8 and quantised per *tensor*; see [`CHECKPOINTS`] for why that is not usable.
45
46One graph is an ONNX export whose tensor table is nevertheless **derived from architecture
47constants and read by name**, rather than walked topologically. TinyCLIP is two towers in one
48graph, interleaved, and its projections are anonymous `onnx::MatMul_NNNN` initializers, so a
49topological walk would emit an order no one could read. See [`ARCHITECTURES`].
50
51 ./scripts/ml/maml_convert.py --check model.onnx --graph u2netp
52 ./scripts/ml/maml_convert.py model.onnx --graph u2netp -o out.maml
53 ./scripts/ml/maml_convert.py model.onnx --graph u2netp --print-layers
54 ./scripts/ml/maml_convert.py model.safetensors --graph small100 -o out.maml
55 ./scripts/ml/maml_convert.py music_detector.sound_model_2 --graph nnfp -o nnfp.maml
56"""
57
58import argparse
59import hashlib
60import math
61import os
62import struct
63import sys
64
65import numpy as np
66import onnx
67from onnx import numpy_helper, shape_inference
68
69# --- .maml ---------------------------------------------------------------------
70#
71# One contiguous blob, so the whole file becomes one VkBuffer and one staging
72# upload. Little-endian throughout; every device we target is.
73#
74# header, 64 bytes
75# 0 4 magic b"MAML"
76# 4 4 u32 format version
77# 8 4 u32 graph id — the runtime rejects a file built for another net
78# 12 4 u32 tensor count
79# 16 32 source SHA-256 of the ONNX or checkpoint, so a shipped asset traces upstream
80# 48 4 u32 offset of the data section
81# 52 4 u32 length of the data section
82# 56 8 reserved, zero
83#
84# tensor table, 32 bytes per entry, immediately after the header
85# 0 4 u32 rank, 1..4
86# 4 16 u32[4] dims, unused trailing entries zero
87# 20 4 u32 dtype, 0 = fp16
88# 24 4 u32 byte offset within the data section
89# 28 4 u32 element count
90#
91# data, fp16, each tensor padded to ALIGNMENT
92MAGIC = b"MAML"
93FORMAT_VERSION = 1
94HEADER_BYTES = 64
95TENSOR_ENTRY_BYTES = 32
96# Tensor payload types. The container carries the type per tensor, so fp16 and int8 can sit in
97# one file and a reader knows the stride without being told.
98DTYPE_F16 = 0
99
100# Signed 8-bit, symmetric, with a per-output-channel scale in the fp16 tensor that follows it.
101#
102# Only for a network where the weights dominate the download: SMaLL-100 is 330 million
103# parameters, 660 MB at fp16 against 330 MB here, and the ncnn build of the same model shipped
104# 1.14 GB. Everything else stays fp16, where the saving would not pay for the loss.
105DTYPE_I8 = 1
106# Signed 4-bit, two per byte along the contraction axis, with a **rank-2** per-block scale in the
107# fp16 tensor that follows it: `(out_channels, ceil(taps / I4_BLOCK))`.
108#
109# Where int8 halves a download, this quarters it, and it is the only way a model whose weights
110# dominate at several gigabytes becomes shippable at all. It costs a scale table 32 times larger
111# than int8's, which at these widths is well under a percent of the tensor it scales.
112#
113# A tensor's byte length is `ceil(len / 2)`, not `len * stride` - the one dtype whose stride is
114# fractional. Reader and writer must agree on that rounding or an odd-length tensor's last
115# element reads as whatever follows it.
116DTYPE_I4 = 2
117# GGUF Q2_K superblocks, carried verbatim: 256 taps per 84-byte block (16 scale bytes +
118# 64 quant bytes + d + dmin as fp16). The per-superblock `(d, dmin)` pair lives in the
119# fp16 tensor that follows it, one row per block, in the slot a per-channel scale would
120# occupy — so a Q2_K layer is the same kernel + scale + bias triple as int8, with a
121# rank-2 scale. A tensor's byte length is `ceil(len / 256) * 84`.
122DTYPE_Q2K = 3
123# Taps one Q2_K superblock covers. Fixed by the GGUF format, not a tuning choice.
124Q2K_BLOCK = 256
125# Bytes one Q2_K superblock occupies: 16 scales + 64 quants + d + dmin.
126Q2K_BYTES = 84
127# Taps one Q2_K lane covers: a superblock is 16 lanes of 16 taps sharing one `(d, dmin)`.
128Q2K_LANE = 16
129# 16 bytes is the largest scalar/vector alignment the shaders index with, and a
130# multiple of 2, so an aligned tensor offset is also an aligned fp16 index.
131ALIGNMENT = 16
132
133SPEC = __doc__
134
135# The floor for `cosine(fp32 weight, int8 * scale)` per tensor. Supertonic's text encoder was
136# reverted to fp16 at 0.99212 while its sampler shipped at 0.99997, so this is set where a layer
137# that quantises this badly is worth looking at rather than shipping.
138MIN_INT8_COSINE = 0.999
139
140# The same floor for int4, which cannot meet the int8 one and should not be asked to.
141#
142# Four bits give seven positive codes against 127, so the quantisation error is roughly eighteen
143# times larger even with a scale per block. Measured on random gaussian weights at
144# `I4_BLOCK` 32, `quantise_per_block` reconstructs at about 0.9956 - comfortably below
145# `MIN_INT8_COSINE` and not a defect. Holding int4 to the int8 gate would either reject every
146# tensor or, worse, invite someone to lower the int8 gate to match.
147#
148# Set where a tensor that quantises *unusually* badly for four bits stands out: real weights are
149# not gaussian and the projections this is meant for measure better than the synthetic case.
150MIN_INT4_COSINE = 0.99
151
152# Graphs the generic ONNX collector reads as int8. See [`int8_eligible`] for what that
153# excludes within a graph, and `scripts/ml/maml_survey.py` for how the list was chosen.
154#
155# Roughly halves each of these: 6.5 -> 3.3 MiB for mobilefacenet, 3.8 -> 1.9 for ppocr_rec,
156# 2.2 -> 1.2 for ppocr_det and u2netp, 1.2 -> 0.7 for scrfd.
157#
158# `selfie` is deliberately absent. It is a 211 KB depthwise net: a `[C, 1, 3, 3]` kernel saves
159# nine bytes per channel and spends two on the scale, so there is nothing to win and it would
160# be one more graph to re-verify.
161INT8_GRAPHS = set()
162
163# Graph ids. Shared with `library/ml/src/main/rust/src/weights.rs`; changing one
164# without the other is what the id exists to catch.
165GRAPHS = {
166 "selfie": 1,
167 "u2netp": 2,
168 "scrfd": 3,
169 "mobilefacenet": 4,
170 # Folded ahead of time by `scripts/ml/ppocr_fold.py`, not by this script.
171 "ppocr_det": 5,
172 "ppocr_rec": 6,
173 # 7..10 were Piper's four graphs — vocoder, encoder, flow and duration predictor —
174 # deleted when Supertonic replaced them. The numbers are **not** reused: an id identifies
175 # a forward pass, and a `.maml` built for the old vocoder must be rejected rather than
176 # loaded as whatever took its slot.
177 "supertonic_voc": 11,
178 "supertonic_dp": 12,
179 "supertonic_ttl": 13,
180 "supertonic_ve": 14,
181 # Read from a PyTorch checkpoint rather than an ONNX graph; see [`CHECKPOINTS`].
182 "small100": 15,
183 # An ONNX graph read by name rather than walked; see [`ARCHITECTURES`].
184 "tinyclip": 16,
185 # Read from a PyTorch checkpoint rather than an ONNX graph; see [`CHECKPOINTS`].
186 "whisper": 17,
187 # NLLB-200-distilled-600M, replacing small100; see [`CHECKPOINTS`].
188 # Agreed with rust-eng/app-eng in team chat (nllb-translate): next free id,
189 # 7..10 stay retired.
190 "nllb600": 18,
191 # Maia3-5M human-move prediction, replacing Stockfish in `:games:chess`; see
192 # [`CHECKPOINTS`]. Next free id after NLLB's 18, with 7..10 and 15 staying retired.
193 "maia": 19,
194 # Gemma 4 E2B instruction-tuned, the text decoder, from `onnx-community/gemma-4-E2B-it-ONNX`.
195 # Next free id after Maia's 19. **Not 19**: the port plan originally claimed that number,
196 # which Maia already holds, and a collision would make a file parse as the wrong net.
197 "gemma4_text": 20,
198 # Gemma 4's two embedding tables, read on the host rather than by any shader. Its own file
199 # because a decode step needs one row of each and nothing binds them.
200 "gemma4_embed": 21,
201 # The vision tower, which restored image input after litertlm was removed.
202 "gemma4_vision": 22,
203 # The Now Playing audio fingerprinter, 415 ms of log-mel in and a 64-d embedding out.
204 # Next free id after Gemma 4's vision tower at 22, with 7..10 and 15 staying retired.
205 # `weights.rs` has `graph::NNFP` at the same number.
206 #
207 # The first graph read from a **TFLite** flatbuffer rather than ONNX or a checkpoint;
208 # see [`TFLITE`] for why not via ONNX.
209 "nnfp": 23,
210 # Gemma 4's audio tower, 12 conformer layers over log-mel frames. Next free id after the
211 # fingerprinter at 23, with 7..10 and 15 staying retired. `weights.rs` has
212 # `graph::GEMMA4_AUDIO` at the same number. Its own file at ~165 MB: bigger than the vision
213 # tower, and a device that never sends audio should not download it.
214 "gemma4_audio": 24,
215 # MADLAD400-3b-mt translation, encoder and decoder in one file. See
216 # [`CHECKPOINTS`].
217 #
218 # Two graphs rather than one file would upload the untied head twice over: the
219 # input table and the logits kernel are separate 256,000-row tables. Next free
220 # id after Gemma 4's audio tower at 24, with 7..10 and 15 staying retired.
221 # `weights.rs` has `graph::MADLAD` at the same number.
222 "madlad400": 25,
223 # Gemma 4's GPU logits head: the 16 int8 head chunks (kernel, scale, bias
224 # each) ALONE in their own file. Next free id after MADLAD's 25, with 7..10
225 # and 15 staying retired. `weights.rs` has `graph::GEMMA4_HEAD` at the same
226 # number.
227 #
228 # Why a third file: the head `Net` uploads its whole `Blob` verbatim, and
229 # the EMBED file grew to 3.6 GB with the chunks inside (TEXT 1.1 GB + EMBED
230 # 3.6 GB = 4.7 GB uploaded vs ~2.6 GB free on a Pixel 8 = OOM-reboot,
231 # twice, 2026-09-26). The head file is ~402 MB: TEXT + HEAD = ~1.5 GB
232 # uploaded, back under the 3.5 GB the old harness proved safe. The EMBED
233 # file itself is never uploaded — host gathers only, as before.
234 "gemma4_head": 26,
235 # The Q2_K port of the same net, from `model-q2k.gguf`. SAME graph id: the tensor
236 # order is identical (684 layers, 1724 tensors, same names) and only the payloads
237 # differ (Q2_K verbatim vs int8 requantised), so the Rust forward pass reads either
238 # file. A separate id would fork the runtime for no reason; the digest tells them apart.
239 "madlad400-q2k": 25,
240 # MODNet photographic-portrait matting (MobileNetV2 backbone), for `:camera`'s
241 # still-capture portrait matte. Converted via `modnet_fold.py`, not this script
242 # directly: the export's Slice-fed batch norms and SE MatMuls are folded first.
243 # Next free id after MADLAD's 25, with 7..10 and 15 staying retired.
244 "modnet": 27,
245}
246
247# Graphs read from a GGUF file rather than safetensors/ONNX/TFLite. The Q2_K port reads
248# the quantised export directly (see `open_gguf`); the safetensors path stays for the
249# int8 fallback.
250GGUF_GRAPHS = {
251 "madlad400-q2k",
252}
253
254# SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with
255# --print-digest after deliberately re-pointing at a new upstream export.
256EXPECTED_DIGEST = {
257 "selfie": "6db422ecfe0af8e37591eb14c195166b2c416649bf9063100bd5bb14eafaad3a",
258 "u2netp": "f5199e05e4d4e93a6af601d04e3e0516bb68b9f292bb81d474704ea0b4e591d0",
259 "scrfd": "d2ce2880a432af03b0ef594029d3ab03d86de54bd0a9f10ea2c8e412309b0f46",
260 "mobilefacenet": "40987839aec03378958581deba29ce9fd9dd1ae9aa88d0c7ad04a885a2e2122c",
261 "ppocr_det": "51b0c9ed871526fa270b4bfa53b393c056db21c58193849fb83d44768f69ef9b",
262 "ppocr_rec": "8c16a8702aa7a1e7b4d94787d089616ca4bc3d8aaeebb0b0159eabc56af3ba08",
263 "supertonic_voc": "5282083898554b1fae28de946bfc1a82a11e2acddf3911877f27b1b115c583aa",
264 "supertonic_dp": "d9a548e1f1ed908a3b0ad27ab543dd7521858f9110b426edb1ed64ba1f1a13e4",
265 "supertonic_ttl": "92d0fa8ae73d4a8a223c77fb4230e390df580744014a3fcf3211ab72a988c020",
266 "supertonic_ve": "48ab5789e8839507ff93e099dc0f61940f25da9ba6201651784f6e68598199e2",
267 "small100": "c9f05f2fb686aa53137ca06b521baf6d7a00f32cfb4ea42bd14a5c3e7cf6c086",
268 "tinyclip": "7557b2725b52ea04bd18b12e089320b9dd419cd3f7344c0e3d32888d61c24fa7",
269 "whisper": "9e2830c5ea5d443fc31eb5c4eb80fa9a3b9bbcccd3c07963256ade50963c72a2",
270 # Filled in by running --print-digest after the first successful conversion;
271 # see fetch_nllb600.py. Placeholder until then (check fails loudly, not silently).
272 "nllb600": "8b5dd248896b11bf1bb0feae6818d4b00b8ad176549df48bdc07f7b970d3480a",
273 # Pinned with --print-digest after the first successful conversion; see fetch_maia.py.
274 "maia": "50da3ca5ebb9a1b54338c43b2a4b798df25279ac6f74fa19b64146b3964b61aa",
275 # Gemma 4's vision tower. Mixed precision: int4 through the sixteen layers, fp16 for the
276 # patch and output projections at the ends. See `collect_gemma4_vision.dense`.
277 "gemma4_vision": "a942080007f7ca9d8fa38a0812a4f858ff1c31afb7c4e94d105428da5fa56f19",
278 # Gemma 4 E2B text decoder converted DIRECTLY from the litertlm GPU bundle
279 # (scripts/ml/litertlm_to_maml.py; the ONNX export is a different model).
280 # 540 layers, 1090 tensors (rotary thetas read off the base bundle's own
281 # Section 10 `maybe_rope` constants: 1e4 sliding / 1e6 full;
282 # --rope-theta overrides both; per-layer `skip` whole-residual scalars;
283 # plus the two shared ones-vectors), fidelity worst 0.9988.
284 # Pinned 2026-09-25 (full-scale O/PL; the 2026-09-17 pin was 538/1088,
285 # pre-ones-vectors and pre-fullfix — see
286 # build/gemma4-s10-fullfix/BLESSED.txt).
287 "gemma4_text": "20262c74605b0c121220cdb25f4c92d8f26607b4d548781035dcdc91209a2c26",
288 # Gemma 4 E2B embedder from the same bundle: 2-bit working table + shared
289 # [8960,1536] INT8 + 35xINT4 mmap tables. 38 layers, 112 tensors,
290 # fidelity worst 0.9985. Pinned 2026-09-17.
291 "gemma4_embed": "a1c7d7f31c2041e2b1faedb3d2792a0c7048f6f59a8cc3657bfa95c79482dff2",
292 # `music_detector.sound_model_2`, pinned with --print-digest against the file recovered
293 # from the APK (SHA-256 7A86281A6DEED410..., 216,320 bytes). The key records the strides,
294 # padding and depth multiplier the export stores, so a re-export that resolved the
295 # VALID-versus-SAME contradiction `nets::nnfp` works around would change this and be
296 # looked at rather than silently disagreeing with the hardcoded pass.
297 "nnfp": "c374708b973b63dad8fd37e4a25ddf584217752a747655e4fbd87899823b3f1c",
298 # Gemma 4's audio tower, pinned with --print-digest after the .maml was checked against
299 # `nets::gemma4_audio`'s `declare_shared` and `declare_layer` shape for shape over all 747
300 # tensors. Mixed precision like the vision tower: int4 through the twelve layers, fp16 for
301 # the two subsampling convolutions, the relative tables, the norms, the clips and the three
302 # end projections. See `collect_gemma4_audio.dense`.
303 "gemma4_audio": "f3c0be0ca09c5ed6882766eabaa6ebb147dc09cd45ab6d881dec12da41b9783d",
304 # MADLAD400-3B-MT, pinned with --print-digest after the .maml was checked against
305 # `nets::madlad`'s layout constants over all 1724 tensors (684 layers). int8
306 # linears throughout (488, all with synthesised zero bias — T5 is bias-free),
307 # fp16 RMSNorm gains, fp16 host-read relative tables. See `collect_madlad`.
308 "madlad400": "36c2c8845d36b33a37dc12ad8255e38deb7664b72aa1e2a2f7b2467a9f05ea2a",
309 # The Q2_K port of the same net, from `model-q2k.gguf`. Same order (684 layers,
310 # 1724 tensors, same names — the Rust walks positionally, so both collectors must
311 # agree); only the payloads differ (Q2_K verbatim vs int8 requantised), hence a
312 # separate digest on the same graph id. See `collect_madlad_q2k`.
313 "madlad400-q2k": "f17cbb4fb9f44eb8a4d94d93f5a00e7ec868d11628a12ea1b2078fbc700124b7",
314 # MODNet photographic portrait matting, folded by `modnet_fold.py`. Pinned
315 # after `nets::modnet` was checked against this table layer for layer.
316 "modnet": "f6ad3e1cdcf38679f89ed15891576a46a2b8c9d3cc110fbd26b746df4194da2a",
317}
318
319# Graphs that are one **module** of a larger export, keyed by the node-name prefix that
320# selects it.
321#
322# Empty at present: every graph here is exported as its own file. The mechanism stays because
323# an export that packs several forward passes into one graph is not convertible as one plan,
324# and a Torch export keeps its module paths - so it partitions along the lines the model was
325# written in, and each static module converts independently.
326#
327# A module-scoped graph has no GEOMETRY entry: its input is another module's output rather
328# than a graph input, so there is nothing at the boundary to check a shape against. What is
329# checked instead is the op inventory within the module, which is the same guard by another
330# route.
331MODULES = {}
332
333# `outputs` are the graph outputs the Rust forward pass corresponds to; the export may
334# declare more (U^2-Netp declares all seven of its side outputs and we read one).
335GEOMETRY = {
336 "selfie": {
337 "input": "pixel_values",
338 "outputs": ["alphas"],
339 "shape": [3, 256, 256],
340 },
341 "u2netp": {
342 "input": "input.1",
343 "outputs": ["1959"],
344 "shape": [3, 320, 320],
345 },
346 # Nine: score, box and keypoint maps at strides 8, 16 and 32. The Rust reads the
347 # convolution outputs feeding these rather than the reshaped tensors themselves,
348 # because a Transpose/Reshape is a relabelling that NCHW indexing does for free.
349 "scrfd": {
350 "input": "input.1",
351 "outputs": [
352 "443", "468", "493",
353 "446", "471", "496",
354 "449", "474", "499",
355 ],
356 "shape": [3, None, None],
357 },
358 "mobilefacenet": {
359 "input": "input.1",
360 "outputs": ["516"],
361 "shape": [3, 112, 112],
362 },
363 # MODNet photographic portrait matting. Dynamic HW like scrfd: the export is
364 # dynamic-batch/dynamic-shape and the branch Resizes are scale-factor based,
365 # so the fixed 512x512 run resolves structurally. Transcribed at SIZE=512.
366 "modnet": {
367 "input": "input",
368 "outputs": ["output"],
369 "shape": [3, None, None],
370 },
371}
372
373# Op-type counts, as a coarse first check that the graph is the one we lowered by
374# hand. Ops absent from the list must be absent from the graph.
375EXPECTED_OPS = {
376 "selfie": {
377 "Conv": 54, "ConvTranspose": 1, "Add": 14, "Mul": 10, "Concat": 3,
378 "ReduceMean": 10, "Relu": 22, "HardSwish": 11, "Sigmoid": 11,
379 "Resize": 3, "Shape": 3, "Slice": 3,
380 },
381 "u2netp": {
382 "Conv": 119, "MaxPool": 33, "Resize": 38, "Concat": 127, "Add": 11,
383 "Relu": 112, "Sigmoid": 7, "Shape": 114, "Gather": 76, "Unsqueeze": 76,
384 "Slice": 38, "Cast": 38, "Constant": 266,
385 },
386 "scrfd": {
387 "Conv": 60, "Relu": 41, "Sigmoid": 3, "Add": 4, "Resize": 2, "Concat": 2,
388 "Reshape": 9, "Transpose": 9, "Shape": 6, "Gather": 4, "Unsqueeze": 4,
389 "Slice": 2,
390 },
391 "mobilefacenet": {
392 "Conv": 49, "PRelu": 34, "Add": 12, "BatchNormalization": 1, "Flatten": 1,
393 "Gemm": 1,
394 },
395 # MODNet photographic portrait matting, AFTER `modnet_fold.py`: the 16
396 # IBNorm batch norms are folded into their Convs and the 2 SE MatMuls are
397 # rewritten as 1x1 Convs, so this counts the folded graph (Conv 69+2, no
398 # BatchNormalization, no MatMul). The 16 InstanceNormalizations and 35
399 # Clip(0,6)/17 Relu/2 Sigmoid are structural, transcribed in
400 # `nets::modnet` rather than emitted.
401 "modnet": {
402 "Conv": 71, "Add": 10, "Mul": 1, "Concat": 24,
403 "InstanceNormalization": 16, "GlobalAveragePool": 1,
404 "Relu": 17, "Clip": 35, "Sigmoid": 2,
405 "Resize": 9, "Slice": 32, "Shape": 3, "Gather": 2, "Unsqueeze": 4,
406 "Reshape": 2, "Expand": 1, "Constant": 241,
407 },
408 # Two towers in one graph. `MatMul` 107 is the 80 weighted projections plus the 26 attention
409 # products and the one `logit_scale` product; `Erf` 13 is the 13 layers' GELU; `Softmax` 13 is
410 # their attention, and the causal mask the text tower's three need is a `-3.4e38` constant
411 # added to the score map, not an op. `ArgMax` 1 is the end-of-text search this runtime does on
412 # the host. Counted rather than transcribed: `python -c` over the graph produced these.
413 "tinyclip": {
414 "Add": 186, "ArgMax": 1, "Cast": 5, "Concat": 27, "ConstantOfShape": 1, "Conv": 1,
415 "Div": 44, "Equal": 4, "Erf": 13, "Expand": 3, "Flatten": 1, "Gather": 20, "Less": 1,
416 "MatMul": 107, "Mul": 73, "Pow": 33, "Range": 2, "ReduceMean": 58, "ReduceSum": 2,
417 "Reshape": 113, "Shape": 12, "Slice": 3, "Softmax": 13, "Sqrt": 29, "Squeeze": 1,
418 "Sub": 31, "Transpose": 68, "Unsqueeze": 20, "Where": 5,
419 },
420}
421
422# ONNX graphs whose tensor table is **derived from these constants and read by name**, rather than
423# produced by the topological walk in [`collect_layers`].
424#
425# One entry, TinyCLIP. Three things make the walk unusable for it:
426#
427# * It is **two towers in one graph**, and the export interleaves them - text layer 0, vision layer
428# 0, text layer 1, and so on. A topological order is therefore an order no reader could check
429# against `nets::tinyclip`, and `Mode::Image` and `Mode::Text` would each read a stride through
430# the table.
431# * Every projection is a bare `MatMul` against an **anonymous** `onnx::MatMul_NNNN` initializer.
432# There is nothing in the initializer's name to say which layer or which projection it is. The
433# *node* names are fully structured (`/vision_model/encoder/layers.3/mlp/fc1/MatMul`), so this
434# reads the weight through the node, which is also what makes the inventory check below possible.
435# * `MatMul` is `x @ W` with a **`[in, out]`** weight, and this runtime indexes a kernel as
436# `[out, in, kh, kw]`. Every attention projection here is square 256 x 256, so reading one
437# convention as the other yields a tensor of exactly the right shape holding exactly the wrong
438# numbers. `fc1` is `[256, 1024]` and `fc2` is `[1024, 256]`, so the shape assertions in
439# [`check_architecture`] are what make that loud.
440#
441# The `Conv` is the one exception and needs **no** transpose: ONNX `Conv` is already
442# `[M, C, kH, kW]`, which is this runtime's own layout.
443#
444# What is checked is the **exact named-parameter inventory** derived from these constants, as
445# [`CHECKPOINTS`] gets, *plus* the op counts in [`EXPECTED_OPS`] that only an ONNX graph can give.
446# There is no [`GEOMETRY`] entry: this export has three inputs and four outputs and is dynamically
447# shaped throughout, so there is no single boundary shape to compare against.
448ARCHITECTURES = {
449 "tinyclip": {
450 # `hidden_size`, shared by both towers, and `num_attention_heads` 4, so `head_dim` is 64
451 # and `Builder::attn_scores`'s own `1 / sqrt(64)` is already the model's 0.125 scale.
452 "width": 256,
453 "heads": 4,
454 "ffn": 1024,
455 "vision_layers": 10,
456 "text_layers": 3,
457 # 16 x 16 patches over 224 x 224 is a 14 x 14 grid, so 196 patches plus the class token.
458 "patch": 16,
459 "grid": 14,
460 "vocab": 49_408,
461 "context": 77,
462 "projection": 512,
463 },
464 "gemma4_text": {
465 # Read off `config.json`'s `text_config`, then checked against the export's own
466 # initializer shapes by `check_architecture`. Transcribed rather than derived: a
467 # constant that disagrees with the file must fail loudly, not be quietly adopted.
468 "d_model": 1536,
469 "heads": 8,
470 "kv_heads": 1,
471 "head_dim": 256,
472 "global_head_dim": 512,
473 "layers": 35,
474 # Layers 0..15 own a KV cache; 15..35 have no k/v projections and a double-wide MLP.
475 "owns_cache_layers": 15,
476 "ffn": 6144,
477 "ffn_wide": 12288,
478 "per_layer": 256,
479 "vocab": 262_144,
480 "head_splits": 4,
481 # Positions the runtime offers, and so the rows the rotary tables are cut to.
482 # `max_position_embeddings` is 131072, which no arena could hold. Mirrors
483 # `nets::gemma4::MAX_CONTEXT`.
484 "max_context": 16384,
485 },
486 "gemma4_embed": {
487 "d_model": 1536,
488 "per_layer": 256,
489 "layers": 35,
490 "vocab": 262_144,
491 # The two constants `embed_tokens.onnx` multiplies its gathers by, folded into the
492 # weights here. 39.25 is `sqrt(1536)` as fp16 rounds it; 16.0 is `sqrt(256)` exactly.
493 "embed_scale": 39.25,
494 "per_layer_scale": 16.0,
495 },
496 "gemma4_vision": {
497 # Read off config.json's vision_config, then checked against the export by
498 # check_architecture. Mirrors nets::gemma4_vision's constants.
499 "d_model": 768,
500 "heads": 12,
501 "head_dim": 64,
502 "ffn": 3072,
503 "layers": 16,
504 "patch": 16,
505 "out_dim": 1536,
506 "positions": 10240,
507 },
508 "gemma4_audio": {
509 # Read off config.json's audio_config and then measured against the export by
510 # collect_gemma4_audio, which asserts every count this walk depends on. Mirrors
511 # nets::gemma4_audio's constants.
512 "d_model": 1024,
513 "heads": 8,
514 "head_dim": 128,
515 "ffn": 4096,
516 "layers": 12,
517 "out_dim": 1536,
518 # Output channels of the two subsampling convolutions, and the mel bins surviving their
519 # two stride-2 halvings. `mel_subsampled * sscp_channels[1]` is d_model, which is why
520 # the input projection is square - arithmetic, not identity.
521 "sscp_channels": [128, 32],
522 "mel_subsampled": 32,
523 # Columns in a layer's relative-position table. NOT the attended span, which is 12: the
524 # thirteenth column exists because the export's _rel_shift skew consumes one, and the
525 # mask's strict `dist < 12` means it is computed and thrown away.
526 "rel_offsets": 13,
527 # Constants nets::gemma4_audio hardcodes, asserted against the graph's folded scalars so
528 # that a changed one fails here rather than becoming a wrong forward pass. The query
529 # scale is `(128 ** -0.5) / ln 2` and the key scale `ln(1 + e) / ln 2`; the `/ ln 2` in
530 # both is the part nobody would guess.
531 "q_scale": 0.127517431974411,
532 "k_scale": 1.8946361541748047,
533 "logit_cap": 50.0,
534 "residual_weight": 0.5,
535 # nets::gemma4_audio::TENSORS. 15 shared plus 12 layers of 61.
536 "tensors": 747,
537 },
538}
539
540# Graphs read from a **PyTorch checkpoint** rather than an ONNX graph, keyed by graph id name.
541#
542# Every other net here converts from a frozen ONNX export, and for good reason: the graph records
543# the shapes and the op inventory, so `check_graph` can refuse an export whose structure moved
544# without anyone transcribing anything. A checkpoint has neither. It is used anyway for SMaLL-100,
545# because the only ONNX exports that exist for it are already int8:
546#
547# * `casawolice/small100-onnx` quantises **per tensor**, not per output channel. Its embedding's
548# row absmax spans 0.258 to 1.740, so one scale for the whole table costs a factor of four in
549# resolution against the per-row scale `quantise_per_channel` produces, and up to 6.7x on the
550# quietest rows. That resolution cannot be recovered by requantising: it is already gone.
551# * It carries the 131M-parameter embedding **three times** - `embed_tokens.weight` in the
552# encoder, `model.shared.weight` in the decoder and a separately quantised `[1024, 128112]`
553# `lm_head` - which is why that deployment set is 609 MB rather than 333 MB. In the checkpoint
554# the weight is tied and appears exactly once, so the tied head costs nothing.
555# * Its two embedding copies are **uint8 with a zero point of 159**. `conv_point_int8.comp`
556# computes `scale[o] * sum(int8_w * in)` and has nowhere to put a zero point.
557#
558# What is checked instead is the **exact parameter inventory** - every name and every shape,
559# derived from the constants below rather than listed - which is a stricter guard than the op
560# counts an ONNX graph gets, because it fails on a renamed or resized parameter as well as on a
561# missing one. The layer table digest still covers the order.
562CHECKPOINTS = {
563 "small100": {
564 "d_model": 1024,
565 "encoder_layers": 12,
566 "decoder_layers": 3,
567 "ffn": 4096,
568 "vocab": 128_112,
569 # The tied embedding is 125.1 MiB of int8, and `maxStorageBufferRange`'s guaranteed
570 # minimum is 128 MiB. Emitting it as two tensors over disjoint class ranges keeps every
571 # binding comfortably under that floor and gives `nets::small100` its two logits ops for
572 # free; 128,112 is 2 x 64,056, so the halves are equal and no range is padded.
573 "head_splits": 2,
574 },
575 # whisper-base, from `openai/whisper-base`. A checkpoint for the same reason SMaLL-100 is one:
576 # the ONNX exports that exist are already int8 and quantised per **tensor**, which is the
577 # coarseness that cost SMaLL-100's embedding a factor of four.
578 #
579 # Two things about this architecture are unlike anything else here, and both are asserted rather
580 # than assumed by [`whisper_inventory`]:
581 #
582 # * **No `k_proj.bias`.** Only `q_proj`, `v_proj` and `out_proj` carry one, in all 18 attentions.
583 # `Builder::conv_int8` always reads a bias after the scale, so the converter synthesises a
584 # zero and records it in the digest key — a checkpoint that grows one must not be read as this
585 # table.
586 # * **A convolution stem.** `conv1` is `[512, 80, 3]` stride 1 and `conv2` is `[512, 512, 3]`
587 # **stride 2**, which is what turns 3000 mel frames into 1500 encoder positions. Both are
588 # rank-3, so they are lifted to the `1 x k` rank-4 kernel this runtime indexes.
589 #
590 # The head is **tied** to `embed_tokens`, as SMaLL-100's is, but at 51,865 x 512 it is 26.6 MB
591 # and fits one binding — so unlike SMaLL-100 it needs no class split.
592 "whisper": {
593 "d_model": 512,
594 "encoder_layers": 6,
595 "decoder_layers": 6,
596 "ffn": 2048,
597 "vocab": 51_865,
598 "mels": 80,
599 # `max_source_positions` and `max_target_positions`. The first is 3000 mel frames after
600 # `conv2`'s stride 2; the second is the decoder's learned position table.
601 "source_positions": 1500,
602 "target_positions": 448,
603 "conv_kernel": 3,
604 },
605 # NLLB-200-distilled-600M, from `facebook/nllb-200-distilled-600M` (gated, MIT-adjacent
606 # CC-BY-NC but fetched fine unauthenticated). A checkpoint for the same reason SMaLL-100
607 # is one: the repo ships only `pytorch_model.bin` (fp32) plus `sentencepiece.bpe.model`
608 # and `tokenizer.json` — there is no ONNX export at all.
609 #
610 # The architecture is `M2M100ForConditionalGeneration` (config.json says so verbatim:
611 # `model_type: m2m_100`, `activation_function: relu`, `scale_embedding: true`,
612 # `d_model: 1024`, `vocab_size: 256206`). So the forward pass is SMaLL-100's with two
613 # differences, both asserted by [`nllb_inventory`] and [`collect_nllb`]:
614 #
615 # * **12 decoder layers, not 3.** The distilled-600M keeps the full decoder.
616 # * **202 language tokens, not 100**, at ids `256001..256202` with `<mask>` at 256203.
617 # Tokenizer detail only — the converter never reads them — but the vocab count pins it.
618 #
619 # Everything else carries over: fairseq sinusoid positions with the +2 offset (same
620 # `M2M100SinusoidalPositionalEmbedding`, offset=2, verified in transformers'
621 # `modeling_m2m_100.py`), pre-norm layers, ReLU FFN, `1/sqrt(64)` query scale already in
622 # `attn_scores`, all four projections biased (unlike whisper's missing k bias), tied
623 # embedding emitted once.
624 #
625 # The checkpoint holds the tied embedding **four times** (`model.shared`,
626 # `model.encoder.embed_tokens`, `model.decoder.embed_tokens`, `lm_head` — all
627 # byte-identical, verified exact-equal). Only `model.shared.weight` is emitted.
628 #
629 # The tied embedding is 262.4 MiB of int8 (256,206 x 1024), so it needs **four** class
630 # splits to stay under `maxStorageBufferRange`'s 128 MiB floor: 256,206 = 2 x 128,103
631 # is not divisible by 4, so the four ranges are 64,052 / 64,052 / 64,051 / 64,051
632 # (first two get the extra row each). `nets::nllb600` reads four logits ops.
633 "nllb600": {
634 "d_model": 1024,
635 "encoder_layers": 12,
636 "decoder_layers": 12,
637 "ffn": 4096,
638 "vocab": 256_206,
639 # Four head splits, uneven (see above): first two ranges hold 64,052 classes,
640 # last two 64,051.
641 "head_splits": 4,
642 "head_rows": [64_052, 64_052, 64_051, 64_051],
643 },
644 # MADLAD400-3B-MT, from `google/madlad400-3b-mt`. A checkpoint for the same reason
645 # NLLB is one: the repo ships `model.safetensors` (fp32) plus `spiece.model` and
646 # `tokenizer.json` — there is no ONNX export at all.
647 #
648 # The architecture is `T5ForConditionalGeneration` (`model_type: t5`,
649 # `feed_forward_proj: gated-gelu`, `tie_word_embeddings: false`), so the forward
650 # pass is an encoder-decoder with 32 pre-norm RMSNorm layers a side, GEGLU
651 # feed-forwards, untied embeddings, and T5 relative position biases — all asserted
652 # by [`madlad_inventory`] and [`collect_madlad`]:
653 #
654 # * **32 encoder + 32 decoder layers**, `d_model` 1024, 16 heads of `d_kv` 128
655 # (`inner_dim` 2048), `d_ff` 8192.
656 # * **Untied embeddings.** `decoder.embed_tokens.weight` is the encoder/decoder
657 # input table and `lm_head.weight` the logits kernel, and they differ —
658 # refuses a checkpoint where they match. Both are emitted, each as four
659 # 64,000-class splits (256,000 divides evenly: no uneven tail as in NLLB).
660 # * **No projection biases anywhere.** Every `q/k/v/o`, `wi_0/wi_1/wo` is
661 # `bias=False`, so each gets a synthesised zero recorded in the digest key —
662 # a checkpoint that grows one must not be read as this table.
663 # * **No learned positions.** T5's position signal is the relative bias, computed
664 # on the host by `nets::madlad::relative_bias` and added as a plan input —
665 # so the bias tables are emitted fp16 for the host to read, not for a shader.
666 # * **Bias tables on block 0 only.** `has_relative_attention_bias=bool(i == 0)`,
667 # so only the two block-0 self-attentions hold a `[32, 16]` table; deeper
668 # layers reuse the computed bias. Both tables are emitted once, at the end.
669 "madlad400": {
670 "d_model": 1024,
671 "heads": 16,
672 "head_dim": 128,
673 "encoder_layers": 32,
674 "decoder_layers": 32,
675 "d_ff": 8192,
676 "vocab": 256_000,
677 # Four even head splits: 256,000 = 4 x 64,000.
678 "head_splits": 4,
679 "head_rows": [64_000, 64_000, 64_000, 64_000],
680 "buckets": 32,
681 },
682 # Maia3-5M, from `UofTCSSLab/Maia3-5M`. A checkpoint because the repo ships a single
683 # `maia3-5m.pt` pickle and nothing else — no ONNX, no safetensors. `fetch_maia.py`
684 # repacks it, as `fetch_nllb600.py` does for NLLB's `.bin`.
685 #
686 # The architecture is `MAIA3Model` from CSSLab/maia3, with `BASE_SIZE_CONFIG` plus the
687 # 5M row of `MODEL_SPECS`: 8 encoder-only blocks over 64 square tokens, `dim_vit` 256,
688 # 8 heads, `mlp_ratio` 2.0. Four things about it are unlike anything else here, and all
689 # four are asserted rather than assumed by [`maia_inventory`] and [`collect_maia`]:
690 #
691 # * **`omit_qkv_biases=True`.** `nn.MultiheadAttention(bias=False)`, so there is no
692 # `in_proj_bias` and no `out_proj.bias`. `Builder::conv` always reads a bias after
693 # its kernel, so four zeros per block are synthesised and recorded in the digest key.
694 # * **A fused `in_proj_weight` `[768, 256]`.** Torch packs q, k and v into one tensor;
695 # the collector splits it into three in that order, which is
696 # `_in_projection_packed`'s.
697 # * **`use_rms_norm=True`, post-norm.** `norm1` and `norm2` are `torch.nn.RMSNorm`, so
698 # they carry a weight and **no bias**. A checkpoint that grew `norm1.bias` would be
699 # an architecture change, not a detail, and fails here.
700 # * **A shared attention-bias weight.** `smolgen_shared_weight` `[4096, 64]` is one
701 # parameter registered under nine names — itself plus
702 # `transformer.layers.N.self_attn.smolgen_weight` for all eight blocks, all aliasing
703 # the same storage. `fetch_maia.py` asserts that and drops the eight extras, so this
704 # inventory names only the shared one. See [`collect_maia`] for why it is emitted
705 # replicated eight times anyway.
706 #
707 # The value and ponder heads (`last_ln`, `fc_value*`, `fc_ponder*`) are in the
708 # checkpoint and so are in the inventory, but are deliberately **not emitted**: nothing
709 # picks a move with them. Asserting them keeps a re-trained head from passing silently.
710 #
711 # Every convolution is int8, quantised per output channel. That was chosen on measured
712 # move agreement rather than on the cosine gate — see [`collect_maia`] and
713 # `scripts/ml/maia_quant_eval.py`, which also rules out int4.
714 "maia": {
715 "d_model": 256,
716 "blocks": 8,
717 "heads": 8,
718 "ffn": 512,
719 "head_hidden": 256,
720 # `gab_intermediate_dim` and `gab_gen_size`.
721 "bias_hidden": 64,
722 "bias_gen": 64,
723 # `dim_emb`, each of the two elo embeddings' width.
724 "elo_dim": 128,
725 # `12 * history + 2 * dim_emb`, the token projection's input width.
726 "input": 12 * 8 + 2 * 128,
727 "squares": 64,
728 "promotions": 4,
729 },
730}
731
732
733class Layer:
734 """One weighted node, as the Rust forward pass needs to see it."""
735
736 def __init__(self, index, op, name, key, first_tensor, tensor_count):
737 self.index = index
738 self.op = op
739 self.name = name
740 self._key = key
741 # Where this layer's tensors start in the `.maml` table, and how many it has.
742 # The Rust indexes by tensor, and with `PRelu` in the mix that is no longer
743 # `2 * layer` — so --print-layers reports it rather than leaving a transcriber
744 # to count.
745 self.first_tensor = first_tensor
746 self.tensor_count = tensor_count
747
748 def key(self):
749 """Everything the Rust hardcodes about this layer, as a stable string."""
750 return self._key
751
752
753def lift_to_2d(weight, node):
754 """A 1-D convolution's rank-3 weight as the rank-4 one this runtime indexes.
755
756 A tensor here is `[c, h, w]` with no rank-3 case, so a 1-D convolution is a 2-D one
757 whose kernel is `1 x k` — which is what every convolution in `nets::supertonic_vocoder`
758 reads. Inserting the height axis is a reshape of the same bytes in the same order, and
759 doing it here means the Rust reads `[out, in, 1, k]` like every other kernel rather than
760 carrying a special case for audio.
761
762 Returns `(weight, spatial)`, where `spatial` is the kernel/dilation/pad/stride form the
763 digest key should record: also lifted to two dimensions, so a reader comparing the key
764 against the Rust sees the same `(1, k)` the Rust wrote.
765 """
766 attrs = {a.name: a for a in node.attribute}
767
768 def ints(name, default):
769 return list(attrs[name].ints) if name in attrs else list(default)
770
771 if weight.ndim != 3:
772 return weight, None
773 lifted = weight.reshape(weight.shape[0], weight.shape[1], 1, weight.shape[2])
774 # ONNX orders pads as all the begins then all the ends, so a 1-D `[before, after]`
775 # becomes `[0, before, 0, after]` rather than being padded on the right.
776 pads = ints("pads", (0, 0))
777 return lifted, {
778 "kernel_shape": [1] + ints("kernel_shape", [weight.shape[2]]),
779 "dilations": [1] + ints("dilations", [1]),
780 "strides": [1] + ints("strides", [1]),
781 "pads": [0, pads[0], 0, pads[1]],
782 }
783
784
785def convolution_key(node, weight, bias, spatial=None):
786 """The digest key for a `Conv`/`ConvTranspose`.
787
788 Byte-for-byte the string the first version of this script produced, so the pinned
789 selfie and u2netp digests survive every later addition here.
790
791 `spatial` overrides the node's own attributes, for a 1-D convolution that
792 [`lift_to_2d`] has turned into a `1 x k` one.
793 """
794 attrs = {a.name: a for a in node.attribute}
795
796 def ints(name, default):
797 if spatial is not None and name in spatial:
798 return list(spatial[name])
799 return list(attrs[name].ints) if name in attrs else list(default)
800
801 return (
802 f"{node.op_type} w={list(weight.shape)} "
803 f"b={list(bias.shape) if bias is not None else None} "
804 f"k={ints('kernel_shape', weight.shape[2:])} "
805 f"d={ints('dilations', (1, 1))} p={ints('pads', (0, 0, 0, 0))} "
806 f"s={ints('strides', (1, 1))} "
807 f"g={attrs['group'].i if 'group' in attrs else 1}"
808 )
809
810
811def inferred_shapes(model):
812 """Every tensor's shape, for the fixed-shape graphs. Empty where inference fails."""
813 try:
814 inferred = shape_inference.infer_shapes(model)
815 except Exception:
816 return {}
817 everything = list(inferred.graph.value_info) + list(inferred.graph.input)
818 return {
819 vi.name: [d.dim_value for d in vi.type.tensor_type.shape.dim]
820 for vi in everything
821 }
822
823
824def flatten_source_shape(node, graph, shapes):
825 """`[c, h, w]` of the map a `Gemm`'s flattened input came from.
826
827 This is what lets a `Gemm` be emitted as a convolution kernel. It is read from the
828 graph rather than assumed, because getting it wrong reshapes the fully-connected
829 weight into the wrong kernel and produces a plausible-looking embedding.
830 """
831 producer = next((n for n in graph.node if node.input[0] in n.output), None)
832 if producer is None or producer.op_type != "Flatten":
833 raise SystemExit(
834 f"{node.output[0]}: a Gemm whose input is not a Flatten. Only a Gemm over a "
835 "flattened feature map can be emitted as a convolution."
836 )
837 shape = shapes.get(producer.input[0])
838 if not shape or len(shape) != 4 or 0 in shape[1:]:
839 raise SystemExit(
840 f"{node.output[0]}: cannot infer the shape feeding {producer.output[0]}, "
841 f"got {shape}. A Gemm can only be reshaped where the map's size is static."
842 )
843 return list(shape[1:])
844
845
846def fold_batch_norm(node, inits, weight, bias):
847 """Fold a `BatchNormalization` into the weight and bias of the layer before it.
848
849 At inference a batch norm is `gamma * (x - mean) / sqrt(var + eps) + beta`, a
850 per-output-channel affine, so pushing it into the preceding layer is exact. Doing it
851 here rather than in a shader is why the runtime has no batch-norm pipeline.
852 """
853 attrs = {a.name: a for a in node.attribute}
854 epsilon = attrs["epsilon"].f if "epsilon" in attrs else 1e-5
855 missing = [n for n in node.input[1:] if n not in inits]
856 if missing:
857 raise SystemExit(f"{node.output[0]}: batch norm parameter {missing} is computed")
858 gamma = numpy_helper.to_array(inits[node.input[1]]).astype(np.float64)
859 beta = numpy_helper.to_array(inits[node.input[2]]).astype(np.float64)
860 mean = numpy_helper.to_array(inits[node.input[3]]).astype(np.float64)
861 var = numpy_helper.to_array(inits[node.input[4]]).astype(np.float64)
862 scale = gamma / np.sqrt(var + epsilon)
863 # fp64 for the fold itself: the division by sqrt(var) can be large, and this is the
864 # one place the file's values are computed rather than copied.
865 folded_weight = weight.astype(np.float64) * scale.reshape([-1] + [1] * (weight.ndim - 1))
866 folded_bias = (bias.astype(np.float64) - mean) * scale + beta
867 return folded_weight, folded_bias
868
869
870def int8_eligible(node, consumers):
871 """Whether `node`, a convolution, can be read as int8 by this runtime.
872
873 Three exclusions, all forced by the runtime rather than chosen:
874
875 * **`ConvTranspose`.** There is no int8 transposed convolution — `Builder` has `conv_int8`
876 and no `conv_transpose_int8`, and `conv_transpose.comp` has no int8 twin.
877 * **A convolution feeding a `PRelu`.** The Rust fuses that into the producing convolution
878 as `Act::PRelu`, whose per-channel slope wants the push-block offset the dequantisation
879 scale occupies. `Builder::conv_int8` refuses it outright.
880 * **Edge padding.** `conv_int8.comp` reads out-of-bounds taps as zero and has no border
881 replication, so a net that called `Builder::edge_padding` cannot quantise a *padded*
882 convolution. Only the four Supertonic graphs do, and they are not converted through
883 here — so this is documented rather than tested for.
884
885 Everything else is fair game. `conv_int8.comp` handles groups, arbitrary kernel sizes,
886 strides, dilations and zero padding, which is worth stating because
887 `nets::supertonic_vocoder::INT8_CONVS` reads as though grouping were the blocker; there,
888 the depthwise convolutions are excluded because they are *edge-padded*, not because they
889 are grouped.
890 """
891 if node.op_type != "Conv":
892 return False
893 return not any(c.op_type == "PRelu" for c in consumers.get(node.output[0], ()))
894
895
896def collect_layers(model, prefix=None, quantise=False):
897 """The weighted nodes in topological order, with the tensors each contributes.
898
899 `prefix` restricts the walk to one Torch module; see [`MODULES`].
900
901 `quantise` reads every eligible convolution as int8 rather than fp16 — three tensors
902 (kernel, per-output-channel scale, bias) instead of two. See [`INT8_GRAPHS`] for which
903 graphs ask for it and [`int8_eligible`] for what "eligible" excludes and why.
904 """
905 graph = model.graph
906 inits = {i.name: i for i in graph.initializer}
907 # A module-scoped export keeps its weights in `Constant` nodes rather than the
908 # initializer list, the way PP-OCRv5's recognition export does.
909 constants = {}
910 for node in graph.node:
911 if node.op_type == "Constant":
912 for attribute in node.attribute:
913 if attribute.name == "value":
914 constants[node.output[0]] = attribute.t
915 shapes = inferred_shapes(model)
916
917 def held(name):
918 return name in inits or name in constants
919
920 def array(name):
921 return numpy_helper.to_array(inits[name] if name in inits else constants[name])
922
923 # Which node's output each BatchNormalization consumes, so the layer producing it
924 # can absorb it.
925 batch_norms = {n.input[0]: n for n in graph.node if n.op_type == "BatchNormalization"}
926 consumers = {}
927 for node in graph.node:
928 for name in node.input:
929 consumers.setdefault(name, []).append(node)
930 folded = set()
931
932 layers = []
933 tensors = []
934 fidelity = Fidelity() if quantise else None
935 for node in graph.node:
936 if prefix is not None and not node.name.startswith(prefix):
937 continue
938 first_tensor = len(tensors)
939 if node.op_type in ("Conv", "ConvTranspose"):
940 missing = [n for n in node.input[1:] if not held(n)]
941 if missing:
942 raise SystemExit(
943 f"{node.output[0]}: weight/bias {missing} is not a constant. "
944 "A computed weight means this is not the frozen export we lower."
945 )
946 weight = array(node.input[1])
947 weight, spatial = lift_to_2d(weight, node)
948 bias = array(node.input[2]) if len(node.input) > 2 else None
949 synthesised = bias is None
950 if synthesised:
951 # The shaders always add a bias, so a layer without one gets a zero. Exact,
952 # and recorded in the key so the digest notices if a layer that used to have
953 # a bias stops having one — which would otherwise look like the same table.
954 channels = weight.shape[1] if node.op_type == "ConvTranspose" else weight.shape[0]
955 bias = np.zeros(channels, dtype=np.float32)
956 key = convolution_key(node, weight, bias, spatial)
957 if synthesised:
958 key += " b0=synthesised"
959 if quantise and int8_eligible(node, consumers):
960 kernel, scale = fidelity.quantise(node.name or node.output[0], weight)
961 tensors.append(kernel)
962 tensors.append(scale)
963 tensors.append(bias)
964 key = key.replace("Conv ", "ConvInt8 ", 1) + " zp=0 dtype=int8"
965 else:
966 tensors.append(weight)
967 tensors.append(bias)
968 elif node.op_type == "PRelu":
969 if not held(node.input[1]):
970 raise SystemExit(f"{node.output[0]}: a computed PRelu slope")
971 slope = array(node.input[1])
972 key = f"PRelu s={list(slope.shape)}"
973 tensors.append(slope)
974 elif node.op_type == "Gemm":
975 attrs = {a.name: a for a in node.attribute}
976 alpha = attrs["alpha"].f if "alpha" in attrs else 1.0
977 beta = attrs["beta"].f if "beta" in attrs else 1.0
978 trans_a = attrs["transA"].i if "transA" in attrs else 0
979 trans_b = attrs["transB"].i if "transB" in attrs else 0
980 if (alpha, beta, trans_a, trans_b) != (1.0, 1.0, 0, 1):
981 raise SystemExit(
982 f"{node.output[0]}: Gemm alpha={alpha} beta={beta} transA={trans_a} "
983 f"transB={trans_b}; only the plain `x @ W.T + b` form is lowered."
984 )
985 missing = [n for n in node.input[1:] if not held(n)]
986 if missing:
987 raise SystemExit(f"{node.output[0]}: Gemm operand {missing} is computed")
988 weight = array(node.input[1])
989 bias = array(node.input[2])
990 batch_norm = batch_norms.get(node.output[0])
991 if batch_norm is not None:
992 weight, bias = fold_batch_norm(batch_norm, inits, weight, bias)
993 folded.add(batch_norm.output[0])
994 spatial = flatten_source_shape(node, graph, shapes)
995 expected = int(np.prod(spatial))
996 if weight.shape[1] != expected:
997 raise SystemExit(
998 f"{node.output[0]}: Gemm weight is {list(weight.shape)} but its input "
999 f"flattens {spatial} = {expected} values"
1000 )
1001 weight = weight.reshape([weight.shape[0]] + spatial)
1002 key = (
1003 f"Gemm w={list(weight.shape)} b={list(bias.shape)} "
1004 f"bn={batch_norm is not None}"
1005 )
1006 tensors.append(weight)
1007 tensors.append(bias)
1008 elif node.op_type == "Gather" and held(node.input[0]) and array(node.input[0]).ndim == 2:
1009 # An embedding table. An export that multiplies the looked-up row by
1010 # `sqrt(d_model)` has that scale folded in here rather than left to a shader: it
1011 # is one op fewer and one rounding fewer, since `round(table * sqrt(d))` is
1012 # closer than `round(table) * sqrt(d)`.
1013 table = array(node.input[0]).astype(np.float64)
1014 table = table * math.sqrt(table.shape[1])
1015 key = f"Embed t={list(table.shape)} scaled=sqrt({table.shape[1]})"
1016 tensors.append(table)
1017 elif node.op_type == "Pad" and held(node.input[0]):
1018 # A relative position table, which the export pads out to `2T-1` entries and
1019 # then skews. `nets::supertonic_text` and `nets::supertonic_duration` read the
1020 # nine unpadded entries directly, so the leading batch axis is dropped and the
1021 # padding never happens.
1022 table = np.squeeze(array(node.input[0]))
1023 if table.ndim != 2 or table.shape[0] % 2 == 0:
1024 raise SystemExit(
1025 f"{node.output[0]}: a padded constant of {list(np.shape(table))}; a "
1026 "relative table is [2 * window + 1, head_dim]"
1027 )
1028 key = f"Relative t={list(table.shape)}"
1029 tensors.append(table)
1030 elif node.op_type == "Mul" and layer_norm_scale(node, consumers, held, array):
1031 # A layer norm's gamma and the beta on the `Add` after it. The export decomposes
1032 # the rest of the norm into ReduceMean/Sub/Pow/Sqrt/Div, none of which carries a
1033 # weight, so this pair is all there is to collect.
1034 gamma = next(array(n) for n in node.input if held(n))
1035 follow = consumers[node.output[0]][0]
1036 beta = next(array(n) for n in follow.input if held(n))
1037 key = f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}"
1038 tensors.append(gamma)
1039 tensors.append(beta)
1040 elif node.op_type == "BatchNormalization":
1041 # Folded above, when the layer it follows was emitted. One that was not is a
1042 # batch norm somewhere in the middle of the graph, which nothing here can
1043 # absorb and no shader implements.
1044 if node.output[0] not in folded:
1045 raise SystemExit(
1046 f"{node.output[0]}: a BatchNormalization that does not follow a Gemm. "
1047 "Only a trailing batch norm can be folded away."
1048 )
1049 continue
1050 else:
1051 continue
1052 layers.append(
1053 Layer(
1054 len(layers),
1055 node.op_type,
1056 node.output[0],
1057 key,
1058 first_tensor,
1059 len(tensors) - first_tensor,
1060 )
1061 )
1062 if fidelity is not None:
1063 fidelity.report()
1064 return layers, tensors
1065
1066
1067def layer_norm_scale(node, consumers, held, array):
1068 """Whether `node` is the `Mul(x, gamma)` of a decomposed layer norm.
1069
1070 Recognised by structure rather than by name: a `Mul` against a rank-1 constant whose one
1071 consumer is an `Add` against a rank-1 constant of the same length. In the exports this reads
1072 that matches the layer norms and nothing else - mask multiplies and embedding scales are
1073 against scalars or computed tensors.
1074 """
1075 scales = [n for n in node.input if held(n) and array(n).ndim == 1]
1076 if len(scales) != 1:
1077 return False
1078 follow = consumers.get(node.output[0], [])
1079 if len(follow) != 1 or follow[0].op_type != "Add":
1080 return False
1081 shifts = [
1082 n
1083 for n in follow[0].input
1084 if held(n) and array(n).ndim == 1 and array(n).size == array(scales[0]).size
1085 ]
1086 return len(shifts) == 1
1087
1088
1089def layer_table_digest(layers):
1090 h = hashlib.sha256()
1091 for layer in layers:
1092 h.update(layer.key().encode())
1093 h.update(b"\n")
1094 return h.hexdigest()
1095
1096
1097def check_graph(model, graph_id_name):
1098 graph = model.graph
1099 prefix = MODULES.get(graph_id_name)
1100 nodes = [n for n in graph.node if prefix is None or n.name.startswith(prefix)]
1101
1102 if prefix is None and graph_id_name in GEOMETRY:
1103 want = GEOMETRY[graph_id_name]
1104 names = [i.name for i in graph.input]
1105 if names != [want["input"]]:
1106 raise SystemExit(f"inputs are {names}, expected [{want['input']!r}]")
1107 dims = [
1108 d.dim_value or d.dim_param for d in graph.input[0].type.tensor_type.shape.dim
1109 ]
1110 # Batch may be symbolic. A spatial dim may be too, but only where the expected
1111 # shape says so: for the fixed-size nets every folded Resize target and pad below
1112 # was resolved at exactly this size, so a dynamic one would silently mislower.
1113 got = list(dims[1:])
1114 expect = want["shape"]
1115 mismatched = len(got) != len(expect) or any(
1116 e is not None and g != e for g, e in zip(got, expect)
1117 )
1118 if mismatched:
1119 raise SystemExit(f"input shape {dims}, expected [batch] + {expect}")
1120
1121 outputs = [o.name for o in graph.output]
1122 absent = [o for o in want["outputs"] if o not in outputs]
1123 if absent:
1124 raise SystemExit(f"outputs are {outputs}, expected {absent} among them")
1125 elif not nodes:
1126 raise SystemExit(
1127 f"no nodes are named {prefix!r}. A module-scoped graph relies on the export "
1128 "keeping its Torch module paths, which this one has not."
1129 )
1130
1131 counts = {}
1132 for node in nodes:
1133 counts[node.op_type] = counts.get(node.op_type, 0) + 1
1134 expected = EXPECTED_OPS.get(graph_id_name)
1135 if expected is None:
1136 # A graph checked by structure rather than by op census. The Gemma 4 exports are the
1137 # ones: a decoder whose op counts move with `num_hidden_layers` and two encoders whose
1138 # initializers are anonymised, so `check_architecture` and the collectors' own node
1139 # numbering carry the check instead. See `ARCHITECTURES`.
1140 if graph_id_name not in ARCHITECTURES:
1141 raise SystemExit(f"{graph_id_name} has neither an op census nor an architecture")
1142 return
1143 if counts != expected:
1144 only_got = {k: v for k, v in counts.items() if expected.get(k) != v}
1145 only_want = {k: v for k, v in expected.items() if counts.get(k) != v}
1146 raise SystemExit(f"op counts differ: got {only_got}, expected {only_want}")
1147
1148
1149def open_checkpoint(path):
1150 """`(name -> ndarray, {name: shape})` for a `.safetensors` file, read one tensor at a time.
1151
1152 Lazily, because the checkpoint is 1.33 GB of fp32 and every tensor is quantised to int8 or
1153 rounded to fp16 the moment it is read - so holding the whole thing costs 1.3 GB of resident
1154 host memory for nothing.
1155 """
1156 try:
1157 from safetensors import safe_open
1158 except ImportError:
1159 raise SystemExit("needs safetensors: python -m pip install safetensors")
1160 handle = safe_open(path, framework="np")
1161 shapes = {name: list(handle.get_slice(name).get_shape()) for name in handle.keys()}
1162 return handle.get_tensor, shapes
1163
1164
1165# GGUF tensor types this reads. Only the two MADLAD's file holds: Q2_K linears and F32
1166# norms/tables. Anything else is a file this has not been read against, and should fail
1167# rather than be silently mis-carried.
1168GGUF_F32 = 0
1169GGUF_Q2_K = 10
1170
1171
1172def open_gguf(path):
1173 """`(get, shapes)` for a GGUF file, mirroring [`open_checkpoint`].
1174
1175 `get(name)` returns `(dtype_code, raw_bytes, gguf_shape)` — the payload untouched,
1176 because Q2_K blocks are carried verbatim (transposed at the block level by the
1177 collector, never dequantised). `shapes` maps names to the GGUF `[cols, rows]` shape
1178 as stored; the collector compares against the transposed expectation.
1179
1180 The reader is hand-rolled (magic, version, counts, KV skip, tensor infos) rather than
1181 via the `gguf` package, because the converter needs file offsets for lazy reads and
1182 the package materialises every tensor. Only versions and tensor layouts verified
1183 against `model-q2k.gguf` are accepted.
1184 """
1185 import struct as struct_
1186
1187 with open(path, "rb") as handle:
1188 blob = handle.read()
1189
1190 if blob[:4] != b"GGUF":
1191 raise SystemExit(f"{path} holds no GGUF flatbuffer")
1192 version = struct_.unpack("<I", blob[4:8])[0]
1193 if version != 2:
1194 raise SystemExit(f"{path} is GGUF version {version}, not the version 2 read here")
1195 n_tensors = struct_.unpack("<Q", blob[8:16])[0]
1196 n_kv = struct_.unpack("<Q", blob[16:24])[0]
1197
1198 at = 24
1199
1200 def read_string():
1201 nonlocal at
1202 (length,) = struct_.unpack("<Q", blob[at : at + 8])
1203 at += 8
1204 value = blob[at : at + length].decode("utf-8")
1205 at += length
1206 return value
1207
1208 def skip_value(type_):
1209 nonlocal at
1210 # GGUF metadata types: u8/i8/u16/i16/u32/i32/f32/bool/string/array/u64/i64/f64.
1211 if type_ == 8: # string
1212 (length,) = struct_.unpack("<Q", blob[at : at + 8])
1213 at += 8 + length
1214 elif type_ == 9: # array
1215 (inner, count) = struct_.unpack("<IQ", blob[at : at + 12])
1216 at += 12
1217 for _ in range(count):
1218 skip_value(inner)
1219 elif type_ in (0, 1, 6):
1220 at += 1
1221 elif type_ in (2, 3, 4, 5):
1222 at += 2 if type_ in (2, 3) else 4
1223 elif type_ in (10, 11, 12):
1224 at += 8
1225 else:
1226 raise SystemExit(f"{path}: unhandled GGUF metadata type {type_}")
1227
1228 for _ in range(n_kv):
1229 read_string()
1230 (type_,) = struct_.unpack("<I", blob[at : at + 4])
1231 at += 4
1232 skip_value(type_)
1233
1234 infos = {}
1235 for _ in range(n_tensors):
1236 name = read_string()
1237 (ndims,) = struct_.unpack("<I", blob[at : at + 4])
1238 at += 4
1239 dims = [struct_.unpack("<Q", blob[at + 8 * i : at + 8 * (i + 1)])[0] for i in range(ndims)]
1240 at += 8 * ndims
1241 (dtype,) = struct_.unpack("<I", blob[at : at + 4])
1242 at += 4
1243 (offset,) = struct_.unpack("<Q", blob[at : at + 8])
1244 at += 8
1245 infos[name] = (dtype, dims, offset)
1246
1247 # Tensor data starts at the first 32-byte-aligned offset past the header.
1248 data_start = (at + 31) & ~31
1249
1250 def get(name):
1251 try:
1252 dtype, dims, offset = infos[name]
1253 except KeyError:
1254 raise SystemExit(f"{path} holds no tensor named {name}")
1255 if dtype == GGUF_Q2_K:
1256 # Q2_K payload size is exact: rows are 256-tap superblocks at 84 bytes.
1257 elems = 1
1258 for d in dims:
1259 elems *= d
1260 size = elems // Q2K_BLOCK * Q2K_BYTES
1261 elif dtype == GGUF_F32:
1262 size = 1
1263 for d in dims:
1264 size *= d
1265 size *= 4
1266 else:
1267 raise SystemExit(f"{name} is GGUF type {dtype}, which is not read")
1268 payload = blob[data_start + offset : data_start + offset + size]
1269 if len(payload) != size:
1270 raise SystemExit(f"{name} runs past the file ({len(payload)} of {size} bytes)")
1271 return dtype, payload, dims
1272
1273 shapes = {name: list(dims) for name, (_, dims, _) in infos.items()}
1274 return get, shapes
1275
1276
1277def small100_inventory(spec):
1278 """`{name: shape}` the checkpoint must hold exactly, derived from [`CHECKPOINTS`].
1279
1280 Derived rather than transcribed: a list of 275 names would be checked against itself.
1281 """
1282 d, ffn = spec["d_model"], spec["ffn"]
1283 want = {"model.shared.weight": [spec["vocab"], d]}
1284 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
1285 want[f"model.{side}.layer_norm.weight"] = [d]
1286 want[f"model.{side}.layer_norm.bias"] = [d]
1287 for index in range(count):
1288 at = f"model.{side}.layers.{index}"
1289 attentions = ["self_attn"] + (["encoder_attn"] if side == "decoder" else [])
1290 for attention in attentions:
1291 want[f"{at}.{attention}_layer_norm.weight"] = [d]
1292 want[f"{at}.{attention}_layer_norm.bias"] = [d]
1293 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
1294 want[f"{at}.{attention}.{projection}.weight"] = [d, d]
1295 want[f"{at}.{attention}.{projection}.bias"] = [d]
1296 want[f"{at}.final_layer_norm.weight"] = [d]
1297 want[f"{at}.final_layer_norm.bias"] = [d]
1298 want[f"{at}.fc1.weight"] = [ffn, d]
1299 want[f"{at}.fc1.bias"] = [ffn]
1300 want[f"{at}.fc2.weight"] = [d, ffn]
1301 want[f"{at}.fc2.bias"] = [d]
1302 return want
1303
1304
1305def whisper_inventory(spec):
1306 """`{name: shape}` whisper-base's checkpoint must hold exactly, derived from [`CHECKPOINTS`].
1307
1308 Derived rather than transcribed: a list of 245 names would be checked against itself.
1309
1310 Two absences are as load-bearing as the presences, so both are stated by *not* appearing:
1311
1312 * **`k_proj.bias` is not here**, in any of the 18 attentions. A checkpoint that grows one would
1313 have 18 unexpected names and fail, rather than being read as this table with the bias ignored.
1314 * **There is no `proj_out`.** The head is tied to `model.decoder.embed_tokens.weight`, which
1315 therefore appears once and is emitted once.
1316
1317 The shapes are `torch.nn.Linear`'s **`[out, in]`**, which is a `[out, in, 1, 1]` kernel and so a
1318 reshape rather than a transpose. `fc1` at `[2048, 512]` and `fc2` at `[512, 2048]` are the
1319 asymmetric pair that makes a transposed checkpoint fail here rather than on the device.
1320 """
1321 d, ffn = spec["d_model"], spec["ffn"]
1322 kernel = spec["conv_kernel"]
1323 want = {
1324 "model.encoder.conv1.weight": [d, spec["mels"], kernel],
1325 "model.encoder.conv1.bias": [d],
1326 "model.encoder.conv2.weight": [d, d, kernel],
1327 "model.encoder.conv2.bias": [d],
1328 # A real tensor, not computed sinusoids: whisper freezes them into the checkpoint.
1329 "model.encoder.embed_positions.weight": [spec["source_positions"], d],
1330 "model.decoder.embed_tokens.weight": [spec["vocab"], d],
1331 # Learned, unlike the encoder's.
1332 "model.decoder.embed_positions.weight": [spec["target_positions"], d],
1333 }
1334 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
1335 want[f"model.{side}.layer_norm.weight"] = [d]
1336 want[f"model.{side}.layer_norm.bias"] = [d]
1337 for index in range(count):
1338 at = f"model.{side}.layers.{index}"
1339 attentions = ["self_attn"] + (["encoder_attn"] if side == "decoder" else [])
1340 for attention in attentions:
1341 want[f"{at}.{attention}_layer_norm.weight"] = [d]
1342 want[f"{at}.{attention}_layer_norm.bias"] = [d]
1343 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
1344 want[f"{at}.{attention}.{projection}.weight"] = [d, d]
1345 # Every projection but the key has a bias. See the docstring.
1346 if projection != "k_proj":
1347 want[f"{at}.{attention}.{projection}.bias"] = [d]
1348 want[f"{at}.final_layer_norm.weight"] = [d]
1349 want[f"{at}.final_layer_norm.bias"] = [d]
1350 want[f"{at}.fc1.weight"] = [ffn, d]
1351 want[f"{at}.fc1.bias"] = [ffn]
1352 want[f"{at}.fc2.weight"] = [d, ffn]
1353 want[f"{at}.fc2.bias"] = [d]
1354 return want
1355
1356
1357# The inventory each checkpoint-sourced graph is checked against, and the collector that emits it.
1358#
1359# Two dicts rather than a key inside [`CHECKPOINTS`] because both hold functions defined below it.
1360INVENTORIES = {}
1361COLLECTORS = {}
1362
1363
1364def check_checkpoint(shapes, graph_id_name):
1365 """Refuse a checkpoint that is not the architecture the Rust forward pass hardcodes.
1366
1367 # The transpose that would otherwise be silent
1368
1369 A `torch.nn.Linear`'s weight is **`[out, in]`**, and this runtime indexes a kernel as
1370 `[out, in, kh, kw]`, so a projection needs a reshape and no transpose. ONNX `MatMul` is the
1371 other way round - `x @ W` with a `[in, out]` weight - and every attention projection here is
1372 square 1024 x 1024, so reading one convention as the other yields a tensor of exactly the
1373 right shape holding exactly the wrong numbers, and a parameter count that still adds up.
1374
1375 `fc1` is `[4096, 1024]` and `fc2` is `[1024, 4096]`, so the shape check below is what makes
1376 that mistake loud: a transposed checkpoint fails on those four numbers before anything is
1377 written. That is the whole reason this asserts shapes rather than just names.
1378 """
1379 want = INVENTORIES[graph_id_name](CHECKPOINTS[graph_id_name])
1380 missing = sorted(set(want) - set(shapes))
1381 extra = sorted(set(shapes) - set(want))
1382 shared = sorted(set(want) & set(shapes))
1383 wrong = {n: (shapes[n], want[n]) for n in shared if shapes[n] != want[n]}
1384 if missing or extra or wrong:
1385 lines = []
1386 if missing:
1387 lines.append(f" absent: {missing[:6]}{' ...' if len(missing) > 6 else ''}")
1388 if extra:
1389 lines.append(f" unexpected: {extra[:6]}{' ...' if len(extra) > 6 else ''}")
1390 for name, (got, expect) in list(wrong.items())[:6]:
1391 lines.append(f" {name}: {got} against {expect}")
1392 raise SystemExit(
1393 f"{graph_id_name}: the checkpoint is not the architecture nets/{graph_id_name}.rs\n"
1394 "hardcodes. A wrong shape here is a wrong forward pass, not a load failure:\n"
1395 + "\n".join(lines)
1396 )
1397
1398
1399class Fidelity:
1400 """The worst per-tensor cosine between an fp32 weight and the `int8 * scale` a device reads.
1401
1402 The only check that looks at the *numbers* a quantisation produces. It is not a check that the
1403 forward pass is right — a transposed read agrees with itself perfectly, which is why
1404 [`check_checkpoint`] and [`check_architecture`] assert shapes — and it is not a check that the
1405 model is accurate, which `scripts/ml/onnx_parity.py` is for. It is the one thing that catches a
1406 layer whose distribution int8 cannot represent, before it ships.
1407 """
1408
1409 def __init__(self):
1410 self.seen = []
1411
1412 def quantise(self, name, weight):
1413 """`(int8, scale)` for `weight`, recording how well the pair reproduces it."""
1414 kernel, scale = quantise_per_channel(weight)
1415 back = kernel.astype(np.float32).reshape(weight.shape[0], -1) * scale[:, None]
1416 flat = np.ascontiguousarray(weight, dtype=np.float32).reshape(weight.shape[0], -1)
1417 cosine = float(
1418 np.dot(flat.ravel(), back.ravel())
1419 / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30)
1420 )
1421 self.seen.append((cosine, name))
1422 return kernel, scale
1423
1424 def quantise4(self, name, weight):
1425 """`(Int4, scale)` for `weight`, recording how well the pair reproduces it.
1426
1427 The int4 counterpart of [`Fidelity.quantise`]. The reconstruction differs: a block's
1428 scale covers `I4_BLOCK` taps rather than a whole row, so the cosine is measured against
1429 the block-wise product a shader actually computes and not against a row-wise one, which
1430 would flatter it.
1431 """
1432 codes, scale = quantise_per_block(weight)
1433 flat = np.ascontiguousarray(weight, dtype=np.float32).reshape(weight.shape[0], -1)
1434 rows, taps = flat.shape
1435 blocks = scale.shape[1]
1436 # Expand the block scale back over the taps it covers, dropping the padding of the last
1437 # short block, so the comparison is element for element.
1438 wide = np.repeat(scale, I4_BLOCK, axis=1)[:, :taps]
1439 back = codes.astype(np.float32).reshape(rows, taps) * wide
1440 cosine = float(
1441 np.dot(flat.ravel(), back.ravel())
1442 / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30)
1443 )
1444 self.seen.append((cosine, name))
1445 del blocks
1446 return Int4(codes), scale
1447
1448 def report(self, floor=None):
1449 """Print the worst three, and refuse the file if any is under the floor.
1450
1451 `floor` defaults to [`MIN_INT8_COSINE`]; an int4 collector passes
1452 [`MIN_INT4_COSINE`], which is looser because four bits cannot meet the int8 bar and
1453 should not be asked to. See that constant for the measured numbers.
1454 """
1455 floor = MIN_INT8_COSINE if floor is None else floor
1456 self.seen.sort()
1457 for cosine, name in self.seen[:3]:
1458 if cosine < floor:
1459 raise SystemExit(
1460 f"{name}: the quantised weight correlates {cosine:.6f} with the fp32 one,"
1461 f" under {floor}.\nQuantising this layer costs too much; exclude it and"
1462 " store it fp16 instead."
1463 )
1464 worst = ", ".join(f"{name} {cosine:.6f}" for cosine, name in self.seen[:3])
1465 print(f"fidelity over {len(self.seen)} tensors, worst three: {worst}")
1466
1467
1468def collect_small100(get, spec):
1469 """SMaLL-100's checkpoint as the ordered tensor table `nets::small100` indexes.
1470
1471 Order is the contract, and it is:
1472
1473 the tied embedding, as `head_splits` disjoint class ranges
1474 each encoder layer, in forward order
1475 the encoder's final layer norm
1476 each decoder layer, in forward order
1477 the decoder's final layer norm
1478
1479 The **tied embedding comes first and appears once**, because it has two roles and neither
1480 wants a second copy. `nets::small100` gathers row `t` of it on the host to build the encoder
1481 and decoder inputs - the rows are contiguous, and each carries its own scale, which is exactly
1482 what a per-output-channel quantiser produces - and binds the same tensors as the kernel of the
1483 logits projection. Splitting it by class range is what keeps that binding under
1484 `maxStorageBufferRange`; see [`CHECKPOINTS`].
1485
1486 # What is folded, and what is not
1487
1488 * `sqrt(d_model)` is **not** folded into the embedding here, unlike the fp16 `Gather` arm in
1489 [`collect_layers`]. The host gather applies it while it is still fp32, which is one rounding
1490 fewer than scaling an int8 code by its scale and then by `sqrt(1024)`.
1491 * The attention query scale is **not** folded into `q_proj`. M2M-100 scales the query by
1492 `head_dim ** -0.5` and `head_dim` is 64, which is the `1 / sqrt(head_dim)` `attn_scores`
1493 already applies. Folding it would apply it twice.
1494 * Sinusoidal positions are not in the checkpoint and are not emitted. They are static, so
1495 `nets::small100` computes them and adds them to the gathered rows in fp32, which also
1496 removes the `pos_weights.f32.bin` the ncnn build had to download.
1497 """
1498 layers = []
1499 tensors = []
1500 # Worst per-tensor cosine between the fp32 weight and `int8 * scale`, which is the numbers
1501 # the device will read. This is the only check that the quantisation itself is usable; the
1502 # shape assertions in [`check_checkpoint`] are what catch a transpose, since a cosine is
1503 # computed against whatever was read and a transposed read agrees with itself perfectly.
1504 fidelity = Fidelity()
1505
1506 def emit(op, name, key, added):
1507 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
1508
1509 def linear(name):
1510 """An int8 kernel as `[out, in, 1, 1]`, its per-output-channel scale, and its bias."""
1511 weight = get(f"{name}.weight")
1512 bias = get(f"{name}.bias")
1513 outputs, inputs = weight.shape
1514 kernel, scale = fidelity.quantise(name, weight.reshape(outputs, inputs, 1, 1))
1515 tensors.extend([kernel, scale, bias])
1516 emit(
1517 "Linear8",
1518 name,
1519 f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "
1520 "zp=0 dtype=int8",
1521 3,
1522 )
1523
1524 def layer_norm(name):
1525 gamma = get(f"{name}.weight")
1526 beta = get(f"{name}.bias")
1527 tensors.extend([gamma, beta])
1528 emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)
1529
1530 embedding = get("model.shared.weight")
1531 splits = spec["head_splits"]
1532 classes, width = embedding.shape
1533 if classes % splits:
1534 raise SystemExit(f"{classes} classes do not divide into {splits} equal ranges")
1535 step = classes // splits
1536 for part in range(splits):
1537 lo = part * step
1538 rows = embedding[lo : lo + step]
1539 name = f"model.shared.weight[{lo}:{lo + step}]"
1540 kernel, scale = fidelity.quantise(name, rows.reshape(step, width, 1, 1))
1541 # `Builder::conv_int8` reads a bias after the scale, and a tied head has none. Zeros are
1542 # exact, and recording it in the key means a checkpoint that grows one is not mistaken for
1543 # this table.
1544 tensors.extend([kernel, scale, np.zeros(step, dtype=np.float32)])
1545 emit(
1546 "Head",
1547 name,
1548 f"Head w={list(kernel.shape)} scale={[step]} b={[step]} "
1549 f"classes={lo}..{lo + step} zp=0 dtype=int8 b0=synthesised",
1550 3,
1551 )
1552
1553 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
1554 for index in range(count):
1555 at = f"model.{side}.layers.{index}"
1556 # Pre-norm, as `M2M100EncoderLayer` and `M2M100DecoderLayer` are: the norm comes
1557 # before the sublayer it feeds and the residual skips both. Emitting in forward order
1558 # is what lets the Rust walk the table without an index table.
1559 layer_norm(f"{at}.self_attn_layer_norm")
1560 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
1561 linear(f"{at}.self_attn.{projection}")
1562 if side == "decoder":
1563 layer_norm(f"{at}.encoder_attn_layer_norm")
1564 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
1565 linear(f"{at}.encoder_attn.{projection}")
1566 layer_norm(f"{at}.final_layer_norm")
1567 linear(f"{at}.fc1")
1568 linear(f"{at}.fc2")
1569 layer_norm(f"model.{side}.layer_norm")
1570
1571 fidelity.report()
1572 return layers, tensors
1573
1574
1575def check_gguf(shapes, graph_id_name):
1576 """Refuse a GGUF that is not the architecture the Rust forward pass hardcodes.
1577
1578 The mirror of [`check_checkpoint`] for GGUF sources: same parameter NAMES as
1579 [`madlad_inventory`] (so the two registries cannot drift — the names are derived
1580 from one spec), but GGUF `[in, out]` shapes and Q2_K/F32 dtype assertions instead
1581 of torch shapes. A transposed or resized file fails here rather than on the device.
1582 """
1583 want_names = madlad_inventory(CHECKPOINTS[graph_id_name])
1584 # GGUF shape is the torch shape reversed: q/k/v `[2048, 1024]` read as `[1024, 2048]`.
1585 want = {name: list(reversed(shape)) for name, shape in want_names.items()}
1586 missing = sorted(set(want) - set(shapes))
1587 extra = sorted(set(shapes) - set(want))
1588 shared = sorted(set(want) & set(shapes))
1589 wrong = {n: (shapes[n], want[n]) for n in shared if shapes[n] != want[n]}
1590 if missing or extra or wrong:
1591 lines = []
1592 if missing:
1593 lines.append(f" absent: {missing[:6]}{' ...' if len(missing) > 6 else ''}")
1594 if extra:
1595 lines.append(f" unexpected: {extra[:6]}{' ...' if len(extra) > 6 else ''}")
1596 for name, (got, expect) in list(wrong.items())[:6]:
1597 lines.append(f" {name}: {got} against {expect}")
1598 raise SystemExit(
1599 f"{graph_id_name}: the GGUF is not the architecture nets/{graph_id_name}.rs\n"
1600 "hardcodes. A wrong shape here is a wrong forward pass, not a load failure:\n"
1601 + "\n".join(lines)
1602 )
1603
1604
1605class Q2K:
1606 """A tensor to serialise as [`DTYPE_Q2K`].
1607
1608 Carries the raw Q2_K superblocks (84 bytes per 256 taps, in flat order) plus the
1609 `(rows, blocks)` count the reader needs. Like [`Int4`]: numpy has no two-bit dtype,
1610 so `build` cannot infer this from values — wrapping says so explicitly.
1611
1612 Quacks like an array for the attributes `build` needs (`shape`, `ndim`, `size`).
1613 """
1614
1615 def __init__(self, blocks, rows, taps):
1616 self.blocks = blocks
1617 self.shape = (rows, taps)
1618 self.ndim = 2
1619 self.size = rows * taps
1620
1621
1622def _q2k_checked(get, name, torch_shape):
1623 """The GGUF payload for `name`, checked against `torch_shape` ([outputs, inputs]).
1624
1625 Verifies dtype, block-divisibility and byte size. GGUF flat order == torch flat order
1626 (candle's dim reversal), so no transpose — the payload goes into the file unchanged.
1627 """
1628 dtype, payload, _ = get(f"{name}.weight")
1629 if dtype != GGUF_Q2_K:
1630 raise SystemExit(f"{name}.weight is GGUF type {dtype}, not Q2_K")
1631 outputs, inputs = torch_shape
1632 if inputs % Q2K_BLOCK:
1633 raise SystemExit(f"{name}: {inputs} taps is not block-divisible by {Q2K_BLOCK}")
1634 blocks = inputs // Q2K_BLOCK
1635 if len(payload) != outputs * blocks * Q2K_BYTES:
1636 raise SystemExit(f"{name}: {len(payload)} bytes, not {outputs * blocks * Q2K_BYTES}")
1637 return payload
1638
1639
1640def _emit_q2k(layers, tensors, emit, name, payload, outputs, inputs, op="LinearQ2K",
1641 extra=""):
1642 """A Q2_K kernel + its `(d, dmin)` fp16 table + a synthesised zero bias (3 tensors).
1643
1644 The `(d, dmin)` table is re-derived from the superblocks rather than sliced, so the
1645 file stays self-describing; the shader reads this table, not the superblocks'
1646 embedded fp16 (same values, one fetch instead of two).
1647 """
1648 import numpy as _np
1649
1650 blocks = inputs // Q2K_BLOCK
1651 tensors.append(Q2K(payload, outputs, inputs))
1652 raw = _np.frombuffer(payload, dtype=_np.uint8).reshape(outputs * blocks, Q2K_BYTES)
1653 table = _np.empty((outputs * blocks, 2), dtype=_np.float32)
1654 for b in range(outputs * blocks):
1655 table[b, 0] = _np.frombuffer(raw[b, 80:82].tobytes(), dtype=_np.float16)[0]
1656 table[b, 1] = _np.frombuffer(raw[b, 82:84].tobytes(), dtype=_np.float16)[0]
1657 tensors.append(_np.ascontiguousarray(table.reshape(outputs * blocks * 2)))
1658 tensors.append(_np.zeros(outputs, dtype=_np.float32))
1659 emit(
1660 op,
1661 name,
1662 f"{op} w={[outputs, inputs]} blocks={blocks} "
1663 f"scale={[outputs, blocks, 2]} b={[outputs]} zp=0 dtype=q2k b0=synthesised"
1664 f"{extra}",
1665 3,
1666 )
1667
1668
1669def collect_madlad_q2k(get, spec):
1670 """MADLAD400-3B-MT's GGUF as the ordered tensor table `nets::madlad` indexes.
1671
1672 Same emission ORDER as [`collect_madlad`] (8 Head + 256 enc + 1 + 416 dec + 1 +
1673 2 Relative = 684 layers, 1724 tensors, same names) — the Rust walks positionally,
1674 so the two collectors must agree exactly. What differs is the source and the
1675 payload: Q2_K superblocks carried verbatim from `model-q2k.gguf` (dequantised only
1676 to verify orientation at development time, never in the pipeline), fp16 norms and
1677 tables read straight from the GGUF's F32 tensors.
1678
1679 Per linear: the GGUF payload reshaped to torch rows via the flat rule
1680 (`torch_flat == gguf_flat`), requantised NOT AT ALL — the 84-byte superblocks go
1681 into the file unchanged, with the per-superblock `(d, dmin)` fp16 table beside them
1682 (in the slot a per-channel scale would occupy) and a synthesised zero bias after
1683 that. No fidelity gate on these tensors: their error is the file's own, already
1684 validated (cosine ~0.96 vs fp32, the Q2_K band).
1685 """
1686 layers = []
1687 tensors = []
1688
1689 def emit(op, name, key, added):
1690 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
1691
1692 def linear_q2k(name, torch_shape):
1693 """A Q2_K kernel verbatim, its `(d, dmin)` table, and a synthesised zero bias."""
1694 payload = _q2k_checked(get, name, torch_shape)
1695 _emit_q2k(layers, tensors, emit, name, payload, *torch_shape)
1696
1697 def rms_norm(name):
1698 """An RMS norm's gain, fp16 from the GGUF's F32. One tensor: no beta."""
1699 dtype, payload, gguf_shape = get(f"{name}.weight")
1700 if dtype != GGUF_F32:
1701 raise SystemExit(f"{name}.weight is GGUF type {dtype}, not F32")
1702 import numpy as _np
1703
1704 gamma = _np.frombuffer(payload, dtype=_np.float32)
1705 tensors.append(gamma)
1706 emit("RmsNorm", name, f"RmsNorm g={list(gamma.shape)}", 1)
1707
1708 def head_q2k(table, rows_spec, torch_taps):
1709 dtype, payload, _ = get(f"{table}.weight")
1710 if dtype != GGUF_Q2_K:
1711 raise SystemExit(f"{table}.weight is GGUF type {dtype}, not Q2_K")
1712 # Whole-table payload, split by class range into per-split kernels. A split
1713 # boundary falls on a superblock boundary (every split row count divides by 256).
1714 # Torch rows: flat payload reshaped. GGUF flat == torch flat.
1715 for rows in rows_spec:
1716 if rows % Q2K_BLOCK:
1717 raise SystemExit(f"{table} split of {rows} classes straddles superblocks")
1718 lo = 0
1719 blocks = torch_taps // Q2K_BLOCK
1720 for rows in rows_spec:
1721 name = f"{table}.weight[{lo}:{lo + rows}]"
1722 chunk = payload[lo * blocks * Q2K_BYTES : (lo + rows) * blocks * Q2K_BYTES]
1723 _emit_q2k(layers, tensors, emit, name, chunk, rows, torch_taps, op="Head",
1724 extra=f" classes={lo}..{lo + rows}")
1725 lo += rows
1726
1727 d, ffn = spec["d_model"], spec["d_ff"]
1728 inner = spec["heads"] * spec["head_dim"]
1729 rows_spec = spec["head_rows"]
1730 head_q2k("decoder.embed_tokens", rows_spec, d)
1731 head_q2k("lm_head", rows_spec, d)
1732
1733 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
1734 for index in range(count):
1735 at = f"{side}.block.{index}"
1736 attentions = ["SelfAttention"] + (["EncDecAttention"] if side == "decoder" else [])
1737 for layer, attention in enumerate(attentions):
1738 rms_norm(f"{at}.layer.{layer}.layer_norm")
1739 linear_q2k(f"{at}.layer.{layer}.{attention}.q", [inner, d])
1740 linear_q2k(f"{at}.layer.{layer}.{attention}.k", [inner, d])
1741 linear_q2k(f"{at}.layer.{layer}.{attention}.v", [inner, d])
1742 linear_q2k(f"{at}.layer.{layer}.{attention}.o", [d, inner])
1743 ff = len(attentions)
1744 rms_norm(f"{at}.layer.{ff}.layer_norm")
1745 # Fused `[gate | up]`, the layout `GatedActivate` halves: row-concatenation of
1746 # the two payloads (each row keeps its own blocks, so no block ever splits and
1747 # the concat is exact). Same fused table the int8 port builds by concatenating
1748 # fp32 rows, but with zero requantisation.
1749 wi_0 = _q2k_checked(get, f"{at}.layer.{ff}.DenseReluDense.wi_0", [ffn, d])
1750 wi_1 = _q2k_checked(get, f"{at}.layer.{ff}.DenseReluDense.wi_1", [ffn, d])
1751 _emit_q2k(layers, tensors, emit,
1752 f"{at}.layer.{ff}.DenseReluDense.wi_01", wi_0 + wi_1, 2 * ffn, d)
1753 linear_q2k(f"{at}.layer.{ff}.DenseReluDense.wo", [d, ffn])
1754 rms_norm(f"{side}.final_layer_norm")
1755
1756 for side in ("encoder", "decoder"):
1757 dtype, payload, gguf_shape = get(
1758 f"{side}.block.0.layer.0.SelfAttention.relative_attention_bias.weight"
1759 )
1760 if dtype != GGUF_F32:
1761 raise SystemExit(f"{side} relative table is GGUF type {dtype}, not F32")
1762 import numpy as _np
1763
1764 # GGUF [16, 32] is torch [32, 16] transposed (reversed dims, same flat bytes).
1765 table = _np.frombuffer(payload, dtype=_np.float32).reshape(
1766 spec["heads"], spec["buckets"]
1767 ).T.copy()
1768 if list(table.shape) != [spec["buckets"], spec["heads"]]:
1769 raise SystemExit(f"{side} block-0 relative table is {list(table.shape)}")
1770 tensors.append(_np.ascontiguousarray(table, dtype=_np.float32))
1771 emit(
1772 "Relative",
1773 f"{side}.block.0.relative_attention_bias",
1774 f"Relative t={list(table.shape)} host-read fp16",
1775 1,
1776 )
1777
1778 return layers, tensors
1779
1780
1781def collect_whisper(get, spec):
1782 """whisper-base's checkpoint as the ordered tensor table `nets::whisper` indexes.
1783
1784 Order is the contract, and it is forward order per stack, encoder first:
1785
1786 `conv1`, `conv2`, the encoder position table, each encoder layer, the encoder's norm
1787 the tied head, the decoder position table, each decoder layer, the decoder's norm
1788
1789 # The two convolutions
1790
1791 Both are rank-3 in the checkpoint and are emitted as the `1 x k` rank-4 kernel this runtime
1792 indexes, which is a reshape of the same bytes. Their geometry is in the digest key rather than in
1793 the Rust alone, because `conv2`'s **stride 2** is what turns 3000 mel frames into 1500 encoder
1794 positions and a wrong stride gives the right rank and the wrong length.
1795
1796 # The absent key bias
1797
1798 No `k_proj` in any of the 18 attentions has one. `Builder::conv_int8` reads a bias after the
1799 scale, so each gets zeros — exact, and recorded in the digest key as `b0=synthesised` so a
1800 checkpoint that grows one is not silently read as this table.
1801
1802 # The tied head
1803
1804 `model.decoder.embed_tokens.weight` is emitted **once** and has two roles, as SMaLL-100's does:
1805 `nets::whisper` gathers a row of it on the host to build a decode step's input, and binds the
1806 same tensor as the kernel of the logits projection. At 51,865 x 512 it is 26.6 MB of int8, well
1807 inside `maxStorageBufferRange`'s guaranteed 128 MiB, so unlike SMaLL-100 it needs no class split.
1808
1809 # What is not folded
1810
1811 * The attention query scale. Whisper scales the query by `head_dim ** -0.5` and `head_dim` is 64,
1812 which is the `1 / sqrt(head_dim)` `attn_scores` already applies. Folding it would apply it
1813 twice.
1814 * `sqrt(d_model)` on the embedding. `config.json` has `scale_embedding: false`, so there is none.
1815 * Both **position tables** are real tensors, and they go opposite ways. The **encoder's** is
1816 added to the conv stem's output, which is a device tensor, so it is transposed to
1817 `[width, 1, positions]` and emitted as a `Kind::Constant`. The **decoder's** is added to a
1818 gathered embedding row on the *host*, in f32, exactly as `nets::small100::embed_positions`
1819 does, so it stays `[positions, width]` and never reaches a shader.
1820 """
1821 layers = []
1822 tensors = []
1823 fidelity = Fidelity()
1824
1825 def emit(op, name, key, added):
1826 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
1827
1828 def convolution(name, stride):
1829 """A rank-3 `[out, in, k]` kernel as the `1 x k` int8 one, its scale and its bias."""
1830 weight = get(f"{name}.weight")
1831 bias = get(f"{name}.bias")
1832 outputs, inputs, width = weight.shape
1833 lifted = weight.reshape(outputs, inputs, 1, width)
1834 kernel, scale = fidelity.quantise(name, lifted)
1835 tensors.extend([kernel, scale, bias])
1836 # ONNX orders pads as all the begins then all the ends, so a 1-D `[1, 1]` is `[0, 1, 0, 1]`.
1837 # `same` padding on a kernel of 3, which is what holds the length at stride 1 and halves it
1838 # at stride 2.
1839 emit(
1840 "Conv8",
1841 name,
1842 f"Conv8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "
1843 f"k={[1, width]} s={[1, stride]} p={[0, 1, 0, 1]} zp=0 dtype=int8",
1844 3,
1845 )
1846
1847 def linear(name, biased=True):
1848 """An int8 kernel as `[out, in, 1, 1]`, its per-output-channel scale, and its bias."""
1849 weight = get(f"{name}.weight")
1850 outputs, inputs = weight.shape
1851 kernel, scale = fidelity.quantise(name, weight.reshape(outputs, inputs, 1, 1))
1852 if biased:
1853 bias = get(f"{name}.bias")
1854 suffix = ""
1855 else:
1856 bias = np.zeros(outputs, dtype=np.float32)
1857 suffix = " b0=synthesised"
1858 tensors.extend([kernel, scale, bias])
1859 emit(
1860 "Linear8",
1861 name,
1862 f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "
1863 f"zp=0 dtype=int8{suffix}",
1864 3,
1865 )
1866
1867 def layer_norm(name):
1868 gamma = get(f"{name}.weight")
1869 beta = get(f"{name}.bias")
1870 tensors.extend([gamma, beta])
1871 emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)
1872
1873 def table(name):
1874 values = get(f"{name}.weight")
1875 tensors.append(values)
1876 emit("Table", name, f"Table t={list(values.shape)}", 1)
1877
1878 def constant(name):
1879 """A `[positions, width]` table as the `[width, 1, positions]` a `Kind::Constant` wants."""
1880 values = get(f"{name}.weight")
1881 positions, width = values.shape
1882 transposed = values.T.reshape(width, 1, positions).copy()
1883 tensors.append(transposed)
1884 emit("Constant", name, f"Constant t={list(transposed.shape)}", 1)
1885
1886 def stack(side, count):
1887 for index in range(count):
1888 at = f"model.{side}.layers.{index}"
1889 # Pre-norm, as `WhisperEncoderLayer` and `WhisperDecoderLayer` are: the norm comes before
1890 # the sublayer it feeds and the residual skips both.
1891 attentions = ["self_attn"] + (["encoder_attn"] if side == "decoder" else [])
1892 for attention in attentions:
1893 layer_norm(f"{at}.{attention}_layer_norm")
1894 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
1895 linear(f"{at}.{attention}.{projection}", biased=projection != "k_proj")
1896 layer_norm(f"{at}.final_layer_norm")
1897 linear(f"{at}.fc1")
1898 linear(f"{at}.fc2")
1899 layer_norm(f"model.{side}.layer_norm")
1900
1901 # --- the encoder ---
1902 convolution("model.encoder.conv1", stride=1)
1903 # Stride 2: 3000 mel frames become the 1500 positions the decoder cross-attends over.
1904 convolution("model.encoder.conv2", stride=2)
1905 # Transposed and device-resident: it is added to the conv stem's output. The decoder's table
1906 # below is not, because the host adds that one.
1907 constant("model.encoder.embed_positions")
1908 stack("encoder", spec["encoder_layers"])
1909
1910 # --- the decoder ---
1911 head = "model.decoder.embed_tokens"
1912 rows = get(f"{head}.weight")
1913 classes, width = rows.shape
1914 kernel, scale = fidelity.quantise(head, rows.reshape(classes, width, 1, 1))
1915 # `Builder::conv_int8` reads a bias after the scale, and a tied head has none.
1916 tensors.extend([kernel, scale, np.zeros(classes, dtype=np.float32)])
1917 emit(
1918 "Head",
1919 head,
1920 f"Head w={list(kernel.shape)} scale={[classes]} b={[classes]} tied=embed_tokens "
1921 "zp=0 dtype=int8 b0=synthesised",
1922 3,
1923 )
1924 table("model.decoder.embed_positions")
1925 stack("decoder", spec["decoder_layers"])
1926
1927 fidelity.report()
1928 return layers, tensors
1929
1930
1931def nllb_inventory(spec):
1932 """`{name: shape}` NLLB-200-distilled-600M's checkpoint must hold exactly.
1933
1934 Derived rather than transcribed: a list of 513 names would be checked against itself.
1935
1936 The checkpoint holds the tied embedding **four times** (`model.shared`,
1937 `model.encoder.embed_tokens`, `model.decoder.embed_tokens`, `lm_head` — verified
1938 byte-identical). Only `model.shared.weight` is wanted; the other three are stated by
1939 *not* appearing, so a checkpoint that unties them fails loudly instead of being read
1940 as this table with three copies ignored.
1941
1942 Unlike whisper, **every** projection (all 96 attentions' q/k/v/out) carries a bias —
1943 `k_proj.bias` is present. And unlike whisper there is no convolution stem and no
1944 learned position table: positions are fairseq sinusoids computed by the Rust, exactly
1945 as for small100.
1946 """
1947 d, ffn = spec["d_model"], spec["ffn"]
1948 want = {"model.shared.weight": [spec["vocab"], d]}
1949 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
1950 want[f"model.{side}.layer_norm.weight"] = [d]
1951 want[f"model.{side}.layer_norm.bias"] = [d]
1952 for index in range(count):
1953 at = f"model.{side}.layers.{index}"
1954 attentions = ["self_attn"] + (["encoder_attn"] if side == "decoder" else [])
1955 for attention in attentions:
1956 want[f"{at}.{attention}_layer_norm.weight"] = [d]
1957 want[f"{at}.{attention}_layer_norm.bias"] = [d]
1958 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
1959 want[f"{at}.{attention}.{projection}.weight"] = [d, d]
1960 want[f"{at}.{attention}.{projection}.bias"] = [d]
1961 want[f"{at}.final_layer_norm.weight"] = [d]
1962 want[f"{at}.final_layer_norm.bias"] = [d]
1963 want[f"{at}.fc1.weight"] = [ffn, d]
1964 want[f"{at}.fc1.bias"] = [ffn]
1965 want[f"{at}.fc2.weight"] = [d, ffn]
1966 want[f"{at}.fc2.bias"] = [d]
1967 return want
1968
1969
1970def collect_gemma4(model, spec):
1971 """Gemma 4's decoder export as the ordered tensor table `nets::gemma4` indexes.
1972
1973 THE TENSOR ORDER (the contract with the Rust net - positional indexing, no names):
1974
1975 1. the logits head, as `head_splits` disjoint class ranges of `vocab / head_splits`.
1976 Each range emits 3 tensors: int4 kernel `[rows, 1536, 1, 1]`, fp16 per-block scale
1977 `[rows, blocks]`, synthesised zero bias `[rows]`. Tensors 0..11.
1978 2. the shared per-layer projection (3 tensors) and its norm (1). Tensors 12..15.
1979 3. the final norm (1). Tensor 16.
1980 4. each layer 0..34, in the order `declare_layer` states. A layer that owns a cache
1981 contributes 32 tensors; one that does not contributes 25.
1982
1983 # Two things the converter does that the export does not
1984
1985 * **Transposes** every projection. The export holds `MatMul` weights as `[in, out]`; every
1986 convolution in this runtime takes an ONNX `Conv` kernel, `[out, in, kh, kw]`.
1987 * **Synthesises a zero bias** for each. Gemma 4 has none - `attention_bias` is false - but a
1988 convolution here always takes one, and a zero bias is `out * 2` bytes against a kernel of
1989 `out * 1536`.
1990
1991 # And two it deliberately does not
1992
1993 * `layer_scalar` is emitted **unchanged**, not folded. Folding it into
1994 `per_layer_projection`'s weights would be exact and would save an op, but the per-layer
1995 branch is the one part of the forward pass with no reference run behind it; folding a
1996 constant into a path whose shape is still unconfirmed makes the eventual comparison harder,
1997 not easier. `nets::gemma4` names it as a host tensor meanwhile.
1998 * The **scale folded into `q_norm`** stays folded. The export applies no `1/sqrt(head_dim)`
1999 between the query projection and the score matmul, and `nets::gemma4` passes a scale of one
2000 to match - see `Q_NORM_CARRIES_SCALE`. Dividing it out here would need the Rust to stop
2001 doing that in the same commit.
2002 """
2003 graph = model.graph
2004 inits = {i.name: i for i in graph.initializer}
2005
2006 def get(name):
2007 found = inits.get(name)
2008 if found is None:
2009 raise SystemExit(f"the export has no tensor named {name}")
2010 return numpy_helper.to_array(found).astype(np.float32)
2011
2012 layers = []
2013 tensors = []
2014 fidelity = Fidelity()
2015
2016 def emit(op, name, key, added):
2017 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
2018
2019 def projection(name, weight=None):
2020 """A `[in, out]` MatMul as an int4 `[out, in, 1, 1]` kernel, its scale, and a zero bias."""
2021 matrix = get(f"{name}.weight") if weight is None else weight
2022 inputs, outputs = matrix.shape
2023 kernel = np.ascontiguousarray(matrix.T).reshape(outputs, inputs, 1, 1)
2024 codes, scale = fidelity.quantise4(name, kernel)
2025 bias = np.zeros(outputs, dtype=np.float32)
2026 tensors.extend([codes, scale, bias])
2027 emit(
2028 "Linear4",
2029 name,
2030 f"Linear4 w={[outputs, inputs, 1, 1]} scale={list(scale.shape)} "
2031 f"b={[outputs]} zp=0 dtype=int4 block={I4_BLOCK}",
2032 3,
2033 )
2034
2035 def projection8(name):
2036 """The same at **eight** bits, whose scale is rank 1.
2037
2038 For the two per-layer-input projections only. They are the smallest weights in a layer
2039 and the only ones that miss `MIN_INT4_COSINE`: `per_layer_input_gate` on layer 21
2040 reconstructs at 0.9870 at four bits, while every large projection clears the floor.
2041 Quantising them further would save about a thousandth of the file for the worst error in
2042 it. `nets::gemma4::projection8` states the same split on the reader's side.
2043 """
2044 matrix = get(f"{name}.weight")
2045 inputs, outputs = matrix.shape
2046 kernel = np.ascontiguousarray(matrix.T).reshape(outputs, inputs, 1, 1)
2047 codes, scale = fidelity.quantise(name, kernel)
2048 bias = np.zeros(outputs, dtype=np.float32)
2049 tensors.extend([codes, scale, bias])
2050 emit(
2051 "Linear8",
2052 name,
2053 f"Linear8 w={[outputs, inputs, 1, 1]} scale={[outputs]} b={[outputs]} "
2054 "zp=0 dtype=int8",
2055 3,
2056 )
2057
2058 def vector(name, expect):
2059 values = get(name)
2060 if list(values.shape) != [expect]:
2061 raise SystemExit(f"{name} is {list(values.shape)}, not [{expect}]")
2062 tensors.append(values)
2063 emit("RmsNorm", name, f"RmsNorm g={[expect]}", 1)
2064
2065 d = spec["d_model"]
2066 per_layer, layer_count = spec["per_layer"], spec["layers"]
2067 splits, vocab = spec["head_splits"], spec["vocab"]
2068
2069 # 1. The logits head, split so no one tensor exceeds a descriptor's guaranteed reach.
2070 head = get("lm_head.MatMul.weight")
2071 rows = vocab // splits
2072 if rows * splits != vocab:
2073 raise SystemExit(f"{vocab} classes do not split into {splits}")
2074 for part in range(splits):
2075 lo = part * rows
2076 projection(f"lm_head[{lo}:{lo + rows}]", weight=head[:, lo : lo + rows])
2077
2078 # 2. The shared per-layer projection and its norm.
2079 projection("model.per_layer_projection.MatMul")
2080 vector("model.per_layer_projection_norm.weight", per_layer)
2081
2082 # 3. The final norm. The export files it under a phantom 36th layer rather than beside the
2083 # other shared tensors, so it is read by that name and emitted here, where the net wants it.
2084 vector("model.layers.35.final_norm_layernorm.weight", d)
2085
2086 # 4. The two rotary tables, truncated and interleaved.
2087 #
2088 # The export ships `cos_cache_*` and `sin_cache_*` at 131072 rows, which is
2089 # `max_position_embeddings` and two orders of magnitude past any context this runtime offers:
2090 # the global pair alone would be 134 MB. They are cut to `max_context` and interleaved into
2091 # one table per layer type, so a position's angles are one contiguous row in the layout
2092 # `Builder::rotary` reads - cosines first, then sines.
2093 context = spec["max_context"]
2094 for kind, dim in (("local", spec["head_dim"]), ("global", spec["global_head_dim"])):
2095 cos = get(f"cos_cache_{kind}")[:context]
2096 sin = get(f"sin_cache_{kind}")[:context]
2097 if cos.shape != (context, dim // 2) or sin.shape != cos.shape:
2098 raise SystemExit(
2099 f"the {kind} rotary tables are {cos.shape} and {sin.shape}, not "
2100 f"({context}, {dim // 2}) - half a head is the rotary width"
2101 )
2102 table = np.concatenate([cos, sin], axis=1).astype(np.float32)
2103 tensors.append(table)
2104 emit("Rotary", f"{kind}_rotary_table", f"Rotary t={list(table.shape)}", 1)
2105
2106 # 4. The layers.
2107 for index in range(layer_count):
2108 at = f"model.layers.{index}"
2109 full = index % 5 == 4
2110 owns = index < spec["owns_cache_layers"]
2111 dim = spec["global_head_dim"] if full else spec["head_dim"]
2112 vector(f"{at}.input_layernorm.weight", d)
2113 vector(f"{at}.attn.q_norm.layernorm.weight", dim)
2114 projection(f"{at}.attn.q_proj.MatMul")
2115 if owns:
2116 vector(f"{at}.attn.k_norm.layernorm.weight", dim)
2117 projection(f"{at}.attn.k_proj.MatMul")
2118 projection(f"{at}.attn.v_proj.MatMul")
2119 # `v_norm`'s gamma is all ones and the export names it with slashes rather than dots,
2120 # so it is read by its node path. Emitted like any other norm rather than synthesised
2121 # here, so the file stays self-describing and a future export that trains it needs no
2122 # converter change.
2123 vector(f"/model/layers.{index}/attn/v_norm/ones_weight", dim)
2124 projection(f"{at}.attn.o_proj.MatMul")
2125 vector(f"{at}.post_attention_layernorm.weight", d)
2126 vector(f"{at}.pre_feedforward_layernorm.weight", d)
2127 projection(f"{at}.mlp.gate_up_proj.MatMul")
2128 projection(f"{at}.mlp.down_proj.MatMul")
2129 vector(f"{at}.post_feedforward_layernorm.weight", d)
2130 projection8(f"{at}.per_layer.per_layer_input_gate.MatMul")
2131 projection8(f"{at}.per_layer.per_layer_projection.MatMul")
2132 vector(f"{at}.post_per_layer_input_norm.weight", d)
2133 scalar = get(f"{at}.layer_scalar")
2134 tensors.append(scalar.reshape(1))
2135 emit("Scalar", f"{at}.layer_scalar", "Scalar g=[1]", 1)
2136
2137 fidelity.report(MIN_INT4_COSINE)
2138 return layers, tensors
2139
2140
2141def collect_gemma4_vision(model, spec):
2142 """Gemma 4's vision tower as the ordered table `nets::gemma4_vision` indexes.
2143
2144 THE TENSOR ORDER (the contract with the Rust net - positional indexing, no names):
2145
2146 0..1 the patch projection, `[768, 768]` in the export, as an fp16 kernel and bias
2147 2 the trailing norm
2148 3..4 the output projection to the decoder's 1536, likewise fp16
2149 5..10 the two `[10240, 768]` position tables, as int4 triples
2150 then each layer 0..15, in the order `declare_layer` reads:
2151 pre-attention norm, clip,
2152 q/k/v (three triples), clip x3,
2153 q/k/v norms,
2154 clip, o_proj, clip,
2155 post-attention norm, pre-feed-forward norm, clip,
2156 gate, up, clip x3, down, clip,
2157 post-feed-forward norm
2158
2159 # The export's initializers are anonymised, so this walks the graph
2160
2161 Unlike the decoder, whose tensors are named `model.layers.7.attn.q_proj.MatMul.weight`, the
2162 vision export calls them `_to_copy_104`. Matching by name is therefore impossible and the
2163 weights are taken from the **nodes** instead.
2164
2165 The anchor is that the nodes themselves are numbered in topological order:
2166 `node_linear`, `node_linear_1` .. `node_linear_113`, and
2167 `_fused_rms_norm/node_mean` .. `node_mean_112`. Seven linears and seven norms a layer, over
2168 sixteen layers, plus a patch projection and an output projection at the ends - which is
2169 checked below rather than assumed, because a renumbering upstream would otherwise shift every
2170 tensor silently.
2171
2172 Clips are taken by graph position between one layer's first norm and the next's: eleven a
2173 layer, and one before the first layer for the patch projection. Also checked.
2174 """
2175 g = model.graph
2176 inits = {i.name: i for i in g.initializer}
2177 position = {n.name: at for at, n in enumerate(g.node)}
2178
2179 def numbered(node, prefix):
2180 """The index in `prefix`, `prefix_1`, `prefix_2`, ... or None.
2181
2182 The q4f16 exports append `_Quant` to every quantised linear
2183 (`node_linear_7_Quant`); the suffix is stripped before matching so both
2184 exports walk the same numbering.
2185 """
2186 name = (node.name or "").replace("_fused_rms_norm/node_mean", "node_mean")
2187 if name.endswith("_Quant"):
2188 name = name[: -len("_Quant")]
2189 if not name.startswith(prefix):
2190 return None
2191 tail = name[len(prefix):]
2192 if tail == "":
2193 return 0
2194 return int(tail[1:]) if tail.startswith("_") and tail[1:].isdigit() else None
2195
2196 def weight(index):
2197 """Linear `index` as fp32 `[in, out]`, from either export.
2198
2199 The fp16 walk stores protos in `linears`; the q4f16 walk stores `None`
2200 there and the dequantised matrix in `decoded`. Both flow into the same
2201 `dense`/`projection` calls below, which is what keeps the file format
2202 identical across sources.
2203 """
2204 if index in decoded:
2205 return decoded[index].astype(np.float32)
2206 return array(linears[index])
2207
2208 linears, norms, clips = {}, {}, []
2209 decoded = {}
2210 # A `Clip`'s bounds can be an initializer or a folded `Constant` node, and the vision export
2211 # uses both - the patch projection's is a Constant while every layer's is an initializer.
2212 constants = {}
2213 for node in g.node:
2214 if node.op_type == "Constant":
2215 for attribute in node.attribute:
2216 if attribute.name == "value":
2217 constants[node.output[0]] = attribute.t
2218
2219 def scalar(name):
2220 held = inits.get(name) or constants.get(name)
2221 if held is None:
2222 return None
2223 flat = numpy_helper.to_array(held).reshape(-1)
2224 return float(flat[0]) if flat.size else None
2225
2226 for node in g.node:
2227 if node.op_type in ("MatMul", "Gemm"):
2228 index = numbered(node, "node_linear")
2229 if index is not None:
2230 held = [inits[i] for i in node.input if i in inits]
2231 if held:
2232 linears[index] = held[0]
2233 elif node.op_type == "MatMulNBits":
2234 # The q4f16 exports: every linear quantised in place. Decoded to
2235 # fp32 [K, N] here so the shared dense/projection path - and its
2236 # fidelity gate - treats both exports identically. Verified against
2237 # onnxruntime's own MatMulNBits to 3.7e-3 (analysis/prove_sign/).
2238 index = numbered(node, "node_linear")
2239 if index is not None:
2240 linears[index] = None
2241 decoded[index] = dequant_matmul_nbits(node, inits)
2242 elif node.op_type == "SimplifiedLayerNormalization":
2243 index = numbered(node, "node_mean")
2244 if index is not None:
2245 held = [inits[i] for i in node.input if i in inits]
2246 if held:
2247 norms[index] = held[0]
2248 elif node.op_type == "Clip":
2249 # `Clip(x, min, max)` with either bound optional. The patch projection's is
2250 # one-sided; every layer's has both. An absent bound becomes a value fp16 cannot
2251 # reach, so the pair is always two numbers and the shader needs no special case.
2252 low = scalar(node.input[1]) if len(node.input) > 1 else None
2253 high = scalar(node.input[2]) if len(node.input) > 2 else None
2254 if low is None and high is None:
2255 continue
2256 clips.append((
2257 position[node.name],
2258 [-FP16_LIMIT if low is None else low, FP16_LIMIT if high is None else high],
2259 ))
2260
2261 layers_count = spec["layers"]
2262 want_linears = layers_count * 7 + 2
2263 want_norms = layers_count * 7 + 1
2264 if len(linears) != want_linears or len(norms) != want_norms:
2265 raise SystemExit(
2266 f"the vision export has {len(linears)} linears and {len(norms)} norms, not "
2267 f"{want_linears} and {want_norms} - the node numbering this relies on has changed"
2268 )
2269
2270 clips.sort()
2271 starts = [position_of_norm(g, position, 7 * i) for i in range(layers_count)]
2272 starts.append(position_of_norm(g, position, layers_count * 7))
2273 head_clips = [c for c in clips if c[0] < starts[0]]
2274 if len(head_clips) != 1:
2275 raise SystemExit(f"{len(head_clips)} clips before the first layer, not 1")
2276 per_layer_clips = []
2277 for i in range(layers_count):
2278 got = [c for c in clips if starts[i] < c[0] < starts[i + 1]]
2279 if len(got) != 11:
2280 raise SystemExit(f"vision layer {i} has {len(got)} clips, not 11")
2281 per_layer_clips.append([bounds for _, bounds in got])
2282
2283 layers, tensors = [], []
2284 fidelity = Fidelity()
2285
2286 def emit(op, name, key, added):
2287 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
2288
2289 def array(tensor):
2290 # A raw numpy array passes through: the q4f16 walk decodes MatMulNBits
2291 # to fp32 itself (see `weight`), so both exports meet here as matrices.
2292 if isinstance(tensor, np.ndarray):
2293 return tensor.astype(np.float32)
2294 return numpy_helper.to_array(tensor).astype(np.float32)
2295
2296 def weight(index):
2297 """Linear `index` as fp32 `[in, out]`, from either export.
2298
2299 The fp16 walk stores protos in `linears`; the q4f16 walk stores `None`
2300 there and the dequantised matrix in `decoded`. Both flow into the same
2301 `dense`/`projection` calls below, which is what keeps the file format
2302 identical across sources.
2303 """
2304 if index in decoded:
2305 return decoded[index].astype(np.float32)
2306 return array(linears[index])
2307
2308 def dense(name, tensor, transposed=False):
2309 """A linear's weight as an **fp16** `[out, in, 1, 1]` kernel and a zero bias.
2310
2311 `transposed` says the weight is **already** `[out, in]`, which a `Gemm` with `transB` is
2312 and a `MatMul` is not. The tower's output projection is the one `Gemm` here, so the two
2313 conventions meet exactly once - and transposing it anyway would be a `[768, 1536]` kernel
2314 that is the right size and the wrong matrix.
2315
2316 # Why these two are not quantised
2317
2318 Sixteen layers of int4 turn a per-layer cosine of 0.9999 into 0.946 at the output, and a
2319 disproportionate share of that enters at the patch projection - 0.9952 before layer 0 has
2320 run - and leaves at the output projection, which takes the pooled state from 0.9747 to
2321 0.9481. Neither has anything downstream to average it away. Together they are 1.7 M
2322 parameters against the tower's 300 M, so fp16 here costs about 2.7 MB.
2323
2324 See `nets::gemma4_vision::PATCH_PROJECTION`.
2325 """
2326 matrix = array(tensor)
2327 if transposed:
2328 outputs, inputs = matrix.shape
2329 kernel = np.ascontiguousarray(matrix).reshape(outputs, inputs, 1, 1)
2330 else:
2331 inputs, outputs = matrix.shape
2332 kernel = np.ascontiguousarray(matrix.T).reshape(outputs, inputs, 1, 1)
2333 tensors.extend([kernel, np.zeros(outputs, dtype=np.float32)])
2334 emit("Linear", name, f"Linear w={[outputs, inputs, 1, 1]} dtype=fp16", 2)
2335
2336 def projection(name, tensor, transposed=False):
2337 """A linear's weight as an int4 `[out, in, 1, 1]` kernel, its scale, and a zero bias.
2338
2339 Every projection inside a layer. The two at the ends go through `dense` instead.
2340 """
2341 matrix = array(tensor)
2342 if transposed:
2343 outputs, inputs = matrix.shape
2344 kernel = np.ascontiguousarray(matrix).reshape(outputs, inputs, 1, 1)
2345 else:
2346 inputs, outputs = matrix.shape
2347 kernel = np.ascontiguousarray(matrix.T).reshape(outputs, inputs, 1, 1)
2348 codes, scale = fidelity.quantise4(name, kernel)
2349 tensors.extend([codes, scale, np.zeros(outputs, dtype=np.float32)])
2350 emit("Linear4", name, f"Linear4 w={[outputs, inputs, 1, 1]} dtype=int4", 3)
2351
2352 def table(name, tensor):
2353 """A `[rows, width]` gather table, **not** transposed.
2354
2355 Unlike a projection, nothing multiplies by this - `Reader::int4_row` reads row `position`
2356 - so transposing it would make every gather stride across the file instead of reading one
2357 contiguous span. The same reason `collect_gemma4_embed` leaves the embedding alone.
2358 """
2359 values = array(tensor)
2360 rows, width = values.shape
2361 codes, scale = fidelity.quantise4(name, values.reshape(rows, width, 1, 1))
2362 tensors.extend([codes, scale, np.zeros(rows, dtype=np.float32)])
2363 emit("Table4", name, f"Table4 w={[rows, width, 1, 1]} dtype=int4", 3)
2364
2365 def vector(name, tensor, expect):
2366 values = array(tensor)
2367 if list(values.shape) != [expect]:
2368 raise SystemExit(f"{name} is {list(values.shape)}, not [{expect}]")
2369 tensors.append(values)
2370 emit("RmsNorm", name, f"RmsNorm g={[expect]}", 1)
2371
2372 def clip(name, bounds):
2373 low, high = bounds
2374 if not low < high:
2375 raise SystemExit(f"{name} clips to [{low}, {high}], which is empty")
2376 tensors.append(np.array([low, high], dtype=np.float32))
2377 emit("Clip", name, f"Clip [{low}, {high}]", 1)
2378
2379 d_model = spec["d_model"]
2380 heads, head_dim, ffn = spec["heads"], spec["head_dim"], spec["ffn"]
2381
2382 dense("patch_projection", weight(0))
2383 vector("final_norm", norms[layers_count * 7], d_model)
2384 dense("output_projection", weight(layers_count * 7 + 1), transposed=True)
2385 # The two learned position tables, `[10240, 768]` each, which the host gathers a row at a
2386 # time. Emitted in the same `[out, in, 1, 1]` triple form as everything else so that
2387 # `Reader::int4_row` can read them, even though nothing binds them to a shader.
2388 #
2389 # The first is gathered by position component 0 and the second by component 1, and the
2390 # reference preprocessor builds those with `indexing="xy"` - so component 0 is the COLUMN.
2391 # Naming them the other way round would transpose every image without changing a shape.
2392 gathers = [
2393 inits[i]
2394 for node in g.node
2395 if node.op_type == "Gather" and (node.name or "").startswith("node_embedding")
2396 for i in node.input
2397 if i in inits and list(inits[i].dims) == [spec["positions"], d_model]
2398 ]
2399 # The q4f16 exports quantise the tables in place (`GatherBlockQuantized`,
2400 # same block packing as MatMulNBits): decode both to fp32 here so the
2401 # shared `table` path - and its fidelity gate - treats both exports alike.
2402 if not gathers:
2403 for node in g.node:
2404 if node.op_type != "GatherBlockQuantized" or not (
2405 node.name or ""
2406 ).startswith("node_embedding"):
2407 continue
2408 attrs = {a.name: a for a in node.attribute}
2409 bits = attrs["bits"].i if "bits" in attrs else 4
2410 if bits != 4:
2411 raise SystemExit(node.name + ": block-quantised gather with " +
2412 str(bits) + " bits, not 4")
2413 gathers.append(dequant_block_quantized(
2414 inits[node.input[0]], inits[node.input[2]], inits[node.input[3]]))
2415 if len(gathers) != 2:
2416 raise SystemExit(f"{len(gathers)} position tables, not 2 - the head has changed")
2417 table("column_positions", gathers[0])
2418 table("row_positions", gathers[1])
2419
2420 for i in range(layers_count):
2421 base = 1 + 7 * i
2422 norm_base = 7 * i
2423 marks = per_layer_clips[i]
2424 at = f"vision.layers.{i}"
2425 vector(f"{at}.pre_attention_norm", norms[norm_base], d_model)
2426 clip(f"{at}.clip_in", marks[0])
2427 projection(f"{at}.q_proj", weight(base))
2428 projection(f"{at}.k_proj", weight(base + 1))
2429 projection(f"{at}.v_proj", weight(base + 2))
2430 clip(f"{at}.clip_q", marks[1])
2431 clip(f"{at}.clip_k", marks[2])
2432 clip(f"{at}.clip_v", marks[3])
2433 vector(f"{at}.q_norm", norms[norm_base + 1], head_dim)
2434 vector(f"{at}.k_norm", norms[norm_base + 2], head_dim)
2435 vector(f"{at}.v_norm", norms[norm_base + 3], head_dim)
2436 clip(f"{at}.clip_mixed", marks[4])
2437 projection(f"{at}.o_proj", weight(base + 3))
2438 clip(f"{at}.clip_o", marks[5])
2439 vector(f"{at}.post_attention_norm", norms[norm_base + 4], d_model)
2440 vector(f"{at}.pre_feedforward_norm", norms[norm_base + 5], d_model)
2441 clip(f"{at}.clip_ff_in", marks[6])
2442 projection(f"{at}.gate_proj", weight(base + 4))
2443 projection(f"{at}.up_proj", weight(base + 5))
2444 clip(f"{at}.clip_gate", marks[7])
2445 clip(f"{at}.clip_up", marks[8])
2446 clip(f"{at}.clip_gated", marks[9])
2447 projection(f"{at}.down_proj", weight(base + 6))
2448 clip(f"{at}.clip_down", marks[10])
2449 vector(f"{at}.post_feedforward_norm", norms[norm_base + 6], d_model)
2450 del heads, ffn
2451 heads, ffn = spec["heads"], spec["ffn"]
2452
2453 fidelity.report(MIN_INT4_COSINE)
2454 return layers, tensors
2455
2456
2457def position_of_norm(graph, position, index):
2458 """Where `node_mean_{index}` sits in topological order."""
2459 want = "node_mean" if index == 0 else f"node_mean_{index}"
2460 for node in graph.node:
2461 name = (node.name or "").replace("_fused_rms_norm/node_mean", "node_mean")
2462 if name == want:
2463 return position[node.name]
2464 raise SystemExit(f"the export has no {want}")
2465
2466
2467def collect_gemma4_audio(model, spec):
2468 """Gemma 4's audio tower as the ordered table `nets::gemma4_audio` indexes.
2469
2470 THE TENSOR ORDER (the contract with the Rust net - positional indexing, no names):
2471
2472 0..1 subsampling conv 0, `[128, 1, 3, 3]` fp16 with its spatial axes SWAPPED, and a
2473 synthesised zero bias
2474 2..3 its layer norm: the export's gain and a synthesised zero beta
2475 4..5 subsampling conv 1, `[32, 128, 3, 3]`, spatial axes swapped, zero bias
2476 6..7 its layer norm, zero beta
2477 8..9 the input projection, `[1024, 1024]` fp16, ROWS PERMUTED - see `input_rows`
2478 10..11 the output projection, `[1536, 1024]` fp16, with its REAL bias
2479 12 the embedder's pre-projection norm, `[1536]`
2480 13..14 the embedder's projection, `[1536, 1536]` fp16, zero bias
2481 then each layer 0..11, in the order `declare_layer` reads:
2482 ffw1 pre-norm, clip, up (triple), clip, clip, down (triple), clip, ffw1 post-norm,
2483 pre-attention norm, clip, q, k, v (three triples), clip x3,
2484 the folded per-channel query scale, the `[8, 128, 13]` relative table,
2485 clip, post (triple), clip, post-attention norm,
2486 conv pre-norm, clip, gate (triple), clip,
2487 the depthwise kernel and its zero bias, conv norm, clip, exit (triple), clip,
2488 ffw2 pre-norm, clip, up, clip, clip, down, clip, ffw2 post-norm,
2489 the terminal norm
2490
2491 # The export's initializers are anonymised, so this walks the graph
2492
2493 Every weight is called `val_2567` or `permute_9` or `_to_copy_16`, so matching by name is
2494 impossible for most of them. HOW EACH FAMILY IS FOUND, weakest tier last:
2495
2496 depthwise convs, SSCP convs ATTRIBUTE: group == 1024 / group == 1, plus asserted
2497 pads and strides. Export-independent.
2498 relative tables SHAPE [8, 128, 13] and consumed by a MatMul.
2499 folded query scales SHAPE [128] and consumed by a Mul. The first SSCP layer
2500 norm's gain is also [128] but is consumed by a
2501 LayerNormalization, so the op type separates them.
2502 SSCP norm gains op type LayerNormalization - the only two in the tower.
2503 linears, RMS norms, clips NODE NUMBERING, the fragile tier.
2504
2505 NAMES ARE THE LAST RESORT AND THE LAST TIER IS GUARDED ACCORDINGLY. Neither namespace is
2506 stable across exports: the fp16 cast renumbers every `node_<Op>_<N>` and renames 44% of the
2507 initializers (618 in each export, only 345 in common), so a name-based collector calibrated
2508 on `audio_encoder.onnx` finds different tensors in `audio_encoder_fp16.onnx`. Counts alone
2509 do not catch a reordering that preserves the count, so the numbered families additionally
2510 assert the SHAPE of all ten linear slots in all twelve layers, and that every layer's
2511 eighteen clips are consumed by the same sequence of op types as layer 0's. A shift that
2512 survived all of that would have to preserve every shape at every slot, which the layer's
2513 [1024, 4096] / [4096, 1024] / [1024, 2048] mix does not allow.
2514
2515 # The hole in the linear numbering
2516
2517 `node_linear` runs 0..134 but **thirteen indices are absent**. Twelve of them are
2518 `relative_k_proj`, one per layer, which the exporter constant-folded into the `[8, 128, 13]`
2519 table this collects separately: the sinusoid it projects depends on nothing but dtype, so
2520 there is nothing left to compute at runtime and no `MatMul` is emitted. The thirteenth is
2521 133, because `output_proj` is the one linear with a bias and the exporter split it - the
2522 `MatMul` is named something else entirely and `node_linear_133` is the `Add`.
2523
2524 Index 0 is PRESENT and is the input projection. It is the bare `node_linear` with no
2525 numeric suffix, which `numbered` maps to 0; a reader that only matches `node_linear_<N>`
2526 misses it, concludes the range starts at 1, and is then off by one for the whole graph.
2527
2528 So the stride is **11 with a hole at +5**, not 10. A naive `1 + 10 * i` is off by one from
2529 layer 0 onward and lands on plausible-looking shapes all the way down; both the hole and the
2530 count are asserted below rather than assumed.
2531 """
2532 g = model.graph
2533 inits = {i.name: i for i in g.initializer}
2534 position = {n.name: at for at, n in enumerate(g.node)}
2535 produced = {out: n for n in g.node for out in n.output}
2536
2537 def numbered(node, prefix):
2538 """The index in `prefix`, `prefix_1`, `prefix_2`, ... or None.
2539
2540 Strips the q4f16 `_Quant` suffix, as the vision walk does.
2541 """
2542 name = (node.name or "").replace("_fused_rms_norm/node_mean", "node_mean")
2543 if name.endswith("_Quant"):
2544 name = name[: -len("_Quant")]
2545 if not name.startswith(prefix):
2546 return None
2547 tail = name[len(prefix):]
2548 if tail == "":
2549 return 0
2550 return int(tail[1:]) if tail.startswith("_") and tail[1:].isdigit() else None
2551
2552 constants = {}
2553 for node in g.node:
2554 if node.op_type == "Constant":
2555 for attribute in node.attribute:
2556 if attribute.name == "value":
2557 constants[node.output[0]] = attribute.t
2558
2559 def held(node, dims=None):
2560 """The initializers or folded constants `node` reads, optionally of one shape."""
2561 out = []
2562 for name in node.input:
2563 tensor = inits.get(name) or constants.get(name)
2564 if tensor is not None and (dims is None or list(tensor.dims) == list(dims)):
2565 out.append(tensor)
2566 return out
2567
2568 def scalar(name):
2569 tensor = inits.get(name) or constants.get(name)
2570 if tensor is None:
2571 return None
2572 flat = numpy_helper.to_array(tensor).reshape(-1)
2573 return float(flat[0]) if flat.size else None
2574
2575 layers_count = spec["layers"]
2576 d_model, heads, head_dim = spec["d_model"], spec["heads"], spec["head_dim"]
2577 ffn, out_dim = spec["ffn"], spec["out_dim"]
2578 offsets, mel_sub = spec["rel_offsets"], spec["mel_subsampled"]
2579 channels = spec["sscp_channels"]
2580
2581 linears, norms, clips = {}, {}, []
2582 relative, per_dim, depthwise, subsample, gains = [], [], [], [], []
2583 reads = {}
2584 for node in g.node:
2585 for i in node.input:
2586 reads.setdefault(i, []).append(node.op_type)
2587 clip_consumers = {}
2588 for node in g.node:
2589 if node.op_type in ("MatMul", "Gemm"):
2590 index = numbered(node, "node_linear")
2591 if index is not None:
2592 for tensor in held(node)[:1]:
2593 linears[index] = tensor
2594 for tensor in held(node, [heads, head_dim, offsets]):
2595 relative.append((position[node.name], tensor))
2596 elif node.op_type == "MatMulNBits":
2597 # The q4f16 exports: decode via the shared block helper (verified
2598 # against onnxruntime to 3.7e-3) and store the fp32 matrix the same
2599 # way the fp16 walk stores its proto.
2600 index = numbered(node, "node_linear")
2601 if index is not None:
2602 linears[index] = numpy_helper.from_array(
2603 dequant_matmul_nbits(node, inits).astype(np.float32),
2604 name=node.name + "_dequant")
2605 elif node.op_type == "SimplifiedLayerNormalization":
2606 index = numbered(node, "node_mean")
2607 if index is not None:
2608 for tensor in held(node)[:1]:
2609 norms[index] = tensor
2610 elif node.op_type == "Mul":
2611 # The folded `softplus(per_dim_scale)`. A `[128]` initializer, which the first
2612 # subsampling layer norm's gain also is - but that one is read by a
2613 # `LayerNormalization`, never by a `Mul`, so the op type separates them.
2614 for tensor in held(node, [head_dim]):
2615 per_dim.append((position[node.name], tensor))
2616 elif node.op_type == "LayerNormalization":
2617 gains.append((position[node.name], held(node)[0]))
2618 elif node.op_type == "Conv":
2619 weights = held(node)
2620 if not weights:
2621 raise SystemExit(f"{node.name} is a Conv with no kernel")
2622 # ATTRIBUTE ANCHORS, not names and not weight rank. `group` separates the two conv
2623 # families exactly and survives a re-export, where node names do not: the fp16 cast
2624 # renumbers every node_<Op>_<N> and renames 44% of the initializers.
2625 attrs = {a.name: list(a.ints) if a.ints else a.i for a in node.attribute}
2626 group, pads = attrs.get("group", 1), attrs.get("pads", [])
2627 strides = attrs.get("strides", [])
2628 if group == d_model:
2629 # CAUSAL: four taps left, none right. Symmetric padding here would not fail a
2630 # shape check - it would shift the whole encoder two positions against the
2631 # reference, in all twelve layers, cumulatively. Asserted rather than trusted.
2632 if pads != [4, 0] or strides != [1]:
2633 raise SystemExit(
2634 f"{node.name} is the depthwise conv with pads={pads} strides={strides}, "
2635 "not the causal pads=[4, 0] strides=[1] nets::gemma4_audio builds. "
2636 "Symmetric padding shifts every frame with no shape error."
2637 )
2638 depthwise.append((position[node.name], weights[0]))
2639 elif group == 1:
2640 if pads != [1, 1, 1, 1] or strides != [2, 2]:
2641 raise SystemExit(
2642 f"{node.name} is a subsampling conv with pads={pads} strides={strides}, "
2643 "not the symmetric pads=[1,1,1,1] strides=[2,2] the transposed layout "
2644 "in nets::gemma4_audio::input_shape relies on being square."
2645 )
2646 subsample.append((position[node.name], weights[0]))
2647 else:
2648 raise SystemExit(f"{node.name} is a Conv with group={group}, neither 1 nor {d_model}")
2649 elif node.op_type == "Clip":
2650 low = scalar(node.input[1]) if len(node.input) > 1 else None
2651 high = scalar(node.input[2]) if len(node.input) > 2 else None
2652 if low is None and high is None:
2653 continue
2654 clip_consumers[position[node.name]] = tuple(sorted(set(reads.get(node.output[0], []))))
2655 clips.append((
2656 position[node.name],
2657 [-FP16_LIMIT if low is None else low, FP16_LIMIT if high is None else high],
2658 ))
2659
2660 # Every count the positional table depends on, asserted so that a re-export fails here
2661 # rather than by writing a well-formed file that decodes to the wrong matrices.
2662 want = {
2663 "linears": (len(linears), layers_count * 10 + 2),
2664 "norms": (len(norms), layers_count * 9 + 1),
2665 "clips": (len(clips), layers_count * 18),
2666 "relative tables": (len(relative), layers_count),
2667 "per-dim scales": (len(per_dim), layers_count),
2668 "depthwise kernels": (len(depthwise), layers_count),
2669 "subsampling kernels": (len(subsample), 2),
2670 "subsampling norm gains": (len(gains), 2),
2671 }
2672 wrong = [f" {k}: {got} against {expect}" for k, (got, expect) in want.items() if got != expect]
2673 if wrong:
2674 raise SystemExit(
2675 "the audio export's node census has changed, so the numbering this collector "
2676 "relies on no longer holds:\n" + "\n".join(wrong)
2677 )
2678 absent = [i for i in range(max(linears) + 1) if i not in linears]
2679 predicted = [6 + 11 * i for i in range(layers_count)] + [11 * layers_count + 1]
2680 if absent != predicted:
2681 raise SystemExit(
2682 f"node_linear is missing {absent}, not {predicted}. The first twelve are the folded "
2683 "relative_k_proj and the last is output_proj's bias Add; a different hole means the "
2684 "stride of 11 with a gap at +5 is no longer the right walk."
2685 )
2686 # The eleven slots of layer 0, checked by shape before the walk is trusted for the other
2687 # eleven layers. `base = 1 + 11 * i` with a hole at +5 is the whole contract, and every one
2688 # of these is a plausible-looking matrix if the stride is wrong by one.
2689 slots = [
2690 ("ffw1.up", 0, [d_model, ffn]),
2691 ("ffw1.down", 1, [ffn, d_model]),
2692 ("q_proj", 2, [d_model, d_model]),
2693 ("k_proj", 3, [d_model, d_model]),
2694 ("v_proj", 4, [d_model, d_model]),
2695 ("post", 6, [d_model, d_model]),
2696 ("lconv.gate", 7, [d_model, 2 * d_model]),
2697 ("lconv.exit", 8, [d_model, d_model]),
2698 ("ffw2.up", 9, [d_model, ffn]),
2699 ("ffw2.down", 10, [ffn, d_model]),
2700 ]
2701 for i in range(layers_count):
2702 for label, slot, shape in slots:
2703 got = list(linears[1 + 11 * i + slot].dims)
2704 if got != shape:
2705 raise SystemExit(
2706 f"layer {i}'s {label} is node_linear_{1 + 11 * i + slot} with shape {got}, "
2707 f"not {shape}. The stride of 11 with a hole at +5 no longer walks this graph."
2708 )
2709
2710 for name, value, uses in (
2711 ("q_scale", spec["q_scale"], layers_count),
2712 ("k_scale", spec["k_scale"], layers_count),
2713 ("logit_cap", spec["logit_cap"], 2 * layers_count),
2714 ("residual_weight", spec["residual_weight"], 2 * layers_count),
2715 ):
2716 found = sum(
2717 1
2718 for node in g.node
2719 for i in node.input
2720 if scalar(i) is not None and abs(scalar(i) - value) < 1e-9
2721 )
2722 if found != uses:
2723 raise SystemExit(
2724 f"{name} = {value} appears {found} times in the graph, not {uses}. "
2725 f"nets::gemma4_audio hardcodes it, so a changed constant is a wrong forward pass."
2726 )
2727
2728 for collection in (relative, per_dim, depthwise, subsample, gains):
2729 collection.sort()
2730 clips.sort()
2731 starts = [position_of_norm(g, position, 9 * i) for i in range(layers_count + 1)]
2732 if [c for c in clips if c[0] < starts[0]] or [c for c in clips if c[0] > starts[-1]]:
2733 raise SystemExit(
2734 "the audio export has clips outside a layer. The input and output projections are "
2735 "plain nn.Linear, unlike the vision tower's head, so there should be none."
2736 )
2737 per_layer_clips = []
2738 signatures = []
2739 for i in range(layers_count):
2740 span = [(at, bounds) for at, bounds in clips if starts[i] < at < starts[i + 1]]
2741 if len(span) != 18:
2742 raise SystemExit(f"audio layer {i} has {len(span)} clips, not 18")
2743 per_layer_clips.append([bounds for _, bounds in span])
2744 signatures.append(tuple(clip_consumers[at] for at, _ in span))
2745 # The eighteen bounds are assigned to ops purely by position, and they are calibrated per
2746 # layer - layer 0's first is [-12.875, 12.8125] and layer 11's is [-9.25, 9.1875] - so a
2747 # layer whose graph order differed would put every bound on the wrong op with no shape
2748 # error and no fidelity warning. Checking that each layer's clips are consumed by the same
2749 # sequence of op types as layer 0's is what turns "positional" into something asserted.
2750 odd = [i for i, s in enumerate(signatures) if s != signatures[0]]
2751 if odd:
2752 raise SystemExit(
2753 f"audio layers {odd} order their 18 clips differently from layer 0, so assigning "
2754 f"the bounds by position would silently mis-apply them. Layer 0 is "
2755 f"{signatures[0]}, layer {odd[0]} is {signatures[odd[0]]}."
2756 )
2757
2758 tensors, table = [], []
2759 fidelity = Fidelity()
2760
2761 def emit(op, name, key, added):
2762 table.append(Layer(len(table), op, name, key, len(tensors) - added, added))
2763
2764 def array(tensor):
2765 return numpy_helper.to_array(tensor).astype(np.float32)
2766
2767 def dense(name, tensor, bias=None, transposed=False):
2768 """A linear's weight as an **fp16** `[out, in, 1, 1]` kernel and a bias.
2769
2770 The three end projections. They go through here rather than `projection` for the reason
2771 the vision tower's two do: an error made before layer 0 has run has twelve layers left
2772 to be amplified through, and one made after the last has nothing downstream to average
2773 it away. Together they are 5.0 M parameters against the tower's 294 M, so fp16 here
2774 costs about 8 MB on a 165 MB file.
2775 """
2776 matrix = array(tensor)
2777 if transposed:
2778 outputs, inputs = matrix.shape
2779 kernel = np.ascontiguousarray(matrix).reshape(outputs, inputs, 1, 1)
2780 else:
2781 inputs, outputs = matrix.shape
2782 kernel = np.ascontiguousarray(matrix.T).reshape(outputs, inputs, 1, 1)
2783 zeros = np.zeros(outputs, dtype=np.float32)
2784 tensors.extend([kernel, zeros if bias is None else array(bias)])
2785 emit("Linear", name, f"Linear w={[outputs, inputs, 1, 1]} dtype=fp16", 2)
2786
2787 def projection(name, tensor):
2788 """A linear's weight as an int4 `[out, in, 1, 1]` kernel, its scale, and a zero bias."""
2789 matrix = array(tensor)
2790 inputs, outputs = matrix.shape
2791 kernel = np.ascontiguousarray(matrix.T).reshape(outputs, inputs, 1, 1)
2792 codes, scale = fidelity.quantise4(name, kernel)
2793 tensors.extend([codes, scale, np.zeros(outputs, dtype=np.float32)])
2794 emit("Linear4", name, f"Linear4 w={[outputs, inputs, 1, 1]} dtype=int4", 3)
2795
2796 def vector(name, tensor, expect):
2797 values = array(tensor)
2798 if list(values.shape) != [expect]:
2799 raise SystemExit(f"{name} is {list(values.shape)}, not [{expect}]")
2800 tensors.append(values)
2801 emit("RmsNorm", name, f"RmsNorm g={[expect]}", 1)
2802
2803 def clip(name, bounds):
2804 low, high = bounds
2805 if not low < high:
2806 raise SystemExit(f"{name} clips to [{low}, {high}], which is empty")
2807 tensors.append(np.array([low, high], dtype=np.float32))
2808 emit("Clip", name, f"Clip [{low}, {high}]", 1)
2809
2810 def kernel(name, tensor, shape, act="", swap_spatial=False):
2811 """A convolution kernel at fp16 and a synthesised zero bias.
2812
2813 None of the three convolutions in this export has a bias, and `Builder::conv` reads one
2814 after every kernel, so the pair is uniform and the shader needs no special case.
2815
2816 `swap_spatial` transposes the last two axes, which the two subsampling kernels need and
2817 the depthwise one does not. `nets::gemma4_audio` carries the mel map as
2818 `[channels, mel, time]` where the export has `[channels, time, mel]` - see `input_rows`
2819 for why - and swapping a convolution's input axes is only exact if its kernel's are
2820 swapped with them. A 3x3 kernel is not symmetric, so feeding a transposed map through an
2821 untransposed kernel is the right shape and a different convolution.
2822
2823 Measured rather than reasoned: running the export up to `input_proj`'s output under
2824 onnxruntime against this layout in numpy gives cosine 0.99999994 with the swap and
2825 0.906 without it, on the same input. See probe/audio_permute.py.
2826 """
2827 values = array(tensor)
2828 if swap_spatial:
2829 values = np.ascontiguousarray(values.transpose(0, 1, 3, 2))
2830 values = values.reshape(shape)
2831 tensors.extend([values, np.zeros(shape[0], dtype=np.float32)])
2832 emit("Conv", name, f"Conv w={list(shape)}{act} dtype=fp16", 2)
2833
2834 def layer_norm(name, tensor, expect):
2835 """A layer norm's gain and a synthesised zero beta.
2836
2837 The two subsampling norms are the only `LayerNormalization` in the tower - everything
2838 else is `SimplifiedLayerNormalization`, i.e. RMS - and the export carries a gain with no
2839 bias (`elementwise_affine=True, bias=False`). `Builder::layer_norm` reads the pair.
2840 """
2841 values = array(tensor)
2842 if list(values.shape) != [expect]:
2843 raise SystemExit(f"{name} is {list(values.shape)}, not [{expect}]")
2844 tensors.extend([values, np.zeros(expect, dtype=np.float32)])
2845 emit("LayerNorm", name, f"LayerNorm g={[expect]} b={[expect]}", 2)
2846
2847 def input_rows(tensor):
2848 """`input_proj_linear`'s weight with its 1024 input rows reordered.
2849
2850 THE FLATTEN ORDER IS THE TRAP, and it is silent: the matrix is square, so both orderings
2851 are the right size and only one is the right matrix.
2852
2853 The export flattens the second subsampling convolution's output **mel-major**. Its
2854 `Transpose` is `perm=[0, 2, 3, 1]` from `[B, ch, time, mel]`, giving `[B, time, mel, ch]`
2855 and an input index of `m * 32 + c`. `nets::gemma4_audio` carries the map as
2856 `[ch, mel, time]` so that the flatten into a `[1024, 1, T]` sequence is a relabelling of
2857 the same bytes rather than a copy of a 23 MB activation - and that ordering is
2858 `c * 32 + m`.
2859
2860 Permuting a `[1024, 1024]` weight once here is free. Transposing the map at runtime, per
2861 clip, is not. Both sides say so: see `nets::gemma4_audio::INPUT_PROJECTION`.
2862 """
2863 matrix = array(tensor)
2864 if list(matrix.shape) != [d_model, d_model]:
2865 raise SystemExit(f"the input projection is {list(matrix.shape)}, not square")
2866 return matrix.reshape(mel_sub, channels[1], d_model).transpose(1, 0, 2).reshape(
2867 d_model, d_model
2868 )
2869
2870 kernel("sscp.conv0", subsample[0][1], (channels[0], 1, 3, 3), swap_spatial=True)
2871 layer_norm("sscp.norm0", gains[0][1], channels[0])
2872 kernel("sscp.conv1", subsample[1][1], (channels[1], channels[0], 3, 3), swap_spatial=True)
2873 layer_norm("sscp.norm1", gains[1][1], channels[1])
2874 dense("input_projection", numpy_helper.from_array(input_rows(linears[0])))
2875
2876 # `output_proj` is the one biased linear, so the exporter split it into a `MatMul` and an
2877 # `Add`. Found by walking BACK from the embedder's pre-projection norm — the last
2878 # SimplifiedLayerNormalization, which this collector already locates as norms[9 * layers] —
2879 # rather than by naming any node. The earlier version of this started from a literal
2880 # `node_linear_133`, in the very namespace this docstring calls unstable; it would have failed
2881 # loudly rather than mislabelled, but the comment claimed edge-following it was not doing.
2882 #
2883 # norms[108] <- Add (output_proj.bias) <- MatMul (output_proj.weight) <- norm_out
2884 tail_norm = [n for n in g.node
2885 if numbered(n, "node_mean") == layers_count * 9
2886 and n.op_type == "SimplifiedLayerNormalization"]
2887 if len(tail_norm) != 1:
2888 raise SystemExit(f"{len(tail_norm)} embedder pre-projection norms, not 1")
2889 adds = [produced[i] for i in tail_norm[0].input if i in produced and produced[i].op_type == "Add"]
2890 if len(adds) != 1:
2891 raise SystemExit(
2892 "the embedder's pre-projection norm is not fed by an Add, so output_proj is no "
2893 "longer a biased linear the exporter split. Check the tail before trusting this."
2894 )
2895 bias = held(adds[0], [out_dim])
2896 matmuls = [produced[i] for i in adds[0].input if i in produced and produced[i].op_type == "MatMul"]
2897 weight = [t for n in matmuls for t in held(n, [d_model, out_dim])]
2898 if not weight:
2899 # The q4f16 exports: output_proj's MatMul is a MatMulNBits. Decoded to
2900 # the fp32 [d_model, out_dim] the fp16 walk reads off its MatMul.
2901 qnodes = [produced[i] for i in adds[0].input
2902 if i in produced and produced[i].op_type == "MatMulNBits"]
2903 weight = [numpy_helper.from_array(dequant_matmul_nbits(n, inits).astype(np.float32),
2904 name=n.name + "_dequant")
2905 for n in qnodes
2906 if dequant_matmul_nbits(n, inits).shape == (d_model, out_dim)]
2907 if len(bias) != 1 or len(weight) != 1:
2908 raise SystemExit(
2909 f"output_proj resolved to {len(weight)} weights and {len(bias)} biases, not one each"
2910 )
2911 dense("output_projection", weight[0], bias=bias[0])
2912 # `with_scale=False` upstream, so the exporter materialised an all-ones gain. Emitted rather
2913 # than dropped: it is 3 KB and it saves the runtime a gainless RMS norm. An RMS norm still
2914 # divides by the RMS, so this is not a no-op whatever the gain is.
2915 vector("embedder.pre_projection_norm", norms[layers_count * 9], out_dim)
2916 dense("embedder.projection", linears[11 * layers_count + 2])
2917
2918 for i in range(layers_count):
2919 base = 1 + 11 * i
2920 norm_base = 9 * i
2921 marks = per_layer_clips[i]
2922 at = f"audio.layers.{i}"
2923
2924 vector(f"{at}.ffw1.pre_norm", norms[norm_base], d_model)
2925 clip(f"{at}.ffw1.clip_in", marks[0])
2926 projection(f"{at}.ffw1.up", linears[base])
2927 clip(f"{at}.ffw1.clip_up_out", marks[1])
2928 clip(f"{at}.ffw1.clip_act", marks[2])
2929 projection(f"{at}.ffw1.down", linears[base + 1])
2930 clip(f"{at}.ffw1.clip_out", marks[3])
2931 vector(f"{at}.ffw1.post_norm", norms[norm_base + 1], d_model)
2932
2933 vector(f"{at}.pre_attention_norm", norms[norm_base + 2], d_model)
2934 clip(f"{at}.clip_qkv_in", marks[4])
2935 projection(f"{at}.q_proj", linears[base + 2])
2936 projection(f"{at}.k_proj", linears[base + 3])
2937 projection(f"{at}.v_proj", linears[base + 4])
2938 clip(f"{at}.clip_q", marks[5])
2939 clip(f"{at}.clip_k", marks[6])
2940 clip(f"{at}.clip_v", marks[7])
2941 # `softplus(per_dim_scale)`, folded by the exporter to a `[128]` fp32 vector, times the
2942 # scalar `q_scale` and tiled over the eight heads. Two multiplies in the export
2943 # (`node_mul_502` then `node_mul_506`) become one per-channel multiply here, and the
2944 # widening from [128] to [1024] is what makes it an ordinary one rather than a per-head
2945 # broadcast the runtime has no op for.
2946 scale = np.tile(array(per_dim[i][1]) * spec["q_scale"], heads)
2947 if scale.shape != (d_model,):
2948 raise SystemExit(f"{at}'s query scale tiled to {scale.shape}, not ({d_model},)")
2949 # Rank three, because `Builder::constant` copies it into the arena as a [C, 1, 1]
2950 # operand for an ordinary per-channel multiply.
2951 tensors.append(scale.reshape(d_model, 1, 1))
2952 emit("QueryScale", f"{at}.query_scale", f"QueryScale s={[d_model, 1, 1]} folded=q_scale", 1)
2953 # `relative_k_proj(sinusoid)`, folded by the exporter and already permuted to
2954 # [heads, head_dim, offsets]. TRANSPOSED HERE to [heads, offsets, head_dim] so that
2955 # head_dim - the axis the shader's dot product contracts over - is the contiguous one.
2956 # Leaving the export's order would be the right size with transposed strides and would
2957 # read wrong taps with no shape error.
2958 #
2959 # Column `offsets - 1` is displacement zero and column 0 is displacement 12, which the
2960 # mask never admits - see `nets::gemma4_audio::rel_column`.
2961 relk = array(relative[i][1])
2962 if list(relk.shape) != [heads, head_dim, offsets]:
2963 raise SystemExit(f"{at}'s relative table is {list(relk.shape)}")
2964 relk = np.ascontiguousarray(relk.transpose(0, 2, 1))
2965 tensors.append(relk)
2966 emit("Relative", f"{at}.relative_k", f"Relative w={list(relk.shape)} dtype=fp16", 1)
2967 clip(f"{at}.clip_attn_out", marks[8])
2968 projection(f"{at}.post_proj", linears[base + 6])
2969 clip(f"{at}.clip_post_out", marks[9])
2970 vector(f"{at}.post_attention_norm", norms[norm_base + 3], d_model)
2971
2972 vector(f"{at}.lconv.pre_norm", norms[norm_base + 4], d_model)
2973 clip(f"{at}.lconv.clip_in", marks[10])
2974 projection(f"{at}.lconv.gate", linears[base + 7])
2975 clip(f"{at}.lconv.clip_gate_out", marks[11])
2976 # `[1024, 1, 5]` in the export, read here as a `1 x 5` grouped convolution over a
2977 # `[1024, 1, T]` sequence, so the kernel gains a unit height. Causal: `pads=[4, 0]`.
2978 kernel(f"{at}.lconv.depthwise", depthwise[i][1], (d_model, 1, 1, 5), act=" group=1024")
2979 vector(f"{at}.lconv.conv_norm", norms[norm_base + 5], d_model)
2980 clip(f"{at}.lconv.clip_act", marks[12])
2981 projection(f"{at}.lconv.exit", linears[base + 8])
2982 clip(f"{at}.lconv.clip_out", marks[13])
2983
2984 vector(f"{at}.ffw2.pre_norm", norms[norm_base + 6], d_model)
2985 clip(f"{at}.ffw2.clip_in", marks[14])
2986 projection(f"{at}.ffw2.up", linears[base + 9])
2987 clip(f"{at}.ffw2.clip_up_out", marks[15])
2988 clip(f"{at}.ffw2.clip_act", marks[16])
2989 projection(f"{at}.ffw2.down", linears[base + 10])
2990 clip(f"{at}.ffw2.clip_out", marks[17])
2991 vector(f"{at}.ffw2.post_norm", norms[norm_base + 7], d_model)
2992 vector(f"{at}.norm_out", norms[norm_base + 8], d_model)
2993
2994 if len(tensors) != spec["tensors"]:
2995 raise SystemExit(
2996 f"{len(tensors)} tensors, not the {spec['tensors']} nets::gemma4_audio::TENSORS "
2997 "declares. The two sides index the same table positionally, so they agree or "
2998 "nothing works."
2999 )
3000 fidelity.report(MIN_INT4_COSINE)
3001 return table, tensors
3002
3003
3004def collect_gemma4_embed(model, spec):
3005 """Gemma 4's two embedding tables as the ordered table `nets::gemma4`'s host side indexes.
3006
3007 THE TENSOR ORDER:
3008
3009 0..2 `model.embed_tokens.weight` int4 `[262144, 1536]`, scale, bias
3010 3..5 `model.embed_tokens_per_layer.weight` int4 `[262144, 8960]`, scale, bias
3011
3012 # The scales the export applies are folded in
3013
3014 `embed_tokens.onnx` is two `Gather`s and two `Mul`s: `inputs_embeds` is the row times 39.25
3015 (`sqrt(1536)` rounded through fp16) and `per_layer_inputs` is its row times 16.0
3016 (`sqrt(256)`). Both are constants over the whole table, so they are folded into the weights
3017 here and the host gathers a row that is already scaled. Applying them at runtime would be one
3018 more multiply per element per token and one more constant to keep in step.
3019
3020 # Not transposed
3021
3022 Unlike every projection in `collect_gemma4`, these stay `[rows, columns]`. Nothing indexes
3023 them as a convolution kernel - `Reader::int4_row` reads row `id` - so transposing would make
3024 a gather stride across the file instead of reading one contiguous span.
3025
3026 # The bias is still there
3027
3028 A zero bias per row, as for the projections, so the triple is the same shape everywhere and
3029 `Reader::int4_row`'s `(kernel, scale)` pair sits at a predictable offset. 262144 rows of fp16
3030 is 512 KB against a 1.2 GB table.
3031 """
3032 inits = {i.name: i for i in model.graph.initializer}
3033
3034 def get(name):
3035 found = inits.get(name)
3036 if found is None:
3037 raise SystemExit(f"the embedding export has no tensor named {name}")
3038 return numpy_helper.to_array(found).astype(np.float32)
3039
3040 layers = []
3041 tensors = []
3042 fidelity = Fidelity()
3043 for name, columns, scale_by in (
3044 ("model.embed_tokens.weight", spec["d_model"], spec["embed_scale"]),
3045 (
3046 "model.embed_tokens_per_layer.weight",
3047 spec["per_layer"] * spec["layers"],
3048 spec["per_layer_scale"],
3049 ),
3050 ):
3051 table = get(name)
3052 if list(table.shape) != [spec["vocab"], columns]:
3053 raise SystemExit(f"{name} is {list(table.shape)}, not {[spec['vocab'], columns]}")
3054 codes, scale = fidelity.quantise4(name, table * scale_by)
3055 bias = np.zeros(spec["vocab"], dtype=np.float32)
3056 tensors.extend([codes, scale, bias])
3057 layers.append(
3058 Layer(
3059 len(layers),
3060 "Embedding4",
3061 name,
3062 f"Embedding4 w={list(table.shape)} scale={list(scale.shape)} "
3063 f"folded={scale_by} dtype=int4 block={I4_BLOCK}",
3064 len(tensors) - 3,
3065 3,
3066 )
3067 )
3068 fidelity.report(MIN_INT4_COSINE)
3069 return layers, tensors
3070
3071
3072def collect_nllb(get, spec):
3073 """NLLB-200-distilled-600M's checkpoint as the ordered tensor table `nets::nllb600` indexes.
3074
3075 THE TENSOR ORDER (the contract with the Rust net — positional indexing, no names):
3076
3077 1. the tied embedding (`model.shared.weight` ONLY), as `head_splits` disjoint
3078 class ranges: [0:64052], [64052:128104], [128104:192155], [192155:256206].
3079 Each range emits 3 tensors: int8 kernel [rows, 1024, 1, 1], fp16 scale [rows],
3080 synthesised zero bias [rows]. Op "Head". Tensors 0..11.
3081 2. each encoder layer 0..11 in forward order. Per layer, in this exact order:
3082 self_attn_layer_norm (LayerNorm, 2 tensors: gamma, beta),
3083 self_attn q/k/v/out_proj (Linear8, 3 tensors each: kernel, scale, bias),
3084 final_layer_norm (LayerNorm, 2),
3085 fc1 (Linear8, 3), fc2 (Linear8, 3).
3086 22 tensors per encoder layer.
3087 3. the encoder's final layer norm (LayerNorm, 2 tensors).
3088 4. each decoder layer 0..11 in forward order. Per layer: self_attn block as in
3089 the encoder (2 + 4*3 = 14 tensors), then encoder_attn_layer_norm (2) +
3090 encoder_attn q/k/v/out_proj (4*3 = 12), then final_layer_norm (2) + fc1/fc2
3091 (2*3 = 6). 36 tensors per decoder layer.
3092 5. the decoder's final layer norm (LayerNorm, 2 tensors). Last.
3093
3094 Totals: 12 head tensors + 12*22 encoder + 2 + 12*36 decoder + 2 = 712 tensors in
3095 258 layers (4 Head + 96 enc + 1 + 156 dec + 1).
3096 196 int8 convolutions (4 head + 12*6 enc + 12*10 dec); everything else fp16 norms
3097 and biases.
3098
3099 # What is folded, and what is not (same as small100 — same M2M-100 forward pass)
3100
3101 * `sqrt(d_model)` is **not** folded into the embedding. The host gather applies it in
3102 fp32 (`embed_positions`), one rounding fewer than scaling int8 codes.
3103 * The attention query scale is **not** folded into `q_proj`. M2M-100 scales the query
3104 by `head_dim ** -0.5` (head_dim 64) = the `1 / sqrt(head_dim)` `attn_scores` applies.
3105 * Sinusoidal positions are not in the checkpoint and are not emitted. `nets::nllb600`
3106 computes fairseq's concatenated-halves sinusoid at position `past + at + 1 + 1`
3107 (padding_idx 1, so first token sits at 2) — byte-identical math to small100.
3108 * FFN activation is **ReLU** (`activation_function: relu` in config.json), so the Rust
3109 uses `Act::Relu` on fc1, not GELU.
3110 * The four checkpoint copies of the tied embedding are asserted byte-identical in
3111 `fetch_nllb600.py` before conversion; only `model.shared.weight` is read here.
3112 """
3113 layers = []
3114 tensors = []
3115 fidelity = Fidelity()
3116
3117 def emit(op, name, key, added):
3118 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
3119
3120 def linear(name):
3121 """An int8 kernel as `[out, in, 1, 1]`, its per-output-channel scale, and its bias."""
3122 weight = get(f"{name}.weight")
3123 bias = get(f"{name}.bias")
3124 outputs, inputs = weight.shape
3125 kernel, scale = fidelity.quantise(name, weight.reshape(outputs, inputs, 1, 1))
3126 tensors.extend([kernel, scale, bias])
3127 emit(
3128 "Linear8",
3129 name,
3130 f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "
3131 "zp=0 dtype=int8",
3132 3,
3133 )
3134
3135 def layer_norm(name):
3136 gamma = get(f"{name}.weight")
3137 beta = get(f"{name}.bias")
3138 tensors.extend([gamma, beta])
3139 emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)
3140
3141 embedding = get("model.shared.weight")
3142 rows_spec = spec["head_rows"]
3143 if sum(rows_spec) != embedding.shape[0]:
3144 raise SystemExit(
3145 f"{embedding.shape[0]} classes do not split as {rows_spec}"
3146 )
3147 lo = 0
3148 for part, rows in enumerate(rows_spec):
3149 chunk = embedding[lo : lo + rows]
3150 name = f"model.shared.weight[{lo}:{lo + rows}]"
3151 kernel, scale = fidelity.quantise(name, chunk.reshape(rows, embedding.shape[1], 1, 1))
3152 # `Builder::conv_int8` reads a bias after the scale, and a tied head has none. Zeros are
3153 # exact, and recording it in the key means a checkpoint that grows one is not mistaken for
3154 # this table.
3155 tensors.extend([kernel, scale, np.zeros(rows, dtype=np.float32)])
3156 emit(
3157 "Head",
3158 name,
3159 f"Head w={list(kernel.shape)} scale={[rows]} b={[rows]} "
3160 f"classes={lo}..{lo + rows} zp=0 dtype=int8 b0=synthesised",
3161 3,
3162 )
3163 lo += rows
3164
3165 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
3166 for index in range(count):
3167 at = f"model.{side}.layers.{index}"
3168 # Pre-norm, as `M2M100EncoderLayer` and `M2M100DecoderLayer` are: the norm comes
3169 # before the sublayer it feeds and the residual skips both. Emitting in forward order
3170 # is what lets the Rust walk the table without an index table.
3171 layer_norm(f"{at}.self_attn_layer_norm")
3172 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
3173 linear(f"{at}.self_attn.{projection}")
3174 if side == "decoder":
3175 layer_norm(f"{at}.encoder_attn_layer_norm")
3176 for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):
3177 linear(f"{at}.encoder_attn.{projection}")
3178 layer_norm(f"{at}.final_layer_norm")
3179 linear(f"{at}.fc1")
3180 linear(f"{at}.fc2")
3181 layer_norm(f"model.{side}.layer_norm")
3182
3183 fidelity.report()
3184 return layers, tensors
3185
3186
3187def maia_inventory(spec):
3188 """`{name: shape}` Maia3-5M's checkpoint must hold exactly, after `fetch_maia.py`'s repack.
3189
3190 Derived rather than transcribed: a list of 148 names would be checked against itself.
3191
3192 Three absences are as load-bearing as the presences, so all three are stated by *not*
3193 appearing:
3194
3195 * **No attention biases.** `omit_qkv_biases=True`, so there is no `mha.in_proj_bias`
3196 and no `mha.out_proj.bias` in any of the eight blocks.
3197 * **No `norm1.bias` or `norm2.bias`.** They are `torch.nn.RMSNorm`, which has a gain
3198 and nothing else. A checkpoint that grew either would be a layer norm, and the Rust
3199 would silently ignore the beta.
3200 * **No `transformer.layers.N.self_attn.smolgen_weight`.** Those eight names alias
3201 `smolgen_shared_weight`; `fetch_maia.py` asserts that and drops them, so a checkpoint
3202 whose blocks stopped sharing one weight fails here with eight unexpected names rather
3203 than being converted as if they still did.
3204
3205 `proj_sq_from`, `proj_sq_to` and `promo_bias_proj` are `bias=False` too. The shapes are
3206 `torch.nn.Linear`'s **`[out, in]`**, so a kernel is a reshape and not a transpose;
3207 `linear1 [512, 256]` against `linear2 [256, 512]` is the asymmetric pair that makes a
3208 transposed checkpoint fail here rather than on the device.
3209 """
3210 d, ffn = spec["d_model"], spec["ffn"]
3211 hidden, gen, heads = spec["bias_hidden"], spec["bias_gen"], spec["heads"]
3212 squares, hid = spec["squares"], spec["head_hidden"]
3213 want = {
3214 "smolgen_shared_weight": [squares * squares, gen],
3215 "elo_embedding_low.weight": [1, spec["elo_dim"]],
3216 "elo_embedding_high.weight": [1, spec["elo_dim"]],
3217 "token_projection.weight": [d, spec["input"]],
3218 "token_projection.bias": [d],
3219 }
3220 for index in range(spec["blocks"]):
3221 at = f"transformer.layers.{index}"
3222 want[f"{at}.self_attn.mha.in_proj_weight"] = [3 * d, d]
3223 want[f"{at}.self_attn.mha.out_proj.weight"] = [d, d]
3224 want[f"{at}.self_attn.sm2.weight"] = [hidden, d]
3225 want[f"{at}.self_attn.sm2.bias"] = [hidden]
3226 want[f"{at}.self_attn.ln1.weight"] = [hidden]
3227 want[f"{at}.self_attn.ln1.bias"] = [hidden]
3228 want[f"{at}.self_attn.sm3.weight"] = [heads * gen, hidden]
3229 want[f"{at}.self_attn.sm3.bias"] = [heads * gen]
3230 want[f"{at}.self_attn.ln2.weight"] = [heads * gen]
3231 want[f"{at}.self_attn.ln2.bias"] = [heads * gen]
3232 want[f"{at}.linear1.weight"] = [ffn, d]
3233 want[f"{at}.linear1.bias"] = [ffn]
3234 want[f"{at}.linear2.weight"] = [d, ffn]
3235 want[f"{at}.linear2.bias"] = [d]
3236 want[f"{at}.norm1.weight"] = [d]
3237 want[f"{at}.norm2.weight"] = [d]
3238 want["transformer.norm.weight"] = [d]
3239 want["transformer.norm.bias"] = [d]
3240 want["proj_sq_from.weight"] = [hid, d]
3241 want["proj_sq_to.weight"] = [hid, d]
3242 want["promo_bias_proj.weight"] = [spec["promotions"], hid]
3243 # The value and ponder heads. Present, asserted, and deliberately not emitted — see
3244 # [`CHECKPOINTS`] and [`collect_maia`].
3245 want["last_ln.weight"] = [d]
3246 want["last_ln.bias"] = [d]
3247 want["fc_value_hid.weight"] = [hid, d]
3248 want["fc_value_hid.bias"] = [hid]
3249 want["fc_value.weight"] = [3, hid]
3250 want["fc_value.bias"] = [3]
3251 want["fc_ponder_hid.weight"] = [hid, d]
3252 want["fc_ponder_hid.bias"] = [hid]
3253 want["fc_ponder.weight"] = [1, hid]
3254 want["fc_ponder.bias"] = [1]
3255 return want
3256
3257
3258def collect_maia(get, spec):
3259 """Maia3-5M's checkpoint as the ordered tensor table `nets::maia` indexes.
3260
3261 THE TENSOR ORDER (the contract with the Rust net — positional indexing, no names):
3262
3263 0. elo_embedding_low.weight [1, 128] op "Host"
3264 1. elo_embedding_high.weight [1, 128] op "Host"
3265 2. token_projection int8 [256, 352, 1, 1] + scale [256] + bias [256]
3266 5. smolgen kernel replicated int8 [32768, 64, 1, 1] + scale [32768] + zero bias
3267 8. each block 0..7 in forward order, 30 tensors each, in this exact order:
3268 sm2 (Linear8, 3), ln1 (LayerNorm, 2), sm3 (Linear8, 3), ln2 (LayerNorm, 2),
3269 q / k / v / out_proj (Linear8, 3 each — bias synthesised),
3270 norm1 (RmsNorm, 1), linear1 (Linear8, 3), linear2 (Linear8, 3),
3271 norm2 (RmsNorm, 1).
3272 248. transformer.norm (LayerNorm, 2).
3273 250. proj_sq_from (Linear8, 3 — bias synthesised).
3274 253. proj_sq_to (Linear8, 3 — bias synthesised).
3275 256. promo_bias_proj (Linear8, 3 — bias synthesised). Last.
3276
3277 Totals: 259 tensors in 104 layers, 69 of them int8 convolutions. Everything else — the
3278 norms, the biases and the two elo tables — stays fp16, and is 1% of the parameters.
3279
3280 # The two structural rewrites
3281
3282 * **The fused `in_proj_weight` is split.** Torch packs q, k and v into one `[768, 256]`
3283 tensor, in that order (`_in_projection_packed` chunks it three ways). Three separate
3284 `[256, 256, 1, 1]` kernels come out, each with a synthesised zero bias because
3285 `omit_qkv_biases=True` and `Builder::conv` always reads one.
3286
3287 * **`smolgen_shared_weight` is replicated eight times.** Upstream expands the bias
3288 generator's `[8, 64]` output with `einsum("bhi,oi->bho")` against a `[4096, 64]`
3289 weight. This runtime has no transpose op, so `nets::maia` expresses that as a
3290 **grouped 1x1 convolution** with `group = 8` — and a grouped convolution's kernel is
3291 `[out, in/group, 1, 1]`, which here is `[32768, 64, 1, 1]`: group `g`'s 4096 output
3292 rows must each hold the same `[4096, 64]` weight. `np.tile` along axis 0 puts them in
3293 exactly the order group `g` reads.
3294
3295 It costs +1.84M elements, and at int8 that is +1.8 MB and 30% of the file. It is
3296 replicated **once, not per block**: the parameter is shared, so all eight blocks pass
3297 tensor 5 as their `weight_index` and the file holds one copy of the replication.
3298
3299 The quantisation is done on the `[4096, 64]` original and then tiled, not the other way
3300 round: the two give identical codes because the replicated rows are identical, but
3301 quantising 262,144 elements instead of 2,097,152 also makes the fidelity line report the
3302 tensor the checkpoint actually holds.
3303
3304 # int8, and why not int4
3305
3306 Every convolution here is int8, quantised per output channel; the norms, the biases and the
3307 two elo tables stay fp16. 13.3 MiB to 6.8 MiB, with the worst per-tensor cosine at
3308 0.999941 against a 0.999 gate.
3309
3310 `scripts/ml/maia_quant_eval.py` is what justifies that, on move agreement rather than on
3311 cosine: over 400 positions at each shipping rating the int8 model picks a different move
3312 0.5% to 1.0% of the time, always where the top two legal moves are within 0.017 — inside
3313 what fp16 rounding does on its own. The same harness rejects int4 at 87% to 91% agreement
3314 with 14 to 29 genuine changes of mind, at any group size.
3315
3316 # What is folded, and what is not
3317
3318 * The attention query scale is **not** folded into the q kernel. Torch scales the query
3319 by `head_dim ** -0.5` and `head_dim` is 32, which is the `1 / sqrt(head_dim)`
3320 `attn_scores` already applies. Folding it would apply it twice.
3321 * The policy head's `1 / sqrt(head_hid_dim)` is not folded either, for the same reason:
3322 `head_hid_dim` is 256 and `attn_scores(from, to, 1)` derives `1 / sqrt(256)` itself.
3323 * `promo_bias_proj`'s `* sqrt(head_hid_dim)` is **not** folded into the kernel. It is
3324 applied by `post::maia` on the host, where the score it is added to has already been
3325 divided by the same factor — folding one of the pair and not the other is the easy
3326 mistake, so neither is folded.
3327 * The elo interpolation is not folded: the two embeddings are emitted raw and blended
3328 on the host by `nets::maia::elo_embedding`, because the blend weight is an input.
3329 """
3330 layers = []
3331 tensors = []
3332 fidelity = Fidelity()
3333
3334 def emit(op, name, key, added):
3335 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
3336
3337 def linear(name, weight=None, bias=None):
3338 """An int8 kernel as `[out, in, 1, 1]`, its per-output-channel scale, and its bias."""
3339 weight = get(f"{name}.weight") if weight is None else weight
3340 outputs, inputs = weight.shape
3341 synthesised = bias is None
3342 if synthesised:
3343 bias = np.zeros(outputs, dtype=np.float32)
3344 kernel, scale = fidelity.quantise(name, weight.reshape(outputs, inputs, 1, 1))
3345 tensors.extend([kernel, scale, bias])
3346 note = " b0=synthesised" if synthesised else ""
3347 emit(
3348 "Linear8",
3349 name,
3350 f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={[outputs]} "
3351 f"zp=0 dtype=int8{note}",
3352 3,
3353 )
3354
3355 def layer_norm(name):
3356 gamma = get(f"{name}.weight")
3357 beta = get(f"{name}.bias")
3358 tensors.extend([gamma, beta])
3359 emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)
3360
3361 def rms_norm(name):
3362 """An RMS norm's gain. One tensor: there is no beta to follow it."""
3363 gamma = get(f"{name}.weight")
3364 tensors.append(gamma)
3365 emit("RmsNorm", name, f"RmsNorm g={list(gamma.shape)}", 1)
3366
3367 d, heads = spec["d_model"], spec["heads"]
3368 gen, squares = spec["bias_gen"], spec["squares"]
3369
3370 for name in ("elo_embedding_low.weight", "elo_embedding_high.weight"):
3371 table = get(name)
3372 tensors.append(table)
3373 emit("Host", name, f"Host t={list(table.shape)}", 1)
3374
3375 linear("token_projection", bias=get("token_projection.bias"))
3376
3377 shared = get("smolgen_shared_weight")
3378 if list(shared.shape) != [squares * squares, gen]:
3379 raise SystemExit(f"smolgen_shared_weight is {list(shared.shape)}, not {[squares*squares, gen]}")
3380 # Quantise the original, then tile the codes and the scale. Tiling first would quantise
3381 # 2,097,152 identical-by-construction rows to reach the same answer, and would report the
3382 # fidelity of a tensor the checkpoint does not hold.
3383 codes, scale = fidelity.quantise("smolgen_shared_weight", shared.reshape(*shared.shape, 1, 1))
3384 replicated = np.tile(codes.reshape(squares * squares, gen), (heads, 1)).reshape(
3385 heads * squares * squares, gen, 1, 1
3386 )
3387 scales = np.tile(scale, heads)
3388 rows = replicated.shape[0]
3389 tensors.extend([replicated, scales, np.zeros(rows, dtype=np.float32)])
3390 emit(
3391 "Smolgen8",
3392 "smolgen_shared_weight",
3393 f"Smolgen8 w={list(replicated.shape)} scale={[rows]} b={[rows]} group={heads} "
3394 f"from={list(shared.shape)} zp=0 dtype=int8 b0=synthesised",
3395 3,
3396 )
3397
3398 for index in range(spec["blocks"]):
3399 at = f"transformer.layers.{index}"
3400 # The bias generator, then attention, then the feed-forward — the order
3401 # `nets::maia::encoder_block` walks, so the Rust needs no index table.
3402 linear(f"{at}.self_attn.sm2", bias=get(f"{at}.self_attn.sm2.bias"))
3403 layer_norm(f"{at}.self_attn.ln1")
3404 linear(f"{at}.self_attn.sm3", bias=get(f"{at}.self_attn.sm3.bias"))
3405 layer_norm(f"{at}.self_attn.ln2")
3406
3407 fused = get(f"{at}.self_attn.mha.in_proj_weight")
3408 if list(fused.shape) != [3 * d, d]:
3409 raise SystemExit(f"{at} in_proj_weight is {list(fused.shape)}, not {[3 * d, d]}")
3410 for part, projection in enumerate(("q_proj", "k_proj", "v_proj")):
3411 linear(f"{at}.self_attn.{projection}", weight=fused[part * d : (part + 1) * d])
3412 linear(f"{at}.self_attn.mha.out_proj")
3413
3414 # Post-norm: `norm1` closes the attention residual and `norm2` the feed-forward's,
3415 # so both come after the sublayer they normalise rather than before it.
3416 rms_norm(f"{at}.norm1")
3417 linear(f"{at}.linear1", bias=get(f"{at}.linear1.bias"))
3418 linear(f"{at}.linear2", bias=get(f"{at}.linear2.bias"))
3419 rms_norm(f"{at}.norm2")
3420
3421 layer_norm("transformer.norm")
3422 linear("proj_sq_from")
3423 linear("proj_sq_to")
3424 linear("promo_bias_proj")
3425
3426 fidelity.report()
3427 return layers, tensors
3428
3429
3430def madlad_inventory(spec):
3431 """`{name: shape}` MADLAD400-3B-MT's checkpoint must hold exactly.
3432
3433 Derived rather than transcribed: a list of ~580 names would be checked against itself.
3434
3435 The names are transformers' `T5ForConditionalGeneration` state-dict names
3436 (`T5LayerSelfAttention.SelfAttention.q`, `T5LayerFF.DenseReluDense.wi_0`, ...).
3437 Three absences are as load-bearing as the presences, so all three are stated by
3438 *not* appearing:
3439
3440 * **No projection biases.** Every `q/k/v/o` and `wi_0/wi_1/wo` is `bias=False`
3441 (all 192 attentions, all 64 feed-forwards). A checkpoint that grew one would
3442 have unexpected names and fail, rather than being read as this table with the
3443 bias ignored.
3444 * **No `layer_norm.bias`.** They are `T5LayerNorm` (RMSNorm), which has a gain
3445 and nothing else. A checkpoint that grew either would be a layer norm, and the
3446 Rust would silently ignore the beta.
3447 * **No relative tables past block 0.** Only the two block-0 self-attentions hold
3448 `relative_attention_bias.weight` (`has_relative_attention_bias=bool(i == 0)`);
3449 deeper layers reuse the computed bias. A checkpoint that grew more would be a
3450 different forward pass.
3451
3452 The input table is `decoder.embed_tokens.weight`, not `shared.weight`: T5's
3453 `_tie_or_clone_weights` clones shared into the decoder embeddings at load, and
3454 this export materialised only that clone. `lm_head.weight` is the separate
3455 logits kernel, and the two differ (checked by `fetch_madlad400.check_untied`).
3456
3457 The shapes are `torch.nn.Linear`'s **`[out, in]`**, so a kernel is a reshape and
3458 not a transpose; `wi_0 [8192, 1024]` against `wo [1024, 8192]` is the asymmetric
3459 set that makes a transposed checkpoint fail here rather than on the device.
3460 """
3461 d, ffn = spec["d_model"], spec["d_ff"]
3462 inner = spec["heads"] * spec["head_dim"]
3463 want = {
3464 "decoder.embed_tokens.weight": [spec["vocab"], d],
3465 "lm_head.weight": [spec["vocab"], d],
3466 }
3467 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
3468 for index in range(count):
3469 at = f"{side}.block.{index}"
3470 attentions = ["SelfAttention"] + (["EncDecAttention"] if side == "decoder" else [])
3471 for layer, attention in enumerate(attentions):
3472 want[f"{at}.layer.{layer}.{attention}.q.weight"] = [inner, d]
3473 want[f"{at}.layer.{layer}.{attention}.k.weight"] = [inner, d]
3474 want[f"{at}.layer.{layer}.{attention}.v.weight"] = [inner, d]
3475 want[f"{at}.layer.{layer}.{attention}.o.weight"] = [d, inner]
3476 want[f"{at}.layer.{layer}.layer_norm.weight"] = [d]
3477 if index == 0:
3478 want[f"{at}.layer.0.SelfAttention.relative_attention_bias.weight"] = [
3479 spec["buckets"],
3480 spec["heads"],
3481 ]
3482 ff = len(attentions)
3483 want[f"{at}.layer.{ff}.DenseReluDense.wi_0.weight"] = [ffn, d]
3484 want[f"{at}.layer.{ff}.DenseReluDense.wi_1.weight"] = [ffn, d]
3485 want[f"{at}.layer.{ff}.DenseReluDense.wo.weight"] = [d, ffn]
3486 want[f"{at}.layer.{ff}.layer_norm.weight"] = [d]
3487 want[f"{side}.final_layer_norm.weight"] = [d]
3488 return want
3489
3490
3491def collect_madlad(get, spec):
3492 """MADLAD400-3B-MT's checkpoint as the ordered tensor table `nets::madlad` indexes.
3493
3494 THE TENSOR ORDER (the contract with the Rust net — positional indexing, no names):
3495
3496 1. the input table (`decoder.embed_tokens.weight` ONLY), as `head_splits`
3497 disjoint class ranges: [0:64000], [64000:128000], [128000:192000],
3498 Each range emits 3 tensors: int8 kernel [rows, 1024, 1, 1], fp16 scale
3499 [rows], synthesised zero bias [rows]. Op "Head". Tensors 0..11.
3500 2. the logits kernel (`lm_head.weight` ONLY), same four ranges. Op "Head".
3501 Tensors 12..23.
3502 3. each encoder layer 0..31 in forward order. Per layer, in this exact order:
3503 self norm (RmsNorm, 1 tensor: gamma),
3504 self q/k/v/o (Linear8, 3 tensors each: kernel, scale, synthesised bias),
3505 ff norm (RmsNorm, 1),
3506 fused wi_01 (Linear8, 3: `[2 * d_ff, d_model, 1, 1]` kernel over
3507 `[wi_0 rows | wi_1 rows]`, scale, synthesised bias), wo (Linear8, 3).
3508 20 tensors per encoder layer.
3509 4. the encoder's final norm (RmsNorm, 1 tensor).
3510 5. each decoder layer 0..31 in forward order. Per layer: self block as in
3511 the encoder (1 + 4*3 = 13 tensors), then cross norm (1) +
3512 cross q/k/v/o (4*3 = 12), then ff norm (1) + fused wi_01/wo (2*3 = 6).
3513 33 tensors per decoder layer.
3514 6. the decoder's final norm (RmsNorm, 1 tensor).
3515 7. the two block-0 relative tables, fp16 verbatim for the host to read:
3516 encoder self `[32, 16]`, decoder self `[32, 16]`. Op "Relative". Last.
3517
3518 Totals: 24 head tensors + 32*20 encoder + 1 + 32*33 decoder + 1 + 2 tables =
3519 1724 tensors in 684 layers (8 Head + 256 enc + 1 + 416 dec + 1 + 2 Relative).
3520 488 int8 convolutions (8 head + 32*6 enc + 32*9 dec); everything else fp16
3521 norms, biases and the two tables.
3522
3523 # What is folded, and what is not
3524
3525 * `sqrt(d_model)` is **not** folded into the embedding — T5 has no embedding
3526 scale at all (no `scale_embedding`). The host gather dequantises the row.
3527 * The attention query scale is **not** folded into `q`. T5 applies none (Mesh
3528 TensorFlow init), and `attn_scores_prescaled` applies exactly 1.0.
3529 * The relative bias is **not** folded into any projection. It is position-
3530 dependent, so it cannot be; the host computes it per shape and hands it in
3531 as a plan input the net adds with a plain `Add`.
3532 * `wi_0` and `wi_1` **are** fused into one `[16384, 1024]` projection. GEGLU
3533 needs `GELU(wi_0(x)) * wi_1(x)`, and `GatedActivate` reads a fused
3534 `[gate | up]` tensor — so the converter concatenates the rows and the Rust
3535 emits one convolution instead of two plus a slice pair.
3536 * FFN activation is **gated-gelu** (`feed_forward_proj: gated-gelu`), so the
3537 Rust uses `Act::Gelu` on the fused projection. T5's is the sigmoid
3538 approximation and the shader is exact-erf; the difference is below fp16
3539 resolution (see `nets::madlad`).
3540 * The two untied tables are each emitted whole-range: `fetch_madlad400.py`
3541 asserts they differ before conversion, so emitting both is exact.
3542 """
3543 layers = []
3544 tensors = []
3545 fidelity = Fidelity()
3546
3547 def emit(op, name, key, added):
3548 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
3549
3550 def linear(name, weight=None):
3551 """An int8 kernel as `[out, in, 1, 1]`, its per-output-channel scale, and a bias.
3552
3553 T5 carries no projection biases, so the bias is always synthesised zeros —
3554 recorded in the key so a checkpoint that grows one is not mistaken for
3555 this table.
3556 """
3557 weight = get(f"{name}.weight") if weight is None else weight
3558 outputs, inputs = weight.shape
3559 kernel, scale = fidelity.quantise(name, weight.reshape(outputs, inputs, 1, 1))
3560 tensors.extend([kernel, scale, np.zeros(outputs, dtype=np.float32)])
3561 emit(
3562 "Linear8",
3563 name,
3564 f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={[outputs]} "
3565 "zp=0 dtype=int8 b0=synthesised",
3566 3,
3567 )
3568
3569 def rms_norm(name):
3570 """An RMS norm's gain. One tensor: there is no beta to follow it."""
3571 gamma = get(f"{name}.weight")
3572 tensors.append(gamma)
3573 emit("RmsNorm", name, f"RmsNorm g={list(gamma.shape)}", 1)
3574
3575 def head(table, rows_spec):
3576 embedding = get(f"{table}.weight")
3577 if sum(rows_spec) != embedding.shape[0]:
3578 raise SystemExit(f"{embedding.shape[0]} classes do not split as {rows_spec}")
3579 lo = 0
3580 for rows in rows_spec:
3581 chunk = embedding[lo : lo + rows]
3582 name = f"{table}.weight[{lo}:{lo + rows}]"
3583 kernel, scale = fidelity.quantise(
3584 name, chunk.reshape(rows, embedding.shape[1], 1, 1)
3585 )
3586 # `Builder::conv_int8` reads a bias after the scale, and an embedding
3587 # table has none. Zeros are exact, and recording it in the key means a
3588 # checkpoint that grows one is not mistaken for this table.
3589 tensors.extend([kernel, scale, np.zeros(rows, dtype=np.float32)])
3590 emit(
3591 "Head",
3592 name,
3593 f"Head w={list(kernel.shape)} scale={[rows]} b={[rows]} "
3594 f"classes={lo}..{lo + rows} zp=0 dtype=int8 b0=synthesised",
3595 3,
3596 )
3597 lo += rows
3598
3599 d, ffn = spec["d_model"], spec["d_ff"]
3600 rows_spec = spec["head_rows"]
3601 head("decoder.embed_tokens", rows_spec)
3602 head("lm_head", rows_spec)
3603
3604 for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):
3605 for index in range(count):
3606 at = f"{side}.block.{index}"
3607 # Pre-norm, as `T5Block` is: the norm comes before the sublayer it feeds
3608 # and the residual skips both. Emitting in forward order is what lets the
3609 # Rust walk the table without an index table.
3610 attentions = ["SelfAttention"] + (["EncDecAttention"] if side == "decoder" else [])
3611 for layer, attention in enumerate(attentions):
3612 rms_norm(f"{at}.layer.{layer}.layer_norm")
3613 for projection in ("q", "k", "v", "o"):
3614 linear(f"{at}.layer.{layer}.{attention}.{projection}")
3615 ff = len(attentions)
3616 rms_norm(f"{at}.layer.{ff}.layer_norm")
3617 wi_0 = get(f"{at}.layer.{ff}.DenseReluDense.wi_0.weight")
3618 wi_1 = get(f"{at}.layer.{ff}.DenseReluDense.wi_1.weight")
3619 if list(wi_0.shape) != [ffn, d] or list(wi_1.shape) != [ffn, d]:
3620 raise SystemExit(
3621 f"{at} wi_0 {list(wi_0.shape)} wi_1 {list(wi_1.shape)}, not "
3622 f"[{ffn}, {d}] each"
3623 )
3624 # Fused `[gate | up]`, the layout `GatedActivate` halves. Quantise the
3625 # concatenation (identical rows quantise identically either way) so the
3626 # fidelity line reports the tensor the file actually holds.
3627 fused = np.concatenate([wi_0, wi_1], axis=0)
3628 linear(f"{at}.layer.{ff}.DenseReluDense.wi_01", weight=fused)
3629 linear(f"{at}.layer.{ff}.DenseReluDense.wo")
3630 rms_norm(f"{side}.final_layer_norm")
3631
3632 for side in ("encoder", "decoder"):
3633 table = get(f"{side}.block.0.layer.0.SelfAttention.relative_attention_bias.weight")
3634 if list(table.shape) != [spec["buckets"], spec["heads"]]:
3635 raise SystemExit(
3636 f"{side} block-0 relative table is {list(table.shape)}, not "
3637 f"[{spec['buckets']}, {spec['heads']}]"
3638 )
3639 tensors.append(np.ascontiguousarray(table, dtype=np.float32))
3640 emit(
3641 "Relative",
3642 f"{side}.block.0.relative_attention_bias",
3643 f"Relative t={list(table.shape)} host-read fp16",
3644 1,
3645 )
3646
3647 fidelity.report()
3648 return layers, tensors
3649
3650
3651def q2k_to_float(payload, gguf_shape, torch_shape):
3652 """GGUF Q2_K payload dequantised to fp32 in torch `torch_shape` row order.
3653
3654 Exact transcription of candle's `BlockQ2K::to_float` (k_quants.rs:1016), composed
3655 with candle's GGUF dim reversal. The physical bytes are the torch matrix in
3656 row-major FLAT order: `torch_flat = gguf_flat`, reshaped to `torch_shape`. The
3657 per-block loop below dequantises physical row by row into the flat order; the
3658 reshape to torch rows happens once at the end.
3659
3660 (Two earlier revisions failed: (1) scattering each block's 256 taps across 256 torch
3661 rows — passed every byte-level check, cosine ~0.0 vs fp32; (2) physical-row-is-torch-row
3662 — row counts differ (1024 vs 2048), impossible. The flat-reshape rule was derived from
3663 candle's shape reversal + `matmul_t` layout and verified at cosine 0.96 on q row 0.)
3664
3665 Per 16-elem lane: `y = dl*(q) - ml`, `dl = d*(sc&0xF)`, `ml = dmin*(sc>>4)`
3666 (superblock `d`/`dmin` straight, NO extra product — `to_float` has no activation
3667 scale to fold, unlike `vec_dot`'s `dall = y.d*x.d`). `q` 2 bits at shift 0/2/4/6
3668 cycling per 32-elem half; halves read separate 32-byte `qs` chunks (`qs[0:32]` then
3669 `qs[32:64]`), `is` stepping by 2 per lane-pair across the whole block. `d`/`dmin`
3670 are fp16.
3671
3672 All GGUF shapes here divide evenly by 256 — a remainder fails loudly in `open_gguf`'s
3673 size computation rather than silently misaligning here.
3674 """
3675 import numpy as _np
3676
3677 gguf_rows, gguf_cols = gguf_shape
3678 n_blocks = gguf_cols // Q2K_BLOCK
3679 # Physical row i holds gguf_cols taps = n_blocks superblocks of 84 bytes.
3680 raw = _np.frombuffer(payload, dtype=_np.uint8).reshape(gguf_rows, n_blocks * Q2K_BYTES)
3681 flat = _np.empty((gguf_rows * gguf_cols,), dtype=_np.float32)
3682 for i in range(gguf_rows):
3683 at = 0
3684 for k in range(n_blocks):
3685 block = raw[i, at : at + Q2K_BYTES]
3686 at += Q2K_BYTES
3687 scales = block[:16]
3688 qs = block[16:80]
3689 d = _np.frombuffer(block[80:82].tobytes(), dtype=_np.float16)[0].astype(_np.float32)
3690 dmin = _np.frombuffer(block[82:84].tobytes(), dtype=_np.float16)[0].astype(_np.float32)
3691 is_ = 0
3692 # 256 taps = 2 halves of 128 (`y_chunks` zipped with 32-byte `qs_chunks`); each
3693 # half consumes 8 scale bytes in 4 lane-pairs. Lane-pair `j` at shift 2*j: the
3694 # even scale covers 16 taps from the half-chunk's `qs[..16]`, the odd scale 16
3695 # taps from `qs[16..]` — both at the SAME shift. Half 1 reads qs[32:64], NOT
3696 # qs[0:32]: the halves are separate 32-byte chunks.
3697 base = (i * n_blocks + k) * Q2K_BLOCK
3698 for half in range(2):
3699 hqs = qs[half * 32 : half * 32 + 32]
3700 shift = 0
3701 for lane in range(4):
3702 sc = scales[is_]
3703 is_ += 1
3704 lo, hi = sc & 0xF, sc >> 4
3705 for l in range(16):
3706 q = (int(hqs[l]) >> shift) & 3
3707 flat[base + half * 128 + lane * 32 + l] = d * (q * lo) - dmin * hi
3708 sc = scales[is_]
3709 is_ += 1
3710 lo, hi = sc & 0xF, sc >> 4
3711 for l in range(16):
3712 q = (int(hqs[16 + l]) >> shift) & 3
3713 flat[base + half * 128 + lane * 32 + 16 + l] = (
3714 d * (q * lo) - dmin * hi
3715 )
3716 shift += 2
3717 rows, taps = torch_shape
3718 if rows * taps != gguf_rows * gguf_cols:
3719 raise SystemExit(f"torch shape {torch_shape} does not tile GGUF shape {gguf_shape}")
3720 return flat.reshape(rows, taps)
3721
3722
3723INVENTORIES.update({"small100": small100_inventory, "whisper": whisper_inventory})
3724COLLECTORS.update({"small100": collect_small100, "whisper": collect_whisper})
3725INVENTORIES.update({"nllb600": nllb_inventory})
3726COLLECTORS.update({"nllb600": collect_nllb})
3727INVENTORIES.update({"maia": maia_inventory})
3728COLLECTORS.update({"maia": collect_maia})
3729INVENTORIES.update({"madlad400": madlad_inventory})
3730COLLECTORS.update({"madlad400": collect_madlad})
3731
3732
3733# The vision position table, after TinyCLIP's export constant-folds it: `position_ids` is a
3734# constant, so the `Gather` that reads the table folds away and its `[1, 197, 256]` result is the
3735# initializer. There is no `vision_model.embeddings.position_embedding.weight` to read.
3736#
3737# Named here because it is the one parameter whose key is an internal tensor name rather than a
3738# module path, and both [`tinyclip_inventory`] and [`collect_tinyclip`] have to agree about it.
3739VISION_POSITIONS_FOLDED = "/vision_model/embeddings/position_embedding/Gather_output_0"
3740
3741
3742def tinyclip_inventory(spec):
3743 """What TinyCLIP's export must hold, as two dicts keyed the two ways the graph names things.
3744
3745 Returned rather than transcribed: a list of 250 names would be checked against itself.
3746
3747 * `parameters` is `{initializer name: dims}` for everything the export names — the norms, the
3748 biases, the patch kernel, both embedding tables and the class token.
3749 * `projections` is `{MatMul node name: dims}` for the 80 anonymous weights. Keyed by node
3750 because the initializer names carry no information; see [`ARCHITECTURES`].
3751
3752 `dims` for a projection is ONNX's own **`[in, out]`**, so this dict is also the statement that
3753 catches a transposed read: `fc1` at `[256, 1024]` and `fc2` at `[1024, 256]` cannot both be
3754 satisfied by a checkpoint whose linears are stored the other way round.
3755 """
3756 width, ffn, projection = spec["width"], spec["ffn"], spec["projection"]
3757 parameters = {
3758 "vision_model.embeddings.patch_embedding.weight": [
3759 width, 3, spec["patch"], spec["patch"],
3760 ],
3761 "vision_model.embeddings.class_embedding": [width],
3762 VISION_POSITIONS_FOLDED: [1, spec["grid"] ** 2 + 1, width],
3763 "vision_model.pre_layrnorm.weight": [width],
3764 "vision_model.pre_layrnorm.bias": [width],
3765 "vision_model.post_layernorm.weight": [width],
3766 "vision_model.post_layernorm.bias": [width],
3767 "text_model.embeddings.token_embedding.weight": [spec["vocab"], width],
3768 "text_model.embeddings.position_embedding.weight": [spec["context"], width],
3769 "text_model.final_layer_norm.weight": [width],
3770 "text_model.final_layer_norm.bias": [width],
3771 }
3772 projections = {
3773 "/visual_projection/MatMul": [width, projection],
3774 "/text_projection/MatMul": [width, projection],
3775 }
3776 for tower, count in (("vision", spec["vision_layers"]), ("text", spec["text_layers"])):
3777 for index in range(count):
3778 at = f"{tower}_model.encoder.layers.{index}"
3779 node = f"/{tower}_model/encoder/layers.{index}"
3780 for norm in ("layer_norm1", "layer_norm2"):
3781 parameters[f"{at}.{norm}.weight"] = [width]
3782 parameters[f"{at}.{norm}.bias"] = [width]
3783 for name in ("q_proj", "k_proj", "v_proj", "out_proj"):
3784 parameters[f"{at}.self_attn.{name}.bias"] = [width]
3785 projections[f"{node}/self_attn/{name}/MatMul"] = [width, width]
3786 parameters[f"{at}.mlp.fc1.bias"] = [ffn]
3787 parameters[f"{at}.mlp.fc2.bias"] = [width]
3788 projections[f"{node}/mlp/fc1/MatMul"] = [width, ffn]
3789 projections[f"{node}/mlp/fc2/MatMul"] = [ffn, width]
3790 return parameters, projections
3791
3792
3793def gemma4_inventory(spec):
3794 """Every named parameter Gemma 4's decoder export must hold, derived from `spec`.
3795
3796 Derived, never transcribed as a list: a hand-written inventory of 900-odd tensors would be
3797 checked against the same file it was copied from. Building it from the constants means a
3798 disagreement between `config.json` and the export is what fails, which is the thing worth
3799 catching.
3800
3801 Returns `(parameters, projections)` to match [`tinyclip_inventory`]'s shape; Gemma's
3802 projections are all named initializers, so the second is empty.
3803 """
3804 d = spec["d_model"]
3805 heads, kv_heads = spec["heads"], spec["kv_heads"]
3806 per_layer = spec["per_layer"]
3807 want = {
3808 "lm_head.MatMul.weight": [d, spec["vocab"]],
3809 "model.per_layer_projection.MatMul.weight": [d, per_layer * spec["layers"]],
3810 "model.per_layer_projection_norm.weight": [per_layer],
3811 # The export files the final norm under a phantom 36th layer.
3812 "model.layers.35.final_norm_layernorm.weight": [d],
3813 # Cut to `max_context` by the collector; asserted here at their shipped length.
3814 "cos_cache_local": [131072, spec["head_dim"] // 2],
3815 "sin_cache_local": [131072, spec["head_dim"] // 2],
3816 "cos_cache_global": [131072, spec["global_head_dim"] // 2],
3817 "sin_cache_global": [131072, spec["global_head_dim"] // 2],
3818 }
3819 for index in range(spec["layers"]):
3820 at = f"model.layers.{index}"
3821 full = index % 5 == 4
3822 owns = index < spec["owns_cache_layers"]
3823 dim = spec["global_head_dim"] if full else spec["head_dim"]
3824 inner = spec["ffn"] if owns else spec["ffn_wide"]
3825 want[f"{at}.input_layernorm.weight"] = [d]
3826 want[f"{at}.attn.q_norm.layernorm.weight"] = [dim]
3827 want[f"{at}.attn.q_proj.MatMul.weight"] = [d, heads * dim]
3828 if owns:
3829 want[f"{at}.attn.k_norm.layernorm.weight"] = [dim]
3830 want[f"{at}.attn.k_proj.MatMul.weight"] = [d, kv_heads * dim]
3831 want[f"{at}.attn.v_proj.MatMul.weight"] = [d, kv_heads * dim]
3832 want[f"/model/layers.{index}/attn/v_norm/ones_weight"] = [dim]
3833 want[f"{at}.attn.o_proj.MatMul.weight"] = [heads * dim, d]
3834 want[f"{at}.post_attention_layernorm.weight"] = [d]
3835 want[f"{at}.pre_feedforward_layernorm.weight"] = [d]
3836 want[f"{at}.mlp.gate_up_proj.MatMul.weight"] = [d, inner * 2]
3837 want[f"{at}.mlp.down_proj.MatMul.weight"] = [inner, d]
3838 want[f"{at}.post_feedforward_layernorm.weight"] = [d]
3839 want[f"{at}.per_layer.per_layer_input_gate.MatMul.weight"] = [d, per_layer]
3840 want[f"{at}.per_layer.per_layer_projection.MatMul.weight"] = [per_layer, d]
3841 want[f"{at}.post_per_layer_input_norm.weight"] = [d]
3842 want[f"{at}.layer_scalar"] = [1]
3843 return want, {}
3844
3845
3846def gemma4_embed_inventory(spec):
3847 """The two tables `embed_tokens.onnx` holds, and nothing else that matters."""
3848 return {
3849 "model.embed_tokens.weight": [spec["vocab"], spec["d_model"]],
3850 "model.embed_tokens_per_layer.weight": [
3851 spec["vocab"],
3852 spec["per_layer"] * spec["layers"],
3853 ],
3854 }, {}
3855
3856
3857# Which inventory `check_architecture` asserts against, for the ONNX-by-name graphs. The
3858# checkpoint graphs register theirs beside their collectors above; this is the same registry.
3859INVENTORIES.update(
3860 {
3861 "tinyclip": tinyclip_inventory,
3862 "gemma4_text": gemma4_inventory,
3863 "gemma4_embed": gemma4_embed_inventory,
3864 # The vision export names every weight `_to_copy_104`, so there is no inventory to check
3865 # against. `collect_gemma4_vision` asserts the node *numbering* instead, which is the
3866 # only structure that export actually carries.
3867 "gemma4_vision": lambda spec: ({}, {}),
3868 # The audio export is anonymised the same way, with two named survivors that are worth
3869 # pinning because both mark a place the structure could move: the bias proves output_proj
3870 # is still the one biased linear the exporter splits, and the depthwise kernel proves the
3871 # conformer convolution is still full-width and five taps.
3872 "gemma4_audio": lambda spec: (
3873 {
3874 "audio_tower.output_proj.bias": [spec["out_dim"]],
3875 "audio_tower.layers.0.lconv1d.depthwise_conv1d.weight": [spec["d_model"], 1, 5],
3876 },
3877 {},
3878 ),
3879 }
3880)
3881
3882
3883def check_architecture(model, graph_id_name, spec):
3884 """Refuse an ONNX export that is not the architecture `nets/<graph>.rs` hardcodes.
3885
3886 The counterpart of [`check_checkpoint`], and the same argument: a wrong shape here is a wrong
3887 forward pass rather than a load failure, so it is asserted before anything is written. The op
3888 counts in [`EXPECTED_OPS`] are checked as well, by [`check_graph`] — this is the stricter of
3889 the two, because it fails on a renamed or resized parameter as well as on a missing one.
3890
3891 `spec` is passed rather than looked up, as [`collect_tinyclip`]'s is, so the two cannot be
3892 given different ones.
3893 """
3894 parameters, projections = INVENTORIES[graph_id_name](spec)
3895 inits = {i.name: list(i.dims) for i in model.graph.initializer}
3896 nodes = {n.name: n for n in model.graph.node}
3897
3898 lines = []
3899 for name, want in sorted(parameters.items()):
3900 got = inits.get(name)
3901 if got != want:
3902 lines.append(f" {name}: {got} against {want}")
3903 for node_name, want in sorted(projections.items()):
3904 node = nodes.get(node_name)
3905 if node is None:
3906 lines.append(f" {node_name}: no such node")
3907 continue
3908 held = [x for x in node.input if x in inits]
3909 if len(held) != 1 or inits[held[0]] != want:
3910 lines.append(f" {node_name}: {[inits.get(h) for h in held]} against {want}")
3911 if lines:
3912 raise SystemExit(
3913 f"{graph_id_name}: the export is not the architecture "
3914 f"nets/{graph_id_name}.rs\nhardcodes. A wrong shape here is a wrong forward pass, "
3915 "not a load failure:\n" + "\n".join(lines[:12])
3916 )
3917 print(
3918 f"{len(parameters)} named parameters and {len(projections)} projections match the "
3919 f"{graph_id_name} architecture"
3920 )
3921
3922
3923def collect_tinyclip(model, spec):
3924 """TinyCLIP's export as the ordered tensor table `nets::tinyclip` indexes.
3925
3926 Order is the contract, and it is forward order **per tower**, vision first:
3927
3928 the patch kernel, the class token, the vision positions, `pre_layrnorm`
3929 each vision layer, then `post_layernorm`, then `visual_projection`
3930 the token embedding, the text positions
3931 each text layer, then `final_layer_norm`, then `text_projection`
3932
3933 The export interleaves the two towers; this does not. See [`ARCHITECTURES`].
3934
3935 # What is transposed, and what is not
3936
3937 * A **`MatMul`** weight is `[in, out]` and becomes `[out, in, 1, 1]`, so every projection is
3938 the `1 x 1` convolution `Builder::conv_int8` already computes.
3939 * The **`Conv`** patch kernel is `[M, C, kH, kW]` already, which is this runtime's own layout,
3940 so it is emitted **verbatim**. The `[256, 3, 16, 16]` assertion in [`check_architecture`] is
3941 what says so; a transpose here would be a plausible-looking embedding.
3942 * The two **position tables** are `[positions, width]` and the vision one becomes
3943 `[width, 1, positions]`, because it is added to a sequence the device holds channel-major.
3944 The text one is **not** transposed: the host reads it, gathers the token rows and adds the
3945 two in f32, exactly as `nets::small100::embed_positions` does, so it never reaches a shader.
3946
3947 # What has no bias, and what gets a synthesised one
3948
3949 The patch embedding and both projections have none — `bias=False` on all three in
3950 `CLIPModel`. The shaders always add one, so each gets zeros, which is exact and is recorded in
3951 the digest key so an export that grows a bias is not read as this table.
3952 """
3953 width = spec["width"]
3954 inits = {i.name: i for i in model.graph.initializer}
3955 nodes = {n.name: n for n in model.graph.node}
3956 layers = []
3957 tensors = []
3958 fidelity = Fidelity()
3959
3960 def array(name):
3961 return numpy_helper.to_array(inits[name]).astype(np.float32)
3962
3963 def emit(op, name, key, added):
3964 layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))
3965
3966 def matmul_weight(node_name):
3967 """The `[in, out]` initializer a projection's `MatMul` reads, by **node** name."""
3968 held = [x for x in nodes[node_name].input if x in inits]
3969 return numpy_helper.to_array(inits[held[0]]).astype(np.float32)
3970
3971 def projection(node_name, name):
3972 """A `MatMul` as an int8 `[out, in, 1, 1]` kernel, its per-output scale and a zero bias."""
3973 weight = matmul_weight(node_name)
3974 inputs, outputs = weight.shape
3975 kernel, scale = fidelity.quantise(name, weight.T.reshape(outputs, inputs, 1, 1))
3976 tensors.extend([kernel, scale, np.zeros(outputs, dtype=np.float32)])
3977 emit(
3978 "Linear8",
3979 name,
3980 f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={[outputs]} "
3981 "zp=0 dtype=int8 b0=synthesised",
3982 3,
3983 )
3984
3985 def linear(node_name, bias_name, name):
3986 """[`projection`] with the export's own bias, which every layer projection has."""
3987 weight = matmul_weight(node_name)
3988 bias = array(bias_name)
3989 inputs, outputs = weight.shape
3990 kernel, scale = fidelity.quantise(name, weight.T.reshape(outputs, inputs, 1, 1))
3991 tensors.extend([kernel, scale, bias])
3992 emit(
3993 "Linear8",
3994 name,
3995 f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "
3996 "zp=0 dtype=int8",
3997 3,
3998 )
3999
4000 def layer_norm(name):
4001 gamma = array(f"{name}.weight")
4002 beta = array(f"{name}.bias")
4003 tensors.extend([gamma, beta])
4004 emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)
4005
4006 def constant(name, values):
4007 tensors.append(values)
4008 emit("Constant", name, f"Constant t={list(values.shape)}", 1)
4009
4010 def encoder_layer(tower, index):
4011 at = f"{tower}_model.encoder.layers.{index}"
4012 node = f"/{tower}_model/encoder/layers.{index}"
4013 # Pre-norm, as `CLIPEncoderLayer` is: the norm comes before the sublayer it feeds and the
4014 # residual skips both. Emitting in forward order is what lets the Rust walk the table.
4015 layer_norm(f"{at}.layer_norm1")
4016 for name in ("q_proj", "k_proj", "v_proj", "out_proj"):
4017 linear(
4018 f"{node}/self_attn/{name}/MatMul",
4019 f"{at}.self_attn.{name}.bias",
4020 f"{at}.self_attn.{name}",
4021 )
4022 layer_norm(f"{at}.layer_norm2")
4023 linear(f"{node}/mlp/fc1/MatMul", f"{at}.mlp.fc1.bias", f"{at}.mlp.fc1")
4024 linear(f"{node}/mlp/fc2/MatMul", f"{at}.mlp.fc2.bias", f"{at}.mlp.fc2")
4025
4026 # --- the vision tower ---
4027 patch = "vision_model.embeddings.patch_embedding.weight"
4028 kernel, scale = fidelity.quantise(patch, array(patch))
4029 tensors.extend([kernel, scale, np.zeros(width, dtype=np.float32)])
4030 emit(
4031 "Conv8",
4032 patch,
4033 f"Conv8 w={list(kernel.shape)} scale={[width]} b={[width]} "
4034 f"k={[spec['patch'], spec['patch']]} s={[spec['patch'], spec['patch']]} "
4035 "p=[0, 0, 0, 0] zp=0 dtype=int8 b0=synthesised",
4036 3,
4037 )
4038 # `[width]` as the `[width, 1, 1]` a `Kind::Constant` wants: one position, every channel.
4039 token = array("vision_model.embeddings.class_embedding").reshape(width, 1, 1)
4040 constant("vision_model.embeddings.class_embedding", token)
4041 positions = np.squeeze(array(VISION_POSITIONS_FOLDED))
4042 constant(VISION_POSITIONS_FOLDED, positions.T.reshape(width, 1, positions.shape[0]).copy())
4043 layer_norm("vision_model.pre_layrnorm")
4044 for index in range(spec["vision_layers"]):
4045 encoder_layer("vision", index)
4046 layer_norm("vision_model.post_layernorm")
4047 projection("/visual_projection/MatMul", "visual_projection")
4048
4049 # --- the text tower ---
4050 table = "text_model.embeddings.token_embedding.weight"
4051 rows = array(table)
4052 # Per **row**, which is per token: the host gathers one row and dequantises it by that row's
4053 # own scale, so this is the same shape of table `collect_small100`'s tied embedding is. The
4054 # export's own int8 file quantises it per *tensor* with a zero point of 226, which is neither
4055 # representable by `conv_int8.comp` nor recoverable by requantising.
4056 kernel, scale = fidelity.quantise(table, rows.reshape(rows.shape[0], rows.shape[1], 1, 1))
4057 tensors.extend([kernel, scale])
4058 emit(
4059 "Embed8",
4060 table,
4061 f"Embed8 t={list(kernel.shape)} scale={[rows.shape[0]]} zp=0 dtype=int8",
4062 2,
4063 )
4064 # Not transposed: the host reads this one. See the docstring.
4065 text_positions = array("text_model.embeddings.position_embedding.weight")
4066 constant("text_model.embeddings.position_embedding.weight", text_positions)
4067 for index in range(spec["text_layers"]):
4068 encoder_layer("text", index)
4069 layer_norm("text_model.final_layer_norm")
4070 projection("/text_projection/MatMul", "text_projection")
4071
4072 fidelity.report()
4073 return layers, tensors
4074
4075
4076def dequant_block_quantized(quant_t, scales_t, zp_t):
4077 """4-bit block-quantised `[rows, cols]` as fp32, low nibble first.
4078
4079 Shared by `MatMulNBits` linears (stored transposed `[N, K/block, 16]`,
4080 decoded to `[N, K]`) and `GatherBlockQuantized` position tables (stored
4081 flat `[rows, cols/2]`, decoded to `[rows, cols]`). The block count always
4082 comes from the scales table (`[rows, blocks]`), so both layouts meet here.
4083 Packing verified against onnxruntime's own MatMulNBits to 3.7e-3
4084 (analysis/prove_sign/).
4085 """
4086 dims = [int(d) for d in quant_t.dims]
4087 scales_dims = [int(d) for d in scales_t.dims]
4088 if len(scales_dims) != 2:
4089 raise SystemExit("block scales of rank " + str(len(scales_dims)))
4090 out_dim, per_col_blocks = scales_dims
4091 quant = numpy_helper.to_array(quant_t).reshape(-1)
4092 if len(dims) == 3:
4093 rows, _, bpb = dims
4094 assert rows == out_dim, (dims, scales_dims)
4095 block = bpb * 2
4096 raw = quant.reshape(out_dim, per_col_blocks, bpb)
4097 elif len(dims) == 2:
4098 rows, packed = dims
4099 assert rows == out_dim, (dims, scales_dims)
4100 raw = quant.reshape(out_dim, per_col_blocks, packed // per_col_blocks)
4101 block = (packed // per_col_blocks) * 2
4102 else:
4103 raise SystemExit("block-quantised tensor of rank " + str(len(dims)))
4104 in_dim = per_col_blocks * block
4105 scales = numpy_helper.to_array(scales_t).astype(np.float32)
4106 zp = numpy_helper.to_array(zp_t).reshape(-1).astype(np.uint8)
4107 vals = np.empty((out_dim, per_col_blocks, block), dtype=np.float32)
4108 vals[:, :, 0::2] = (raw & 0xF).astype(np.float32)
4109 vals[:, :, 1::2] = ((raw >> 4) & 0xF).astype(np.float32)
4110 zb = zp.reshape(out_dim, (per_col_blocks + 1) // 2)
4111 zf = np.empty((out_dim, per_col_blocks), dtype=np.float32)
4112 zf[:, 0::2] = (zb & 0xF).astype(np.float32)[:, : (per_col_blocks + 1) // 2]
4113 if per_col_blocks > 1:
4114 zf[:, 1::2] = ((zb >> 4) & 0xF).astype(np.float32)[:, : per_col_blocks // 2]
4115 if scales.shape != (out_dim, per_col_blocks):
4116 raise SystemExit(
4117 "scales " + str(list(scales.shape)) + ", not [" + str(out_dim) + ", " +
4118 str(per_col_blocks) + "]")
4119 return ((vals.reshape(out_dim, in_dim) - zf.repeat(block, axis=1)) *
4120 scales.repeat(block, axis=1))
4121
4122
4123def dequant_matmul_nbits(node, inits):
4124 """An ONNX `MatMulNBits` weight as fp32 `[K, N]`, matching a MatMul's `[in, out]`.
4125
4126 The quant tensor is stored TRANSPOSED as `[N, K/block, 16]` (verified: a
4127 K=768 N=3072 node holds `[3072, 24, 16]`), decoded to `[N, K]` natively and
4128 transposed back.
4129 """
4130 attrs = {a.name: a for a in node.attribute}
4131 bits = attrs["bits"].i if "bits" in attrs else 4
4132 if bits != 4:
4133 raise SystemExit(node.name + ": MatMulNBits with " + str(bits) + " bits, not 4")
4134 native = dequant_block_quantized(inits[node.input[1]], inits[node.input[2]],
4135 inits[node.input[3]])
4136 k = attrs["K"].i if "K" in attrs else native.shape[1]
4137 n = attrs["N"].i if "N" in attrs else native.shape[0]
4138 if native.shape != (n, k):
4139 raise SystemExit(node.name + ": decoded " + str(list(native.shape)) + ", not [" +
4140 str(n) + ", " + str(k) + "]")
4141 return native.T
4142
4143
4144def quantise_per_channel(kernel):
4145 """An fp32 kernel as `(int8, scale)`, symmetric and absmax, one scale per output channel.
4146
4147 Every int8 tensor in this tree goes through here. Nothing reads a pre-quantised export:
4148 Supertonic's are fp32, and SMaLL-100's only int8 export quantises per tensor, which throws
4149 away the resolution this recovers - see [`CHECKPOINTS`].
4150
4151 # Symmetric, with no zero point
4152
4153 `conv_int8.comp` and `conv_point_int8.comp` compute `scale[o] * sum(int8_w * in)`: there is
4154 nowhere for a zero point to go, and adding one would cost a second pass over the taps to
4155 subtract `zp * sum(in)`. So the scale is `absmax / 127` and 0 maps to 0, which is also what
4156 onnxruntime's dynamic quantiser was measured to emit for SMaLL-100 — every entry of every
4157 weight zero point in that export is 0.
4158
4159 127 rather than 128: the range is made symmetric by giving up the one extra negative code, so
4160 that `-absmax` and `+absmax` both round to a representable value. Using 128 would let a
4161 weight at exactly `+absmax` quantise to 128, which does not exist in int8.
4162
4163 # Per output channel, not per tensor
4164
4165 A row of the kernel is one output channel, and the scale multiplies that row's finished
4166 accumulator, so a scale per row costs nothing over a scalar — see `Builder::conv_int8`. It
4167 buys a great deal: a layer whose channels differ in range by 100x loses most of its
4168 resolution on the quiet ones under a single tensor-wide scale.
4169
4170 # An all-zero channel
4171
4172 Its absmax is 0, and `0 / 127` is a scale of 0, which is *correct* — every weight in the row
4173 is 0, so any scale reproduces it — but it is also a division by zero when computing the
4174 codes. Those rows are given a scale of 1 instead, which is exact for the same reason and is
4175 finite.
4176 """
4177 kernel = np.ascontiguousarray(kernel, dtype=np.float32)
4178 if kernel.ndim < 1:
4179 raise SystemExit(f"rank {kernel.ndim} kernel; quantisation needs an output axis")
4180 if not np.isfinite(kernel).all():
4181 raise SystemExit("a kernel holding a non-finite value cannot be quantised")
4182 rows = kernel.reshape(kernel.shape[0], -1)
4183 absmax = np.abs(rows).max(axis=1)
4184 scale = np.where(absmax > 0, absmax / 127.0, 1.0).astype(np.float32)
4185 # Round half away from zero, as `np.round` does not: it rounds half to even, which biases a
4186 # symmetric weight distribution towards the even codes.
4187 codes = np.floor(np.abs(rows) / scale[:, None] + 0.5) * np.sign(rows)
4188 quantised = np.clip(codes, -127, 127).astype(np.int8).reshape(kernel.shape)
4189 # The scale is stored as fp16 beside the weights, so the reconstruction the shader performs
4190 # uses the *rounded* scale. Rounding it here means the error reported below is the error the
4191 # device will have, not an optimistic one.
4192 scale = scale.astype(np.float16).astype(np.float32)
4193 # And the rounding itself can produce a zero, for a row whose absmax is small enough that
4194 # `absmax / 127` underflows fp16. A zero scale reconstructs the whole row as zero however
4195 # large its codes are, so the guard belongs **after** the round-trip, not before it. As in
4196 # `quantise_per_block`: such a row cannot be represented and is stored as zeros.
4197 scale = np.where(scale > 0, scale, 1.0)
4198 return quantised, scale
4199
4200
4201# Taps one int4 scale covers. Mirrors `weights::I4_BLOCK` and `I4_BLOCK` in `common.glsl`.
4202#
4203# 32 rather than 64: at 4.5 bits per weight against 4.25 the difference is 3% of a download, and
4204# `MIN_INT8_COSINE` is a strict gate that the wider block is the more likely to miss.
4205I4_BLOCK = 32
4206
4207# Stands in for an absent `Clip` bound: past fp16's largest finite value, so clamping to it is a
4208# no-op for any number the tower can hold, and it still round-trips through the fp16 table the
4209# bounds are stored in.
4210FP16_LIMIT = 65504.0
4211
4212
4213def quantise_per_block(kernel, block=I4_BLOCK):
4214 """An fp32 kernel as `(int4, scale)`, symmetric and absmax, one scale per block of taps.
4215
4216 # Why four bits need a finer scale than eight
4217
4218 `quantise_per_channel` gives a whole output row one scale, which works at eight bits because
4219 127 codes still resolve a row whose taps vary by an order of magnitude. Four bits have seven
4220 positive codes. Under one row-wide scale a row containing a single large tap quantises almost
4221 everything else to zero, so the scale is per block of `block` consecutive taps instead.
4222
4223 # The blocks run along the contraction axis
4224
4225 A row is flattened to `in * kh * kw` and cut into blocks of `block`, which is the axis the
4226 shader's inner loop walks - so a block is contiguous in memory and the shader reads one scale
4227 per block rather than gathering. The last block of a row is short whenever `taps` is not a
4228 multiple of `block`, and is scaled on what it actually holds.
4229
4230 # 7, not 8
4231
4232 As `quantise_per_channel` uses 127 rather than 128: the range is made symmetric by giving up
4233 the extra negative code, so `-absmax` and `+absmax` both land on a representable value.
4234 `int4_at` sign-extends, so the stored range is -8..7 and only -8 is unused.
4235
4236 Returns the codes shaped like `kernel` and a `(rows, blocks)` fp32 scale table, already
4237 rounded through fp16 so the error reported by the caller is the error the device will have.
4238 """
4239 kernel = np.ascontiguousarray(kernel, dtype=np.float32)
4240 if kernel.ndim < 1:
4241 raise SystemExit(f"rank {kernel.ndim} kernel; quantisation needs an output axis")
4242 if not np.isfinite(kernel).all():
4243 raise SystemExit("a kernel holding a non-finite value cannot be quantised")
4244 rows = kernel.reshape(kernel.shape[0], -1)
4245 count, taps = rows.shape
4246 blocks = (taps + block - 1) // block
4247 # Pad the tap axis so it divides into whole blocks. The padding is zero, which cannot raise a
4248 # block's absmax, so the last block's scale is decided by the real taps alone.
4249 padded = np.zeros((count, blocks * block), dtype=np.float32)
4250 padded[:, :taps] = rows
4251 grouped = padded.reshape(count, blocks, block)
4252 absmax = np.abs(grouped).max(axis=2)
4253 scale = np.where(absmax > 0, absmax / 7.0, 1.0).astype(np.float32)
4254 scale = scale.astype(np.float16).astype(np.float32)
4255 # A block whose absmax is small enough that `absmax / 7` underflows fp16 rounds to a scale of
4256 # **zero**, and then `0 / 0` is NaN and `NaN.astype(int8)` is undefined - a block of garbage
4257 # codes with nothing to show it. Such a block cannot be represented at all, so it is given a
4258 # scale of 1 and quantises to zeros, which is what the file would reconstruct anyway.
4259 scale = np.where(scale > 0, scale, 1.0)
4260 codes = np.floor(np.abs(grouped) / scale[:, :, None] + 0.5) * np.sign(grouped)
4261 codes = np.clip(codes, -7, 7).astype(np.int8)
4262 quantised = codes.reshape(count, blocks * block)[:, :taps].reshape(kernel.shape)
4263 return quantised, scale
4264
4265
4266def pack_int4(values):
4267 """Signed 4-bit codes as bytes, two per byte, **low nibble first**.
4268
4269 An odd length leaves the final high nibble as padding, which is what `Dtype::bytes`'s
4270 `div_ceil` accounts for on the reader's side. Writing `len // 2` bytes instead would produce
4271 a file that parses - the bounds check would pass - and whose last element read as whatever
4272 followed it.
4273 """
4274 flat = np.ascontiguousarray(values, dtype=np.int8).reshape(-1)
4275 if flat.size and (flat.min() < -8 or flat.max() > 7):
4276 raise SystemExit(f"int4 codes out of range: {flat.min()}..{flat.max()}")
4277 nibbles = (flat.astype(np.uint8) & 0x0F).astype(np.uint8)
4278 if nibbles.size % 2:
4279 nibbles = np.concatenate([nibbles, np.zeros(1, dtype=np.uint8)])
4280 pairs = nibbles.reshape(-1, 2)
4281 return (pairs[:, 0] | (pairs[:, 1] << 4)).astype(np.uint8).tobytes()
4282
4283
4284class Int4:
4285 """A tensor to serialise as [`DTYPE_I4`].
4286
4287 numpy has no four-bit dtype, so `build` cannot tell an int4 kernel from an int8 one by
4288 `tensor.dtype` the way it tells int8 from fp32. Wrapping it says so explicitly rather than
4289 inferring from a value range, which would misread an int8 kernel that happened to hold only
4290 small codes.
4291
4292 Quacks like an array for the three attributes `build` needs.
4293 """
4294
4295 def __init__(self, codes):
4296 self.codes = np.ascontiguousarray(codes, dtype=np.int8)
4297 self.shape = self.codes.shape
4298 self.ndim = self.codes.ndim
4299 self.size = self.codes.size
4300
4301
4302class Raw:
4303 """A tensor copied verbatim from another `.maml`: its table entry's dtype, shape and element
4304 count plus its payload bytes, so a re-packed file is bit-identical to its source."""
4305
4306 def __init__(self, dtype, shape, size, payload):
4307 self.dtype_code = dtype
4308 self.shape = tuple(shape)
4309 self.ndim = len(self.shape)
4310 self.size = size
4311 self.payload = payload
4312
4313
4314def payload_bytes(dtype, size):
4315 """Payload length of a tensor of `size` elements stored as `dtype` (mirrors `Dtype::bytes`)."""
4316 if dtype == DTYPE_F16:
4317 return size * 2
4318 if dtype == DTYPE_I8:
4319 return size
4320 if dtype == DTYPE_I4:
4321 return (size + 1) // 2
4322 if dtype == DTYPE_Q2K:
4323 return (size + Q2K_BLOCK - 1) // Q2K_BLOCK * Q2K_BYTES
4324 raise SystemExit(f"unknown dtype {dtype}")
4325
4326
4327def build(layers, tensors, graph_id, onnx_sha256):
4328 """Serialise the tensor table and the data section.
4329
4330 A tensor is fp16 unless it arrives as `int8` (bytes go through unchanged as
4331 [`DTYPE_I8`]) or as [`Int4`]/[`Q2K`] (packed/verbatim payloads as [`DTYPE_I4`]/
4332 [`DTYPE_Q2K`]). A quantised kernel's scale is a separate fp16 tensor that the
4333 caller has already placed after it.
4334 """
4335 table = bytearray()
4336 data = bytearray()
4337 for tensor in tensors:
4338 if tensor.ndim < 1 or tensor.ndim > 4:
4339 raise SystemExit(f"rank {tensor.ndim} tensor; the table holds 1..4")
4340 while len(data) % ALIGNMENT:
4341 data.append(0)
4342 offset = len(data)
4343 if isinstance(tensor, Raw):
4344 dtype = tensor.dtype_code
4345 if len(tensor.payload) != payload_bytes(dtype, tensor.size):
4346 raise SystemExit(f"a raw payload of {len(tensor.payload)} bytes for {tensor.size} taps")
4347 data.extend(tensor.payload)
4348 elif isinstance(tensor, Int4):
4349 dtype = DTYPE_I4
4350 data.extend(pack_int4(tensor.codes))
4351 elif isinstance(tensor, Q2K):
4352 # Verbatim superblocks: 84 bytes per 256 taps. The reader's `Dtype::bytes`
4353 # must agree on `len.div_ceil(256) * 84` or the last block reads neighbour
4354 # bytes at the right shape.
4355 dtype = DTYPE_Q2K
4356 payload = bytes(tensor.blocks)
4357 expect = tensor.size // Q2K_BLOCK * Q2K_BYTES
4358 if len(payload) != expect:
4359 raise SystemExit(
4360 f"a Q2_K payload of {len(payload)} bytes for {tensor.size} taps, "
4361 f"not {expect}"
4362 )
4363 data.extend(payload)
4364 elif tensor.dtype == np.int8:
4365 # Already quantised, so nothing to round: the bytes are the payload.
4366 dtype = DTYPE_I8
4367 data.extend(tensor.tobytes())
4368 else:
4369 dtype = DTYPE_F16
4370 half = np.ascontiguousarray(tensor, dtype=np.float32).astype(np.float16)
4371 if not np.isfinite(half).all():
4372 raise SystemExit(
4373 f"a weight of shape {list(tensor.shape)} overflows fp16. "
4374 "Storing this net at half precision needs per-tensor scaling."
4375 )
4376 data.extend(half.tobytes())
4377 dims = list(tensor.shape) + [0] * (4 - tensor.ndim)
4378 table.extend(struct.pack("<I", tensor.ndim))
4379 table.extend(struct.pack("<4I", *dims))
4380 table.extend(struct.pack("<III", dtype, offset, tensor.size))
4381 assert len(table) == len(tensors) * TENSOR_ENTRY_BYTES
4382
4383 data_offset = HEADER_BYTES + len(table)
4384 header = bytearray()
4385 header.extend(MAGIC)
4386 header.extend(struct.pack("<III", FORMAT_VERSION, graph_id, len(tensors)))
4387 header.extend(onnx_sha256)
4388 header.extend(struct.pack("<II", data_offset, len(data)))
4389 header.extend(b"\0" * 8)
4390 assert len(header) == HEADER_BYTES
4391
4392 return bytes(header) + bytes(table) + bytes(data), len(layers)
4393
4394
4395# --- TFLite --------------------------------------------------------------------
4396#
4397# A third input kind, after ONNX graphs and the PyTorch checkpoints in [`CHECKPOINTS`].
4398#
4399# The Now Playing models ship as TFLite flatbuffers and there is no ONNX export of them to
4400# convert through: they were recovered from an APK, and the only route to ONNX would be a
4401# TFLite -> ONNX converter whose op coverage would have to be trusted for the custom
4402# `CIRCULAR_BUFFER` and depthwise-with-multiplier layers this graph is mostly made of. Reading
4403# the flatbuffer here is both shorter and the version whose tensor order can be read off the
4404# file, which is the only thing the Rust actually depends on.
4405#
4406# Two differences from the ONNX path worth knowing:
4407#
4408# * A TFLite kernel is `[out, kh, kw, in]` and this runtime wants `[out, in / group, kh, kw]`,
4409# so unlike the ONNX path there **is** a transpose here. It is per layer kind, in
4410# [`collect_tflite`], and `nets::nnfp`'s `the_layer_table_matches_the_tflite_export` is the
4411# assertion on the other side of it.
4412# * The weights arrive int8 with a scale per tensor and are **dequantised to fp16**, not
4413# carried through as [`DTYPE_I8`]. At 172,576 parameters int8 would save nine kilobytes
4414# against fp16 - 337 KB versus 346 KB - which does not pay for per-tensor int8 arithmetic
4415# or for a second thing to verify. See [`INT8_GRAPHS`] for when it would.
4416TFLITE = {
4417 "nnfp": {
4418 # `music_detector.sound_model_2`, one subgraph. Note the file has 432 bytes of
4419 # container in front of the flatbuffer; [`open_tflite`] finds the magic rather than
4420 # assuming offset zero.
4421 "subgraph": 0,
4422 "input": [1, 1, 32, 1],
4423 "output": [1, 64],
4424 # The whole op census. `CIRCULAR_BUFFER` and the reshapes carry no weights and are
4425 # unrolled or relabelled by the Rust, so they appear here and nowhere else.
4426 "ops": {
4427 "CONV_2D": 10,
4428 "DEPTHWISE_CONV_2D": 2,
4429 "CIRCULAR_BUFFER": 6,
4430 "RESHAPE": 3,
4431 },
4432 # The weighted ops in graph order, which is the `.maml` tensor order and so the entire
4433 # contract with `nets::nnfp`. Each entry is the layout to emit, the kernel shape
4434 # **after** the transpose, and the bias length. Checked against the file, not assumed:
4435 # a re-export that changed a channel count fails here rather than at inference.
4436 "layers": [
4437 ("conv", [8, 1, 1, 4], 8),
4438 ("conv", [16, 8, 4, 1], 16),
4439 ("conv", [24, 16, 1, 4], 24),
4440 ("conv", [32, 24, 4, 1], 32),
4441 ("conv", [48, 32, 1, 4], 48),
4442 ("conv", [64, 48, 4, 1], 64),
4443 ("conv", [96, 64, 1, 4], 96),
4444 ("conv", [128, 96, 4, 1], 128),
4445 ("conv", [96, 128, 1, 2], 96),
4446 ("conv", [64, 96, 4, 1], 64),
4447 # The full-width depthwise with `depth_multiplier = 8`, read as a grouped
4448 # convolution: 512 outputs over 64 groups of one input channel each.
4449 ("depthwise", [512, 1, 1, 50], 512),
4450 # The final projection, which the Rust reads as two constants rather than as a
4451 # convolution's parameters because the export's preceding reshape is a channel
4452 # shuffle it cannot express. See `nets::nnfp::build`.
4453 ("shuffled", [1, 8, 64], 64),
4454 ],
4455 },
4456}
4457
4458# Numeric TFLite tensor types this reads. Anything else is a graph we have not seen.
4459TFLITE_DTYPES = {0: "float32", 2: "int32", 7: "int16", 9: "int8"}
4460
4461
4462def open_tflite(path):
4463 """The flatbuffer at `path`, and a `{opcode index: name}` for its operator table.
4464
4465 The magic is located rather than assumed at offset 0: `music_detector.sound_model_2` has
4466 432 bytes of container in front of it, and a reader that starts at zero sees garbage.
4467 """
4468 try:
4469 from tflite.BuiltinOperator import BuiltinOperator
4470 from tflite.Model import Model
4471 except ImportError:
4472 raise SystemExit("needs the TFLite schema bindings: python -m pip install tflite")
4473
4474 with open(path, "rb") as handle:
4475 raw = handle.read()
4476 offset = 0
4477 if raw[4:8] != b"TFL3":
4478 found = raw.find(b"TFL3")
4479 if found < 4:
4480 raise SystemExit(f"{path} holds no TFL3 flatbuffer")
4481 offset = found - 4
4482 model = Model.GetRootAsModel(raw[offset:], 0)
4483
4484 builtins = {v: k for k, v in vars(BuiltinOperator).items() if isinstance(v, int)}
4485 names = {}
4486 for index in range(model.OperatorCodesLength()):
4487 code = model.OperatorCodes(index)
4488 custom = code.CustomCode()
4489 # A `custom_code` string wins over the numeric code, rather than the documented
4490 # "builtin 32 means CUSTOM" test. Both Now Playing files get that number wrong:
4491 # `sound_model_2` stores builtin 0 - which reads as `ADD` - on all six
4492 # `CIRCULAR_BUFFER` entries while still carrying the name beside them, and
4493 # `sound_model` does the same to an `IF`. A builtin never has a `custom_code`, so
4494 # trusting the string is both safe and the only reading that survives these files.
4495 if custom:
4496 names[index] = custom.decode()
4497 continue
4498 # `builtin_code` is a later, wider field than `deprecated_builtin_code`, and an older
4499 # converter leaves it zero. Fall back rather than reading every old op as `ADD`.
4500 builtin = code.BuiltinCode() or code.DeprecatedBuiltinCode()
4501 names[index] = builtins.get(builtin, f"op{builtin}")
4502 return model, names
4503
4504
4505def tflite_tensor(model, graph, index):
4506 """Tensor `index` of `graph`, dequantised to fp32.
4507
4508 Refuses per-axis quantisation rather than guessing which axis survives the transpose in
4509 [`collect_tflite`]. Nothing in the graphs read here uses it - every tensor in
4510 `sound_model_2` is per-tensor - so a file that does is a file this has not been read
4511 against, and should fail rather than be silently wrong along one axis.
4512 """
4513 tensor = graph.Tensors(index)
4514 shape = [tensor.Shape(axis) for axis in range(tensor.ShapeLength())]
4515 buffer = model.Buffers(tensor.Buffer())
4516 if buffer.DataLength() == 0:
4517 raise SystemExit(f"tensor {index} {shape} has no buffer, so it is not a constant")
4518 dtype = TFLITE_DTYPES.get(tensor.Type())
4519 if dtype is None:
4520 raise SystemExit(f"tensor {index} has TFLite type {tensor.Type()}, which is not read")
4521 values = np.frombuffer(buffer.DataAsNumpy().tobytes(), dtype=dtype).reshape(shape)
4522
4523 quant = tensor.Quantization()
4524 if quant is None or quant.ScaleLength() == 0:
4525 return np.ascontiguousarray(values, dtype=np.float32)
4526 if quant.ScaleLength() != 1:
4527 raise SystemExit(
4528 f"tensor {index} is quantised per axis over {quant.ScaleLength()} scales. "
4529 "This reader only does per-tensor; see its docstring."
4530 )
4531 scale = float(quant.ScaleAsNumpy()[0])
4532 zero = float(quant.ZeroPointAsNumpy()[0]) if quant.ZeroPointLength() else 0.0
4533 # In f64 and back, so a large int32 bias does not lose its low bits to f32 before scaling.
4534 return ((values.astype(np.float64) - zero) * scale).astype(np.float32)
4535
4536
4537def tflite_options(operator, depthwise):
4538 """`(stride_h, stride_w, padding, depth_multiplier, activation)`, for the digest key.
4539
4540 Recorded rather than acted on. The Rust hardcodes its own padding, because `sound_model_2`
4541 stores `Padding = VALID` on every convolution while recording output shapes that only
4542 `SAME` produces on the frequency axis - see `nets::nnfp`. Putting the stored value in the
4543 key means a re-export that *fixed* that inconsistency changes the digest and gets looked
4544 at, instead of quietly disagreeing with the hardcoded pass.
4545 """
4546 from tflite.Conv2DOptions import Conv2DOptions
4547 from tflite.DepthwiseConv2DOptions import DepthwiseConv2DOptions
4548
4549 table = operator.BuiltinOptions()
4550 if table is None:
4551 return (0, 0, 0, 0, 0)
4552 options = DepthwiseConv2DOptions() if depthwise else Conv2DOptions()
4553 options.Init(table.Bytes, table.Pos)
4554 multiplier = options.DepthMultiplier() if depthwise else 1
4555 return (
4556 options.StrideH(),
4557 options.StrideW(),
4558 options.Padding(),
4559 multiplier,
4560 options.FusedActivationFunction(),
4561 )
4562
4563
4564def check_tflite(model, names, graph_id_name):
4565 """The graph's boundary shapes and op census against [`TFLITE`]."""
4566 spec = TFLITE[graph_id_name]
4567 graph = model.Subgraphs(spec["subgraph"])
4568
4569 def shape_of(index):
4570 tensor = graph.Tensors(index)
4571 return [tensor.Shape(axis) for axis in range(tensor.ShapeLength())]
4572
4573 got_in = [shape_of(graph.Inputs(i)) for i in range(graph.InputsLength())]
4574 if got_in != [spec["input"]]:
4575 raise SystemExit(f"graph inputs are {got_in}, expected [{spec['input']}]")
4576 got_out = [shape_of(graph.Outputs(i)) for i in range(graph.OutputsLength())]
4577 if got_out != [spec["output"]]:
4578 raise SystemExit(f"graph outputs are {got_out}, expected [{spec['output']}]")
4579
4580 counts = {}
4581 for index in range(graph.OperatorsLength()):
4582 name = names[graph.Operators(index).OpcodeIndex()]
4583 counts[name] = counts.get(name, 0) + 1
4584 if counts != spec["ops"]:
4585 only_got = {k: v for k, v in counts.items() if spec["ops"].get(k) != v}
4586 only_want = {k: v for k, v in spec["ops"].items() if counts.get(k) != v}
4587 raise SystemExit(f"op counts differ: got {only_got}, expected {only_want}")
4588
4589
4590def collect_tflite(model, names, spec):
4591 """`(layers, tensors)` for a TFLite graph, in the order the Rust forward pass reads them.
4592
4593 Graph order, weighted ops only: kernel then bias, exactly as the ONNX collector emits a
4594 `Conv`. The transpose from TFLite's `[out, kh, kw, in]` into this runtime's
4595 `[out, in / group, kh, kw]` happens here, per layer kind.
4596 """
4597 graph = model.Subgraphs(spec["subgraph"])
4598 weighted = []
4599 for index in range(graph.OperatorsLength()):
4600 operator = graph.Operators(index)
4601 name = names[operator.OpcodeIndex()]
4602 if name in ("CONV_2D", "DEPTHWISE_CONV_2D"):
4603 weighted.append((index, operator, name))
4604 if len(weighted) != len(spec["layers"]):
4605 raise SystemExit(
4606 f"{len(weighted)} weighted ops, expected {len(spec['layers'])}. The export's "
4607 "layer count changed, so the hardcoded forward pass no longer describes it."
4608 )
4609
4610 layers, tensors = [], []
4611 for position, ((at, operator, op_name), want) in enumerate(zip(weighted, spec["layers"])):
4612 kind, want_kernel, want_bias = want
4613 kernel = tflite_tensor(model, graph, operator.Inputs(1))
4614 bias = tflite_tensor(model, graph, operator.Inputs(2))
4615 stored = list(kernel.shape)
4616 options = tflite_options(operator, op_name == "DEPTHWISE_CONV_2D")
4617
4618 if kind == "conv":
4619 # `[out, kh, kw, in]` to `[out, in, kh, kw]`.
4620 kernel = kernel.transpose(0, 3, 1, 2)
4621 elif kind == "depthwise":
4622 # A depthwise kernel is `[1, kh, kw, out]`, where `out` is `in * depth_multiplier`
4623 # indexed as `channel * multiplier + m`. Moving that axis to the front gives
4624 # `[out, 1, kh, kw]`, which is what a grouped convolution with one input channel
4625 # per group reads - and the `channel * multiplier + m` ordering is exactly the
4626 # group ordering the shader uses, so nothing has to be reordered within it.
4627 kernel = kernel.transpose(3, 0, 1, 2)
4628 elif kind == "shuffled":
4629 # Read as constants, not as a convolution: `[1, 1, 8, 64]` to `[1, 8, 64]` and the
4630 # bias to `[64, 1, 1]`, which is the rank a constant has. Both are relabellings of
4631 # the same bytes in the same order.
4632 kernel = kernel.reshape(kernel.shape[1:])
4633 bias = bias.reshape(bias.shape[0], 1, 1)
4634 else:
4635 raise SystemExit(f"layer {position} has unknown kind {kind!r}")
4636 kernel = np.ascontiguousarray(kernel, dtype=np.float32)
4637
4638 if list(kernel.shape) != want_kernel:
4639 raise SystemExit(
4640 f"layer {position} ({op_name} at op {at}) is {list(kernel.shape)} after the "
4641 f"transpose, expected {want_kernel}"
4642 )
4643 if bias.size != want_bias:
4644 raise SystemExit(f"layer {position} bias is {bias.size} long, expected {want_bias}")
4645
4646 key = (
4647 f"TFLite{op_name} w={stored} b={[want_bias]} "
4648 f"s={list(options[:2])} p={options[2]} m={options[3]} a={options[4]}"
4649 )
4650 layers.append(Layer(position, op_name, f"op{at}", key, len(tensors), 2))
4651 tensors.append(kernel)
4652 tensors.append(np.ascontiguousarray(bias, dtype=np.float32))
4653 return layers, tensors
4654
4655
4656def main():
4657 parser = argparse.ArgumentParser(description=SPEC.splitlines()[0])
4658 parser.add_argument(
4659 "model", help="an ONNX export, a .safetensors for a CHECKPOINTS graph, or a .tflite"
4660 )
4661 parser.add_argument("--graph", required=True, choices=sorted(GRAPHS))
4662 parser.add_argument("-o", "--out", help="where to write the .maml")
4663 parser.add_argument("--check", action="store_true", help="validate only")
4664 parser.add_argument("--print-layers", action="store_true")
4665 parser.add_argument("--print-digest", action="store_true")
4666 args = parser.parse_args()
4667
4668 source_sha256 = hashlib.sha256()
4669 with open(args.model, "rb") as f:
4670 for block in iter(lambda: f.read(1 << 20), b""):
4671 source_sha256.update(block)
4672 source_size = os.path.getsize(args.model)
4673
4674 if args.graph in TFLITE:
4675 model, names = open_tflite(args.model)
4676 check_tflite(model, names, args.graph)
4677 layers, tensors = collect_tflite(model, names, TFLITE[args.graph])
4678 elif args.graph in GGUF_GRAPHS:
4679 get, shapes = open_gguf(args.model)
4680 check_gguf(shapes, "madlad400")
4681 layers, tensors = collect_madlad_q2k(get, CHECKPOINTS["madlad400"])
4682 elif args.graph in CHECKPOINTS:
4683 get, shapes = open_checkpoint(args.model)
4684 check_checkpoint(shapes, args.graph)
4685 layers, tensors = COLLECTORS[args.graph](get, CHECKPOINTS[args.graph])
4686 elif args.graph in ARCHITECTURES:
4687 model = onnx.load(args.model)
4688 check_graph(model, args.graph)
4689 check_architecture(model, args.graph, ARCHITECTURES[args.graph])
4690 if args.graph == "gemma4_text":
4691 layers, tensors = collect_gemma4(model, ARCHITECTURES[args.graph])
4692 elif args.graph == "gemma4_embed":
4693 layers, tensors = collect_gemma4_embed(model, ARCHITECTURES[args.graph])
4694 elif args.graph == "gemma4_vision":
4695 layers, tensors = collect_gemma4_vision(model, ARCHITECTURES[args.graph])
4696 elif args.graph == "gemma4_audio":
4697 layers, tensors = collect_gemma4_audio(model, ARCHITECTURES[args.graph])
4698 else:
4699 layers, tensors = collect_tinyclip(model, ARCHITECTURES[args.graph])
4700 else:
4701 model = onnx.load(args.model)
4702 check_graph(model, args.graph)
4703 layers, tensors = collect_layers(
4704 model, MODULES.get(args.graph), quantise=args.graph in INT8_GRAPHS
4705 )
4706
4707 digest = layer_table_digest(layers)
4708 if args.print_digest:
4709 print(f' "{args.graph}": "{digest}",')
4710 pinned = EXPECTED_DIGEST.get(args.graph)
4711 if pinned is None:
4712 message = (
4713 f"{args.graph} has no pinned layer table digest. Add\n"
4714 f' "{args.graph}": "{digest}",\n'
4715 "to EXPECTED_DIGEST once the Rust net agrees with this table, so that a later\n"
4716 "change to either side fails loudly instead of shifting every tensor."
4717 )
4718 if not args.print_digest:
4719 raise SystemExit(message)
4720 print(message, file=sys.stderr)
4721 elif digest != pinned:
4722 message = (
4723 f"layer table digest {digest}\n"
4724 f" pinned {pinned}\n"
4725 "The ordered Conv/ConvTranspose table changed, so the hardcoded forward\n"
4726 f"pass in library/ml/src/main/rust/src/nets/{args.graph}.rs no longer\n"
4727 "matches this export. Re-read it with --print-layers, update the Rust,\n"
4728 "then re-pin with --print-digest."
4729 )
4730 if not args.print_digest:
4731 raise SystemExit(message)
4732 print(message, file=sys.stderr)
4733
4734 if args.print_layers:
4735 for layer in layers:
4736 print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()} # {layer.name}")
4737
4738 blob, count = build(layers, tensors, GRAPHS[args.graph], source_sha256.digest())
4739 if args.out:
4740 with open(args.out, "wb") as f:
4741 f.write(blob)
4742 print(
4743 f"{args.graph}: {count} layers, {len(tensors)} tensors, "
4744 f"{len(blob)} bytes ({source_size} fp32 in)"
4745 )
4746
4747
4748if __name__ == "__main__":
4749 main()