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

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

run_gemma4.rs733 lines · 31.2 KiBRaw
1//! Generates text with Gemma 4 on the Vulkan runtime.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example run_gemma4 -- \
5//! gemma4_text.maml gemma4_embed.maml gemma4_tokenizer.spm1 "The capital of France is" 20
6//! ```
7//!
8//! # Why this exists beside `check_gemma4_parity`
9//!
10//! Parity checks one step against a reference and reports a cosine. That proves the arithmetic
11//! and says nothing about whether the thing is *usable*: a model can match logits on step one and
12//! still fall apart at step twenty because the KV cache is written at the wrong position, the
13//! window slides the wrong way, or the record-once plan reads a stale prefix. Only generation
14//! surfaces those, and only past the point where the cache stops being empty.
15use std::path::PathBuf;
16use std::sync::Arc;
17use std::time::Instant;
18
19use modelrunner::nets::gemma4;
20use modelrunner::post::sentencepiece::Table;
21use modelrunner::post::sentencepiece_flavours::GEMMA;
22use modelrunner::vulkan::context;
23use modelrunner::vulkan::reshape::Reshaped;
24use modelrunner::vulkan::run::StepParams;
25use modelrunner::weights::{graph, Weights};
26
27/// The cache these examples record against: the top tier, so a long prompt fits.
28///
29/// `GEMMA4_TIER` overrides it. Needed because a `.maml` carries rotary tables sized for the
30/// `MAX_CONTEXT` it was converted at, and the current source says 16,384 while the weights on
31/// the test device were converted at 2,048 — which fails at load with
32/// `tensor 17 is [2048, 256], the forward pass wants [16384, 256]`. Overriding lets an older
33/// export be measured without a reconvert; it does not paper over anything, because a wrong
34/// value still fails loudly at the same check.
35fn tier() -> u32 {
36 std::env::var("GEMMA4_TIER")
37 .ok()
38 .and_then(|v| v.parse::<u32>().ok())
39 .filter(|v| *v > 0)
40 .unwrap_or(gemma4::MAX_CONTEXT)
41}
42
43fn main() {
44 // Reads both files whole (1.09 + 3.6 GB of host RAM) and builds nets over
45 // EMBED: an OOM kernel panic on a Pixel 8. Use check_gemma4_parity there.
46 if cfg!(target_os = "android") {
47 println!("run_gemma4 is host-only: it holds 4.7 GB of weights; use check_gemma4_parity --head");
48 return;
49 }
50 let mut args = std::env::args().skip(1);
51 let (Some(text), Some(embed), Some(tokenizer), Some(prompt)) =
52 (args.next(), args.next(), args.next(), args.next())
53 else {
54 println!("usage: run_gemma4 <text.maml> <embed.maml> <table.spm1> <prompt> [tokens]");
55 return;
56 };
57 let limit: usize = args.next().and_then(|n| n.parse().ok()).unwrap_or(24);
58 // `--chat` wraps the prompt in the turn markers the instruction-tuned model expects, which
59 // is what `Gemma4Handle.render` does in the app. Without it a bare prompt is a completion,
60 // and an instruction-tuned Gemma answers most of those by ending the turn immediately - so
61 // timings taken without it are not timings of a chat.
62 let chat = std::env::args().any(|a| a == "--chat");
63 // `--gather-parity` runs the device-combine parity gate instead of generating:
64 // host rows in, device `combined` vs host `combine` per prompt token, cosine
65 // reported per token, nonzero exit on mismatch. The gate the device gather
66 // must pass before `Gemma4Handle.gather_net` is wired in.
67 let gather_parity = std::env::args().any(|a| a == "--gather-parity");
68
69 let read = |p: &str| std::fs::read(PathBuf::from(p));
70 let (Ok(text_bytes), Ok(embed_bytes), Ok(table_bytes)) =
71 (read(&text), read(&embed), read(&tokenizer))
72 else {
73 println!("cannot read one of the three files");
74 return;
75 };
76 let (Ok(weights), Ok(embed_weights)) = (
77 Weights::parse(&text_bytes, graph::GEMMA4_TEXT),
78 Weights::parse(&embed_bytes, graph::GEMMA4_EMBED),
79 ) else {
80 println!("the weights do not parse");
81 return;
82 };
83 let table = match Table::parse_with(&table_bytes, GEMMA) {
84 Ok(table) => table,
85 Err(why) => return println!("the tokenizer does not parse: {why}"),
86 };
87
88 // Only the four sentencepiece specials below are matched, so a chat marker like `<|turn>`
89 // would tokenise as `<`, `|`, `turn`, `>` instead of the single id the model was trained on.
90 // That fails silently and plausibly: the run completes, the output reads like prose, and the
91 // prompt the model saw was structurally different from the one that was written.
92 //
93 // The marker set belongs to the template rather than the tokenizer, which is why
94 // `encode_with_specials` takes it as an argument and why the app passes `Gemma4Handle.MARKERS`
95 // across JNI. An example cannot read a Kotlin companion object, so the two lists cannot be
96 // shared and will drift. Refusing is what stops that drift from being drawn a conclusion from.
97 if chat {
98 return run_chat(&weights, &embed_weights, &table, &prompt, limit);
99 }
100 if gather_parity {
101 return gather_parity_gate(&weights, &embed_weights, &table, &prompt);
102 }
103 if prompt.contains("<|") || prompt.contains("|>") {
104 println!(
105 "this example takes a plain completion prompt, not a chat-formatted one.\n\
106 it found a chat marker (`<|` or `|>`), which it would encode as literal characters \
107 rather than as the single ids the model was trained on - silently, and the output \
108 would look reasonable.\n\
109 for chat, tool or multimodal prompts go through `Gemma4Handle.generate`, which passes \
110 the full marker set."
111 );
112 return;
113 }
114
115 let specials = ["<bos>", "<eos>", "<pad>", "<unk>"];
116 let mut tokens = vec![GEMMA.bos];
117 tokens.extend(table.encode_with_specials(&prompt, &specials));
118 println!("prompt {prompt:?}");
119 println!(" {} tokens: {tokens:?}", tokens.len());
120
121 let context = match context::shared() {
122 Ok(context) => context,
123 Err(why) => return println!("no Vulkan device: {why}"),
124 };
125 match generate(&context, &weights, &embed_weights, &mut tokens, limit) {
126 Ok((elapsed, produced)) => {
127 println!();
128 println!("generated {:?}", table.decode(&produced));
129 println!();
130 println!(" {} tokens in {:.2}s", produced.len(), elapsed);
131 println!(" {:.1} ms a token", elapsed * 1000.0 / produced.len().max(1) as f64);
132 }
133 Err(why) => println!("generation failed: {why}"),
134 }
135}
136
137/// Positions one prefill submit covers. Attention is quadratic in this.
138const PREFILL_CHUNK_DEFAULT: usize = 128;
139
140/// `GEMMA4_PREFILL_CHUNK` overrides it, for sweeping the cost curve against the fence timeout.
141fn prefill_chunk() -> usize {
142 std::env::var("GEMMA4_PREFILL_CHUNK")
143 .ok()
144 .and_then(|v| v.parse().ok())
145 .filter(|v| *v > 0)
146 .unwrap_or(PREFILL_CHUNK_DEFAULT)
147}
148
149/// Write one position's `values` into column `column` of a `[C, 1, width]` block.
150fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) {
151 for (channel, &value) in values.iter().enumerate() {
152 if let Some(slot) = into.get_mut(channel * width as usize + column as usize) {
153 *slot = value;
154 }
155 }
156}
157
158/// Ids that end a generation, from `generation_config.json`'s `eos_token_id`.
159///
160/// Three, not one. `<eos>` is 1, but an instruction-tuned Gemma ends its *reply* with `<turn|>`
161/// (106) and the tokenizer's `<eos>` almost never appears - stopping only on 1 lets the model run
162/// on emitting turn markers until the token budget does the stopping instead.
163const STOP: [u32; 3] = [1, 106, 50];
164
165/// Device-combine parity gate (`--gather-parity`).
166///
167/// For each prompt token: host rows in (the 36 `int4_row` reads, as today),
168/// device `combined` via `gemma4_gather::build_plan` vs host `combine`,
169/// cosine reported per token. Exit nonzero on the first mismatch below
170/// 0.9999. The gate `Gemma4Handle.gather_net` must pass before it is wired
171/// into the step path — until then the handle carries `None` and this is
172/// the only caller of the combine plan.
173fn gather_parity_gate(
174 _weights: &Weights,
175 embed: &Weights,
176 table: &Table<'_>,
177 prompt: &str,
178) -> () {
179 use modelrunner::nets::gemma4_gather;
180 let specials = ["<bos>", "<eos>", "<pad>", "<unk>"];
181 let mut tokens = vec![GEMMA.bos];
182 tokens.extend(table.encode_with_specials(prompt, &specials));
183 println!("prompt {prompt:?}");
184 println!(" {} tokens: {tokens:?}", tokens.len());
185 let context = match context::shared() {
186 Ok(context) => context,
187 Err(why) => return println!("no Vulkan device: {why}"),
188 };
189 let plan = match gemma4_gather::build_plan(&embed.offsets()) {
190 Ok(plan) => plan,
191 Err(why) => return println!("the combine plan does not build: {why}"),
192 };
193 println!(" combine plan: {} ops, {} inputs, {} outputs", plan.ops.len(), plan.inputs.len(), plan.outputs.len());
194 let mut net = match modelrunner::vulkan::run::Net::new(
195 std::sync::Arc::clone(&context),
196 plan,
197 embed,
198 modelrunner::preprocess::RESCALE_ONLY,
199 ) {
200 Ok(net) => net,
201 Err(why) => return println!("the combine net does not open: {why}"),
202 };
203 let reader = embed.reader();
204 let mut worst = 1.0f64;
205 for &token in &tokens {
206 let (hidden, embedded) = match gather_rows(&reader, token) {
207 Ok(rows) => rows,
208 Err(why) => return println!("token {token}: {why}"),
209 };
210 let host = match gather_combine_host(&reader, &hidden, &embedded) {
211 Ok(combined) => combined,
212 Err(why) => return println!("token {token} host combine: {why}"),
213 };
214 let out = match net.infer_raw_many(&[&hidden, &embedded]) {
215 Ok(out) => out,
216 Err(why) => return println!("token {token} device combine: {why}"),
217 };
218 if out.len() != 1 || out[0].len() != host.len() {
219 return println!("token {token}: device shape {:?}, host {}", out.iter().map(|v| v.len()).collect::<Vec<_>>(), host.len());
220 }
221 let dot: f64 = out[0].iter().zip(host.iter()).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum();
222 let (na, nb): (f64, f64) = (
223 out[0].iter().map(|a| f64::from(*a) * f64::from(*a)).sum::<f64>().sqrt(),
224 host.iter().map(|b| f64::from(*b) * f64::from(*b)).sum::<f64>().sqrt(),
225 );
226 let cosine = dot / (na * nb).max(1e-30);
227 worst = worst.min(cosine);
228 println!(" token {token:>6}: device-vs-host cosine {cosine:.6}");
229 if cosine < 0.9999 {
230 println!();
231 println!("GATHER PARITY FAIL at token {token}: {cosine:.6} < 0.9999");
232 std::process::exit(1);
233 }
234 }
235 println!();
236 println!("GATHER PARITY PASS: worst cosine {worst:.6} over {} tokens", tokens.len());
237}
238
239/// Host rows + host combine for the parity gate (mirrors `gemma4::gather`
240/// without the bridge handle: 36 `int4_row` reads, then the same projection
241/// + grouped-norm + scaled add as `gemma4_part4::combine`).
242fn gather_rows(
243 reader: &modelrunner::weights::Reader<'_>,
244 token: u32,
245) -> Result<(Vec<f32>, Vec<f32>), String> {
246 if token >= gemma4::VOCAB {
247 return Err(format!("token {token} is past the {}-entry vocabulary", gemma4::VOCAB));
248 }
249 let hidden = reader.int4_row(
250 gemma4::embed::TOKENS,
251 gemma4::embed::TOKENS + 1,
252 &[gemma4::VOCAB, gemma4::D_MODEL],
253 token,
254 )?;
255 let per_layer_row = if gemma4::embed::PLACEHOLDERS.contains(&token) { 0 } else { token };
256 let mut embedded = Vec::with_capacity((gemma4::PER_LAYER as usize) * gemma4::LAYERS);
257 for i in 0..gemma4::LAYERS {
258 let at = gemma4::embed::table(i);
259 embedded.extend(reader.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], per_layer_row)?);
260 }
261 Ok((hidden, embedded))
262}
263
264/// Host combine over already-gathered rows (see `gather_rows`).
265///
266/// A thin wrapper over the shared cached implementation
267/// (`gemma4::combine_cached`): int8 `SHARED_PROJ` projection, grouped RMS norm
268/// with `SHARED_NORM` gamma, `(16 * embedded + normed) / sqrt(2)`.
269fn gather_combine_host(
270 reader: &modelrunner::weights::Reader<'_>,
271 hidden: &[f32],
272 embedded: &[f32],
273) -> Result<Vec<f32>, String> {
274 use modelrunner::nets::gemma4;
275 gemma4::combine_cached(reader, hidden, embedded)
276}
277
278/// Logits for `hidden`: the GPU head when the EMBED file carries chunks.
279///
280/// The device runs the 16 chunk projections; the host concatenates the
281/// splits and softcaps, exactly as the host head does. Falls back to the
282/// host tied head (`hidden @ HEAD_TABLE^T` in `HEAD_SPLITS` quarters) on
283/// files without chunks.
284///
285/// `GEMMA4_GREEDY=1` instead reduces on the device: the greedy plan
286/// (`build_plan_greedy`) concatenates the 16 splits on-device and one
287/// `Argmax` op returns the winning index as fp16 bits — 1 value back instead
288/// of 262144, no 512 KB readback, no host scan. The returned id is checked
289/// against the host argmax every token (greedy parity gate); any mismatch
290/// fails the run loudly rather than generating from the wrong token.
291fn head_logits(
292 _context: &Arc<context::Context>,
293 head: &mut Option<Reshaped<()>>,
294 reader: &modelrunner::weights::Reader<'_>,
295 hidden: &[f32],
296 head_embed: Option<&Weights>,
297) -> Result<Vec<f32>, String> {
298 use modelrunner::nets::gemma4_head;
299 if std::env::var("GEMMA4_GREEDY").is_ok() {
300 if let Some(embed) = head_embed {
301 if let Some(id) = head_greedy_id(_context, embed, hidden)? {
302 // Greedy parity gate: the device id must equal the host argmax.
303 // Falls through to the full path below on mismatch (loud, not silent).
304 let full = head_logits_full(head, reader, hidden)?;
305 let host = full
306 .iter()
307 .enumerate()
308 .max_by(|(_, a), (_, b)| a.total_cmp(b))
309 .map(|(i, _)| i as u32);
310 if host != Some(id) {
311 return Err(format!("greedy parity: device id {id} vs host {host:?}"));
312 }
313 return Ok(full);
314 }
315 }
316 }
317 head_logits_full(head, reader, hidden)
318}
319
320/// The device greedy id, or `None` when the head net is absent.
321///
322/// The greedy plan (`build_plan_greedy`) is a different output signature
323/// (16 splits + 1 id), so it needs its own recording alongside the logits
324/// plan. SIMPLIFICATION for the parity gate: rebuild a dedicated `Net` per
325/// call (correct; one extra upload+record per token while proving
326/// bit-identity). The cached second handle lands once parity is proven.
327fn head_greedy_id(
328 context: &Arc<context::Context>,
329 embed: &Weights,
330 hidden: &[f32],
331) -> Result<Option<u32>, String> {
332 use modelrunner::nets::gemma4_head;
333 use modelrunner::vulkan::run::Net;
334 if embed.offsets().len() < gemma4_head::TENSORS_WITH_HEAD {
335 return Ok(None);
336 }
337 let plan = gemma4_head::build_plan_greedy(&embed.offsets())?;
338 let mut net = Net::new(
339 Arc::clone(context),
340 plan,
341 embed,
342 modelrunner::preprocess::RESCALE_ONLY,
343 )?;
344 let out = net.infer_raw_many(&[hidden])?;
345 if out.len() != gemma4_head::HEAD_CHUNKS + 1 {
346 return Err(format!("greedy head returned {} outputs, not {}", out.len(), gemma4_head::HEAD_CHUNKS + 1));
347 }
348 let id_out = &out[gemma4_head::HEAD_CHUNKS];
349 if id_out.len() != 2 {
350 return Err(format!("greedy id output holds {} values, not 2", id_out.len()));
351 }
352 // The shader stored `lo = id % 2048`, `hi = id / 2048` as fp16 values
353 // (both exactly representable) — reconstruct exactly.
354 let lo = id_out[0] as u32;
355 let hi = id_out[1] as u32;
356 Ok(Some(hi * 2048 + lo))
357}
358
359/// Full logits via the GPU head (or host fallback). See [`head_logits`].
360fn head_logits_full(
361 head: &mut Option<Reshaped<()>>,
362 reader: &modelrunner::weights::Reader<'_>,
363 hidden: &[f32],
364) -> Result<Vec<f32>, String> {
365 use modelrunner::nets::gemma4_head;
366 if let Some(net) = head.as_mut() {
367 let at = net.at(())?;
368 let t = std::time::Instant::now();
369 let out = at.infer_raw_many(&[hidden])?;
370 eprintln!("head submit: {:.0} ms", t.elapsed().as_secs_f64() * 1000.0);
371 if out.len() == gemma4_head::HEAD_CHUNKS
372 && out.iter().all(|s| s.len() == gemma4_head::CLASSES_PER_CHUNK as usize)
373 {
374 let mut logits = Vec::with_capacity(gemma4::VOCAB as usize);
375 for split in &out {
376 for &value in split {
377 logits.push(gemma4::LOGIT_CAP * (value / gemma4::LOGIT_CAP).tanh());
378 }
379 }
380 return Ok(logits);
381 }
382 // Wrong shape: the file's chunks do not match the plan. Fall through
383 // to the host head rather than failing the run.
384 }
385 // The tied head on the host, in vocabulary splits (see `gemma4::HEAD_SPLITS`).
386 // `Mode::DecodeStep` returns the normed hidden state, not logits: litertlm
387 // stores no logits head, so logits are hidden @ E^T over the raw-scale head
388 // table (`gemma4::embed::HEAD_TABLE`), softcapped. Mirrors
389 // `check_gemma4_parity::run`.
390 let mut logits = vec![0f32; gemma4::VOCAB as usize];
391 for split in 0..gemma4::HEAD_SPLITS {
392 let start = (split as u32) * gemma4::CLASSES_PER_SPLIT;
393 let block = reader.fp16_rows(
394 gemma4::embed::HEAD_TABLE,
395 &[gemma4::VOCAB, gemma4::D_MODEL],
396 start,
397 gemma4::CLASSES_PER_SPLIT,
398 )?;
399 for (offset, row) in block.chunks_exact(gemma4::D_MODEL as usize).enumerate() {
400 let dot: f32 = row.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum();
401 logits[start as usize + offset] =
402 gemma4::LOGIT_CAP * (dot / gemma4::LOGIT_CAP).tanh();
403 }
404 }
405 Ok(logits)
406}
407
408/// Feed the prompt, then sample greedily until `limit` new tokens or a stop id.
409fn generate(
410 context: &Arc<context::Context>,
411 weights: &Weights,
412 embed: &Weights,
413 tokens: &mut Vec<u32>,
414 limit: usize,
415) -> Result<(f64, Vec<u32>), String> {
416 let mut net = Reshaped::new(Arc::clone(context), weights, gemma4::Mode::DecodeStep.at(tier()), |o, m| {
417 gemma4::build(o, m)
418 })?;
419 // The GPU tied head over the EMBED file, upload-once. `None` on files
420 // without head chunks — the host head below covers those.
421 let mut head: Option<Reshaped<()>> = if embed.offsets().len() >= modelrunner::nets::gemma4_head::TENSORS_WITH_HEAD {
422 Reshaped::new(
423 Arc::clone(context),
424 embed,
425 (),
426 |o, ()| modelrunner::nets::gemma4_head::build_plan(o),
427 )
428 .ok()
429 } else {
430 None
431 };
432 let reader = embed.reader();
433 let rotary = weights.reader();
434 // The tables are read once rather than per step: 2048 rows of fp16 is a few megabytes and
435 // re-reading them each token would dominate the measurement below.
436 let local = rotary.fp16(gemma4::ROTARY_LOCAL, &[tier(), gemma4::HEAD_DIM])?;
437 let global =
438 rotary.fp16(gemma4::ROTARY_GLOBAL, &[tier(), gemma4::GLOBAL_HEAD_DIM])?;
439
440 let prompt_len = tokens.len();
441 let started = Instant::now();
442
443 // The prompt in batched submits, then one decode step per generated token. Everything but
444 // the last prompt token only fills the cache, so its logits would be computed and thrown
445 // away - which at 262,144 classes is most of the pass.
446 let prefill_started = Instant::now();
447 let mut fed = 0usize;
448 // `GEMMA4_NO_PREFILL=1` feeds the prompt one position at a time instead, which is what the
449 // decode path does. Kept as a switch rather than deleted: batched prefill and sequential
450 // prefill must produce the same tokens, and the only way to know they do is to run both.
451 let batched = std::env::var("GEMMA4_NO_PREFILL").is_err();
452 let chunk_size = if batched { prefill_chunk() } else { 1 };
453 for chunk in tokens[..prompt_len - 1].chunks(chunk_size) {
454 let width = chunk.len() as u32;
455 let base = fed as u32;
456 let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize];
457 let mut per_layer =
458 vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize];
459 let mut angles_local = vec![0f32; (gemma4::HEAD_DIM * width) as usize];
460 let mut angles_global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];
461 for (offset, &token) in chunk.iter().enumerate() {
462 let column = offset as u32;
463 let position = base + column;
464 let (h, p) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(weights))?;
465 place(&mut hidden, &h, column, width);
466 place(&mut per_layer, &p, column, width);
467 let take = |table: &[f32], dim: u32| {
468 let from = (position * dim) as usize;
469 table[from..from + dim as usize].to_vec()
470 };
471 place(&mut angles_local, &take(&local, gemma4::HEAD_DIM), column, width);
472 place(&mut angles_global, &take(&global, gemma4::GLOBAL_HEAD_DIM), column, width);
473 }
474 let at = net.at(if batched {
475 gemma4::Mode::Prefill { tokens: width }.at(tier())
476 } else {
477 gemma4::Mode::DecodeStep.at(tier())
478 })?;
479 at.set_params(StepParams {
480 prefix: base,
481 window_start: base.saturating_sub(gemma4::WINDOW - 1),
482 })?;
483 at.infer_raw_many(&[&hidden, &per_layer, &angles_local, &angles_global])?;
484 fed += chunk.len();
485 }
486 println!(
487 " prefill {} tokens in {:.2}s ({:.2} ms a token){}",
488 fed,
489 prefill_started.elapsed().as_secs_f64(),
490 prefill_started.elapsed().as_secs_f64() * 1000.0 / fed.max(1) as f64,
491 if batched { "" } else { " [sequential]" },
492 );
493
494 let mut generated = 0;
495 for step in fed..prompt_len + limit {
496 let position = u32::try_from(step).map_err(|_| "a step past u32")?;
497 if position >= tier() {
498 break;
499 }
500 let token = tokens[step];
501 let (hidden, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(weights))?;
502 let row = |table: &[f32], width: u32| {
503 let from = (position * width) as usize;
504 table[from..from + width as usize].to_vec()
505 };
506 let at = net.at(gemma4::Mode::DecodeStep.at(tier()))?;
507 at.set_params(StepParams {
508 prefix: position,
509 window_start: position.saturating_sub(gemma4::WINDOW - 1),
510 })?;
511 let out = at.infer_raw_many(&[
512 &hidden,
513 &per_layer,
514 &row(&local, gemma4::HEAD_DIM),
515 &row(&global, gemma4::GLOBAL_HEAD_DIM),
516 ])?;
517
518 // Only the last prompt token's logits are a prediction; the rest just fill the cache.
519 if step + 1 < prompt_len {
520 continue;
521 }
522 if out.len() != 1 {
523 return Err(format!("a step returned {} tensors, not the hidden state", out.len()));
524 }
525 let hidden = &out[0];
526 if hidden.len() != gemma4::D_MODEL as usize {
527 return Err(format!(
528 "hidden state of {} values, not {}",
529 hidden.len(),
530 gemma4::D_MODEL
531 ));
532 }
533 let logits = head_logits(context, &mut head, &reader, hidden, Some(embed))?;
534 let mut best = (f32::NEG_INFINITY, 0u32);
535 for (id, &value) in logits.iter().enumerate() {
536 if value > best.0 {
537 best = (value, id as u32);
538 }
539 }
540 if STOP.contains(&best.1) {
541 break;
542 }
543 tokens.push(best.1);
544 generated += 1;
545 if generated >= limit {
546 break;
547 }
548 }
549 Ok((started.elapsed().as_secs_f64(), tokens[prompt_len..].to_vec()))
550}
551
552/// One templated turn, timed the way a user experiences it.
553///
554/// Mirrors `Gemma4Handle.render` and `Gemma4Handle.generate`: the same markers, the same marker
555/// set passed to the encoder, the same stop ids. Kept in step by hand, which is why the plain
556/// path above refuses chat markers rather than letting the two drift silently.
557fn run_chat(
558 weights: &Weights,
559 embed: &Weights,
560 table: &Table<'_>,
561 prompt: &str,
562 limit: usize,
563) -> () {
564 const MARKERS: [&str; 11] = [
565 "<bos>", "<eos>", "<|turn>", "<turn|>", "<|tool>", "<tool|>", "<|tool_call>",
566 "<tool_call|>", "<|tool_response>", "<tool_response|>", "<|\"|>",
567 ];
568 let rendered = format!("<bos><|turn>user\n{prompt}<turn|>\n<|turn>model\n");
569 let tokens = table.encode_with_specials(&rendered, &MARKERS);
570 println!("prompt {prompt:?} ({} tokens templated)", tokens.len());
571
572 let context = match context::shared() {
573 Ok(context) => context,
574 Err(why) => return println!("no Vulkan device: {why}"),
575 };
576 let opened = Instant::now();
577 let mut net = match Reshaped::new(
578 std::sync::Arc::clone(&context),
579 weights,
580 gemma4::Mode::DecodeStep.at(tier()),
581 |o, m| gemma4::build(o, m),
582 ) {
583 Ok(net) => net,
584 Err(why) => return println!("the model did not open: {why}"),
585 };
586 // The GPU tied head over the EMBED file, upload-once (`None` on files
587 // without head chunks — `head_logits` falls back to the host head).
588 let mut head: Option<Reshaped<()>> = if embed.offsets().len() >= modelrunner::nets::gemma4_head::TENSORS_WITH_HEAD {
589 Reshaped::new(
590 std::sync::Arc::clone(&context),
591 embed,
592 (),
593 |o, ()| modelrunner::nets::gemma4_head::build_plan(o),
594 )
595 .ok()
596 } else {
597 None
598 };
599 let reader = embed.reader();
600 let rotary = weights.reader();
601 let (local, global) = match (
602 rotary.fp16(gemma4::ROTARY_LOCAL, &[tier(), gemma4::HEAD_DIM]),
603 rotary.fp16(gemma4::ROTARY_GLOBAL, &[tier(), gemma4::GLOBAL_HEAD_DIM]),
604 ) {
605 (Ok(l), Ok(g)) => (l, g),
606 _ => return println!("the rotary tables did not load"),
607 };
608 println!(" open {:.2}s", opened.elapsed().as_secs_f64());
609
610 let first = Instant::now();
611 let mut fed = 0usize;
612 for chunk in tokens[..tokens.len() - 1].chunks(prefill_chunk()) {
613 let width = chunk.len() as u32;
614 let base = fed as u32;
615 let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize];
616 let mut per_layer =
617 vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize];
618 let mut al = vec![0f32; (gemma4::HEAD_DIM * width) as usize];
619 let mut ag = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];
620 for (offset, &token) in chunk.iter().enumerate() {
621 let column = offset as u32;
622 let position = base + column;
623 let Ok((h, p)) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(weights)) else { return };
624 place(&mut hidden, &h, column, width);
625 place(&mut per_layer, &p, column, width);
626 let from = (position * gemma4::HEAD_DIM) as usize;
627 place(&mut al, &local[from..from + gemma4::HEAD_DIM as usize], column, width);
628 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
629 place(&mut ag, &global[from..from + gemma4::GLOBAL_HEAD_DIM as usize], column, width);
630 }
631 let Ok(at) = net.at(gemma4::Mode::Prefill { tokens: width }.at(tier())) else { return };
632 let _ = at.set_params(StepParams {
633 prefix: base,
634 window_start: base.saturating_sub(gemma4::WINDOW - 1),
635 });
636 if at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]).is_err() {
637 return println!("prefill failed");
638 }
639 fed += chunk.len();
640 }
641 let prefilled = first.elapsed();
642
643 let mut produced: Vec<u32> = Vec::new();
644 let mut next = tokens[tokens.len() - 1];
645 let mut first_token = None;
646 // Where the decode step's wall time actually goes.
647 //
648 // The measured step is 282 ms while the GPU's own gemv work accounts for roughly 71 ms
649 // (1.30 GB at the 18.4 GB/s a faithful probe of this kernel reaches), leaving ~211 ms
650 // unattributed. Before that is blamed on per-dispatch cost, note this loop does two large
651 // pieces of HOST work per token that no GPU probe models: `gemma4::gather` reads embedding
652 // rows out of a 1.55 GB mapped file, and the argmax scans 262,144 logits. Split them rather
653 // than assume.
654 let mut spent_gather = std::time::Duration::ZERO;
655 let mut spent_infer = std::time::Duration::ZERO;
656 let mut spent_argmax = std::time::Duration::ZERO;
657 let decode_started = Instant::now();
658 for step in 0..limit {
659 let position = (fed + step) as u32;
660 let at_gather = Instant::now();
661 let Ok((hidden, per_layer)) = gemma4::gather_input(&reader, next, gemma4::combines_in_plan(weights)) else { break };
662 let from = (position * gemma4::HEAD_DIM) as usize;
663 let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec();
664 let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
665 let ag = global[from..from + gemma4::GLOBAL_HEAD_DIM as usize].to_vec();
666 spent_gather += at_gather.elapsed();
667
668 let at_infer = Instant::now();
669 let Ok(at) = net.at(gemma4::Mode::DecodeStep.at(tier())) else { break };
670 let _ = at.set_params(StepParams {
671 prefix: position,
672 window_start: position.saturating_sub(gemma4::WINDOW - 1),
673 });
674 let Ok(out) = at.infer_raw_many(&[&hidden, &per_layer, &al, &ag]) else { break };
675 spent_infer += at_infer.elapsed();
676
677 let at_argmax = Instant::now();
678 if out.len() != 1 || out[0].len() != gemma4::D_MODEL as usize {
679 break;
680 }
681 let hidden = &out[0];
682 let logits = match head_logits(&context, &mut head, &reader, hidden, Some(embed)) {
683 Ok(logits) => logits,
684 Err(_) => break,
685 };
686 // Host argmax over the reassembled logits (GPU or host head alike).
687 let mut best = (f32::NEG_INFINITY, 0u32);
688 for (id, &value) in logits.iter().enumerate() {
689 if value > best.0 {
690 best = (value, id as u32);
691 }
692 }
693 spent_argmax += at_argmax.elapsed();
694
695 if first_token.is_none() {
696 first_token = Some(first.elapsed());
697 }
698 if STOP.contains(&best.1) {
699 break;
700 }
701 produced.push(best.1);
702 next = best.1;
703 }
704 let decoded = decode_started.elapsed();
705
706 println!(" prefill {:.0} ms for {fed} tokens", prefilled.as_secs_f64() * 1000.0);
707 println!(
708 " first {:.0} ms to the first token",
709 first_token.unwrap_or(prefilled).as_secs_f64() * 1000.0
710 );
711 println!(
712 " decode {:.0} ms for {} tokens ({:.0} ms each)",
713 decoded.as_secs_f64() * 1000.0,
714 produced.len(),
715 decoded.as_secs_f64() * 1000.0 / produced.len().max(1) as f64
716 );
717 println!(" reply {:?}", table.decode(&produced));
718 let steps = produced.len().max(1) as f64;
719 println!();
720 println!(" decode step breakdown, per token, over {} steps:", produced.len());
721 println!(
722 " gather {:6.1} ms HOST: embedding rows from the 1.55 GB mapped file + rotary slices",
723 spent_gather.as_secs_f64() * 1000.0 / steps,
724 );
725 println!(
726 " infer {:6.1} ms upload + submit + fence + readback (the only part with GPU in it)",
727 spent_infer.as_secs_f64() * 1000.0 / steps,
728 );
729 println!(
730 " argmax {:6.1} ms HOST: scan of 262,144 logits",
731 spent_argmax.as_secs_f64() * 1000.0 / steps,
732 );
733}