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

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

dump_gemma4_hidden.rs78 lines · 3.3 KiBRaw
1//! Dump the decode step's final hidden state for one fixed prompt, as raw fp32.
2//!
3//! `cargo run --offline --release -p modelrunner --example dump_gemma4_hidden -- \
4//! gemma4_text.maml gemma4_embed.maml out.bin`
5//!
6//! Scratch bisect aid: writes 1536 fp32 LE values (the normed hidden state the
7//! tied head consumes). Compare against a numpy ideal-forward to localise a
8//! composition error the argmax gate already caught.
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use modelrunner::nets::gemma4;
13use modelrunner::vulkan::context;
14use modelrunner::vulkan::reshape::Reshaped;
15use modelrunner::vulkan::run::StepParams;
16use modelrunner::weights::{graph, Weights};
17
18const TIER: u32 = gemma4::MAX_CONTEXT;
19const TOKENS: [u32; 6] = [2, 818, 5279, 529, 7001, 563];
20
21fn rotary_row(
22 reader: &modelrunner::weights::Reader<'_>,
23 index: usize,
24 width: u32,
25 position: u32,
26) -> Vec<f32> {
27 let all = reader.fp16(index, &[gemma4::MAX_CONTEXT, width]).unwrap();
28 let from = (position * width) as usize;
29 all[from..from + width as usize].to_vec()
30}
31
32fn main() {
33 // Reads gemma4_embed.maml whole (3.6 GB of host RAM): an OOM kernel panic on a Pixel 8.
34 if cfg!(target_os = "android") {
35 println!("dump_gemma4_hidden is host-only: it reads the 3.6 GB embed file whole");
36 return;
37 }
38 let mut args = std::env::args().skip(1);
39 let (Some(text), Some(embed), Some(out)) = (args.next().map(PathBuf::from), args.next().map(PathBuf::from), args.next())
40 else {
41 println!("usage: dump_gemma4_hidden <text.maml> <embed.maml> <out.bin>");
42 return;
43 };
44 let text_bytes = std::fs::read(&text).unwrap();
45 let embed_bytes = std::fs::read(&embed).unwrap();
46 let weights = Weights::parse(&text_bytes, graph::GEMMA4_TEXT).unwrap();
47 let embed_weights = Weights::parse(&embed_bytes, graph::GEMMA4_EMBED).unwrap();
48 let context = context::shared().unwrap();
49 let mut net = Reshaped::new(
50 Arc::clone(&context),
51 &weights,
52 gemma4::Mode::DecodeStep.at(TIER),
53 |offsets, mode| gemma4::build(offsets, mode),
54 )
55 .unwrap();
56 let reader = embed_weights.reader();
57 let rotary = weights.reader();
58 let mut hidden = Vec::new();
59 for (step, &token) in TOKENS.iter().enumerate() {
60 let position = step as u32;
61 let (hidden_in, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)).unwrap();
62 let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position);
63 let angles_global =
64 rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position);
65 let at = net.at(gemma4::Mode::DecodeStep.at(TIER)).unwrap();
66 at.set_params(StepParams {
67 prefix: position,
68 window_start: position.saturating_sub(gemma4::WINDOW - 1),
69 })
70 .unwrap();
71 let out = at.infer_raw_many(&[&hidden_in, &per_layer, &angles_local, &angles_global]).unwrap();
72 hidden = out.into_iter().next().unwrap_or_default();
73 }
74 println!("hidden len {} rms {:.4}", hidden.len(), (hidden.iter().map(|x| x * x).sum::<f32>() / hidden.len() as f32).sqrt());
75 let bytes: Vec<u8> = hidden.iter().flat_map(|v| v.to_le_bytes()).collect();
76 std::fs::write(&out, bytes).unwrap();
77 println!("wrote {out}");
78}