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

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

check_gemma4_vision_parity.rs393 lines · 15.8 KiBRaw
1//! Runs Gemma 4's vision tower on the GPU and compares it with onnxruntime's.
2//!
3//! ```text
4//! python scripts/ml/gemma4_vision_parity.py vision_encoder_fp16.onnx -o vision_golden.json
5//! cargo run --offline --release -p modelrunner --example check_gemma4_vision_parity -- \
6//! gemma4_vision.maml vision_golden.json
7//! ```
8//!
9//! # What only this catches
10//!
11//! `nets::gemma4_vision`'s unit tests check that 637 tensors are declared in the order the
12//! converter writes them, that a grid divides by the pooling kernel, that a pixel lands in the
13//! channel the export's patchify would put it. All of that passes on a tower that is wrong,
14//! because a transposed read agrees with itself.
15//!
16//! Sixteen layers against real weights catch errors of *composition*, and this tower has four
17//! that no shape would notice:
18//!
19//! * the two learned position tables swapped, so every image is transposed;
20//! * the two rotary blocks swapped, likewise;
21//! * `1 / sqrt(head_dim)` applied when the export applies none, flattening all sixteen layers;
22//! * a clip dropped, which moves values fp16 was calibrated to hold.
23//!
24//! The golden is generated on a **33 x 18** patch grid precisely so the first two are visible. On
25//! a square grid they are not.
26//!
27//! # What agreement to expect
28//!
29//! The reference is fp16 weights in fp32 arithmetic; this is int4 weights with a per-block scale,
30//! and the worst tensor's conversion fidelity was 0.9927. So the numbers will not match, and the
31//! bar is a cosine that stays near one *and does not fall as the layers accumulate*. A wrong
32//! composition does not drift, it steps.
33use std::path::PathBuf;
34use std::sync::Arc;
35
36use modelrunner::nets::gemma4_vision as vision;
37use modelrunner::vulkan::context;
38use modelrunner::vulkan::reshape::Reshaped;
39#[path = "common/gemma4_tower_time.rs"]
40mod tower_time;
41use modelrunner::weights::{graph, Weights};
42
43/// A reproducible byte for pixel `(y, x)`, channel `(0, 1, 2)` = `(r, g, b)`.
44///
45/// Must stay bit-identical to `synthetic_pixel` in `scripts/ml/gemma4_vision_parity.py`, which is
46/// how the two sides agree on an image without the golden carrying one. A hash rather than a
47/// gradient because a linear ramp is nearly rank-one, and a rank-one input hides exactly the
48/// errors above.
49fn synthetic_pixel(y: u32, x: u32, channel: u32) -> u32 {
50 let mut h =
51 y.wrapping_mul(73_856_093) ^ x.wrapping_mul(19_349_663) ^ channel.wrapping_mul(83_492_791);
52 h ^= h >> 13;
53 h = h.wrapping_mul(1_274_126_177);
54 h ^= h >> 16;
55 h & 0xff
56}
57
58/// The whole image as ARGB_8888, which is what [`vision::patchify`] takes.
59fn synthetic_image(grid: vision::Grid) -> Vec<i32> {
60 let (width, height) = grid.pixels();
61 let mut pixels = Vec::with_capacity((width * height) as usize);
62 for y in 0..height {
63 for x in 0..width {
64 let argb = 0xff00_0000
65 | (synthetic_pixel(y, x, 0) << 16)
66 | (synthetic_pixel(y, x, 1) << 8)
67 | synthetic_pixel(y, x, 2);
68 pixels.push(argb as i32);
69 }
70 }
71 pixels
72}
73
74fn main() {
75 let mut args = std::env::args().skip(1);
76 let (Some(model), Some(golden)) = (args.next().map(PathBuf::from), args.next()) else {
77 println!("usage: check_gemma4_vision_parity <vision.maml> <vision_golden.json> [--time N]");
78 return;
79 };
80 let repeats = match (args.next().as_deref(), args.next()) {
81 (Some("--time"), n) => Some(n.and_then(|n| n.parse().ok()).unwrap_or(3)),
82 _ => None,
83 };
84 let bytes = match std::fs::read(&model) {
85 Ok(bytes) => bytes,
86 Err(why) => return println!("cannot read {}: {why}", model.display()),
87 };
88 let weights = match Weights::parse(&bytes, graph::GEMMA4_VISION) {
89 Ok(w) => w,
90 Err(why) => return println!("the vision model does not parse: {why}"),
91 };
92 if weights.len() != vision::TENSORS {
93 return println!("{} tensors, not {}", weights.len(), vision::TENSORS);
94 }
95 let golden = match std::fs::read_to_string(&golden) {
96 Ok(text) => text,
97 Err(why) => return println!("cannot read the golden: {why}"),
98 };
99 let (Some(rows), Some(cols)) = (scalar(&golden, "rows"), scalar(&golden, "cols")) else {
100 return println!("the golden has no grid");
101 };
102 let grid = match vision::Grid::new(rows, cols) {
103 Ok(grid) => grid,
104 Err(why) => return println!("the golden's grid is not one this builds: {why}"),
105 };
106 println!(
107 "grid {}x{} patches = {} patches, {} soft tokens",
108 grid.rows,
109 grid.cols,
110 grid.patches(),
111 grid.soft_tokens()
112 );
113 if grid.rows == grid.cols {
114 println!("WARNING: a square grid cannot tell a row from a column");
115 }
116
117 let context = match context::shared() {
118 Ok(context) => context,
119 Err(why) => return println!("no Vulkan device: {why}"),
120 };
121 let pixels = synthetic_image(grid);
122 let inputs = match vision::prepare(&weights.reader(), grid, &pixels) {
123 Ok(inputs) => inputs,
124 Err(why) => return println!("the host preprocessing failed: {why}"),
125 };
126 if let Some(repeats) = repeats {
127 let mode = vision::Mode::Image(grid);
128 let tick = std::time::Instant::now();
129 let built = Reshaped::new(Arc::clone(&context), &weights, mode, |offsets, mode| {
130 vision::build(offsets, mode)
131 });
132 let mut net = match built {
133 Ok(net) => net,
134 Err(why) => return println!("the image net does not build: {why}"),
135 };
136 println!("image net built in {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0);
137 if let Err(why) =
138 tower_time::time_runs(&mut net, mode, &[&inputs[0], &inputs[1], &inputs[2]], repeats)
139 {
140 println!("timing failed: {why}");
141 }
142 return;
143 }
144
145 // Bisect first: a whole-tower disagreement is much easier to read once the layers below it
146 // have been placed.
147 println!();
148 println!("bisect against the reference's intermediates");
149 println!(" exact = the export as published, int4 = the same weights through four bits");
150 let mut worst = 1.0_f64;
151 let mut labels: Vec<(String, usize)> =
152 (0..vision::LAYERS).map(|i| (format!("layer_in_{i}"), i)).collect();
153 labels.push(("tower_out".to_string(), vision::LAYERS));
154 for (label, layers) in labels {
155 let (Some(exact), Some(probes)) =
156 (field(&golden, &label), field_usize(&golden, &format!("{label}_rows")))
157 else {
158 continue;
159 };
160 match trace(&context, &weights, grid, layers, &inputs) {
161 Ok((hidden, _)) => {
162 let got = gather_rows(
163 &hidden,
164 grid.patches() as usize,
165 vision::D_MODEL as usize,
166 &probes,
167 );
168 let control = field(&golden, &format!("{label}_int4"));
169 let (line, cosine) = against(&got, &exact, control.as_deref(), TRACE_FLOOR);
170 worst = worst.min(cosine);
171 println!(" {label:<12} {line}");
172 }
173 Err(why) => println!(" {label:<12} failed: {why}"),
174 }
175 }
176 if let (Some(exact), Some(probes)) =
177 (field(&golden, "pooled_in"), field_usize(&golden, "pooled_in_rows"))
178 {
179 match trace(&context, &weights, grid, vision::LAYERS, &inputs) {
180 Ok((_, pooled)) => {
181 let got = gather_rows(
182 &pooled,
183 grid.soft_tokens() as usize,
184 vision::D_MODEL as usize,
185 &probes,
186 );
187 let control = field(&golden, "pooled_in_int4");
188 let (line, cosine) = against(&got, &exact, control.as_deref(), TRACE_FLOOR);
189 worst = worst.min(cosine);
190 println!(" {:<12} {line}", "pooled_in");
191 }
192 Err(why) => println!(" {:<12} failed: {why}", "pooled_in"),
193 }
194 }
195
196 println!();
197 let Some(exact) = field(&golden, "image_features") else {
198 return println!("the golden has no image_features");
199 };
200 let control = field(&golden, "image_features_int4");
201 match run(&context, &weights, grid, &inputs) {
202 Ok(features) => report(&features, &exact, control.as_deref(), grid, worst),
203 Err(why) => println!("the image pass failed: {why}"),
204 }
205}
206
207/// Compare against the exact reference and, when it is in the golden, the int4 control.
208///
209/// The returned cosine is the one that decides: against the control if there is one, since that
210/// is the only bar the device can actually meet. See `gemma4_vision_parity.py`.
211fn against(got: &[f32], exact: &[f32], control: Option<&[f32]>, floor: f64) -> (String, f64) {
212 let (exact_line, exact_cosine) = compare(got, exact);
213 match control {
214 None => (format!("exact {exact_line}"), exact_cosine),
215 Some(control) => {
216 let (_line, cosine) = compare(got, control);
217 let verdict = if cosine > floor { "ok" } else { "WRONG" };
218 (
219 format!(
220 "int4 cosine {cosine:.6} {verdict} (exact {exact_cosine:.6}, \
221 which four bits alone cost)"
222 ),
223 cosine,
224 )
225 }
226 }
227}
228
229/// Rows `probes` of a `[channels, 1, positions]` tensor, laid out row-major as the golden is.
230fn gather_rows(values: &[f32], positions: usize, channels: usize, probes: &[usize]) -> Vec<f32> {
231 let mut out = Vec::with_capacity(probes.len() * channels);
232 for &position in probes {
233 for channel in 0..channels {
234 out.push(values.get(channel * positions + position).copied().unwrap_or(f32::NAN));
235 }
236 }
237 out
238}
239
240/// The tower stopped after `layers` layers: `(hidden, pooled)`.
241fn trace(
242 context: &Arc<context::Context>,
243 weights: &Weights,
244 grid: vision::Grid,
245 layers: usize,
246 inputs: &[Vec<f32>; vision::INPUTS],
247) -> Result<(Vec<f32>, Vec<f32>), String> {
248 let mode = vision::Mode::Trace { grid, layers };
249 let mut net = Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| {
250 vision::build(offsets, mode)
251 })?;
252 let out = net.at(mode)?.infer_raw_many(&[&inputs[0], &inputs[1], &inputs[2]])?;
253 let mut it = out.into_iter();
254 Ok((it.next().unwrap_or_default(), it.next().unwrap_or_default()))
255}
256
257/// The whole pass: `[soft_tokens, 1536]`, laid out row-major as the golden is.
258fn run(
259 context: &Arc<context::Context>,
260 weights: &Weights,
261 grid: vision::Grid,
262 inputs: &[Vec<f32>; vision::INPUTS],
263) -> Result<Vec<f32>, String> {
264 let mode = vision::Mode::Image(grid);
265 let mut net = Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| {
266 vision::build(offsets, mode)
267 })?;
268 let out = net.at(mode)?.infer_raw_many(&[&inputs[0], &inputs[1], &inputs[2]])?;
269 let features = out.into_iter().next().ok_or("the plan produced no output")?;
270 let tokens = grid.soft_tokens() as usize;
271 let width = vision::OUT_DIM as usize;
272 if features.len() != tokens * width {
273 return Err(format!("{} values, not {}", features.len(), tokens * width));
274 }
275 // The plan writes `[1536, 1, tokens]`; the golden is `[tokens, 1536]`.
276 Ok(gather_rows(&features, tokens, width, &(0..tokens).collect::<Vec<_>>()))
277}
278
279/// Cosine and RMS between a device tensor and the reference's.
280fn compare(got: &[f32], want: &[f32]) -> (String, f64) {
281 if got.len() != want.len() {
282 return (format!("length {} against {}", got.len(), want.len()), 0.0);
283 }
284 let dot: f64 = got.iter().zip(want).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum();
285 let na: f64 = got.iter().map(|a| f64::from(*a) * f64::from(*a)).sum::<f64>().sqrt();
286 let nb: f64 = want.iter().map(|b| f64::from(*b) * f64::from(*b)).sum::<f64>().sqrt();
287 let cosine = dot / (na * nb).max(1e-30);
288 let n = got.len() as f64;
289 let verdict = if cosine > 0.99 { "ok" } else { "WRONG" };
290 (
291 format!(
292 "cosine {cosine:.6} rms {:.4} against {:.4} {verdict}",
293 na / n.sqrt(),
294 nb / n.sqrt()
295 ),
296 cosine,
297 )
298}
299
300/// The bar an intermediate must clear against the int4 control.
301///
302/// The measured values sit at 0.99999 through the tower, so this is loose by two orders of
303/// magnitude and still nowhere near what a composition error produces. Measured, by building the
304/// same tower with `attn_scores` instead of `attn_scores_prescaled`: `tower_out` falls to 0.444
305/// and the output to 0.635. There is no overlap between the two populations.
306const TRACE_FLOOR: f64 = 0.9995;
307
308/// The bar the output must clear, which is looser than [`TRACE_FLOOR`] on purpose.
309///
310/// The arena is fp16 and the pooled state has an RMS near 1100, so the final norm and the
311/// `[1536, 768]` projection accumulate 768 terms at a magnitude where fp16's step is about half a
312/// unit. That is real rounding the control does not model, since onnxruntime accumulates in fp32.
313const OUTPUT_FLOOR: f64 = 0.998;
314
315/// The bar the worst single soft token must clear. One bad token hides inside a whole-tensor
316/// cosine, and a soft token is what the decoder actually reads.
317const TOKEN_FLOOR: f64 = 0.99;
318
319/// Print the comparison, and say plainly whether it passed.
320fn report(
321 got: &[f32],
322 exact: &[f32],
323 control: Option<&[f32]>,
324 grid: vision::Grid,
325 worst_trace: f64,
326) {
327 let (line, cosine) = against(got, exact, control, OUTPUT_FLOOR);
328 println!("image_features {line}");
329 if got.len() != exact.len() {
330 return println!("FAIL: the shapes do not even agree");
331 }
332 let bar = control.unwrap_or(exact);
333
334 // Per-soft-token cosine, because one bad token hides inside a whole-tensor cosine.
335 let width = vision::OUT_DIM as usize;
336 let mut lowest = (0usize, 1.0_f64);
337 for token in 0..grid.soft_tokens() as usize {
338 let a = &got[token * width..(token + 1) * width];
339 let b = &bar[token * width..(token + 1) * width];
340 let dot: f64 = a.iter().zip(b).map(|(x, y)| f64::from(*x) * f64::from(*y)).sum();
341 let na: f64 = a.iter().map(|x| f64::from(*x) * f64::from(*x)).sum::<f64>().sqrt();
342 let nb: f64 = b.iter().map(|y| f64::from(*y) * f64::from(*y)).sum::<f64>().sqrt();
343 let each = dot / (na * nb).max(1e-30);
344 if each < lowest.1 {
345 lowest = (token, each);
346 }
347 }
348 println!("worst soft token {} at cosine {:.6}", lowest.0, lowest.1);
349
350 println!();
351 if control.is_none() {
352 println!("NOTE: the golden has no int4 control, so this is measured against fp16 weights");
353 println!(" and cannot tell a bug from four bits. Regenerate without --no-control.");
354 return;
355 }
356 if cosine > OUTPUT_FLOOR && lowest.1 > TOKEN_FLOOR && worst_trace > TRACE_FLOOR {
357 println!("PASS: the vision tower is as close to the reference as four bits allow");
358 } else {
359 println!("FAIL: this is a composition error, not quantisation");
360 println!(" the bisect above says which layer it enters at");
361 }
362}
363
364/// One `"key": number` from the golden.
365fn scalar(text: &str, key: &str) -> Option<u32> {
366 let at = text.find(&format!("\"{key}\""))?;
367 let rest = &text[at..];
368 let colon = rest.find(':')?;
369 rest[colon + 1..]
370 .trim_start()
371 .split(|c: char| !c.is_ascii_digit())
372 .next()
373 .and_then(|n| n.parse().ok())
374}
375
376/// One named array from the golden.
377fn field(text: &str, key: &str) -> Option<Vec<f32>> {
378 Some(array(text, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())
379}
380
381/// One named array of indices from the golden.
382fn field_usize(text: &str, key: &str) -> Option<Vec<usize>> {
383 Some(array(text, key)?.split(',').filter_map(|p| p.trim().parse().ok()).collect())
384}
385
386/// The text between the brackets of `"key": [...]`.
387fn array<'a>(text: &'a str, key: &str) -> Option<&'a str> {
388 let at = text.find(&format!("\"{key}\""))?;
389 let rest = &text[at..];
390 let open = rest.find('[')?;
391 let close = rest[open..].find(']')?;
392 Some(&rest[open + 1..open + close])
393}