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

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

dump_dev_caches.rs92 lines · 3.9 KiBRaw
1//! Export the KV caches after feeding the golden tokens, one layer at a time.
2//!
3//! Drives the decode net for TOKENS (prefill-style, position by position) and
4//! writes each owning layer's K and V cache rows for the fed positions as raw
5//! fp16 LE: `dev_caches/layer{L}_{k,v}.bin`, each `[positions, head_dim]`.
6//! Compare against analysis/prove_sign/ref_caches/layer{L}_{k,v}.npy (int8,
7//! [1,1,32003,head_dim] K / [1,1,head_dim,32003] V) after dequantising.
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use modelrunner::nets::gemma4;
12use modelrunner::vulkan::context;
13use modelrunner::vulkan::reshape::Reshaped;
14use modelrunner::vulkan::run::StepParams;
15use modelrunner::weights::{graph, Weights};
16
17const TIER: u32 = gemma4::MAX_CONTEXT;
18const TOKENS: [u32; 6] = [2, 818, 5279, 529, 7001, 563];
19
20fn rotary_row(
21 reader: &modelrunner::weights::Reader<'_>,
22 index: usize,
23 width: u32,
24 position: u32,
25) -> Vec<f32> {
26 let all = reader.fp16(index, &[gemma4::MAX_CONTEXT, width]).unwrap();
27 let from = (position * width) as usize;
28 all[from..from + width as usize].to_vec()
29}
30
31fn main() {
32 let mut args = std::env::args().skip(1);
33 let (Some(text), Some(embed), Some(outdir)) =
34 (args.next().map(PathBuf::from), args.next().map(PathBuf::from), args.next())
35 else {
36 println!("usage: dump_dev_caches <text.maml> <embed.maml> <outdir>");
37 return;
38 };
39 let text_bytes = std::fs::read(&text).unwrap();
40 let embed_bytes = std::fs::read(&embed).unwrap();
41 let weights = Weights::parse(&text_bytes, graph::GEMMA4_TEXT).unwrap();
42 let embed_weights = Weights::parse(&embed_bytes, graph::GEMMA4_EMBED).unwrap();
43 let context = context::shared().unwrap();
44 let mut net = Reshaped::new(
45 Arc::clone(&context),
46 &weights,
47 gemma4::Mode::DecodeStep.at(TIER),
48 |offsets, mode| gemma4::build(offsets, mode),
49 )
50 .unwrap();
51 let reader = embed_weights.reader();
52 let rotary = weights.reader();
53 for (step, &token) in TOKENS.iter().enumerate() {
54 let position = step as u32;
55 let (hidden_in, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)).unwrap();
56 let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position);
57 let angles_global =
58 rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position);
59 let at = net.at(gemma4::Mode::DecodeStep.at(TIER)).unwrap();
60 at.set_params(StepParams {
61 prefix: position,
62 window_start: position.saturating_sub(gemma4::WINDOW - 1),
63 })
64 .unwrap();
65 at.infer_raw_many(&[&hidden_in, &per_layer, &angles_local, &angles_global]).unwrap();
66 }
67 // Pinned layout: CACHE_TENSORS K/V pairs per owning layer. Read back via
68 // export_pinned and split per the cache shapes in gemma4.rs.
69 let at = net.at(gemma4::Mode::DecodeStep.at(TIER)).unwrap();
70 let bytes = at
71 .export_pinned(gemma4::CACHE_TENSORS, TOKENS.len() as u32)
72 .unwrap();
73 std::fs::create_dir_all(&outdir).unwrap();
74 // Walk the pinned list in order; each cache contributes positions*width fp16.
75 // Widths: layer i owns dim(i) head-dim (256 sliding, 512 full), K then V.
76 let mut at_byte = 0usize;
77 let mut manifest = String::new();
78 for layer in 0..gemma4::OWNS_CACHE_LAYERS {
79 let dim = gemma4::head_dim(layer) as usize;
80 for kind in ["k", "v"] {
81 let count = TOKENS.len() * dim;
82 let span = count * 2;
83 let chunk = &bytes[at_byte..at_byte + span];
84 let path = format!("{outdir}/layer{layer}_{kind}.bin");
85 std::fs::write(&path, chunk).unwrap();
86 manifest.push_str(&format!("layer{layer}_{kind} dim={dim}\n"));
87 at_byte += span;
88 }
89 }
90 std::fs::write(format!("{outdir}/manifest.txt"), manifest).unwrap();
91 println!("exported {at_byte} bytes of {len} total", len = bytes.len());
92}