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