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

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

probe_gemma4.rs216 lines · 9.4 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 modelrunner::nets::{gemma4, gemma4_head, gemma4_vision};
22use modelrunner::weights::{graph, Blob, Weights};
23use std::path::PathBuf;
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!(
125 " {} ops, {} inputs, {} outputs",
126 plan.ops.len(),
127 plan.inputs.len(),
128 plan.outputs.len()
129 );
130 let classes: u32 = plan.outputs.iter().map(|b| b.shape.c).sum();
131 println!(" {classes} logits over {} splits", plan.outputs.len());
132 println!(" {:.1} MB of arena", f64::from(plan.arena_elems) * 2.0 / 1e6);
133 }
134 Err(why) => println!("the GPU head plan does NOT build: {why}"),
135 }
136 match gemma4_head::build_plan_greedy(&embed) {
137 Ok(plan) => {
138 println!("the greedy head plan builds against the real table");
139 println!(
140 " {} ops, {} inputs, {} outputs",
141 plan.ops.len(),
142 plan.inputs.len(),
143 plan.outputs.len()
144 );
145 for (i, o) in plan.outputs.iter().enumerate() {
146 println!(" out[{i}]: c={} h={} w={}", o.shape.c, o.shape.h, o.shape.w);
147 }
148 }
149 Err(why) => println!("the greedy head plan does NOT build: {why}"),
150 }
151
152 // The vision tower, if it is beside the other two.
153 if let Some(path) = std::env::args().nth(3).map(PathBuf::from) {
154 // A square image, which is the grid the reference resize picks for a 1:1 aspect ratio.
155 let grid =
156 match gemma4_vision::Grid::for_image(1024, 1024, gemma4_vision::DEFAULT_SOFT_TOKENS) {
157 Ok(grid) => grid,
158 Err(why) => {
159 println!("no grid for a square image: {why}");
160 return;
161 }
162 };
163 match std::fs::read(&path).ok().and_then(|bytes| {
164 Weights::parse(&bytes, graph::GEMMA4_VISION).ok().map(|w| {
165 let tensors = w.tensors().len();
166 let plan = gemma4_vision::build(&w, gemma4_vision::Mode::Image(grid));
167 (
168 tensors,
169 plan.map(|p| (p.ops.len(), p.inputs.len(), p.outputs.len(), p.arena_elems)),
170 )
171 })
172 }) {
173 Some((tensors, plan)) => {
174 println!();
175 println!("vision {}", path.display());
176 println!("tensors {tensors} (the module expects {})", gemma4_vision::TENSORS);
177 println!(
178 "grid {}x{} patches -> {} soft tokens",
179 grid.rows,
180 grid.cols,
181 grid.soft_tokens()
182 );
183 match plan {
184 Ok((ops, ins, outs, arena)) => {
185 println!(" the image plan builds against the real table");
186 println!(" {ops} ops, {ins} inputs, {outs} outputs");
187 println!(" {:.1} MB of arena", f64::from(arena) * 2.0 / 1e6);
188 }
189 Err(why) => println!(" the image plan does NOT build: {why}"),
190 }
191 }
192 None => println!("the vision file does not parse"),
193 }
194 }
195
196 let reader = embed.reader();
197 // `<bos>` is 2, and 105 is an ordinary piece. A placeholder is included because it takes the
198 // masked path, which is the one a gather written from the shapes alone would get wrong.
199 for token in [2u32, 105, gemma4::embed::PLACEHOLDERS[0]] {
200 match gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)) {
201 Ok((hidden, per_layer)) => {
202 let rms =
203 |v: &[f32]| (v.iter().map(|x| x * x).sum::<f32>() / v.len() as f32).sqrt();
204 println!(
205 " token {token:>6}: embedding {} values rms {:.4}, per-layer {} values \
206 rms {:.4}",
207 hidden.len(),
208 rms(&hidden),
209 per_layer.len(),
210 rms(&per_layer)
211 );
212 }
213 Err(why) => println!(" token {token}: {why}"),
214 }
215 }
216}