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

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

check_gemma4_audio_parity.rs473 lines · 21.5 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(context: &Arc<context::Context>, weights: &Weights, seconds: f64, repeats: usize) -> Result<(), String> {
186 let real = ((seconds * 16_000.0) as usize).min(audio::MAX_SAMPLES);
187 let (mel, frames) = mel_for(real)?;
188 let input = audio::prepare(&mel, frames)?;
189 let mode = audio::Mode::Clip { frames };
190 println!();
191 println!("=== {seconds} s: {frames} frames, T {}", audio::tokens(frames));
192 let tick = std::time::Instant::now();
193 let mut net = Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| audio::build(offsets, mode))?;
194 println!("clip net built in {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0);
195 tower_time::time_runs(&mut net, mode, &[&input], repeats)
196}
197
198fn main() {
199 let mut args = std::env::args().skip(1);
200 let (Some(model), Some(path)) = (args.next().map(PathBuf::from), args.next()) else {
201 println!("usage: check_gemma4_audio_parity <gemma4_audio.maml> <audio_golden.json> [--time N]");
202 return;
203 };
204 let repeats = match (args.next().as_deref(), args.next()) {
205 (Some("--time"), n) => Some(n.and_then(|n| n.parse().ok()).unwrap_or(3)),
206 _ => None,
207 };
208 let bytes = match std::fs::read(&model) {
209 Ok(bytes) => bytes,
210 Err(why) => return println!("cannot read {}: {why}", model.display()),
211 };
212 let weights = match Weights::parse(&bytes, graph::GEMMA4_AUDIO) {
213 Ok(w) => w,
214 Err(why) => return println!("the audio model does not parse: {why}"),
215 };
216 if weights.len() != audio::TENSORS {
217 return println!("{} tensors, not {}", weights.len(), audio::TENSORS);
218 }
219 let golden = match std::fs::read_to_string(&path) {
220 Ok(text) => text,
221 Err(why) => return println!("cannot read the golden: {why}"),
222 };
223 let context = match context::shared() {
224 Ok(context) => context,
225 Err(why) => return println!("no Vulkan device: {why}"),
226 };
227 if let Some(repeats) = repeats {
228 for seconds in [5.0, 30.0] {
229 if let Err(why) = time_clip(&context, &weights, seconds, repeats) {
230 println!("timing {seconds} s failed: {why}");
231 }
232 }
233 return;
234 }
235
236 let mut worst = (1.0_f64, String::new());
237 let mut any_control = false;
238 for clip in clips(&golden) {
239 let (Some(real), Some(want_frames), Some(want_tokens)) = (
240 scalar(&golden, &clip, "real"),
241 scalar(&golden, &clip, "frames"),
242 scalar(&golden, &clip, "tokens"),
243 ) else {
244 println!("{clip}: incomplete entry, skipped");
245 continue;
246 };
247 let probes = field_usize(&golden, &clip, "probe_tokens").unwrap_or_default();
248 println!();
249 println!("=== {clip}: {real} samples, {want_frames} frames, T {want_tokens}");
250
251 let (mel, frames) = match mel_for(real) {
252 Ok(pair) => pair,
253 Err(why) => {
254 println!(" the front end failed: {why}");
255 continue;
256 }
257 };
258 if frames != want_frames as u32 {
259 println!(" FRAME COUNT DISAGREES: {frames} here, {want_frames} in the golden");
260 continue;
261 }
262 let input = match audio::prepare(&mel, frames) {
263 Ok(input) => input,
264 Err(why) => {
265 println!(" prepare failed: {why}");
266 continue;
267 }
268 };
269 let tokens = audio::tokens(frames) as usize;
270 if tokens != want_tokens {
271 println!(" TOKEN COUNT DISAGREES: {tokens} here, {want_tokens} in the golden");
272 continue;
273 }
274 // The module refuses a clip shorter than the attention band, and it is right to: the band
275 // is a property of the model, not of the clip. So the two short cases in the golden - the
276 // T = 1 and T = 4 clips chosen to sit entirely inside the start-of-sequence ramp - cannot
277 // execute here at all, and this says so once instead of failing fifteen times.
278 //
279 // The ramp is still covered. Queries 0..10 of EVERY clip are on it, and `probe_tokens`
280 // includes 0, 1, 11 and 12 precisely to straddle its boundary.
281 if tokens < audio::MIN_TOKENS as usize {
282 println!(
283 " skipped: T {tokens} is under MIN_TOKENS {}, which the 12-wide band requires.",
284 audio::MIN_TOKENS
285 );
286 println!(" the ramp it was chosen for is still probed at tokens 0, 1, 11, 12 elsewhere");
287 continue;
288 }
289
290 // The front end. Only `projected` is compared: the device's `sscp_out` is in a PERMUTED
291 // channel order relative to the export's, because the converter permutes the input
292 // projection's rows (`input_rows` in `collect_gemma4_audio`) and the projection undoes it.
293 // Measured: sscp_out reads 0.29 against the golden while projected reads 1.000000 on the
294 // same run, which is the permutation and not a fault. Comparing it would need the golden
295 // to carry the permutation, which it does not.
296 match run(&context, &weights, audio::Mode::Sscp { frames }, &input) {
297 Ok(out) => {
298 let Some(values) = out.get(1) else {
299 println!(" Sscp produced no projected output");
300 continue;
301 };
302 let got = gather_rows(values, tokens, audio::D_MODEL as usize, &probes);
303 let (line, c, controlled) = against(&got, &clip, "layer0_in_projected", &golden);
304 any_control |= controlled;
305 println!(" {:<22} {line}", "layer0_in_projected");
306 println!(" {:<22} not compared: permuted channel order, see the source", "sscp_out");
307 if c < worst.0 {
308 worst = (c, format!("{clip}/layer0_in_projected"));
309 }
310 }
311 Err(why) => println!(" Sscp failed: {why}"),
312 }
313
314 // The layer sweep, on the two extremes only. Every stop point re-records the plan, so
315 // thirteen of them per clip is the expensive part of this harness; `tiny` is the
316 // start-of-sequence ramp where every query is on the edge, and `multi` is the longest and
317 // the one where int4 costs the most, which is where a fault hides best.
318 if clip == "multi" || clip == "tiny" {
319 for layer in 0..=audio::LAYERS {
320 let mode = audio::Mode::Trace { frames, layers: layer };
321 let label = if layer == audio::LAYERS {
322 "tower_out".to_string()
323 } else {
324 format!("layer_in_{layer}")
325 };
326 match run(&context, &weights, mode, &input) {
327 Ok(out) => {
328 let Some(hidden) = out.first() else { continue };
329 let got = gather_rows(hidden, tokens, audio::D_MODEL as usize, &probes);
330 let (line, c, controlled) = against(&got, &clip, &label, &golden);
331 any_control |= controlled;
332 println!(" {label:<22} {line}");
333 if c < worst.0 {
334 worst = (c, format!("{clip}/{label}"));
335 }
336 if layer == audio::LAYERS {
337 if let Some(tail) = out.get(1) {
338 let got =
339 gather_rows(tail, tokens, audio::OUT_DIM as usize, &probes);
340 let (line, c, _) = against(&got, &clip, "encoder_out", &golden);
341 println!(" {:<22} {line}", "encoder_out");
342 if c < worst.0 {
343 worst = (c, format!("{clip}/encoder_out"));
344 }
345 }
346 }
347 }
348 Err(why) => println!(" {label:<22} failed: {why}"),
349 }
350 }
351 }
352
353 // The output, which is the only figure with a floor under it.
354 match run(&context, &weights, audio::Mode::Clip { frames }, &input) {
355 Ok(out) => {
356 let Some(features) = out.first() else {
357 println!(" the clip pass produced no output");
358 continue;
359 };
360 let all: Vec<usize> = (0..tokens).collect();
361 let whole = gather_rows(features, tokens, audio::OUT_DIM as usize, &all);
362 let got = gather_rows(features, tokens, audio::OUT_DIM as usize, &probes);
363 let (line, c, controlled) = against(&got, &clip, "audio_features", &golden);
364 any_control |= controlled;
365 let verdict = if !controlled {
366 "NO CONTROL, unreadable"
367 } else if c > OUTPUT_FLOOR {
368 "ok"
369 } else {
370 "WRONG"
371 };
372 println!(" {:<22} {line} {verdict}", "audio_features");
373 // Per token, because the ramp is a fault in tokens 0..10 only and the pooled
374 // figure above averages it away. This is the check that stands in for the T = 1
375 // clip the module will not run.
376 let bar = field(&golden, &clip, "audio_features_int4")
377 .or_else(|| field(&golden, &clip, "audio_features"));
378 if let Some(bar) = bar {
379 let (token, each) =
380 worst_token(&got, &bar, &probes, audio::OUT_DIM as usize);
381 let ramp = if token < audio::ATTEND_SPAN as usize { " ON THE RAMP" } else { "" };
382 let mark = if each > OUTPUT_FLOOR { "ok" } else { "WRONG" };
383 println!(
384 " {:<22} token {token} at {each:.6} {mark}{ramp}",
385 "worst probe token"
386 );
387 if each < worst.0 {
388 worst = (each, format!("{clip}/token {token}"));
389 }
390 }
391 let _ = whole;
392 }
393 Err(why) => println!(" the clip pass failed: {why}"),
394 }
395 }
396
397 println!();
398 if !any_control {
399 println!("NOTE: the golden carries no int4 control, so nothing above can tell a bug from");
400 println!(" four bits. Regenerate the golden without --no-control.");
401 return;
402 }
403 let verdict = if worst.0 > PROBE_FLOOR { "PASS" } else { "FAIL" };
404 println!("worst probe {:.6} at {} floor {PROBE_FLOOR} {verdict}", worst.0, worst.1);
405 println!();
406 if worst.0 > PROBE_FLOOR {
407 println!("The tower is as close to the reference as four bits allow, at every probe.");
408 println!("For scale: the generator's negative controls read 0.9677 (all twelve relative");
409 println!("tables reversed), 0.9874 (layer 6's alone) and 0.9111 (q/k swapped) against the");
410 println!("same control. A composition error is three orders of magnitude away from here.");
411 } else {
412 println!("This is a composition error, not quantisation. Read the profile above: the");
413 println!("first probe to fall names the layer AFTER the fault. Smooth and monotonic is");
414 println!("quantisation; a step at one layer is not.");
415 }
416}
417
418/// The clip names in the golden, in order.
419fn clips(text: &str) -> Vec<String> {
420 let mut out = Vec::new();
421 let mut at = 0usize;
422 while let Some(found) = text[at..].find("\"name\":") {
423 let start = at + found + "\"name\":".len();
424 let rest = text[start..].trim_start();
425 if let Some(stripped) = rest.strip_prefix('"') {
426 if let Some(end) = stripped.find('"') {
427 out.push(stripped[..end].to_string());
428 }
429 }
430 at = start;
431 }
432 out
433}
434
435/// The slice of the golden belonging to `clip`, so a key lookup cannot cross into another one.
436fn slice<'a>(text: &'a str, clip: &str) -> Option<&'a str> {
437 let start = text.find(&format!("\"name\": \"{clip}\""))?;
438 let rest = &text[start + 1..];
439 let end = rest.find("\"name\":").map_or(text.len(), |n| start + 1 + n);
440 Some(&text[start..end])
441}
442
443/// One `"key": number` from a clip's slice.
444fn scalar(text: &str, clip: &str, key: &str) -> Option<usize> {
445 let body = slice(text, clip)?;
446 let at = body.find(&format!("\"{key}\""))?;
447 let rest = &body[at..];
448 let colon = rest.find(':')?;
449 rest[colon + 1..]
450 .trim_start()
451 .split(|c: char| !c.is_ascii_digit())
452 .next()
453 .and_then(|n| n.parse().ok())
454}
455
456/// One named array of floats from a clip's slice.
457fn field(text: &str, clip: &str, key: &str) -> Option<Vec<f32>> {
458 Some(array(slice(text, clip)?, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())
459}
460
461/// One named array of indices from a clip's slice.
462fn field_usize(text: &str, clip: &str, key: &str) -> Option<Vec<usize>> {
463 Some(array(slice(text, clip)?, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())
464}
465
466/// The text between the brackets of `"key": [...]`, matching the key exactly.
467fn array<'a>(text: &'a str, key: &str) -> Option<&'a str> {
468 let at = text.find(&format!("\"{key}\": ["))?;
469 let rest = &text[at..];
470 let open = rest.find('[')?;
471 let close = rest[open..].find(']')?;
472 Some(&rest[open + 1..open + close])
473}