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

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

gemma4_audio_encoder_parity.py855 lines · 41.9 KiBRaw
1#!/usr/bin/env python3
2"""Golden for Gemma 4's audio encoder: onnxruntime's answer, with an int4 control.
3
4`examples/check_gemma4_audio_parity.rs` reads what this writes. It is the audio counterpart of
5`gemma4_vision_parity.py` and follows it closely; read that one first.
6
7Not to be confused with `gemma4_audio_parity.py`, which is the FRONT END - waveform to log-mel.
8This one starts where that one stops. It imports `load_extractor` from it rather than repeating
9the importlib bypass, so there is one copy of the trick that gets transformers imported on a
10machine where its package `__init__` fails a huggingface-hub version check.
11
12# The control is the point, again
13
14The device runs int4 weights and the export runs fp16 ones, so the two cannot agree closely and
15the interesting question is never "how close is it" but "is it as close as four bits allow". On
16the vision tower a completely correct encoder read 0.946 against the exact reference and 0.999
17against the int4 control, and without the second number the first is unreadable - we nearly
18concluded a correct tower was broken.
19
20So this runs the reference twice, and the second run is the bar.
21
22WHAT THE CONTROL QUANTISES IS NOT A GUESS. It is read out of `collect_gemma4_audio` in
23`maml_convert.py`, which is the code that actually writes the `.maml`:
24
25 int4 `projection()` ten linears per layer, twelve layers, 120 total:
26 ffw1.up ffw1.down q k v post_proj lconv.gate lconv.exit
27 ffw2.up ffw2.down
28 fp16 everything else the file holds. `maml_convert` writes any tensor that is not int4 or
29 int8 as `DTYPE_F16` (line 3413), so the norms, the clip bounds, the
30 query scales and the twelve relative tables are all fp16 in the `.maml`
31 even though the converter carries them as fp32 numpy on the way through.
32
33That second row is why this INSISTS ON THE fp16 EXPORT. Loading `audio_encoder.onnx` instead of
34`audio_encoder_fp16.onnx` would leave every non-int4 weight at fp32 while the device has it
35fp16-rounded, and the control would then be a bar the device cannot meet for a reason that has
36nothing to do with four bits. `require_fp16` refuses the fp32 export rather than quietly
37measuring against it.
38
39A control that quantised the relative tables, or the SSCP convs, or the input projection would
40flatter the device against a bar it is not trying to meet. The count is asserted: exactly 120.
41
42# The clips, and what the padding cases turned into
43
44The brief originally asked for a clip with a padded tail, to exercise the -65504 fill and the
45bounds guard. `audio-net` then measured that `nets::gemma4_audio` DOES NOT PAD - it feeds F real
46frames with the mask all true, where the reference pads to a multiple and masks - and that the
47two arms are bit-identical on the export across eight configurations. So there is no padded tail
48on the device, the second SSCP mask does no work, and a padded-tail clip would measure a code
49path that does not exist.
50
51What survives is the START of the sequence, which is where the fill and the bounds guard actually
52live: queries `q < 11` whose band reaches `k = q - 11 + j < 0`. Hence:
53
54 short T = 4 every query is on the ramp. The case that matters most.
55 ragged T = 29 T % 12 != 0, so the last chunk is partial
56 multi T = 63 several chunks and still not a multiple
57 exact T = 48 a clean multiple, as contrast. It is the WEAK case and is here to show
58 that the others are doing something it does not.
59
60`no_pad_equivalence` additionally re-runs every residue-2 clip through the reference's own
61padded-and-masked arm and asserts it matches the unpadded arm the device uses. That turns
62`audio-net`'s measurement into a standing check rather than a fact in a chat message.
63
64# The negative control
65
66`break_relative` reverses the offset axis of the twelve relative-position tables and reports what
67that does to the output cosine. A harness that has never been shown to fail is not evidence, and
68the reversal is the error `maml_convert.py:2405-2411` warns about: shape-preserving, so no plan
69builder catches it, and wrong at every position. If a deliberately broken graph still reads above
700.99 the harness says so and tells you not to trust a pass.
71
72# What it measured, and why the control is not optional
73
74Run against `audio_encoder_fp16.onnx`, four bits alone cost this much cosine AT THE OUTPUT:
75
76 tiny T = 1 0.009283
77 short T = 4 0.001913
78 ragged T = 25 0.016667
79 multi T = 56 0.037371
80 exact T = 48 0.041174
81
82So the int4 penalty GROWS with clip length and reaches four percent on ordinary clips. Against
83the exact reference a correct encoder therefore reads anywhere from 0.998 to 0.958 depending only
84on how long the audio is, and there is no fixed floor anyone could set. That is the whole reason
85for the control: measured against it the bar is clip-independent.
86
87The negative control, on the longest clip, with the reversed tables then quantised exactly as the
88device's are:
89
90 against the exact reference 0.936792
91 against the int4 control 0.967655 <- the number that decides
92 a correct encoder would read 1.000000 against the same control
93
94Read those two columns together. Against the exact reference a BROKEN encoder reads 0.9368 while
95a CORRECT one reads 0.9588 on a comparable clip - a gap of two percent, and the two populations
96very nearly touch. Against the control the broken one reads 0.9677 against a known 1.0. The
97control does not widen the gap much; what it does is make the correct answer a CONSTANT instead
98of a function of clip length, which is what lets a floor exist at all.
99
100Be honest about the margin: 0.9677 is not far below a floor of 0.99, and a subtler bug than a
101fully reversed table will sit closer still. The per-layer bisect, not the output cosine, is what
102localises anything; the output figure is a verdict, not a diagnosis.
103
104# The negative controls, and what they establish
105
106`break_relative` and `swap_qk` perturb the graph deliberately, then quantise and fp16-round it
107exactly as the device's weights are, so each is a like-for-like stand-in for a broken device.
108Measured on the longest clip:
109
110 perturbation vs exact vs control enters at
111 all 12 relative tables reversed 0.936792 0.967655 layer_in_1
112 layer 6's relative table reversed 0.953414 0.987361 layer_in_7
113 q and k projections swapped 0.909556 0.911101 layer_in_1
114
115Each names the layer AFTER the fault, which is the right answer in all three. That localisation
116is exact, and it is exact only because the criterion is "any departure from 1.0" - see
117[`DEPARTURE`], which also explains why that criterion does NOT transfer to the device.
118
119The output column is the warning. A fault confined to one layer reads 0.987 at the output against
120the control, while four bits alone cost 0.037 on the same clip - the bug is three times smaller
121than the noise it hides in. Against the exact reference it reads 0.9534, BETTER than a correct
122encoder scores on a comparable clip. So the output figure is a detector of gross errors only, and
123the per-probe profile is what finds anything subtler.
124
125 python scripts/ml/gemma4_audio_encoder_parity.py audio_encoder_fp16.onnx -o audio_golden.json
126"""
127import argparse
128import json
129import os
130import sys
131
132import numpy as np
133import onnx
134import onnxruntime as ort
135from onnx import numpy_helper
136
137sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
138from gemma4_audio_parity import load_extractor # noqa: E402
139from maml_convert import I4_BLOCK, quantise_per_block # noqa: E402
140
141LAYERS = 12
142D_MODEL = 1024
143HEADS = 8
144HEAD_DIM = 128
145REL_OFFSETS = 13
146OUT_DIM = 1536
147NORMS_PER_LAYER = 9
148CHUNK = 12
149MAX_SAMPLES = 480_000
150PAD_MULTIPLE = 128
151INT4_PER_LAYER = 10
152# `maml_convert.FP16_LIMIT`: fp16's largest finite value, which the converter substitutes for an
153# absent clip bound rather than storing an infinity.
154FP16_LIMIT = 65504.0
155
156# Real sample counts, computed rather than picked. `check_clip` re-derives every property and
157# fails if it stops holding.
158#
159# THREE OF THE FIVE SIT AT F % 4 == 2, which is not decoration. The reference's second SSCP mask
160# does observable work only when the valid frame count is EVEN, and corrupts a valid soft token
161# only when it is 2 (mod 4) - then exactly one, always the last. We pad nothing and mask nothing,
162# so that residue class is the only place our shortcut and the reference could diverge. A golden
163# without it tests nothing about the no-padding decision. `audio-net`'s first no-padding run
164# sampled F in {37, 40, 52, 61, 99, 100}, residues {1, 0, 0, 1, 3, 0}, and missed the hazard
165# entirely; my own first four clips were F in {16, 116, 252, 189}, residues {0, 0, 0, 1}, and
166# missed it the same way.
167CLIPS = [
168 ("tiny", 385), # F 2 T 1 F%4=2. One token: every band position but k=q is < 0.
169 ("short", 2_704), # F 16 T 4 T < 12, so every query is still on the ramp.
170 ("ragged", 15_745), # F 98 T 25 F%4=2, T%12=1.
171 ("multi", 35_585), # F 222 T 56 F%4=2, T%12=8, several chunks.
172 ("exact", 30_248), # F 189 T 48 clean multiple, no hazard. The weak contrast case.
173]
174
175
176# The ONNX initializer shape of each int4 slot, by its offset from `base`. From `audio-net`'s
177# worked examples. Asserting these is much stronger than counting 120: a shift in the node
178# numbering that preserved the count would still have to preserve this [1024,4096] /
179# [4096,1024] / [1024,2048] / [1024,1024] pattern at every one of ten slots in all twelve layers.
180SLOT_SHAPES = {
181 0: (1024, 4096), # ffw1.up
182 1: (4096, 1024), # ffw1.down
183 2: (1024, 1024), # q_proj
184 3: (1024, 1024), # k_proj
185 4: (1024, 1024), # v_proj
186 6: (1024, 1024), # post_proj
187 7: (1024, 2048), # lconv.gate
188 8: (1024, 1024), # lconv.exit
189 9: (1024, 4096), # ffw2.up
190 10: (4096, 1024), # ffw2.down
191}
192
193
194# How far from 1.0 counts as a departure, WHEN COMPARING TWO ONNXRUNTIME RUNS.
195#
196# READ THIS BEFORE REUSING IT AS A DEVICE THRESHOLD. IT IS NOT ONE.
197#
198# The negative-control profile is control-versus-perturbed-control: both sides are onnxruntime,
199# same arithmetic, same order of operations, differing only by the perturbation. Under those
200# conditions a correct build reads EXACTLY 1.000000 at every probe upstream of the fault, which
201# is what makes "any departure at all" a usable criterion and what makes the localisation exact.
202#
203# The DEVICE is not that. It is Vulkan fp16 compute, a different implementation with a different
204# summation order and an fp16 arena, so device-versus-control will sit below 1.0 at EVERY probe
205# even when the device is perfectly correct, and that baseline will grow with depth. Applying
206# 1e-6 to it would report "enters at layer_in_0" for a flawless device.
207#
208# So the device bar has to be MEASURED from a known-good run and cannot be guessed here. Until
209# someone has that, the Rust side should print the profile and let its SHAPE speak - a correct
210# device diverges smoothly and monotonically, a composition error adds a step on top of that
211# trend - rather than render a verdict against a number nobody has justified.
212DEPARTURE = 1e-6
213
214
215def synthetic_pcm(count):
216 """A reproducible waveform in -1..1, bit-identical to `synthetic_pcm` in the Rust example.
217
218 Integer hash to i16 and then a divide by 32768, which is exact in binary, so the two sides
219 agree to the bit and the golden carries no waveform. A hash rather than a tone because a
220 single frequency excites almost none of the 128 mel channels, and a near-rank-one input hides
221 exactly the composition errors this is looking for.
222 """
223 index = np.arange(count, dtype=np.uint64)
224 mask = np.uint64(0xFFFFFFFF)
225 h = (index * np.uint64(73_856_093)) & mask
226 h ^= h >> np.uint64(13)
227 h = (h * np.uint64(1_274_126_177)) & mask
228 h ^= h >> np.uint64(16)
229 return (((h & np.uint64(0xFFFF)).astype(np.int64) - 32768) / 32768.0).astype(np.float32)
230
231
232def frame_count(n):
233 """`logmel::frame_count`, the mel unfold at 321 rather than 320."""
234 return (n + 160 - 321) // 160 + 1 if n + 160 >= 321 else 0
235
236
237def subsample(n):
238 return -(-n // 2)
239
240
241def tokens(frames):
242 """`gemma4_audio::tokens`: two stride-2 convolutions, so ceil(ceil(F/2)/2)."""
243 return subsample(subsample(frames))
244
245
246def check_clip(name, real):
247 """The clip's shape, and a hard failure if it no longer exercises what it is here for.
248
249 `frames` is what the DEVICE feeds: `frame_count(real)` real rows, no padding. The reference's
250 padded row count is carried too, but only so `no_pad_equivalence` can build the other arm.
251 """
252 padded = min(MAX_SAMPLES, -(-real // PAD_MULTIPLE) * PAD_MULTIPLE)
253 frames = frame_count(min(real, MAX_SAMPLES))
254 facts = dict(
255 name=name, real=real, padded=padded, frames=frames,
256 frames_padded=frame_count(padded), tokens=tokens(frames), residue=frames % 4,
257 )
258 t = facts["tokens"]
259 if name == "short":
260 if t >= CHUNK:
261 raise SystemExit(f"{name}: T={t} no longer sits inside one chunk")
262 elif name == "tiny":
263 if t != 1:
264 raise SystemExit(f"{name}: T={t}, not the single-token case")
265 elif name == "exact":
266 if t % CHUNK:
267 raise SystemExit(f"{name}: T={t} is not the clean multiple this case is for")
268 elif t % CHUNK == 0:
269 raise SystemExit(f"{name}: T={t} is a clean multiple, which is the weak case")
270 if name == "multi" and t < 4 * CHUNK:
271 raise SystemExit(f"{name}: T={t} is not several chunks")
272 # The seam's predicted victim, from op-designer's and audio-tracer's independent derivations:
273 # at F == 2 (mod 4) the smeared SSCP position reaches exactly one valid output, index
274 # (F - 2) / 4, and that index is always the LAST valid token. Re-derived here rather than
275 # trusted, because it is the token the golden checks specifically.
276 if facts["residue"] == 2:
277 victim = (frames - 2) // 4
278 if victim != t - 1:
279 raise SystemExit(
280 f"{name}: the seam victim (F-2)/4 = {victim} is not the last token {t - 1}"
281 )
282 facts["seam_victim"] = victim
283 return facts
284
285
286def mel_for(extractor, facts):
287 """`(device_mel, padded_mel, padded_mask)` for a clip, from the shipped extractor.
288
289 `device_mel` is the first `frames` rows only, which is what `nets::gemma4_audio` is fed: real
290 audio, no padding, mask all true. The padded pair is the reference's own arm, kept so the two
291 can be compared rather than assumed equal.
292
293 Passed as a LIST: handing `__call__` a bare 1-D array trips a squeeze on the batch axis and
294 raises for every length but one.
295 """
296 wave = synthetic_pcm(facts["real"])[:MAX_SAMPLES]
297 out = extractor([wave])
298 padded_mel = np.asarray(out["input_features"][0], dtype=np.float32)
299 padded_mask = np.asarray(out["input_features_mask"][0]).astype(bool)
300 if padded_mel.shape[0] != facts["frames_padded"]:
301 raise SystemExit(
302 f"{facts['real']} samples gave {padded_mel.shape[0]} rows, not {facts['frames_padded']}"
303 )
304 if int(padded_mask.sum()) != facts["frames"]:
305 raise SystemExit(
306 f"the reference says {int(padded_mask.sum())} valid rows, frame_count says"
307 f" {facts['frames']}"
308 )
309 return padded_mel[: facts["frames"]], padded_mel, padded_mask
310
311
312def require_fp16(model, path):
313 """Refuse the fp32 export, because the control models a file whose non-int4 tensors are fp16.
314
315 `maml_convert` writes everything that is not int4 or int8 as `DTYPE_F16`, so the norms, clip
316 bounds, query scales and relative tables are all fp16 on the device. The fp16 export already
317 holds them at that precision, which is why the control does not need to round them itself -
318 but only if this really is the fp16 export.
319 """
320 kinds = {}
321 for tensor in model.graph.initializer:
322 kinds[tensor.data_type] = kinds.get(tensor.data_type, 0) + 1
323 half = kinds.get(onnx.TensorProto.FLOAT16, 0)
324 full = kinds.get(onnx.TensorProto.FLOAT, 0)
325 if full > half:
326 raise SystemExit(
327 f"{path} holds {full} fp32 initializers against {half} fp16: this looks like the fp32"
328 " export. Use audio_encoder_fp16.onnx - the control assumes every non-int4 tensor is"
329 " already at the precision the .maml stores it in."
330 )
331 return half, full
332
333
334def int4_linears(model):
335 """The initializer names `collect_gemma4_audio` sends through `projection()`, and only those.
336
337 `node_linear` runs 0..134 with a hole at every `base + 5` - the twelve `relative_k_proj`,
338 which the exporter folded away - and another at 133, which is the `Add` that applies
339 `output_proj`'s bias. Index 0 is the input projection and is emitted at fp16, as are the
340 output and embedder projections, so the int4 set is exactly `1 + 11*i + d` for
341 `d in {0,1,2,3,4,6,7,8,9,10}`. See `maml_convert.collect_gemma4_audio`.
342 """
343 numbered = {}
344 for node in model.graph.node:
345 name = node.name or ""
346 if node.op_type not in ("MatMul", "Gemm") or not name.startswith("node_linear"):
347 continue
348 tail = name[len("node_linear"):]
349 if tail == "":
350 numbered[0] = node
351 elif tail.startswith("_") and tail[1:].isdigit():
352 numbered[int(tail[1:])] = node
353 wanted = []
354 for layer in range(LAYERS):
355 base = 1 + 11 * layer
356 for step in sorted(SLOT_SHAPES):
357 node = numbered.get(base + step)
358 if node is None:
359 raise SystemExit(f"node_linear_{base + step} is missing; the numbering moved")
360 wanted.append((node, SLOT_SHAPES[step], f"layer {layer} slot +{step}"))
361 if len(wanted) != LAYERS * INT4_PER_LAYER:
362 raise SystemExit(f"{len(wanted)} int4 linears, not {LAYERS * INT4_PER_LAYER}")
363 if 1 + 11 * (LAYERS - 1) + 5 in numbered:
364 raise SystemExit("node_linear at base+5 exists; relative_k_proj was not folded")
365 return wanted
366
367
368def quantise_in_place(model):
369 """Round-trip every int4 linear's weight through the converter's own quantiser. Returns how many.
370
371 The converter transposes the `[in, out]` MatMul initializer to an `[out, in]` kernel before
372 quantising, so the blocks run along the contraction axis. Doing it any other way here would
373 measure a bar the device is not trying to meet.
374 """
375 inits = {i.name: i for i in model.graph.initializer}
376 touched = 0
377 for node, expect, label in int4_linears(model):
378 for name in node.input:
379 tensor = inits.get(name)
380 if tensor is None:
381 continue
382 original = numpy_helper.to_array(tensor)
383 matrix = original.astype(np.float32)
384 if matrix.ndim != 2:
385 continue
386 if matrix.shape != expect:
387 raise SystemExit(f"{label} is {matrix.shape}, not {expect}: the numbering moved")
388 kernel = matrix.T
389 codes, scale = quantise_per_block(kernel)
390 # rows = out, taps = in, blocks = ceil(in / I4_BLOCK). Asserted because getting the
391 # orientation backwards puts the blocks along the OUTPUT axis, which quantises fine,
392 # produces the right shapes, and measures a bar the device is not trying to meet.
393 blocks = -(-kernel.shape[1] // I4_BLOCK)
394 if scale.shape != (kernel.shape[0], blocks):
395 raise SystemExit(
396 f"{label}: scale is {scale.shape}, not {(kernel.shape[0], blocks)} -"
397 " the blocks are not running along the contraction axis"
398 )
399 flat = kernel.reshape(kernel.shape[0], -1)
400 wide = np.repeat(scale, I4_BLOCK, axis=1)[:, : flat.shape[1]]
401 back = (np.asarray(codes).astype(np.float32).reshape(flat.shape) * wide)
402 back = back.reshape(kernel.shape).T
403 # `original.dtype`, not `matrix.dtype`: `matrix` is the fp32 working copy, so using
404 # its dtype writes fp32 into an fp16 graph and onnxruntime refuses the model with
405 # "Type parameter (T) of Optype (MatMul) bound to different types".
406 tensor.CopyFrom(numpy_helper.from_array(back.astype(original.dtype), name))
407 touched += 1
408 if touched != LAYERS * INT4_PER_LAYER:
409 raise SystemExit(f"quantised {touched} weights, not {LAYERS * INT4_PER_LAYER}")
410 return touched
411
412
413def fp16_round(model):
414 """Put every non-int4 initializer through fp16, as `maml_convert.build` does. Returns what moved.
415
416 `audio-net`'s correction: the `.maml` has no fp32, so the 109 norm gains, the clip bounds,
417 the query scales, the relative tables, the conv kernels and every synthesised bias are all
418 fp16 on the device. A control that round-tripped only the int4 linears would leave those at
419 whatever the export holds and be slightly optimistic.
420
421 Rather than reason about whether the fp16 export already stores them at that precision, this
422 does the rounding unconditionally and reports how many tensors it actually changed. Zero is
423 the answer that says the export was already fp16; anything else is a gap the control would
424 otherwise have missed. Doing it is cheaper than arguing about it and is correct either way.
425 """
426 skip = {name for node, _, _ in int4_linears(model) for name in node.input}
427 moved, worst = 0, 0.0
428 for tensor in model.graph.initializer:
429 if tensor.name in skip or tensor.data_type != onnx.TensorProto.FLOAT:
430 continue
431 values = numpy_helper.to_array(tensor)
432 if not np.issubdtype(values.dtype, np.floating):
433 continue
434 # Clamp before casting, because the converter SUBSTITUTES rather than overflows: an
435 # absent clip bound becomes +-FP16_LIMIT (`maml_convert.py`'s `FP16_LIMIT = 65504.0`),
436 # and `build()` raises rather than storing an infinity. Three tensors in this export hold
437 # values past fp16's range - a blind `.astype(np.float16)` turns them into inf, which is
438 # not what the device gets and poisons everything downstream of them.
439 clamped = np.clip(values, -FP16_LIMIT, FP16_LIMIT)
440 rounded = clamped.astype(np.float16).astype(values.dtype)
441 gap = float(np.abs(rounded - values).max()) if values.size else 0.0
442 if not np.isfinite(gap):
443 raise SystemExit(f"{tensor.name} still overflows fp16 after clamping")
444 if gap > 0.0:
445 moved += 1
446 worst = max(worst, gap)
447 tensor.CopyFrom(numpy_helper.from_array(rounded, tensor.name))
448 return moved, worst
449
450
451def break_relative(model, only=None):
452 """Reverse the offset axis of the relative tables. A deliberate, realistic, shape-preserving bug.
453
454 The harness has to demonstrate that it can FAIL before its passing means anything - the
455 standard `audio-net` set with their arm D, which deleted the mask multiplies and showed the
456 comparison caught it. An assertion that has never fired is not evidence.
457
458 This is the error the converter itself warns about at `maml_convert.py:2405-2411`: the table
459 is `[heads, head_dim, offsets]` and column `offsets - 1` is displacement zero, so getting the
460 column order backwards reads the wrong tap at every position while preserving every shape.
461 Shape-preserving on purpose - a bug that changes a shape is caught by the plan builder and
462 never reaches a cosine.
463
464 `only` breaks a single layer instead of all twelve, which is the harder and more realistic
465 case: most real composition errors are one wrong line in one place, and a localised bug is
466 exactly what an output cosine averages away.
467 """
468 touched, seen = 0, 0
469 inits = {i.name: i for i in model.graph.initializer}
470 for node in model.graph.node:
471 if node.op_type != "MatMul":
472 continue
473 for name in node.input:
474 tensor = inits.get(name)
475 if tensor is None or list(tensor.dims) != [HEADS, HEAD_DIM, REL_OFFSETS]:
476 continue
477 seen += 1
478 if only is not None and seen - 1 != only:
479 continue
480 values = numpy_helper.to_array(tensor)
481 tensor.CopyFrom(
482 numpy_helper.from_array(np.ascontiguousarray(values[:, :, ::-1]), name)
483 )
484 touched += 1
485 if seen != LAYERS:
486 raise SystemExit(f"found {seen} relative tables, not {LAYERS}")
487 if touched != (1 if only is not None else LAYERS):
488 raise SystemExit(f"reversed {touched} tables, not what was asked")
489 return touched
490
491
492def swap_qk(model):
493 """Exchange every layer's q and k projections. The other classic composition error.
494
495 Shapes are identical - both [1024, 1024] - so nothing downstream notices, and the attention
496 still produces a plausible distribution. Vision had four errors of exactly this family and
497 none of them changed a shape.
498 """
499 inits = {i.name: i for i in model.graph.initializer}
500 slots = int4_linears(model)
501 touched = 0
502 for layer in range(LAYERS):
503 q = slots[layer * INT4_PER_LAYER + 2][0]
504 k = slots[layer * INT4_PER_LAYER + 3][0]
505 qw = [inits[n] for n in q.input if n in inits]
506 kw = [inits[n] for n in k.input if n in inits]
507 if len(qw) != 1 or len(kw) != 1:
508 raise SystemExit(f"layer {layer}: q has {len(qw)} weights and k has {len(kw)}")
509 a, b = numpy_helper.to_array(qw[0]).copy(), numpy_helper.to_array(kw[0]).copy()
510 qw[0].CopyFrom(numpy_helper.from_array(b, qw[0].name))
511 kw[0].CopyFrom(numpy_helper.from_array(a, kw[0].name))
512 touched += 1
513 return touched
514
515
516# Each is applied to a fresh copy of the graph, then quantised and fp16-rounded exactly as the
517# device's weights are, so the comparison is like for like. The point is not that each fails -
518# it is HOW FAR each falls, because that is the harness's detection power stated as a number
519# rather than assumed.
520NEGATIVE_CONTROLS = [
521 ("all 12 relative tables reversed", lambda m: break_relative(m)),
522 ("layer 6's relative table reversed", lambda m: break_relative(m, only=6)),
523 ("q and k projections swapped", swap_qk),
524]
525
526
527def trace_points(model):
528 """`{label: tensor_name}` for the SSCP output and the input to each of the twelve layers.
529
530 Anchored the way `collect_gemma4_audio` anchors, because that is the reading which has
531 already been checked against this graph:
532
533 * there are `9 * LAYERS + 1` SimplifiedLayerNormalization nodes, nine per layer plus the
534 embedder's, and layer `i`'s input is the input of `node_mean_{9i}` - its ffw1 pre-norm;
535 * `node_mean_{9 * LAYERS}` is the embedder's pre-projection norm, whose input is the
536 encoder's output;
537 * the bare `node_linear` with no numeric suffix is the input projection, so its non-weight
538 input is what the SSCP produced and its output is what enters layer 0.
539
540 The SSCP pair is the point of this function. It is where the seam-smearing mask lives and
541 where three time axes differ by factors of two, so separating "the front end is wrong" from
542 "a layer is wrong" is most of the value of a bisect here.
543 """
544 norms, projection, tail = {}, None, None
545 for node in model.graph.node:
546 if node.op_type == "SimplifiedLayerNormalization":
547 name = (node.name or "").replace("_fused_rms_norm/node_mean", "node_mean")
548 if name.startswith("node_mean"):
549 suffix = name[len("node_mean"):]
550 if suffix == "":
551 norms[0] = node.input[0]
552 elif suffix.startswith("_") and suffix[1:].isdigit():
553 norms[int(suffix[1:])] = node.input[0]
554 elif node.op_type == "MatMul" and node.name == "node_linear":
555 projection = node
556 elif node.name == "node_linear_133":
557 tail = node
558 if len(norms) != NORMS_PER_LAYER * LAYERS + 1:
559 raise SystemExit(
560 f"{len(norms)} norms, not {NORMS_PER_LAYER * LAYERS + 1} - the numbering has changed"
561 )
562 if projection is None:
563 raise SystemExit("no bare node_linear - the input projection is not where it was")
564 inits = {i.name for i in model.graph.initializer}
565 activation = [i for i in projection.input if i not in inits]
566 if len(activation) != 1:
567 raise SystemExit(f"the input projection has {len(activation)} activation inputs, not one")
568 points = {"sscp_out": activation[0], "layer0_in_projected": projection.output[0]}
569 for layer in range(LAYERS):
570 points[f"layer_in_{layer}"] = norms[NORMS_PER_LAYER * layer]
571 # The tower's own output, 1024 wide, BEFORE output_proj. `encoder_out` below is the input to
572 # the embedder's pre-projection norm and is therefore already 1536 wide and past that
573 # projection, so without this pair a disagreement in the tail cannot be told from one in the
574 # tower. `audio-net` asked whether I wanted it; I did not have it and did.
575 #
576 # output_proj is the one biased linear, so the exporter split it: node_linear_133 is the Add
577 # and the weight belongs to the MatMul feeding it. Followed by edge rather than by name, as
578 # `collect_gemma4_audio` does.
579 if tail is not None and tail.op_type == "Add":
580 produced = {out: n for n in model.graph.node for out in n.output}
581 for name in tail.input:
582 source = produced.get(name)
583 if source is not None and source.op_type == "MatMul":
584 upstream = [i for i in source.input if i not in inits]
585 if len(upstream) == 1:
586 points["tower_out"] = upstream[0]
587 if "tower_out" not in points:
588 raise SystemExit("could not follow node_linear_133 back to the tower's output")
589 points["encoder_out"] = norms[NORMS_PER_LAYER * LAYERS]
590 return points
591
592
593def graph_inputs(model):
594 """`{name: (dims, elem_type)}` so the feed can be built without guessing shapes."""
595 out = {}
596 for value in model.graph.input:
597 shape = value.type.tensor_type.shape
598 dims = [d.dim_value if d.dim_value else d.dim_param for d in shape.dim]
599 out[value.name] = (dims, value.type.tensor_type.elem_type)
600 return out
601
602
603def collect(model, points, feed):
604 """`{label: array}` for every trace point plus the encoder's output, from one session."""
605 existing = {o.name for o in model.graph.output}
606 for tensor in points.values():
607 if tensor not in existing:
608 model.graph.output.add().name = tensor
609 existing.add(tensor)
610 session = ort.InferenceSession(
611 model.SerializeToString(), providers=["CPUExecutionProvider"]
612 )
613 names = [o.name for o in session.get_outputs()]
614 raw = dict(zip(names, session.run(names, feed)))
615 out = {}
616 for label, tensor in points.items():
617 out[label] = np.asarray(raw[tensor], dtype=np.float32)
618 for name in names:
619 if name not in points.values():
620 out.setdefault("audio_features", np.asarray(raw[name], dtype=np.float32))
621 return out
622
623
624def cosine(a, b):
625 a = np.asarray(a, dtype=np.float64).ravel()
626 b = np.asarray(b, dtype=np.float64).ravel()
627 return float(a @ b / max(np.linalg.norm(a) * np.linalg.norm(b), 1e-30))
628
629
630def probe_tokens(facts):
631 """Token rows worth carrying: the start ramp, a chunk boundary, the middle, the last.
632
633 0 and 1 are where `k = q - 11 + j` runs off the front of the sequence and an unguarded read
634 walks into whatever precedes the K tensor in the arena. 11 is the last query on the ramp and
635 12 the first fully-live one, so the pair straddles the boundary the bounds guard defends.
636 There is no padded token to probe: the device does not pad.
637 """
638 total = facts["tokens"]
639 wanted = {0, 1, CHUNK - 1, CHUNK, total // 2, total - 1}
640 return sorted(t for t in wanted if 0 <= t < total)
641
642
643def no_pad_equivalence(model, points, unpadded, padded_feed, facts):
644 """`audio-net`'s claim, re-measured on the residue class where it could actually fail.
645
646 They compared the padded-and-masked arm against the unpadded one and found them
647 bit-identical, which is why the second SSCP mask was cancelled. Their first run sampled six
648 frame counts and hit none at `F % 4 == 2`, which is the only residue where the mask does
649 observable work; the re-run covered 50 such cases and still found zero difference.
650
651 This re-runs it as a standing check rather than a fact in a chat message. `unpadded` is the
652 already-computed device arm, so only the padded arm costs a forward pass.
653
654 Returns `(worst, where, victim_gap)`. `victim_gap` is the difference at the token the seam is
655 predicted to corrupt - the last valid one - reported separately because a maximum over 1536
656 channels and every trace point is not evidence about a specific position.
657 """
658 padded = collect(onnx.load_from_string(model.SerializeToString()), points, padded_feed)
659 worst, where, victim_gap = 0.0, "", 0.0
660 victim = facts.get("seam_victim")
661 for label, value in unpadded.items():
662 other = padded.get(label)
663 if other is None:
664 continue
665 a = value.reshape(-1, value.shape[-1])
666 b = other.reshape(-1, other.shape[-1])[: a.shape[0]]
667 if a.shape != b.shape:
668 return float("inf"), f"{label} is {a.shape} against {b.shape}", float("inf")
669 gap = float(np.abs(a - b).max()) if a.size else 0.0
670 if gap > worst:
671 worst, where = gap, label
672 if victim is not None and victim < a.shape[0]:
673 victim_gap = max(victim_gap, float(np.abs(a[victim] - b[victim]).max()))
674 return worst, where, victim_gap
675
676
677def main():
678 ap = argparse.ArgumentParser(description=__doc__)
679 ap.add_argument("onnx", help="audio_encoder_fp16.onnx")
680 ap.add_argument("-o", "--out", required=True)
681 ap.add_argument(
682 "--no-control",
683 action="store_true",
684 help="skip the int4 reference, which is most of the runtime and all of the value",
685 )
686 args = ap.parse_args()
687
688 extractor = load_extractor()
689 base = onnx.load(args.onnx)
690 half, full = require_fp16(base, args.onnx)
691 print(f"{args.onnx}: {half} fp16 initializers, {full} fp32")
692 print("graph inputs: " + ", ".join(
693 f"{n}{d}" for n, (d, _) in graph_inputs(base).items()
694 ))
695 points = trace_points(base)
696 print(f"tracing {len(points)} points, sscp_out = {points['sscp_out']}")
697
698 golden = {"clips": []}
699 for name, real in CLIPS:
700 facts = check_clip(name, real)
701 device_mel, padded_mel, padded_mask = mel_for(extractor, facts)
702 probes = probe_tokens(facts)
703 print(
704 f"\n{name}: {real} samples -> {facts['frames']} mel rows -> T {facts['tokens']}"
705 f", probing {probes}"
706 )
707
708 feed = build_feed(base, device_mel, None)
709 exact = collect(onnx.load(args.onnx), points, feed)
710 entry = dict(facts)
711 entry["probe_tokens"] = probes
712
713 if facts["residue"] == 2:
714 # Every clip in the hazard residue, not one of them: this is the only place the
715 # no-padding shortcut could diverge from the reference, and it is the whole reason
716 # those lengths were chosen. Costs one extra forward pass, since the device arm is
717 # the `exact` run already computed.
718 padded_feed = build_feed(base, padded_mel, padded_mask)
719 gap, where, victim_gap = no_pad_equivalence(base, points, exact, padded_feed, facts)
720 entry["no_pad_max_abs_diff"] = gap
721 entry["no_pad_victim_diff"] = victim_gap
722 verdict = "bit-identical" if gap == 0.0 else f"DIFFERS at {where}"
723 print(
724 f" padded arm vs unpadded: max abs diff {gap:.9f} -> {verdict};"
725 f" at the predicted victim token {facts['seam_victim']}: {victim_gap:.9f}"
726 )
727
728 control = None
729 if not args.no_control:
730 model = onnx.load(args.onnx)
731 touched = quantise_in_place(model)
732 moved, worst_round = fp16_round(model)
733 print(
734 f" {touched} weights through int4; {moved} more tensors moved by fp16 rounding"
735 f" (worst {worst_round:.6g})"
736 )
737 control = collect(model, points, feed)
738
739 # The negative control, on the LONGEST clip because that is where discrimination is
740 # hardest: four bits alone cost more cosine as the layers accumulate, so a bug hides
741 # best in a long clip.
742 #
743 # MEASURED AGAINST THE CONTROL, NOT THE EXACT REFERENCE. That distinction is the whole
744 # lesson of the vision tower. A broken graph reads 0.9565 against the exact reference and
745 # int4 alone reads 0.9626 on this clip - the two OVERLAP, so "cosine against exact" has
746 # no discriminating power at all here. The device is judged against the control, so the
747 # question the negative control has to answer is what a BUG scores against the control.
748 if name == "multi" and control is not None:
749 print(" NEGATIVE CONTROLS, each quantised as the device is, on the longest clip:")
750 print(
751 f" {'perturbation':<36}{'vs exact':>10}{'vs control':>12}"
752 f" where it enters"
753 )
754 golden["negative_controls"] = {}
755 for label, mutate in NEGATIVE_CONTROLS:
756 broken = onnx.load(args.onnx)
757 mutate(broken)
758 quantise_in_place(broken)
759 fp16_round(broken)
760 wrong = collect(broken, points, feed)
761 out_exact = cosine(wrong["audio_features"], exact["audio_features"])
762 out_control = cosine(wrong["audio_features"], control["audio_features"])
763 # WHERE IT FIRST DEPARTS, not where it is worst. Error accumulates through the
764 # stack, so the minimum cosine is always the LAST trace point and says nothing
765 # about origin - my first version reported that and localised every bug to
766 # `encoder_out`, including one confined to layer 6. The first point to fall
767 # below the floor is the one that names the layer.
768 # WHERE IT FIRST DEPARTS FROM 1.0, which is the only statistic that localises.
769 # Two earlier versions of this line were wrong and both looked reasonable:
770 #
771 # the WORST probe always the last one, because error accumulates
772 # the BIGGEST STEP also the last one, because the error GROWS as it goes
773 # first below 0.999 four layers late, because the departure starts at 6e-5
774 #
775 # A correct build reproduces the control exactly, so every probe upstream of the
776 # fault reads 1.000000 and the first one that does not names the layer. Measured:
777 # a fault in layer 6 first departs at layer_in_7, by 5.9e-5, with layer_in_0..6
778 # all exactly 1.0.
779 ordered = [p for p in points if p in wrong and p in control]
780 per_point = [(p, cosine(wrong[p], control[p])) for p in ordered]
781 entered = next((p for p, c in per_point if 1.0 - c > DEPARTURE), "nowhere")
782 worst_point, worst_cosine = min(per_point, key=lambda pair: pair[1])
783 golden["negative_controls"][label] = {
784 "vs_exact": out_exact,
785 "vs_control": out_control,
786 "enters_at": entered,
787 "worst_trace_cosine": worst_cosine,
788 "worst_trace_point": worst_point,
789 "profile": {p: c for p, c in per_point},
790 }
791 print(
792 f" {label:<36}{out_exact:>10.6f}{out_control:>12.6f}"
793 f" enters at {entered}"
794 )
795 if out_control > 0.99 and entered == "nowhere":
796 print(
797 f" WARNING: '{label}' is invisible to BOTH the output and the bisect."
798 " This harness cannot detect it."
799 )
800 elif out_control > 0.99:
801 print(
802 f" NOTE: '{label}' reads {out_control:.6f} at the output, which is"
803 f" above a 0.99 floor. Only the bisect catches it, at {entered}."
804 )
805
806 print(f" {'tensor':<22}{'rows':>7}{'rms':>11}{'int4 vs exact':>16}")
807 for label in list(points) + ["audio_features"]:
808 value = exact.get(label)
809 if value is None:
810 continue
811 flat = value.reshape(-1, value.shape[-1])
812 rows = [p for p in probes if p < flat.shape[0]]
813 entry[label] = flat[rows].reshape(-1).tolist()
814 entry[f"{label}_rows"] = rows
815 note = ""
816 if control is not None and label in control:
817 other = control[label].reshape(-1, control[label].shape[-1])
818 entry[f"{label}_int4"] = other[rows].reshape(-1).tolist()
819 note = f"{cosine(other, value):>16.6f}"
820 print(f" {label:<22}{flat.shape[0]:>7}{float(np.sqrt((value ** 2).mean())):>11.4f}{note}")
821 if control is not None and "audio_features" in control:
822 bar = cosine(control["audio_features"], exact["audio_features"])
823 entry["output_int4_cosine"] = bar
824 print(f" four bits alone cost {1 - bar:.6f} of cosine at the OUTPUT.")
825 golden["clips"].append(entry)
826
827 with open(args.out, "w", encoding="utf-8") as f:
828 json.dump(golden, f)
829 print(f"\nwrote {args.out}")
830
831
832def build_feed(model, mel, mask):
833 """The graph's inputs, filled from a mel block and its row mask.
834
835 Built by inspecting `model.graph.input` rather than by hardcoding names, since a re-export
836 renames freely. Pass `mask=None` for the device's arm, which is all-true over every row it
837 supplies; pass the reference's mask with its padded mel for the other arm.
838 """
839 feed = {}
840 for name, (dims, elem_type) in graph_inputs(model).items():
841 rank = len(dims)
842 if "mask" in name.lower():
843 dtype = onnx.helper.tensor_dtype_to_np_dtype(elem_type)
844 rows = np.ones(mel.shape[0], dtype=bool) if mask is None else mask[: mel.shape[0]]
845 value = rows.astype(dtype)
846 feed[name] = value.reshape((1,) + value.shape + (1,) * (rank - 2))
847 else:
848 feed[name] = mel.reshape((1,) + mel.shape).astype(np.float32)
849 if not feed:
850 raise SystemExit("the graph declares no inputs")
851 return feed
852
853
854if __name__ == "__main__":
855 main()