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

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

bake_gemma4_prefix.rs355 lines · 14.7 KiBRaw
1//! Precomputes the KV cache for Gemma 4's fixed prompt prefix and writes it to a file.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example bake_gemma4_prefix -- \
5//! gemma4_text.maml gemma4_embed.maml gemma4_tokenizer.spm1 prefix.txt gemma4_prefix.kv
6//! ```
7//!
8//! # Why this exists
9//!
10//! The system block and the tool declarations are ~1,870 positions and they never change. On a
11//! Tensor G4 prefilling them costs about **14 seconds**, and every device pays it on every cold
12//! start, forever, to compute numbers that are identical everywhere.
13//!
14//! They are identical because the inputs are: the same tokens against the same weights. So they
15//! can be computed once, here, and shipped.
16//!
17//! # Not bit-identical, and that is fine
18//!
19//! A desktop GPU and a phone will not produce the same bits - different reduction orders, fp16
20//! rounding. The difference is far inside the noise the int4 weights already carry, and the cache
21//! is not compared against anything, only attended over. What must match exactly is the **token
22//! sequence**, which is why the digest below covers it.
23//!
24//! # The format
25//!
26//! ```text
27//! magic "GKV1" 4 bytes
28//! positions u32
29//! tensors u32 (30: fifteen layers, keys and values)
30//! digest 32 bytes, SHA-256 of the prefix tokens
31//! payload per tensor, in plan order: positions * width fp16 values
32//! ```
33//!
34//! Per tensor rather than one flat arena image, so the file does not depend on arena offsets and
35//! survives being loaded into a different cache tier than it was baked at.
36use std::path::PathBuf;
37use std::sync::Arc;
38
39use modelrunner::nets::gemma4;
40use modelrunner::post::sentencepiece::Table;
41use modelrunner::post::sentencepiece_flavours::GEMMA;
42use modelrunner::vulkan::context;
43use modelrunner::vulkan::reshape::Reshaped;
44use modelrunner::vulkan::run::StepParams;
45use modelrunner::weights::{graph, Weights};
46
47/// Positions one prefill submit covers. As the bridge's, for the same fence reasons.
48const CHUNK: usize = 4096;
49
50/// The markers a rendered prompt may contain. Mirrors `Gemma4Handle.MARKERS`.
51const MARKERS: [&str; 11] = [
52 "<bos>", "<eos>", "<|turn>", "<turn|>", "<|tool>", "<tool|>", "<|tool_call>", "<tool_call|>",
53 "<|tool_response>", "<tool_response|>", "<|\"|>",
54];
55
56/// Whether the text file carries the combine, so plans take raw per-layer rows.
57static FUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
58
59fn gather_in(reader: &modelrunner::weights::Reader<'_>, token: u32) -> Result<(Vec<f32>, Vec<f32>), String> {
60 gemma4::gather_input(reader, token, FUSED.load(std::sync::atomic::Ordering::Relaxed))
61}
62
63fn main() {
64 // Reads gemma4_embed.maml whole (3.6 GB of host RAM): an OOM kernel panic on a Pixel 8.
65 if cfg!(target_os = "android") {
66 println!("bake_gemma4_prefix is host-only: it reads the 3.6 GB embed file whole");
67 return;
68 }
69 let mut args = std::env::args().skip(1);
70 let (Some(text), Some(embed), Some(tokenizer), Some(prefix), Some(out)) =
71 (args.next(), args.next(), args.next(), args.next(), args.next())
72 else {
73 println!(
74 "usage: bake_gemma4_prefix <text.maml> <embed.maml> <table.spm1> <prefix.txt> <out.kv>"
75 );
76 return;
77 };
78 let read = |p: &str| std::fs::read(PathBuf::from(p));
79 let (Ok(text_bytes), Ok(embed_bytes), Ok(table_bytes)) =
80 (read(&text), read(&embed), read(&tokenizer))
81 else {
82 return println!("cannot read the model files");
83 };
84 let Ok(rendered) = std::fs::read_to_string(&prefix) else {
85 return println!("cannot read {prefix}");
86 };
87 let (Ok(weights), Ok(embed_weights)) = (
88 Weights::parse(&text_bytes, graph::GEMMA4_TEXT),
89 Weights::parse(&embed_bytes, graph::GEMMA4_EMBED),
90 ) else {
91 return println!("the weights do not parse");
92 };
93 FUSED.store(gemma4::combines_in_plan(&weights), std::sync::atomic::Ordering::Relaxed);
94 let table = match Table::parse_with(&table_bytes, GEMMA) {
95 Ok(table) => table,
96 Err(why) => return println!("the tokenizer does not parse: {why}"),
97 };
98
99 let tokens = table.encode_with_specials(rendered.trim_end_matches('\n'), &MARKERS);
100 println!("prefix {} chars -> {} positions", rendered.len(), tokens.len());
101 if tokens.is_empty() {
102 return println!("an empty prefix");
103 }
104
105 let context = match context::shared() {
106 Ok(context) => context,
107 Err(why) => return println!("no Vulkan device: {why}"),
108 };
109 // Baked at the top tier so the file covers any device; a smaller tier reads the prefix it
110 // has room for and refuses the rest, which `import_pinned` checks.
111 let tier = gemma4::MAX_CONTEXT;
112 let mut net = match Reshaped::new(Arc::clone(&context), &weights, gemma4::Mode::DecodeStep.at(tier), |o, m| {
113 gemma4::build(o, m)
114 }) {
115 Ok(net) => net,
116 Err(why) => return println!("the model did not open: {why}"),
117 };
118 let reader = embed_weights.reader();
119 let rotary = weights.reader();
120 let (Ok(local), Ok(global)) = (
121 rotary.fp16(gemma4::ROTARY_LOCAL, &[gemma4::MAX_CONTEXT, gemma4::HEAD_DIM]),
122 rotary.fp16(gemma4::ROTARY_GLOBAL, &[gemma4::MAX_CONTEXT, gemma4::GLOBAL_HEAD_DIM]),
123 ) else {
124 return println!("the rotary tables did not load");
125 };
126
127 // Every position, including the last: this is a prefix, not a prompt, so nothing here is a
128 // prediction and the whole thing belongs in the cache.
129 let mut fed = 0usize;
130 for chunk in tokens.chunks(CHUNK) {
131 let width = chunk.len() as u32;
132 let base = fed as u32;
133 let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize];
134 let mut per_layer =
135 vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize];
136 let mut al = vec![0f32; (gemma4::HEAD_DIM * width) as usize];
137 let mut ag = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];
138 for (offset, &token) in chunk.iter().enumerate() {
139 let column = offset as u32;
140 let position = base + column;
141 let Ok((h, p)) = gather_in(&reader, token) else {
142 return println!("token {token} is not in the embedding");
143 };
144 place(&mut hidden, &h, column, width);
145 place(&mut per_layer, &p, column, width);
146 let from = (position * gemma4::HEAD_DIM) as usize;
147 place(&mut al, &local[from..from + gemma4::HEAD_DIM as usize], column, width);
148 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
149 place(&mut ag, &global[from..from + gemma4::GLOBAL_HEAD_DIM as usize], column, width);
150 }
151 let Ok(at) = net.at(gemma4::Mode::Prefill { tokens: width }.at(tier)) else {
152 return println!("the prefill plan did not build");
153 };
154 let _ = at.set_params(StepParams {
155 prefix: base,
156 window_start: base.saturating_sub(gemma4::WINDOW - 1),
157 });
158 if at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).is_err() {
159 return println!("the prefill failed at {base}");
160 }
161 fed += chunk.len();
162 print!("\r {fed} / {} positions", tokens.len());
163 }
164 println!();
165
166 let positions = fed as u32;
167 let payload = match net.at(gemma4::Mode::DecodeStep.at(tier)) {
168 Ok(net) => match net.export_pinned(gemma4::CACHE_TENSORS, positions) {
169 Ok(bytes) => bytes,
170 Err(why) => return println!("the cache did not export: {why}"),
171 },
172 Err(why) => return println!("{why}"),
173 };
174
175 let mut file = Vec::with_capacity(payload.len() + 64);
176 file.extend_from_slice(b"GKV1");
177 file.extend_from_slice(&positions.to_le_bytes());
178 file.extend_from_slice(&(payload.len() as u32 / positions.max(1)).to_le_bytes());
179 file.extend_from_slice(&digest(&tokens));
180 file.extend_from_slice(&payload);
181 // Round-trip it before claiming success. Importing into a *fresh* net and continuing from
182 // the same position must give the same next token as the net that just prefilled it - which
183 // is the only property the app relies on, and the only one worth checking.
184 let expected = argmax_next(&mut net, &reader, &local, &global, tokens[tokens.len() - 1], positions);
185 let mut fresh = match Reshaped::new(Arc::clone(&context), &weights, gemma4::Mode::DecodeStep.at(tier), |o, m| {
186 gemma4::build(o, m)
187 }) {
188 Ok(net) => net,
189 Err(why) => return println!("the check net did not open: {why}"),
190 };
191 match fresh.at(gemma4::Mode::DecodeStep.at(tier)) {
192 Ok(net) => {
193 if let Err(why) = net.import_pinned(gemma4::CACHE_TENSORS, positions, &payload) {
194 return println!("the cache did not import: {why}");
195 }
196 }
197 Err(why) => return println!("{why}"),
198 }
199 // Continue for a while, not one token. One token agreeing only says export and import are
200 // each other's inverse; it says nothing about whether the numbers mean anything to a model
201 // that keeps reading them. A cache that is subtly wrong still produces *a* plausible first
202 // token and then falls apart, which is exactly what shipping this did.
203 let ask = table.encode_with_specials("<turn|>\n<|turn>user\nWhat is 2+2?<turn|>\n<|turn>model\n", &MARKERS);
204 let live = continue_with(&mut net, &reader, &local, &global, &ask, positions, 12);
205 let baked = continue_with(&mut fresh, &reader, &local, &global, &ask, positions, 12);
206 println!(" prefilled continues: {:?}", table.decode(&live));
207 println!(" imported continues: {:?}", table.decode(&baked));
208 if live != baked {
209 println!("MISMATCH: the imported cache does not behave like the prefilled one");
210 }
211 let got = argmax_next(&mut fresh, &reader, &local, &global, tokens[tokens.len() - 1], positions);
212 match (expected, got) {
213 (Some(a), Some(b)) if a == b => println!("round trip ok: both continue with token {a}"),
214 (a, b) => {
215 return println!("ROUND TRIP FAILED: prefilled gives {a:?}, imported gives {b:?}");
216 }
217 }
218
219 match std::fs::write(&out, &file) {
220 Ok(()) => {
221 println!("wrote {out} {:.1} MB", file.len() as f64 / 1e6);
222 println!(" {positions} positions, {} bytes each", payload.len() / positions as usize);
223 }
224 Err(why) => println!("cannot write {out}: {why}"),
225 }
226}
227
228/// Write one position's `values` into column `column` of a `[C, 1, width]` block.
229fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) {
230 for (channel, &value) in values.iter().enumerate() {
231 if let Some(slot) = into.get_mut(channel * width as usize + column as usize) {
232 *slot = value;
233 }
234 }
235}
236
237/// A digest of the token sequence, so a cache cannot be used against a prompt it was not baked
238/// for.
239///
240/// Not cryptographic - FNV-1a widened to 32 bytes. The threat is a stale asset after someone
241/// edits the system prompt, not an adversary: the file ships beside the weights over the same
242/// channel, and anyone who could substitute it could substitute those.
243fn digest(tokens: &[u32]) -> [u8; 32] {
244 let mut out = [0u8; 32];
245 for lane in 0..4usize {
246 let mut hash: u64 = 0xcbf2_9ce4_8422_2325 ^ (lane as u64).wrapping_mul(0x9e37_79b9);
247 for &token in tokens {
248 for byte in token.to_le_bytes() {
249 hash ^= u64::from(byte);
250 hash = hash.wrapping_mul(0x100_0000_01b3);
251 }
252 }
253 out[lane * 8..lane * 8 + 8].copy_from_slice(&hash.to_le_bytes());
254 }
255 out
256}
257
258/// The token this net would produce next, given `token` at `position`.
259fn argmax_next(
260 net: &mut Reshaped<gemma4::Pass>,
261 reader: &modelrunner::weights::Reader<'_>,
262 local: &[f32],
263 global: &[f32],
264 token: u32,
265 position: u32,
266) -> Option<u32> {
267 let (hidden, per_layer) = gather_in(reader, token).ok()?;
268 let from = (position * gemma4::HEAD_DIM) as usize;
269 let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec();
270 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
271 let ag = global[from..from + gemma4::GLOBAL_HEAD_DIM as usize].to_vec();
272 let at = net.at(gemma4::Mode::DecodeStep.at(gemma4::MAX_CONTEXT)).ok()?;
273 at.set_params(StepParams {
274 prefix: position,
275 window_start: position.saturating_sub(gemma4::WINDOW - 1),
276 })
277 .ok()?;
278 let out = at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).ok()?;
279 let mut best = (f32::NEG_INFINITY, 0u32);
280 let mut base = 0u32;
281 for split in out.iter().take(gemma4::HEAD_SPLITS) {
282 for (offset, &value) in split.iter().enumerate() {
283 if value > best.0 {
284 best = (value, base + offset as u32);
285 }
286 }
287 base += split.len() as u32;
288 }
289 Some(best.1)
290}
291
292/// Feed `ask` at `from`, then generate `limit` tokens greedily.
293fn continue_with(
294 net: &mut Reshaped<gemma4::Pass>,
295 reader: &modelrunner::weights::Reader<'_>,
296 local: &[f32],
297 global: &[f32],
298 ask: &[u32],
299 from: u32,
300 limit: usize,
301) -> Vec<u32> {
302 let mut out = Vec::new();
303 let mut at = from;
304 for &token in ask {
305 if argmax_at(net, reader, local, global, token, at).is_none() {
306 return out;
307 }
308 at += 1;
309 }
310 let mut next = *ask.last().unwrap_or(&2);
311 for _ in 0..limit {
312 let Some(token) = argmax_at(net, reader, local, global, next, at) else { break };
313 at += 1;
314 if token == 1 || token == 106 {
315 break;
316 }
317 out.push(token);
318 next = token;
319 }
320 out
321}
322
323/// One decode step, returning the argmax.
324fn argmax_at(
325 net: &mut Reshaped<gemma4::Pass>,
326 reader: &modelrunner::weights::Reader<'_>,
327 local: &[f32],
328 global: &[f32],
329 token: u32,
330 position: u32,
331) -> Option<u32> {
332 let (hidden, per_layer) = gather_in(reader, token).ok()?;
333 let from = (position * gemma4::HEAD_DIM) as usize;
334 let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec();
335 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
336 let ag = global[from..from + gemma4::GLOBAL_HEAD_DIM as usize].to_vec();
337 let at = net.at(gemma4::Mode::DecodeStep.at(gemma4::MAX_CONTEXT)).ok()?;
338 at.set_params(StepParams {
339 prefix: position,
340 window_start: position.saturating_sub(gemma4::WINDOW - 1),
341 })
342 .ok()?;
343 let out = at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).ok()?;
344 let mut best = (f32::NEG_INFINITY, 0u32);
345 let mut base = 0u32;
346 for split in out.iter().take(gemma4::HEAD_SPLITS) {
347 for (offset, &value) in split.iter().enumerate() {
348 if value > best.0 {
349 best = (value, base + offset as u32);
350 }
351 }
352 base += split.len() as u32;
353 }
354 Some(best.1)
355}