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

Modern-Apps.git / library / ml / src / main / rust / examples / check_gemma4_audio_parity.rs

check_gemma4_audio_parity.rs487 lines · 21.7 KiBRaw
1//! Runs Gemma 4's audio tower on the GPU and compares it with onnxruntime's.
2//!
3//! ```text
4//! python scripts/ml/gemma4_audio_encoder_parity.py audio_encoder_fp16.onnx -o audio_golden.json
5//! cargo run --offline --release -p modelrunner --example check_gemma4_audio_parity -- \
6//! gemma4_audio.maml audio_golden.json
7//! ```
8//!
9//! # What only this catches
10//!
11//! Until this existed the audio tower had never executed on a GPU in any form. `nets::gemma4_audio`
12//! has twenty unit tests and `vulkan::parity` has ten for the banded ops, and all of them pass —
13//! but the unit tests check that 747 tensors are declared in the order the converter writes them,
14//! and the parity tests check one op against its own oracle. Both are satisfied by a tower whose
15//! twelve layers are composed wrongly.
16//!
17//! # The int4 control is the bar, and it is not optional
18//!
19//! The device runs int4 weights and the export runs fp16 ones, so the two cannot agree closely.
20//! Measured by the generator, four bits alone cost this much cosine at the output:
21//!
22//! ```text
23//! T = 1 0.009 T = 25 0.017 T = 48 0.041
24//! T = 4 0.002 T = 56 0.037
25//! ```
26//!
27//! So against the exact reference a *correct* tower reads anywhere from 0.998 to 0.958 depending
28//! only on how long the clip is, and no fixed floor exists that anyone could set. The control's
29//! value is not that it widens the gap — it is that it makes the correct answer a CONSTANT. Every
30//! comparison below is against `_int4` when the golden carries it.
31//!
32//! # The per-probe bar, which I expected not to exist
33//!
34//! The plan was to print the profile unthresholded, on the reasoning that fp16 Vulkan against
35//! fp32 onnxruntime must drift with depth and no floor could be both tight enough to localise and
36//! loose enough to pass. The first device run disproved that: the drift across twelve layers is
37//! two parts in a million, against negative controls three orders of magnitude further out. So
38//! [`PROBE_FLOOR`] is real and measured, not assumed.
39use std::path::PathBuf;
40use std::sync::Arc;
41
42use modelrunner::logmel::{self, LogMel};
43use modelrunner::nets::gemma4_audio as audio;
44use modelrunner::vulkan::context;
45use modelrunner::vulkan::reshape::Reshaped;
46#[path = "common/gemma4_tower_time.rs"]
47mod tower_time;
48use modelrunner::weights::{graph, Weights};
49
50/// The bar every probe must clear against the int4 control.
51///
52/// I expected this to be impossible to set. The reasoning was that Vulkan fp16 against fp32
53/// onnxruntime must drift with depth, so any threshold tight enough to localise a fault would
54/// fire on a correct run. The first device run disproved it. Measured on `multi`, T = 56:
55///
56/// ```text
57/// layer0_in_projected 1.000000 layer_in_4..9 0.999999 tower_out 0.999998
58/// layer_in_0..3 1.000000 layer_in_10,11 0.999998 encoder_out 0.999998
59/// ```
60///
61/// Two parts in one millionth across twelve layers. The drift is real and monotonic and it is
62/// four orders of magnitude smaller than I assumed. Against that, the generator's three negative
63/// controls read 0.9677, 0.9874 and 0.9111 on the same clip, so this floor sits with roughly
64/// three orders of margin on both sides.
65///
66/// Tighten it if the drift ever comes in lower; do NOT loosen it to accommodate a failure.
67const PROBE_FLOOR: f64 = 0.9995;
68
69/// The bar the output must clear against the int4 control.
70///
71/// Measured rather than chosen. The generator's three negative controls — all twelve relative
72/// tables reversed, layer 6's alone, and q/k swapped — read 0.9677, 0.9874 and 0.9111 against the
73/// same control. A correct device should reach the control almost exactly, so 0.99 sits between
74/// the two populations. Note how little room that leaves: the single-layer fault is at 0.9874, so
75/// a subtler one will sit above this floor and only the profile will show it.
76const OUTPUT_FLOOR: f64 = 0.99;
77
78/// A reproducible sample, bit-identical to `synthetic_pcm` in the generator.
79///
80/// Integer hash to i16 then a divide by 32768, which is exact in binary, so both sides agree to
81/// the bit and the golden carries no waveform.
82fn synthetic_pcm(count: usize) -> Vec<f32> {
83 (0..count)
84 .map(|i| {
85 let mut h = (i as u32).wrapping_mul(73_856_093);
86 h ^= h >> 13;
87 h = h.wrapping_mul(1_274_126_177);
88 h ^= h >> 16;
89 ((h & 0xFFFF) as i32 - 32768) as f32 / 32768.0
90 })
91 .collect()
92}
93
94/// The mel frames for a clip, through this crate's own front end.
95///
96/// Deliberately `logmel` rather than a dump from the golden: it makes the harness end to end, and
97/// `logmel` is already pinned against the same reference extractor to 2.24e-7 of the frame peak,
98/// so it cannot be the source of a disagreement seen here.
99fn mel_for(real: usize) -> Result<(Vec<f32>, u32), String> {
100 let waveform = synthetic_pcm(real);
101 let mut frames = Vec::new();
102 let count = LogMel::new().spectrogram(&waveform, &mut frames);
103 if count != logmel::frame_count(real) {
104 return Err(format!("{count} frames, not {}", logmel::frame_count(real)));
105 }
106 Ok((frames, count as u32))
107}
108
109/// One plan, run once. `outputs` is however many the mode produces.
110fn run(
111 context: &Arc<context::Context>,
112 weights: &Weights,
113 mode: audio::Mode,
114 input: &[f32],
115) -> Result<Vec<Vec<f32>>, String> {
116 let mut net = Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| {
117 audio::build(offsets, mode)
118 })?;
119 net.at(mode)?.infer_raw_many(&[input])
120}
121
122/// Rows `probes` of a `[channels, 1, positions]` tensor, laid out row-major as the golden is.
123fn gather_rows(values: &[f32], positions: usize, channels: usize, probes: &[usize]) -> Vec<f32> {
124 let mut out = Vec::with_capacity(probes.len() * channels);
125 for &position in probes {
126 for channel in 0..channels {
127 out.push(values.get(channel * positions + position).copied().unwrap_or(f32::NAN));
128 }
129 }
130 out
131}
132
133/// Cosine between a device tensor and the reference's.
134fn cosine(got: &[f32], want: &[f32]) -> f64 {
135 if got.len() != want.len() || got.is_empty() {
136 return f64::NAN;
137 }
138 let dot: f64 = got.iter().zip(want).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum();
139 let na: f64 = got.iter().map(|a| f64::from(*a) * f64::from(*a)).sum::<f64>().sqrt();
140 let nb: f64 = want.iter().map(|b| f64::from(*b) * f64::from(*b)).sum::<f64>().sqrt();
141 dot / (na * nb).max(1e-30)
142}
143
144/// The worst single probe token, and which one.
145///
146/// A pooled cosine over six probe rows hides a fault confined to one of them, and the ramp is
147/// exactly such a fault: an unguarded band read corrupts only tokens 0..10, which is 44 % of a
148/// T = 25 clip but 1.5 % of a T = 750 one. The clips that would make it unmissable - T = 1 and
149/// T = 4 - cannot execute, because `MIN_TOKENS` is 12 and the band is the model's rather than
150/// the clip's. So the ramp has to be caught per token instead of per clip, and `probe_tokens`
151/// carries 0, 1, 11 and 12 for that reason.
152fn worst_token(got: &[f32], want: &[f32], probes: &[usize], width: usize) -> (usize, f64) {
153 let mut lowest = (usize::MAX, 1.0_f64);
154 for (row, token) in probes.iter().enumerate() {
155 let (from, to) = (row * width, (row + 1) * width);
156 let (Some(a), Some(b)) = (got.get(from..to), want.get(from..to)) else { continue };
157 let each = cosine(a, b);
158 if each < lowest.1 {
159 lowest = (*token, each);
160 }
161 }
162 lowest
163}
164
165/// Compare one probe point against the control when there is one, else the exact reference.
166///
167/// Returns `(line, cosine, measured_against_control)`. The third matters: a cosine against the
168/// exact reference is not comparable to [`OUTPUT_FLOOR`], because four bits alone move it by up
169/// to 0.04 and the amount depends on the clip's length.
170fn against(got: &[f32], clip: &str, label: &str, golden: &str) -> (String, f64, bool) {
171 let Some(exact) = field(golden, clip, label) else {
172 return (format!("{label}: absent from the golden"), f64::NAN, false);
173 };
174 let exact_cosine = cosine(got, &exact);
175 match field(golden, clip, &format!("{label}_int4")) {
176 Some(control) => {
177 let c = cosine(got, &control);
178 (format!("int4 {c:.6} (exact {exact_cosine:.6})"), c, true)
179 }
180 None => (format!("exact {exact_cosine:.6} NO CONTROL"), exact_cosine, false),
181 }
182}
183
184/// `--time N`: the clip pass at `seconds` of synthetic audio, built once and run `N` times.
185fn time_clip(
186 context: &Arc<context::Context>,
187 weights: &Weights,
188 seconds: f64,
189 repeats: usize,
190) -> Result<(), String> {
191 let real = ((seconds * 16_000.0) as usize).min(audio::MAX_SAMPLES);
192 let (mel, frames) = mel_for(real)?;
193 let input = audio::prepare(&mel, frames)?;
194 let mode = audio::Mode::Clip { frames };
195 println!();
196 println!("=== {seconds} s: {frames} frames, T {}", audio::tokens(frames));
197 let tick = std::time::Instant::now();
198 let mut net = Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| {
199 audio::build(offsets, mode)
200 })?;
201 println!("clip net built in {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0);
202 tower_time::time_runs(&mut net, mode, &[&input], repeats)
203}
204
205fn main() {
206 let mut args = std::env::args().skip(1);
207 let (Some(model), Some(path)) = (args.next().map(PathBuf::from), args.next()) else {
208 println!(
209 "usage: check_gemma4_audio_parity <gemma4_audio.maml> <audio_golden.json> [--time N]"
210 );
211 return;
212 };
213 let repeats = match (args.next().as_deref(), args.next()) {
214 (Some("--time"), n) => Some(n.and_then(|n| n.parse().ok()).unwrap_or(3)),
215 _ => None,
216 };
217 let bytes = match std::fs::read(&model) {
218 Ok(bytes) => bytes,
219 Err(why) => return println!("cannot read {}: {why}", model.display()),
220 };
221 let weights = match Weights::parse(&bytes, graph::GEMMA4_AUDIO) {
222 Ok(w) => w,
223 Err(why) => return println!("the audio model does not parse: {why}"),
224 };
225 if weights.len() != audio::TENSORS {
226 return println!("{} tensors, not {}", weights.len(), audio::TENSORS);
227 }
228 let golden = match std::fs::read_to_string(&path) {
229 Ok(text) => text,
230 Err(why) => return println!("cannot read the golden: {why}"),
231 };
232 let context = match context::shared() {
233 Ok(context) => context,
234 Err(why) => return println!("no Vulkan device: {why}"),
235 };
236 if let Some(repeats) = repeats {
237 for seconds in [5.0, 30.0] {
238 if let Err(why) = time_clip(&context, &weights, seconds, repeats) {
239 println!("timing {seconds} s failed: {why}");
240 }
241 }
242 return;
243 }
244
245 let mut worst = (1.0_f64, String::new());
246 let mut any_control = false;
247 for clip in clips(&golden) {
248 let (Some(real), Some(want_frames), Some(want_tokens)) = (
249 scalar(&golden, &clip, "real"),
250 scalar(&golden, &clip, "frames"),
251 scalar(&golden, &clip, "tokens"),
252 ) else {
253 println!("{clip}: incomplete entry, skipped");
254 continue;
255 };
256 let probes = field_usize(&golden, &clip, "probe_tokens").unwrap_or_default();
257 println!();
258 println!("=== {clip}: {real} samples, {want_frames} frames, T {want_tokens}");
259
260 let (mel, frames) = match mel_for(real) {
261 Ok(pair) => pair,
262 Err(why) => {
263 println!(" the front end failed: {why}");
264 continue;
265 }
266 };
267 if frames != want_frames as u32 {
268 println!(" FRAME COUNT DISAGREES: {frames} here, {want_frames} in the golden");
269 continue;
270 }
271 let input = match audio::prepare(&mel, frames) {
272 Ok(input) => input,
273 Err(why) => {
274 println!(" prepare failed: {why}");
275 continue;
276 }
277 };
278 let tokens = audio::tokens(frames) as usize;
279 if tokens != want_tokens {
280 println!(" TOKEN COUNT DISAGREES: {tokens} here, {want_tokens} in the golden");
281 continue;
282 }
283 // The module refuses a clip shorter than the attention band, and it is right to: the band
284 // is a property of the model, not of the clip. So the two short cases in the golden - the
285 // T = 1 and T = 4 clips chosen to sit entirely inside the start-of-sequence ramp - cannot
286 // execute here at all, and this says so once instead of failing fifteen times.
287 //
288 // The ramp is still covered. Queries 0..10 of EVERY clip are on it, and `probe_tokens`
289 // includes 0, 1, 11 and 12 precisely to straddle its boundary.
290 if tokens < audio::MIN_TOKENS as usize {
291 println!(
292 " skipped: T {tokens} is under MIN_TOKENS {}, which the 12-wide band requires.",
293 audio::MIN_TOKENS
294 );
295 println!(
296 " the ramp it was chosen for is still probed at tokens 0, 1, 11, 12 elsewhere"
297 );
298 continue;
299 }
300
301 // The front end. Only `projected` is compared: the device's `sscp_out` is in a PERMUTED
302 // channel order relative to the export's, because the converter permutes the input
303 // projection's rows (`input_rows` in `collect_gemma4_audio`) and the projection undoes it.
304 // Measured: sscp_out reads 0.29 against the golden while projected reads 1.000000 on the
305 // same run, which is the permutation and not a fault. Comparing it would need the golden
306 // to carry the permutation, which it does not.
307 match run(&context, &weights, audio::Mode::Sscp { frames }, &input) {
308 Ok(out) => {
309 let Some(values) = out.get(1) else {
310 println!(" Sscp produced no projected output");
311 continue;
312 };
313 let got = gather_rows(values, tokens, audio::D_MODEL as usize, &probes);
314 let (line, c, controlled) = against(&got, &clip, "layer0_in_projected", &golden);
315 any_control |= controlled;
316 println!(" {:<22} {line}", "layer0_in_projected");
317 println!(
318 " {:<22} not compared: permuted channel order, see the source",
319 "sscp_out"
320 );
321 if c < worst.0 {
322 worst = (c, format!("{clip}/layer0_in_projected"));
323 }
324 }
325 Err(why) => println!(" Sscp failed: {why}"),
326 }
327
328 // The layer sweep, on the two extremes only. Every stop point re-records the plan, so
329 // thirteen of them per clip is the expensive part of this harness; `tiny` is the
330 // start-of-sequence ramp where every query is on the edge, and `multi` is the longest and
331 // the one where int4 costs the most, which is where a fault hides best.
332 if clip == "multi" || clip == "tiny" {
333 for layer in 0..=audio::LAYERS {
334 let mode = audio::Mode::Trace { frames, layers: layer };
335 let label = if layer == audio::LAYERS {
336 "tower_out".to_string()
337 } else {
338 format!("layer_in_{layer}")
339 };
340 match run(&context, &weights, mode, &input) {
341 Ok(out) => {
342 let Some(hidden) = out.first() else { continue };
343 let got = gather_rows(hidden, tokens, audio::D_MODEL as usize, &probes);
344 let (line, c, controlled) = against(&got, &clip, &label, &golden);
345 any_control |= controlled;
346 println!(" {label:<22} {line}");
347 if c < worst.0 {
348 worst = (c, format!("{clip}/{label}"));
349 }
350 if layer == audio::LAYERS {
351 if let Some(tail) = out.get(1) {
352 let got =
353 gather_rows(tail, tokens, audio::OUT_DIM as usize, &probes);
354 let (line, c, _) = against(&got, &clip, "encoder_out", &golden);
355 println!(" {:<22} {line}", "encoder_out");
356 if c < worst.0 {
357 worst = (c, format!("{clip}/encoder_out"));
358 }
359 }
360 }
361 }
362 Err(why) => println!(" {label:<22} failed: {why}"),
363 }
364 }
365 }
366
367 // The output, which is the only figure with a floor under it.
368 match run(&context, &weights, audio::Mode::Clip { frames }, &input) {
369 Ok(out) => {
370 let Some(features) = out.first() else {
371 println!(" the clip pass produced no output");
372 continue;
373 };
374 let all: Vec<usize> = (0..tokens).collect();
375 let whole = gather_rows(features, tokens, audio::OUT_DIM as usize, &all);
376 let got = gather_rows(features, tokens, audio::OUT_DIM as usize, &probes);
377 let (line, c, controlled) = against(&got, &clip, "audio_features", &golden);
378 any_control |= controlled;
379 let verdict = if !controlled {
380 "NO CONTROL, unreadable"
381 } else if c > OUTPUT_FLOOR {
382 "ok"
383 } else {
384 "WRONG"
385 };
386 println!(" {:<22} {line} {verdict}", "audio_features");
387 // Per token, because the ramp is a fault in tokens 0..10 only and the pooled
388 // figure above averages it away. This is the check that stands in for the T = 1
389 // clip the module will not run.
390 let bar = field(&golden, &clip, "audio_features_int4")
391 .or_else(|| field(&golden, &clip, "audio_features"));
392 if let Some(bar) = bar {
393 let (token, each) = worst_token(&got, &bar, &probes, audio::OUT_DIM as usize);
394 let ramp =
395 if token < audio::ATTEND_SPAN as usize { " ON THE RAMP" } else { "" };
396 let mark = if each > OUTPUT_FLOOR { "ok" } else { "WRONG" };
397 println!(
398 " {:<22} token {token} at {each:.6} {mark}{ramp}",
399 "worst probe token"
400 );
401 if each < worst.0 {
402 worst = (each, format!("{clip}/token {token}"));
403 }
404 }
405 let _ = whole;
406 }
407 Err(why) => println!(" the clip pass failed: {why}"),
408 }
409 }
410
411 println!();
412 if !any_control {
413 println!("NOTE: the golden carries no int4 control, so nothing above can tell a bug from");
414 println!(" four bits. Regenerate the golden without --no-control.");
415 return;
416 }
417 let verdict = if worst.0 > PROBE_FLOOR { "PASS" } else { "FAIL" };
418 println!("worst probe {:.6} at {} floor {PROBE_FLOOR} {verdict}", worst.0, worst.1);
419 println!();
420 if worst.0 > PROBE_FLOOR {
421 println!("The tower is as close to the reference as four bits allow, at every probe.");
422 println!("For scale: the generator's negative controls read 0.9677 (all twelve relative");
423 println!("tables reversed), 0.9874 (layer 6's alone) and 0.9111 (q/k swapped) against the");
424 println!("same control. A composition error is three orders of magnitude away from here.");
425 } else {
426 println!("This is a composition error, not quantisation. Read the profile above: the");
427 println!("first probe to fall names the layer AFTER the fault. Smooth and monotonic is");
428 println!("quantisation; a step at one layer is not.");
429 }
430}
431
432/// The clip names in the golden, in order.
433fn clips(text: &str) -> Vec<String> {
434 let mut out = Vec::new();
435 let mut at = 0usize;
436 while let Some(found) = text[at..].find("\"name\":") {
437 let start = at + found + "\"name\":".len();
438 let rest = text[start..].trim_start();
439 if let Some(stripped) = rest.strip_prefix('"') {
440 if let Some(end) = stripped.find('"') {
441 out.push(stripped[..end].to_string());
442 }
443 }
444 at = start;
445 }
446 out
447}
448
449/// The slice of the golden belonging to `clip`, so a key lookup cannot cross into another one.
450fn slice<'a>(text: &'a str, clip: &str) -> Option<&'a str> {
451 let start = text.find(&format!("\"name\": \"{clip}\""))?;
452 let rest = &text[start + 1..];
453 let end = rest.find("\"name\":").map_or(text.len(), |n| start + 1 + n);
454 Some(&text[start..end])
455}
456
457/// One `"key": number` from a clip's slice.
458fn scalar(text: &str, clip: &str, key: &str) -> Option<usize> {
459 let body = slice(text, clip)?;
460 let at = body.find(&format!("\"{key}\""))?;
461 let rest = &body[at..];
462 let colon = rest.find(':')?;
463 rest[colon + 1..]
464 .trim_start()
465 .split(|c: char| !c.is_ascii_digit())
466 .next()
467 .and_then(|n| n.parse().ok())
468}
469
470/// One named array of floats from a clip's slice.
471fn field(text: &str, clip: &str, key: &str) -> Option<Vec<f32>> {
472 Some(array(slice(text, clip)?, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())
473}
474
475/// One named array of indices from a clip's slice.
476fn field_usize(text: &str, clip: &str, key: &str) -> Option<Vec<usize>> {
477 Some(array(slice(text, clip)?, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())
478}
479
480/// The text between the brackets of `"key": [...]`, matching the key exactly.
481fn array<'a>(text: &'a str, key: &str) -> Option<&'a str> {
482 let at = text.find(&format!("\"{key}\": ["))?;
483 let rest = &text[at..];
484 let open = rest.find('[')?;
485 let close = rest[open..].find(']')?;
486 Some(&rest[open + 1..open + close])
487}