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_vision_parity.rs

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