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

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

bake_gemma4_prefix.rs378 lines · 14.8 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>",
53 "<eos>",
54 "<|turn>",
55 "<turn|>",
56 "<|tool>",
57 "<tool|>",
58 "<|tool_call>",
59 "<tool_call|>",
60 "<|tool_response>",
61 "<tool_response|>",
62 "<|\"|>",
63];
64
65/// Whether the text file carries the combine, so plans take raw per-layer rows.
66static FUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
67
68fn gather_in(
69 reader: &modelrunner::weights::Reader<'_>,
70 token: u32,
71) -> Result<(Vec<f32>, Vec<f32>), String> {
72 gemma4::gather_input(reader, token, FUSED.load(std::sync::atomic::Ordering::Relaxed))
73}
74
75fn main() {
76 // Reads gemma4_embed.maml whole (3.6 GB of host RAM): an OOM kernel panic on a Pixel 8.
77 if cfg!(target_os = "android") {
78 println!("bake_gemma4_prefix is host-only: it reads the 3.6 GB embed file whole");
79 return;
80 }
81 let mut args = std::env::args().skip(1);
82 let (Some(text), Some(embed), Some(tokenizer), Some(prefix), Some(out)) =
83 (args.next(), args.next(), args.next(), args.next(), args.next())
84 else {
85 println!(
86 "usage: bake_gemma4_prefix <text.maml> <embed.maml> <table.spm1> <prefix.txt> <out.kv>"
87 );
88 return;
89 };
90 let read = |p: &str| std::fs::read(PathBuf::from(p));
91 let (Ok(text_bytes), Ok(embed_bytes), Ok(table_bytes)) =
92 (read(&text), read(&embed), read(&tokenizer))
93 else {
94 return println!("cannot read the model files");
95 };
96 let Ok(rendered) = std::fs::read_to_string(&prefix) else {
97 return println!("cannot read {prefix}");
98 };
99 let (Ok(weights), Ok(embed_weights)) = (
100 Weights::parse(&text_bytes, graph::GEMMA4_TEXT),
101 Weights::parse(&embed_bytes, graph::GEMMA4_EMBED),
102 ) else {
103 return println!("the weights do not parse");
104 };
105 FUSED.store(gemma4::combines_in_plan(&weights), std::sync::atomic::Ordering::Relaxed);
106 let table = match Table::parse_with(&table_bytes, GEMMA) {
107 Ok(table) => table,
108 Err(why) => return println!("the tokenizer does not parse: {why}"),
109 };
110
111 let tokens = table.encode_with_specials(rendered.trim_end_matches('\n'), &MARKERS);
112 println!("prefix {} chars -> {} positions", rendered.len(), tokens.len());
113 if tokens.is_empty() {
114 return println!("an empty prefix");
115 }
116
117 let context = match context::shared() {
118 Ok(context) => context,
119 Err(why) => return println!("no Vulkan device: {why}"),
120 };
121 // Baked at the top tier so the file covers any device; a smaller tier reads the prefix it
122 // has room for and refuses the rest, which `import_pinned` checks.
123 let tier = gemma4::MAX_CONTEXT;
124 let mut net = match Reshaped::new(
125 Arc::clone(&context),
126 &weights,
127 gemma4::Mode::DecodeStep.at(tier),
128 |o, m| gemma4::build(o, m),
129 ) {
130 Ok(net) => net,
131 Err(why) => return println!("the model did not open: {why}"),
132 };
133 let reader = embed_weights.reader();
134 let rotary = weights.reader();
135 let (Ok(local), Ok(global)) = (
136 rotary.fp16(gemma4::ROTARY_LOCAL, &[gemma4::MAX_CONTEXT, gemma4::HEAD_DIM]),
137 rotary.fp16(gemma4::ROTARY_GLOBAL, &[gemma4::MAX_CONTEXT, gemma4::GLOBAL_HEAD_DIM]),
138 ) else {
139 return println!("the rotary tables did not load");
140 };
141
142 // Every position, including the last: this is a prefix, not a prompt, so nothing here is a
143 // prediction and the whole thing belongs in the cache.
144 let mut fed = 0usize;
145 for chunk in tokens.chunks(CHUNK) {
146 let width = chunk.len() as u32;
147 let base = fed as u32;
148 let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize];
149 let mut per_layer =
150 vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize];
151 let mut al = vec![0f32; (gemma4::HEAD_DIM * width) as usize];
152 let mut ag = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];
153 for (offset, &token) in chunk.iter().enumerate() {
154 let column = offset as u32;
155 let position = base + column;
156 let Ok((h, p)) = gather_in(&reader, token) else {
157 return println!("token {token} is not in the embedding");
158 };
159 place(&mut hidden, &h, column, width);
160 place(&mut per_layer, &p, column, width);
161 let from = (position * gemma4::HEAD_DIM) as usize;
162 place(&mut al, &local[from..from + gemma4::HEAD_DIM as usize], column, width);
163 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
164 place(&mut ag, &global[from..from + gemma4::GLOBAL_HEAD_DIM as usize], column, width);
165 }
166 let Ok(at) = net.at(gemma4::Mode::Prefill { tokens: width }.at(tier)) else {
167 return println!("the prefill plan did not build");
168 };
169 let _ = at.set_params(StepParams {
170 prefix: base,
171 window_start: base.saturating_sub(gemma4::WINDOW - 1),
172 });
173 if at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).is_err() {
174 return println!("the prefill failed at {base}");
175 }
176 fed += chunk.len();
177 print!("\r {fed} / {} positions", tokens.len());
178 }
179 println!();
180
181 let positions = fed as u32;
182 let payload = match net.at(gemma4::Mode::DecodeStep.at(tier)) {
183 Ok(net) => match net.export_pinned(gemma4::CACHE_TENSORS, positions) {
184 Ok(bytes) => bytes,
185 Err(why) => return println!("the cache did not export: {why}"),
186 },
187 Err(why) => return println!("{why}"),
188 };
189
190 let mut file = Vec::with_capacity(payload.len() + 64);
191 file.extend_from_slice(b"GKV1");
192 file.extend_from_slice(&positions.to_le_bytes());
193 file.extend_from_slice(&(payload.len() as u32 / positions.max(1)).to_le_bytes());
194 file.extend_from_slice(&digest(&tokens));
195 file.extend_from_slice(&payload);
196 // Round-trip it before claiming success. Importing into a *fresh* net and continuing from
197 // the same position must give the same next token as the net that just prefilled it - which
198 // is the only property the app relies on, and the only one worth checking.
199 let expected =
200 argmax_next(&mut net, &reader, &local, &global, tokens[tokens.len() - 1], positions);
201 let mut fresh = match Reshaped::new(
202 Arc::clone(&context),
203 &weights,
204 gemma4::Mode::DecodeStep.at(tier),
205 |o, m| gemma4::build(o, m),
206 ) {
207 Ok(net) => net,
208 Err(why) => return println!("the check net did not open: {why}"),
209 };
210 match fresh.at(gemma4::Mode::DecodeStep.at(tier)) {
211 Ok(net) => {
212 if let Err(why) = net.import_pinned(gemma4::CACHE_TENSORS, positions, &payload) {
213 return println!("the cache did not import: {why}");
214 }
215 }
216 Err(why) => return println!("{why}"),
217 }
218 // Continue for a while, not one token. One token agreeing only says export and import are
219 // each other's inverse; it says nothing about whether the numbers mean anything to a model
220 // that keeps reading them. A cache that is subtly wrong still produces *a* plausible first
221 // token and then falls apart, which is exactly what shipping this did.
222 let ask = table.encode_with_specials(
223 "<turn|>\n<|turn>user\nWhat is 2+2?<turn|>\n<|turn>model\n",
224 &MARKERS,
225 );
226 let live = continue_with(&mut net, &reader, &local, &global, &ask, positions, 12);
227 let baked = continue_with(&mut fresh, &reader, &local, &global, &ask, positions, 12);
228 println!(" prefilled continues: {:?}", table.decode(&live));
229 println!(" imported continues: {:?}", table.decode(&baked));
230 if live != baked {
231 println!("MISMATCH: the imported cache does not behave like the prefilled one");
232 }
233 let got =
234 argmax_next(&mut fresh, &reader, &local, &global, tokens[tokens.len() - 1], positions);
235 match (expected, got) {
236 (Some(a), Some(b)) if a == b => println!("round trip ok: both continue with token {a}"),
237 (a, b) => {
238 return println!("ROUND TRIP FAILED: prefilled gives {a:?}, imported gives {b:?}");
239 }
240 }
241
242 match std::fs::write(&out, &file) {
243 Ok(()) => {
244 println!("wrote {out} {:.1} MB", file.len() as f64 / 1e6);
245 println!(" {positions} positions, {} bytes each", payload.len() / positions as usize);
246 }
247 Err(why) => println!("cannot write {out}: {why}"),
248 }
249}
250
251/// Write one position's `values` into column `column` of a `[C, 1, width]` block.
252fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) {
253 for (channel, &value) in values.iter().enumerate() {
254 if let Some(slot) = into.get_mut(channel * width as usize + column as usize) {
255 *slot = value;
256 }
257 }
258}
259
260/// A digest of the token sequence, so a cache cannot be used against a prompt it was not baked
261/// for.
262///
263/// Not cryptographic - FNV-1a widened to 32 bytes. The threat is a stale asset after someone
264/// edits the system prompt, not an adversary: the file ships beside the weights over the same
265/// channel, and anyone who could substitute it could substitute those.
266fn digest(tokens: &[u32]) -> [u8; 32] {
267 let mut out = [0u8; 32];
268 for lane in 0..4usize {
269 let mut hash: u64 = 0xcbf2_9ce4_8422_2325 ^ (lane as u64).wrapping_mul(0x9e37_79b9);
270 for &token in tokens {
271 for byte in token.to_le_bytes() {
272 hash ^= u64::from(byte);
273 hash = hash.wrapping_mul(0x100_0000_01b3);
274 }
275 }
276 out[lane * 8..lane * 8 + 8].copy_from_slice(&hash.to_le_bytes());
277 }
278 out
279}
280
281/// The token this net would produce next, given `token` at `position`.
282fn argmax_next(
283 net: &mut Reshaped<gemma4::Pass>,
284 reader: &modelrunner::weights::Reader<'_>,
285 local: &[f32],
286 global: &[f32],
287 token: u32,
288 position: u32,
289) -> Option<u32> {
290 let (hidden, per_layer) = gather_in(reader, token).ok()?;
291 let from = (position * gemma4::HEAD_DIM) as usize;
292 let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec();
293 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
294 let ag = global[from..from + gemma4::GLOBAL_HEAD_DIM as usize].to_vec();
295 let at = net.at(gemma4::Mode::DecodeStep.at(gemma4::MAX_CONTEXT)).ok()?;
296 at.set_params(StepParams {
297 prefix: position,
298 window_start: position.saturating_sub(gemma4::WINDOW - 1),
299 })
300 .ok()?;
301 let out = at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).ok()?;
302 let mut best = (f32::NEG_INFINITY, 0u32);
303 let mut base = 0u32;
304 for split in out.iter().take(gemma4::HEAD_SPLITS) {
305 for (offset, &value) in split.iter().enumerate() {
306 if value > best.0 {
307 best = (value, base + offset as u32);
308 }
309 }
310 base += split.len() as u32;
311 }
312 Some(best.1)
313}
314
315/// Feed `ask` at `from`, then generate `limit` tokens greedily.
316fn continue_with(
317 net: &mut Reshaped<gemma4::Pass>,
318 reader: &modelrunner::weights::Reader<'_>,
319 local: &[f32],
320 global: &[f32],
321 ask: &[u32],
322 from: u32,
323 limit: usize,
324) -> Vec<u32> {
325 let mut out = Vec::new();
326 let mut at = from;
327 for &token in ask {
328 if argmax_at(net, reader, local, global, token, at).is_none() {
329 return out;
330 }
331 at += 1;
332 }
333 let mut next = *ask.last().unwrap_or(&2);
334 for _ in 0..limit {
335 let Some(token) = argmax_at(net, reader, local, global, next, at) else { break };
336 at += 1;
337 if token == 1 || token == 106 {
338 break;
339 }
340 out.push(token);
341 next = token;
342 }
343 out
344}
345
346/// One decode step, returning the argmax.
347fn argmax_at(
348 net: &mut Reshaped<gemma4::Pass>,
349 reader: &modelrunner::weights::Reader<'_>,
350 local: &[f32],
351 global: &[f32],
352 token: u32,
353 position: u32,
354) -> Option<u32> {
355 let (hidden, per_layer) = gather_in(reader, token).ok()?;
356 let from = (position * gemma4::HEAD_DIM) as usize;
357 let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec();
358 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
359 let ag = global[from..from + gemma4::GLOBAL_HEAD_DIM as usize].to_vec();
360 let at = net.at(gemma4::Mode::DecodeStep.at(gemma4::MAX_CONTEXT)).ok()?;
361 at.set_params(StepParams {
362 prefix: position,
363 window_start: position.saturating_sub(gemma4::WINDOW - 1),
364 })
365 .ok()?;
366 let out = at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).ok()?;
367 let mut best = (f32::NEG_INFINITY, 0u32);
368 let mut base = 0u32;
369 for split in out.iter().take(gemma4::HEAD_SPLITS) {
370 for (offset, &value) in split.iter().enumerate() {
371 if value > best.0 {
372 best = (value, base + offset as u32);
373 }
374 }
375 base += split.len() as u32;
376 }
377 Some(best.1)
378}