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

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

dump_gemma4_hidden.rs85 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)) =
40 (args.next().map(PathBuf::from), args.next().map(PathBuf::from), args.next())
41 else {
42 println!("usage: dump_gemma4_hidden <text.maml> <embed.maml> <out.bin>");
43 return;
44 };
45 let text_bytes = std::fs::read(&text).unwrap();
46 let embed_bytes = std::fs::read(&embed).unwrap();
47 let weights = Weights::parse(&text_bytes, graph::GEMMA4_TEXT).unwrap();
48 let embed_weights = Weights::parse(&embed_bytes, graph::GEMMA4_EMBED).unwrap();
49 let context = context::shared().unwrap();
50 let mut net = Reshaped::new(
51 Arc::clone(&context),
52 &weights,
53 gemma4::Mode::DecodeStep.at(TIER),
54 |offsets, mode| gemma4::build(offsets, mode),
55 )
56 .unwrap();
57 let reader = embed_weights.reader();
58 let rotary = weights.reader();
59 let mut hidden = Vec::new();
60 for (step, &token) in TOKENS.iter().enumerate() {
61 let position = step as u32;
62 let (hidden_in, per_layer) =
63 gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)).unwrap();
64 let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position);
65 let angles_global =
66 rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position);
67 let at = net.at(gemma4::Mode::DecodeStep.at(TIER)).unwrap();
68 at.set_params(StepParams {
69 prefix: position,
70 window_start: position.saturating_sub(gemma4::WINDOW - 1),
71 })
72 .unwrap();
73 let out =
74 at.infer_raw_many(&[&hidden_in, &per_layer, &angles_local, &angles_global]).unwrap();
75 hidden = out.into_iter().next().unwrap_or_default();
76 }
77 println!(
78 "hidden len {} rms {:.4}",
79 hidden.len(),
80 (hidden.iter().map(|x| x * x).sum::<f32>() / hidden.len() as f32).sqrt()
81 );
82 let bytes: Vec<u8> = hidden.iter().flat_map(|v| v.to_le_bytes()).collect();
83 std::fs::write(&out, bytes).unwrap();
84 println!("wrote {out}");
85}