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

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

probe_gemma4.rs205 lines · 9.1 KiBRaw
1//! Parses a converted Gemma 4 `.maml` and builds its decode plan against the real tensor table.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example probe_gemma4 -- <file.maml>
5//! ```
6//!
7//! # What this checks that the layout tests cannot
8//!
9//! `nets::gemma4`'s tests assert the ordered table against `nets::tests::Shapes`, a stub that
10//! hands back whatever index it is asked for. That catches a net walking its own span wrongly,
11//! and cannot catch the net and the **converter** disagreeing - both sides would have to be wrong
12//! in the same way, but nothing forces them to be right in the same way either.
13//!
14//! This resolves every tensor against a file `maml_convert.py` actually wrote: each `shaped` call
15//! checks the requested dims against the table, so a transposed kernel, a scale of the wrong
16//! rank, or a layer at the wrong offset is refused here rather than producing a plan that runs
17//! and is wrong.
18//!
19//! It does **not** check the numbers. That needs a reference run, which needs the tokenizer and
20//! the embedding export; see `check_nllb_parity.rs` for the shape that takes.
21use std::path::PathBuf;
22use modelrunner::nets::{gemma4, gemma4_head, gemma4_vision};
23use modelrunner::weights::{graph, Blob, Weights};
24/// The cache these examples record against: the top tier, so a long prompt fits.
25const TIER: u32 = gemma4::MAX_CONTEXT;
26fn main() {
27 // Reads gemma4_embed.maml whole (3.6 GB of host RAM): an OOM kernel panic on a Pixel 8.
28 if cfg!(target_os = "android") {
29 println!("probe_gemma4 is host-only: it reads the 3.6 GB embed file whole");
30 return;
31 }
32 let Some(path) = std::env::args().nth(1).map(PathBuf::from) else {
33 println!("usage: probe_gemma4 <gemma4_text.maml> [gemma4_embed.maml]");
34 return;
35 };
36 let bytes = match std::fs::read(&path) {
37 Ok(bytes) => bytes,
38 Err(why) => {
39 println!("cannot read {}: {why}", path.display());
40 return;
41 }
42 };
43 println!("file {} {:.2} GB", path.display(), bytes.len() as f64 / 1e9);
44
45 let weights = match Weights::parse(&bytes, graph::GEMMA4_TEXT) {
46 Ok(weights) => weights,
47 Err(why) => {
48 println!("parse failed: {why}");
49 return;
50 }
51 };
52 println!("tensors {} (the module expects {})", weights.tensors().len(), gemma4::TENSORS);
53 println!("data {:.2} GB", weights.data().len() as f64 / 1e9);
54 if weights.tensors().len() != gemma4::TENSORS {
55 println!("MISMATCH: the converter and nets::gemma4 disagree about the table's length");
56 return;
57 }
58
59 match gemma4::build(&weights, gemma4::Mode::DecodeStep.at(TIER)) {
60 Ok(plan) => {
61 println!();
62 println!("the decode plan builds against the real table");
63 println!(" {} ops", plan.ops.len());
64 println!(" {} inputs, {} outputs", plan.inputs.len(), plan.outputs.len());
65 println!(" {:.1} MB of arena", f64::from(plan.arena_elems) * 2.0 / 1e6);
66 let classes: u32 = plan.outputs.iter().map(|b| b.shape.c).sum();
67 println!(" {classes} logits over {} splits", plan.outputs.len());
68 {
69 use std::collections::BTreeMap;
70 let mut tally: BTreeMap<String, usize> = BTreeMap::new();
71 for op in &plan.ops {
72 let name = match op {
73 modelrunner::nets::Op::Dispatch { kind, .. } => format!("{kind:?}"),
74 modelrunner::nets::Op::Copy { .. } => "Copy".to_string(),
75 };
76 *tally.entry(name).or_default() += 1;
77 }
78 let mut rows: Vec<_> = tally.into_iter().collect();
79 rows.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
80 println!(" ops by kind, {} total:", plan.ops.len());
81 for (name, n) in rows {
82 println!(" {n:5} {:6.2} per layer {name}", n as f64 / 35.0);
83 }
84 }
85 println!(" {} pinned", plan.pinned.len());
86 for (i, b) in plan.pinned.iter().take(3).enumerate() {
87 println!(" pinned {i}: c={} h={} w={}", b.shape.c, b.shape.h, b.shape.w);
88 }
89 }
90 Err(why) => println!("the decode plan does NOT build: {why}"),
91 }
92
93 // The embedding, if it is beside the text model. Its own file and its own graph id.
94 let Some(embed_path) = std::env::args().nth(2).map(PathBuf::from) else {
95 println!();
96 println!("pass the embedding .maml as a second argument to exercise the host gather");
97 return;
98 };
99 let embed_bytes = match std::fs::read(&embed_path) {
100 Ok(bytes) => bytes,
101 Err(why) => {
102 println!("cannot read {}: {why}", embed_path.display());
103 return;
104 }
105 };
106 let embed = match Weights::parse(&embed_bytes, graph::GEMMA4_EMBED) {
107 Ok(weights) => weights,
108 Err(why) => {
109 println!("the embedding does not parse: {why}");
110 return;
111 }
112 };
113 println!();
114 println!("embedding {} {:.2} GB", embed_path.display(), embed_bytes.len() as f64 / 1e9);
115 println!(
116 "tensors {} (fp16 chunks: {} / int8 chunks: {})",
117 embed.tensors().len(),
118 gemma4_head::TENSORS_WITH_HEAD,
119 gemma4_head::TENSORS_WITH_HEAD8,
120 );
121 match gemma4_head::build_plan(&embed) {
122 Ok(plan) => {
123 println!("the GPU head plan builds against the real table");
124 println!(" {} ops, {} inputs, {} outputs", plan.ops.len(), plan.inputs.len(), plan.outputs.len());
125 let classes: u32 = plan.outputs.iter().map(|b| b.shape.c).sum();
126 println!(" {classes} logits over {} splits", plan.outputs.len());
127 println!(" {:.1} MB of arena", f64::from(plan.arena_elems) * 2.0 / 1e6);
128 }
129 Err(why) => println!("the GPU head plan does NOT build: {why}"),
130 }
131 match gemma4_head::build_plan_greedy(&embed) {
132 Ok(plan) => {
133 println!("the greedy head plan builds against the real table");
134 println!(" {} ops, {} inputs, {} outputs", plan.ops.len(), plan.inputs.len(), plan.outputs.len());
135 for (i, o) in plan.outputs.iter().enumerate() {
136 println!(" out[{i}]: c={} h={} w={}", o.shape.c, o.shape.h, o.shape.w);
137 }
138 }
139 Err(why) => println!("the greedy head plan does NOT build: {why}"),
140 }
141
142 // The vision tower, if it is beside the other two.
143 if let Some(path) = std::env::args().nth(3).map(PathBuf::from) {
144 // A square image, which is the grid the reference resize picks for a 1:1 aspect ratio.
145 let grid = match gemma4_vision::Grid::for_image(
146 1024,
147 1024,
148 gemma4_vision::DEFAULT_SOFT_TOKENS,
149 ) {
150 Ok(grid) => grid,
151 Err(why) => {
152 println!("no grid for a square image: {why}");
153 return;
154 }
155 };
156 match std::fs::read(&path).ok().and_then(|bytes| {
157 Weights::parse(&bytes, graph::GEMMA4_VISION).ok().map(|w| {
158 let tensors = w.tensors().len();
159 let plan = gemma4_vision::build(&w, gemma4_vision::Mode::Image(grid));
160 (tensors, plan.map(|p| (p.ops.len(), p.inputs.len(), p.outputs.len(), p.arena_elems)))
161 })
162 }) {
163 Some((tensors, plan)) => {
164 println!();
165 println!("vision {}", path.display());
166 println!("tensors {tensors} (the module expects {})", gemma4_vision::TENSORS);
167 println!(
168 "grid {}x{} patches -> {} soft tokens",
169 grid.rows,
170 grid.cols,
171 grid.soft_tokens()
172 );
173 match plan {
174 Ok((ops, ins, outs, arena)) => {
175 println!(" the image plan builds against the real table");
176 println!(" {ops} ops, {ins} inputs, {outs} outputs");
177 println!(" {:.1} MB of arena", f64::from(arena) * 2.0 / 1e6);
178 }
179 Err(why) => println!(" the image plan does NOT build: {why}"),
180 }
181 }
182 None => println!("the vision file does not parse"),
183 }
184 }
185
186 let reader = embed.reader();
187 // `<bos>` is 2, and 105 is an ordinary piece. A placeholder is included because it takes the
188 // masked path, which is the one a gather written from the shapes alone would get wrong.
189 for token in [2u32, 105, gemma4::embed::PLACEHOLDERS[0]] {
190 match gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)) {
191 Ok((hidden, per_layer)) => {
192 let rms = |v: &[f32]| (v.iter().map(|x| x * x).sum::<f32>() / v.len() as f32).sqrt();
193 println!(
194 " token {token:>6}: embedding {} values rms {:.4}, per-layer {} values \
195 rms {:.4}",
196 hidden.len(),
197 rms(&hidden),
198 per_layer.len(),
199 rms(&per_layer)
200 );
201 }
202 Err(why) => println!(" token {token}: {why}"),
203 }
204 }
205}