Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / check_gemma4_parity.rs
check_gemma4_parity.rs1334 lines · 60.2 KiBRaw
| 1 | //! Runs Gemma 4's decode step on the GPU and compares its logits with onnxruntime's. |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! cargo run --offline --release -p modelrunner --example check_gemma4_parity -- \ |
| 5 | //! gemma4_text.maml gemma4_embed.maml logits_golden.json |
| 6 | //! ``` |
| 7 | //! |
| 8 | //! # This is the check nothing else substitutes for |
| 9 | //! |
| 10 | //! Every other test in this port checks *layout* - that 999 tensors are declared in the order the |
| 11 | //! converter writes them, that a scale has the rank its precision implies, that one op agrees |
| 12 | //! with a CPU oracle. All of that can pass while the model is wrong, because a transposed read |
| 13 | //! agrees with itself and a doubled scale is still a number. |
| 14 | //! |
| 15 | //! Thirty-five layers in sequence against real weights is the only thing that catches an error of |
| 16 | //! *composition*: a residual added before its norm instead of after, a rotary applied to the key |
| 17 | //! but not the query, a cache written at the wrong position. Those produce plausible logits. |
| 18 | //! |
| 19 | //! # What agreement to expect |
| 20 | //! |
| 21 | //! The reference is fp16 weights in fp32 arithmetic; this is int4 weights with a per-block scale. |
| 22 | //! The logits will not match to the bit and should not be expected to. What must match is the |
| 23 | //! **argmax** and the broad ordering of the top few - a model that is right differs from the |
| 24 | //! reference by quantisation noise, and a model that is wrong differs by rearranging the ranking. |
| 25 | use std::path::PathBuf; |
| 26 | use std::sync::Arc; |
| 27 | |
| 28 | use modelrunner::nets::gemma4; |
| 29 | use modelrunner::nets::gemma4_head::HeadOut; |
| 30 | use modelrunner::vulkan::context; |
| 31 | use modelrunner::vulkan::reshape::Reshaped; |
| 32 | use modelrunner::vulkan::run::StepParams; |
| 33 | use modelrunner::weights::{Streamed, graph}; |
| 34 | |
| 35 | /// The app's starting cache tier (1024 positions, 19 MB): the 16K tier adds 280 MB of KV, which |
| 36 | /// the Pixel 8 cannot spare beside TEXT and the head. |
| 37 | const TIER: u32 = gemma4::CONTEXT_TIERS[0]; |
| 38 | |
| 39 | /// Open both `.maml` files as [`Streamed`] instead of `std::fs::read` + [`Weights::parse`]. |
| 40 | /// |
| 41 | /// The old path held 1.09 GB + 2.39 GB resident and then copied each data section again |
| 42 | /// inside `parse`, which is ~7 GB of peak host RSS against the ~2.4 GB a 7 GB Pixel 8 has |
| 43 | /// free — the OOM-reboot this harness caused twice. `Streamed::open` reads only the |
| 44 | /// ~64 KB header/table prefix; the data section stays in the file and is pulled through |
| 45 | /// `Net`'s 8 MB chunked staging upload plus row-at-a-time host gathers, so peak host RSS |
| 46 | /// is tens of MB. Identical bytes reach the device (`read_at` over the same section). |
| 47 | fn open_streamed(path: &PathBuf, expect_graph: u32) -> Result<Streamed, String> { |
| 48 | let file = std::fs::File::open(path) |
| 49 | .map_err(|e| format!("cannot open {}: {e}", path.display()))?; |
| 50 | let len = file |
| 51 | .metadata() |
| 52 | .map_err(|e| format!("cannot size {}: {e}", path.display()))? |
| 53 | .len(); |
| 54 | Streamed::open(file, 0, len, expect_graph) |
| 55 | } |
| 56 | |
| 57 | /// Every GPU net this example builds goes through here. |
| 58 | /// |
| 59 | /// `Reshaped::streamed` uploads the whole file it is given, so a net over |
| 60 | /// gemma4_embed.maml is a 3.6 GB upload on top of TEXT: the Pixel 8 OOM |
| 61 | /// kernel panic. EMBED is read on the host only, a row at a time. |
| 62 | fn streamed_net<S: Copy + PartialEq>( |
| 63 | context: &Arc<context::Context>, |
| 64 | weights: &Streamed, |
| 65 | shape: S, |
| 66 | plan: fn(&modelrunner::weights::Offsets, S) -> Result<modelrunner::nets::Plan, String>, |
| 67 | ) -> Result<Reshaped<S>, String> { |
| 68 | if weights.graph_id == graph::GEMMA4_EMBED { |
| 69 | return Err("refusing to upload gemma4_embed.maml to the GPU (3.6 GB); pass --head".into()); |
| 70 | } |
| 71 | Reshaped::streamed(Arc::clone(context), weights.offsets(), weights, shape, plan) |
| 72 | } |
| 73 | |
| 74 | fn gemma4_plan(offsets: &modelrunner::weights::Offsets, pass: gemma4::Pass) -> Result<modelrunner::nets::Plan, String> { |
| 75 | gemma4::build(offsets, pass) |
| 76 | } |
| 77 | |
| 78 | /// Whether the text file carries the combine, so plans take raw per-layer rows (set in `main`). |
| 79 | static FUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); |
| 80 | |
| 81 | fn fused() -> bool { |
| 82 | FUSED.load(std::sync::atomic::Ordering::Relaxed) |
| 83 | } |
| 84 | |
| 85 | /// One token's text-plan inputs 0 and 1 for this run's text file. |
| 86 | fn gather_in(embed: &modelrunner::weights::Reader<'_>, token: u32) -> Result<(Vec<f32>, Vec<f32>), String> { |
| 87 | gemma4::gather_input(embed, token, fused()) |
| 88 | } |
| 89 | |
| 90 | fn head_plan(offsets: &modelrunner::weights::Offsets, out: HeadOut) -> Result<modelrunner::nets::Plan, String> { |
| 91 | modelrunner::nets::gemma4_head::build_plan_standalone(offsets, out) |
| 92 | } |
| 93 | |
| 94 | struct Args { |
| 95 | positional: Vec<String>, |
| 96 | head: Option<PathBuf>, |
| 97 | time: Option<usize>, |
| 98 | prefill: Option<Vec<u32>>, |
| 99 | sample: bool, |
| 100 | topk: bool, |
| 101 | split: Option<u32>, |
| 102 | len: Option<u32>, |
| 103 | gather: bool, |
| 104 | soft: bool, |
| 105 | spread: bool, |
| 106 | } |
| 107 | |
| 108 | /// `--head <path>`, `--time <repeats>`, `--prefill <tokens>`, `--sample`; the |
| 109 | /// rest are positional: text embed golden [trace] [tail] [head]. |
| 110 | fn parse_args() -> Args { |
| 111 | let mut args = |
| 112 | Args { positional: Vec::new(), head: None, time: None, prefill: None, sample: false, topk: false, split: None, len: None, gather: false, soft: false, spread: false }; |
| 113 | let mut it = std::env::args().skip(1); |
| 114 | while let Some(arg) = it.next() { |
| 115 | match arg.as_str() { |
| 116 | "--head" => args.head = it.next().map(PathBuf::from), |
| 117 | "--time" => args.time = it.next().and_then(|n| n.parse().ok()), |
| 118 | "--prefill" => args.prefill = it.next().map(|n| n.split(',').filter_map(|w| w.parse().ok()).collect()), |
| 119 | "--sample" => args.sample = true, |
| 120 | "--topk" => args.topk = true, |
| 121 | "--split" => args.split = it.next().and_then(|n| n.parse().ok()), |
| 122 | "--len" => args.len = it.next().and_then(|n| n.parse().ok()), |
| 123 | "--gather" => args.gather = true, |
| 124 | "--soft" => args.soft = true, |
| 125 | "--spread" => args.spread = true, |
| 126 | _ => args.positional.push(arg), |
| 127 | } |
| 128 | } |
| 129 | if args.head.is_none() { |
| 130 | args.head = args.positional.get(5).map(PathBuf::from); |
| 131 | } |
| 132 | args |
| 133 | } |
| 134 | |
| 135 | fn main() { |
| 136 | let args = parse_args(); |
| 137 | let (Some(text), Some(embed), Some(golden)) = ( |
| 138 | args.positional.first().map(PathBuf::from), |
| 139 | args.positional.get(1).map(PathBuf::from), |
| 140 | args.positional.get(2), |
| 141 | ) else { |
| 142 | println!( |
| 143 | "usage: check_gemma4_parity <text.maml> <embed.maml> <golden.json> [trace] [tail] \ |
| 144 | [--head head.maml] [--time N [--sample] [--topk]] [--prefill N] [--split K [--len N]]" |
| 145 | ); |
| 146 | return; |
| 147 | }; |
| 148 | let weights = match open_streamed(&text, graph::GEMMA4_TEXT) { |
| 149 | Ok(w) => w, |
| 150 | Err(why) => return println!("the text model does not stream: {why}"), |
| 151 | }; |
| 152 | FUSED.store(gemma4::combines_in_plan(&weights.offsets()), std::sync::atomic::Ordering::Relaxed); |
| 153 | println!("text plans combine the per-layer rows: {}", fused()); |
| 154 | let mut embed_weights = match open_streamed(&embed, graph::GEMMA4_EMBED) { |
| 155 | Ok(w) => w, |
| 156 | Err(why) => return println!("the embedding does not stream: {why}"), |
| 157 | }; |
| 158 | println!("embed rows mapped: {}", embed_weights.map()); |
| 159 | let head_weights: Option<Streamed> = match &args.head { |
| 160 | Some(path) => match open_streamed(path, graph::GEMMA4_HEAD) { |
| 161 | Ok(w) => Some(w), |
| 162 | Err(why) => return println!("the head file does not stream: {why}"), |
| 163 | }, |
| 164 | None => None, |
| 165 | }; |
| 166 | let golden = match std::fs::read_to_string(&golden) { |
| 167 | Ok(text) => text, |
| 168 | Err(why) => return println!("cannot read the golden: {why}"), |
| 169 | }; |
| 170 | let (tokens, want_ids, want_logits) = parse_golden(&golden); |
| 171 | if tokens.is_empty() { |
| 172 | return println!("the golden holds no tokens"); |
| 173 | } |
| 174 | println!("tokens {tokens:?}"); |
| 175 | |
| 176 | let context = match context::shared() { |
| 177 | Ok(context) => context, |
| 178 | Err(why) => return println!("no Vulkan device: {why}"), |
| 179 | }; |
| 180 | if let Some(repeats) = args.time { |
| 181 | let mode = if args.topk { HeadOut::TopK } else if args.sample { HeadOut::Logits } else { HeadOut::Greedy }; |
| 182 | time_decode(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, repeats, mode, args.gather); |
| 183 | return print_memory(); |
| 184 | } |
| 185 | if args.soft { |
| 186 | if let Err(why) = soft_check(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens) { |
| 187 | println!("the soft check failed to run: {why}"); |
| 188 | } |
| 189 | return print_memory(); |
| 190 | } |
| 191 | if args.gather { |
| 192 | if let Err(why) = gather_check(&context, &embed_weights, &tokens) { |
| 193 | println!("the gather check failed: {why}"); |
| 194 | } |
| 195 | return print_memory(); |
| 196 | } |
| 197 | if let Some(k) = args.split { |
| 198 | let n = args.len.unwrap_or(tokens.len() as u32) as usize; |
| 199 | let prompt: Vec<u32> = tokens.iter().copied().cycle().take(n).collect(); |
| 200 | if let Err(why) = split_check(&context, &weights, &embed_weights, head_weights.as_ref(), &prompt, k) { |
| 201 | println!("the split check failed to run: {why}"); |
| 202 | } |
| 203 | return print_memory(); |
| 204 | } |
| 205 | if let Some(widths) = args.prefill { |
| 206 | // `--spread`: a prompt of distinct ids, where no row read repeats (the golden cycles 6). |
| 207 | let spread: Vec<u32> = (0..TIER).map(|i| (i * 7919 + 1000) % 250_000).collect(); |
| 208 | let prompt = if args.spread { &spread } else { &tokens }; |
| 209 | time_prefill(&context, &weights, &embed_weights, head_weights.as_ref(), prompt, &widths); |
| 210 | return print_memory(); |
| 211 | } |
| 212 | match run(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens) { |
| 213 | Ok(logits) => report(&logits, &want_ids, &want_logits), |
| 214 | Err(why) => println!("the decode failed: {why}"), |
| 215 | } |
| 216 | print_memory(); |
| 217 | |
| 218 | // Bisect: where do the two first disagree? Only useful when the logits already failed, but |
| 219 | // cheap enough to always print. |
| 220 | let Some(trace_path) = args.positional.get(3) else { return }; |
| 221 | let Ok(trace) = std::fs::read_to_string(trace_path) else { |
| 222 | return println!("cannot read {trace_path}"); |
| 223 | }; |
| 224 | println!(); |
| 225 | println!("bisect against the reference's intermediates"); |
| 226 | for (label, layers) in [("ple_combined", 0usize), ("l0_out", 1), ("l1_out", 2)] { |
| 227 | let Some(want) = field(&trace, label) else { |
| 228 | println!(" {label:<14} not in the trace file"); |
| 229 | continue; |
| 230 | }; |
| 231 | match trace_run(&context, &weights, &embed_weights, &tokens, layers) { |
| 232 | Ok((hidden, per_layer)) => { |
| 233 | let got: &[f32] = if label == "ple_combined" { &per_layer } else { &hidden }; |
| 234 | println!(" {label:<14} {}", compare(got, &want)); |
| 235 | } |
| 236 | Err(why) => println!(" {label:<14} failed: {why}"), |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // L0 tail bisect: the four branch vectors against the numpy-fp oracle, in |
| 241 | // tail order. The first label where the device drops below 0.99 while numpy |
| 242 | // holds is the divergence point (see `Mode::TraceTail`). |
| 243 | let Some(tail_path) = args.positional.get(4) else { return }; |
| 244 | let Ok(tail) = std::fs::read_to_string(tail_path) else { |
| 245 | return println!("cannot read {tail_path}"); |
| 246 | }; |
| 247 | println!(); |
| 248 | println!("L0 tail against the numpy oracle"); |
| 249 | match tail_run(&context, &weights, &embed_weights, &tokens) { |
| 250 | Ok(branches) => { |
| 251 | for (label, got) in |
| 252 | ["attn_branch", "mlp_branch", "ple_branch", "l0_out"].into_iter().zip(branches.iter()) |
| 253 | { |
| 254 | match field(&tail, label) { |
| 255 | Some(want) => println!(" {label:<14} {}", compare(got, &want)), |
| 256 | None => println!(" {label:<14} not in the tail file"), |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | Err(why) => println!(" the tail trace failed: {why}"), |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// Cosine and relative RMS between a device tensor and the reference's. |
| 265 | fn compare(got: &[f32], want: &[f32]) -> String { |
| 266 | if got.len() != want.len() { |
| 267 | return format!("length {} against {}", got.len(), want.len()); |
| 268 | } |
| 269 | let dot: f64 = got.iter().zip(want).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum(); |
| 270 | let na: f64 = got.iter().map(|a| f64::from(*a) * f64::from(*a)).sum::<f64>().sqrt(); |
| 271 | let nb: f64 = want.iter().map(|b| f64::from(*b) * f64::from(*b)).sum::<f64>().sqrt(); |
| 272 | let cosine = dot / (na * nb).max(1e-30); |
| 273 | let verdict = if cosine > 0.99 { "ok" } else { "WRONG" }; |
| 274 | format!("cosine {cosine:.6} rms {:.4} against {:.4} {verdict}", na / got.len() as f64, nb / want.len() as f64) |
| 275 | } |
| 276 | |
| 277 | /// One named array from the trace file. |
| 278 | fn field(text: &str, key: &str) -> Option<Vec<f32>> { |
| 279 | let at = text.find(&format!("\"{key}\""))?; |
| 280 | let rest = &text[at..]; |
| 281 | let open = rest.find('[')?; |
| 282 | let close = rest[open..].find(']')?; |
| 283 | Some(rest[open + 1..open + close].split(',').filter_map(|p| p.trim().parse().ok()).collect()) |
| 284 | } |
| 285 | |
| 286 | /// [`run`] stopping after `layers` layers, returning `(hidden, per_layer)`. |
| 287 | fn trace_run( |
| 288 | context: &Arc<context::Context>, |
| 289 | weights: &Streamed, |
| 290 | embed: &Streamed, |
| 291 | tokens: &[u32], |
| 292 | layers: usize, |
| 293 | ) -> Result<(Vec<f32>, Vec<f32>), String> { |
| 294 | let mode = gemma4::Mode::Trace { layers }.at(TIER); |
| 295 | let mut net = streamed_net(context, weights, mode, gemma4_plan)?; |
| 296 | let reader = embed.reader(); |
| 297 | let rotary = weights.reader(); |
| 298 | let mut last = (Vec::new(), Vec::new()); |
| 299 | for (step, &token) in tokens.iter().enumerate() { |
| 300 | let position = u32::try_from(step).map_err(|_| "a step past u32")?; |
| 301 | let (hidden, per_layer) = gather_in(&reader, token)?; |
| 302 | let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; |
| 303 | let angles_global = |
| 304 | rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; |
| 305 | let at = net.at(mode)?; |
| 306 | at.set_params(StepParams { |
| 307 | prefix: position, |
| 308 | window_start: position.saturating_sub(gemma4::WINDOW - 1), |
| 309 | })?; |
| 310 | let out = at.infer_raw_many(&[&hidden, &per_layer, &angles_local, &angles_global])?; |
| 311 | let mut it = out.into_iter(); |
| 312 | last = (it.next().unwrap_or_default(), it.next().unwrap_or_default()); |
| 313 | } |
| 314 | Ok(last) |
| 315 | } |
| 316 | |
| 317 | /// Layer 0's four tail branches at the last step, in tail order |
| 318 | /// (`attn_branch`, `mlp_branch`, `ple_branch`, `l0_out`). |
| 319 | /// |
| 320 | /// Same OOM-safe shape as [`trace_run`]: the KV cache fills one step at a time and only |
| 321 | /// the last step's four 1536-float branches are kept. |
| 322 | fn tail_run( |
| 323 | context: &Arc<context::Context>, |
| 324 | weights: &Streamed, |
| 325 | embed: &Streamed, |
| 326 | tokens: &[u32], |
| 327 | ) -> Result<[Vec<f32>; 4], String> { |
| 328 | let mode = gemma4::Mode::TraceTail.at(TIER); |
| 329 | let mut net = streamed_net(context, weights, mode, gemma4_plan)?; |
| 330 | let reader = embed.reader(); |
| 331 | let rotary = weights.reader(); |
| 332 | let mut last = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; |
| 333 | for (step, &token) in tokens.iter().enumerate() { |
| 334 | let position = u32::try_from(step).map_err(|_| "a step past u32")?; |
| 335 | let (hidden, per_layer) = gather_in(&reader, token)?; |
| 336 | let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; |
| 337 | let angles_global = |
| 338 | rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; |
| 339 | let at = net.at(mode)?; |
| 340 | at.set_params(StepParams { |
| 341 | prefix: position, |
| 342 | window_start: position.saturating_sub(gemma4::WINDOW - 1), |
| 343 | })?; |
| 344 | let out = at.infer_raw_many(&[&hidden, &per_layer, &angles_local, &angles_global])?; |
| 345 | if out.len() != 4 { |
| 346 | return Err(format!("a tail step returned {} tensors, not the four branches", out.len())); |
| 347 | } |
| 348 | let mut it = out.into_iter(); |
| 349 | last = [ |
| 350 | it.next().unwrap_or_default(), |
| 351 | it.next().unwrap_or_default(), |
| 352 | it.next().unwrap_or_default(), |
| 353 | it.next().unwrap_or_default(), |
| 354 | ]; |
| 355 | } |
| 356 | Ok(last) |
| 357 | } |
| 358 | |
| 359 | /// One decode step's host and device split, in ms. |
| 360 | #[derive(Default)] |
| 361 | struct StepTimes { |
| 362 | rows: f64, |
| 363 | combine: f64, |
| 364 | infer: f64, |
| 365 | head: f64, |
| 366 | } |
| 367 | |
| 368 | /// One token through the app's decode path: host rows + combine, the |
| 369 | /// transformer submit, then the head submit. Returns the next token (device |
| 370 | /// argmax, or the host argmax over softcapped logits with `sample`). |
| 371 | #[allow(clippy::too_many_arguments)] |
| 372 | fn decode_one( |
| 373 | net: &mut Reshaped<gemma4::Pass>, |
| 374 | head: Option<&mut Reshaped<HeadOut>>, |
| 375 | gather: Option<&mut Reshaped<u32>>, |
| 376 | embed: &modelrunner::weights::Reader<'_>, |
| 377 | rotary: &modelrunner::weights::Reader<'_>, |
| 378 | token: u32, |
| 379 | position: u32, |
| 380 | mode: HeadOut, |
| 381 | times: &mut StepTimes, |
| 382 | ) -> Result<Option<u32>, String> { |
| 383 | use std::time::Instant; |
| 384 | let (hidden_in, per_layer, gtimes) = match gather { |
| 385 | _ if fused() => { |
| 386 | let tick = Instant::now(); |
| 387 | let (hidden, embedded) = gemma4::gather_input(embed, token, true)?; |
| 388 | let rows_ms = tick.elapsed().as_secs_f64() * 1000.0; |
| 389 | (hidden, embedded, gemma4::GatherTimes { rows_ms, bulk_ms: 0.0, matmul_ms: 0.0 }) |
| 390 | } |
| 391 | Some(gather) => { |
| 392 | let tick = Instant::now(); |
| 393 | let hidden = embed.int4_row( |
| 394 | gemma4::embed::TOKENS, |
| 395 | gemma4::embed::TOKENS + 1, |
| 396 | &[gemma4::VOCAB, gemma4::D_MODEL], |
| 397 | token, |
| 398 | )?; |
| 399 | let row = if gemma4::embed::PLACEHOLDERS.contains(&token) { 0 } else { token }; |
| 400 | let mut embedded = Vec::with_capacity((gemma4::PER_LAYER as usize) * gemma4::LAYERS); |
| 401 | for i in 0..gemma4::LAYERS { |
| 402 | let at = gemma4::embed::table(i); |
| 403 | embedded.extend(embed.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], row)?); |
| 404 | } |
| 405 | let rows_ms = tick.elapsed().as_secs_f64() * 1000.0; |
| 406 | let tick = Instant::now(); |
| 407 | let out = gather.at(1)?.infer_raw_many(&[&hidden, &embedded])?; |
| 408 | let per_layer = out.into_iter().next().ok_or("the gather net returned nothing")?; |
| 409 | let matmul_ms = tick.elapsed().as_secs_f64() * 1000.0; |
| 410 | (hidden, per_layer, gemma4::GatherTimes { rows_ms, bulk_ms: 0.0, matmul_ms }) |
| 411 | } |
| 412 | None => gemma4::gather_timed(embed, token)?, |
| 413 | }; |
| 414 | let rows_tick = Instant::now(); |
| 415 | let angles_local = rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; |
| 416 | let angles_global = rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; |
| 417 | times.rows += gtimes.rows_ms + gtimes.bulk_ms + rows_tick.elapsed().as_secs_f64() * 1000.0; |
| 418 | times.combine += gtimes.matmul_ms; |
| 419 | let tick = Instant::now(); |
| 420 | let at = net.at(gemma4::Mode::DecodeStep.at(TIER))?; |
| 421 | at.set_params(StepParams { |
| 422 | prefix: position, |
| 423 | window_start: position.saturating_sub(gemma4::WINDOW - 1), |
| 424 | })?; |
| 425 | let out = at.infer_raw_many(&[&hidden_in, &per_layer, &angles_local, &angles_global])?; |
| 426 | times.infer += tick.elapsed().as_secs_f64() * 1000.0; |
| 427 | let Some(head) = head else { return Ok(None) }; |
| 428 | let hidden = out.into_iter().next().ok_or("the step returned nothing")?; |
| 429 | let tick = Instant::now(); |
| 430 | let out = head.at(mode)?.infer_raw_many(&[&hidden])?; |
| 431 | let id = if mode == HeadOut::TopK { |
| 432 | let top = out.first().ok_or("the top-k head returned nothing")?; |
| 433 | top[2] as u32 * 2048 + top[1] as u32 |
| 434 | } else if mode == HeadOut::Logits { |
| 435 | let logits = softcapped(&out)?; |
| 436 | let mut best = (f32::NEG_INFINITY, 0u32); |
| 437 | for (i, &v) in logits.iter().enumerate() { |
| 438 | if v > best.0 { |
| 439 | best = (v, i as u32); |
| 440 | } |
| 441 | } |
| 442 | best.1 |
| 443 | } else { |
| 444 | let id = out.last().ok_or("the greedy head returned nothing")?; |
| 445 | if id.len() != 2 { |
| 446 | return Err(format!("greedy id holds {} values, not 2", id.len())); |
| 447 | } |
| 448 | id[1] as u32 * 2048 + id[0] as u32 |
| 449 | }; |
| 450 | times.head += tick.elapsed().as_secs_f64() * 1000.0; |
| 451 | Ok(Some(id)) |
| 452 | } |
| 453 | |
| 454 | fn build_head(context: &Arc<context::Context>, head: Option<&Streamed>, mode: HeadOut) -> Result<Option<Reshaped<HeadOut>>, String> { |
| 455 | match head { |
| 456 | Some(file) => streamed_net(context, file, mode, head_plan).map(Some), |
| 457 | None => { |
| 458 | println!("no --head: timings exclude the head"); |
| 459 | Ok(None) |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | /// Decode-speed probe: the app's per-token loop repeated `repeats` times over |
| 465 | /// the golden's tokens. Pass 0 is warmup; the rest are steady state. With a |
| 466 | /// head file each step includes the head: the device-greedy plan, or with |
| 467 | /// `--sample` the full-logits readback + softcap the sampling path pays. |
| 468 | #[allow(clippy::too_many_arguments)] |
| 469 | fn time_decode( |
| 470 | context: &Arc<context::Context>, |
| 471 | weights: &Streamed, |
| 472 | embed: &Streamed, |
| 473 | head: Option<&Streamed>, |
| 474 | tokens: &[u32], |
| 475 | repeats: usize, |
| 476 | mode: HeadOut, |
| 477 | device_gather: bool, |
| 478 | ) { |
| 479 | use std::time::Instant; |
| 480 | let mut net = match streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan) { |
| 481 | Ok(net) => net, |
| 482 | Err(why) => return println!("the net does not build: {why}"), |
| 483 | }; |
| 484 | let mut gather_net = if device_gather { |
| 485 | match gather_plan(context, embed) { |
| 486 | Ok(net) => Some(net), |
| 487 | Err(why) => return println!("the gather net does not build: {why}"), |
| 488 | } |
| 489 | } else { |
| 490 | None |
| 491 | }; |
| 492 | let mut head_net = match build_head(context, head, mode) { |
| 493 | Ok(net) => net, |
| 494 | Err(why) => return println!("the head does not build: {why}"), |
| 495 | }; |
| 496 | let reader = embed.reader(); |
| 497 | let rotary = weights.reader(); |
| 498 | let stamps = modelrunner::knobs::is_set("timestamps"); |
| 499 | let repeats = repeats.max(1); |
| 500 | let mut steady: Vec<f64> = Vec::new(); |
| 501 | let mut split = StepTimes::default(); |
| 502 | let mut ids = Vec::new(); |
| 503 | for pass in 0..repeats { |
| 504 | let mut step_ms: Vec<f64> = Vec::with_capacity(tokens.len()); |
| 505 | ids.clear(); |
| 506 | for (step, &token) in tokens.iter().enumerate() { |
| 507 | let tick = Instant::now(); |
| 508 | let mut times = StepTimes::default(); |
| 509 | match decode_one(&mut net, head_net.as_mut(), gather_net.as_mut(), &reader, &rotary, token, step as u32, mode, &mut times) { |
| 510 | Ok(id) => ids.extend(id), |
| 511 | Err(why) => return println!("step {step} failed: {why}"), |
| 512 | } |
| 513 | step_ms.push(tick.elapsed().as_secs_f64() * 1000.0); |
| 514 | if pass > 0 { |
| 515 | split.rows += times.rows; |
| 516 | split.combine += times.combine; |
| 517 | split.infer += times.infer; |
| 518 | split.head += times.head; |
| 519 | } |
| 520 | } |
| 521 | let mean = step_ms.iter().sum::<f64>() / step_ms.len().max(1) as f64; |
| 522 | println!("pass {pass}: {} steps, mean {mean:.1} ms/step", step_ms.len()); |
| 523 | if pass > 0 { |
| 524 | steady.extend(step_ms); |
| 525 | } |
| 526 | } |
| 527 | println!("next-token ids {ids:?}"); |
| 528 | if !steady.is_empty() { |
| 529 | let n = steady.len() as f64; |
| 530 | let mean = steady.iter().sum::<f64>() / n; |
| 531 | println!( |
| 532 | "steady-state ({}): {mean:.1} ms/token = {:.2} tok/s", |
| 533 | if head_net.is_none() { "no head" } else { match mode { HeadOut::Logits => "sampled head", HeadOut::TopK => "top-k head", HeadOut::Greedy => "greedy head" } }, |
| 534 | 1000.0 / mean.max(1e-9) |
| 535 | ); |
| 536 | println!( |
| 537 | "per step: rows {:.1} ms, combine {:.1} ms, infer {:.1} ms, head {:.1} ms ({} steps)", |
| 538 | split.rows / n, |
| 539 | split.combine / n, |
| 540 | split.infer / n, |
| 541 | split.head / n, |
| 542 | steady.len() |
| 543 | ); |
| 544 | } |
| 545 | if stamps { |
| 546 | match net.at(gemma4::Mode::DecodeStep.at(TIER)).and_then(|at| at.op_times()) { |
| 547 | Ok(report) => { |
| 548 | print_kinds("decode step", &report); |
| 549 | if let Ok(plan) = gemma4::build(&weights.offsets(), gemma4::Mode::DecodeStep.at(TIER)) { |
| 550 | print_shapes(&report, &plan); |
| 551 | } |
| 552 | } |
| 553 | Err(why) => println!("timestamps unreadable: {why}"), |
| 554 | } |
| 555 | if let Some(head) = head_net.as_mut() { |
| 556 | match head.at(mode).and_then(|at| at.op_times()) { |
| 557 | Ok(report) => print_kinds("head", &report), |
| 558 | Err(why) => println!("head timestamps unreadable: {why}"), |
| 559 | } |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | /// Write one position's `values` into column `column` of a `[C, 1, width]` block. |
| 565 | fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) { |
| 566 | for (channel, &value) in values.iter().enumerate() { |
| 567 | into[channel * width as usize + column as usize] = value; |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | /// The device combine over the EMBED file, uploading only the tensors it reads, keyed by width. |
| 572 | fn gather_plan(context: &Arc<context::Context>, embed: &Streamed) -> Result<Reshaped<u32>, String> { |
| 573 | Reshaped::windowed(Arc::clone(context), embed.offsets(), embed, &[1], |offsets, width| { |
| 574 | modelrunner::nets::gemma4_gather::build_plan_at(offsets, width) |
| 575 | }) |
| 576 | } |
| 577 | |
| 578 | /// Positions one prefill submit covers. Mirrors the bridge's `CHUNK`. |
| 579 | const CHUNK: usize = 256; |
| 580 | |
| 581 | /// Milliseconds per stage of one prompt, summed over its chunks. |
| 582 | #[derive(Default)] |
| 583 | struct PrefillTimes { |
| 584 | rows: f64, |
| 585 | combine: f64, |
| 586 | rotary: f64, |
| 587 | plan_wait: f64, |
| 588 | record: f64, |
| 589 | gpu: f64, |
| 590 | /// The last token's `Mode::Tail` submit. |
| 591 | tail: f64, |
| 592 | /// Per-kind GPU tables of the last chunk's prefill and tail, under `MODELRUNNER_TIMESTAMPS`. |
| 593 | reports: Vec<(&'static str, Vec<(String, f64, f64)>)>, |
| 594 | /// The last token's final-normed state, which the head reads. |
| 595 | state: Vec<f32>, |
| 596 | } |
| 597 | |
| 598 | /// `prompt` at position 0 exactly as `Gemma4Handle::prefill` feeds it: per chunk (padded to |
| 599 | /// `gemma4_gather::padded` when `pad`), the host rows straight into `[C, 1, T]` while an evicted |
| 600 | /// plan builds on another thread, one device combine, the rotary rows, then the Prefill submit. |
| 601 | fn prefill_app( |
| 602 | net: &mut Reshaped<gemma4::Pass>, |
| 603 | gather: Option<&mut Reshaped<u32>>, |
| 604 | embed: &modelrunner::weights::Reader<'_>, |
| 605 | rotary: &modelrunner::weights::Reader<'_>, |
| 606 | prompt: &[u32], |
| 607 | pad: bool, |
| 608 | ) -> Result<PrefillTimes, String> { |
| 609 | use modelrunner::nets::gemma4_gather as g; |
| 610 | use std::time::Instant; |
| 611 | let mut times = PrefillTimes::default(); |
| 612 | let mut gather = gather; |
| 613 | for (index, chunk) in prompt.chunks(CHUNK).enumerate() { |
| 614 | let start = (index * CHUNK) as u32; |
| 615 | let width = if pad { g::padded(chunk.len() as u32, TIER - start) } else { chunk.len() as u32 }; |
| 616 | let mut fed = chunk.to_vec(); |
| 617 | fed.resize(width as usize, 0); |
| 618 | let mode = if start == 0 { gemma4::Mode::PrefillFresh { tokens: width } } else { gemma4::Mode::Prefill { tokens: width } }.at(TIER); |
| 619 | let mut pending = (!net.holds(mode)).then(|| net.planner()); |
| 620 | let tick = Instant::now(); |
| 621 | if fused() { |
| 622 | // As `Gemma4Handle::prefill_chunk`: built on this thread, which keeps its core awake. |
| 623 | if let Some((plan, offsets)) = pending.take() { |
| 624 | net.adopt(mode, plan(&offsets, mode)?); |
| 625 | } |
| 626 | } |
| 627 | times.plan_wait += tick.elapsed().as_secs_f64() * 1000.0; |
| 628 | let tick = Instant::now(); |
| 629 | let building = pending.map(|(plan, offsets)| std::thread::spawn(move || plan(&offsets, mode))); |
| 630 | let tables = if fused() { gemma4::OWNS_CACHE_LAYERS } else { gemma4::LAYERS }; |
| 631 | let (hidden, embedded) = g::token_rows(embed, &fed).and_then(|h| Ok((h, g::leading_layer_rows(embed, &fed, tables)?)))?; |
| 632 | let tail_rows = if fused() { Some(g::layer_rows(embed, &chunk[chunk.len() - 1..])?) } else { None }; |
| 633 | times.rows += tick.elapsed().as_secs_f64() * 1000.0; |
| 634 | let tick = Instant::now(); |
| 635 | let per_layer = if fused() { |
| 636 | embedded |
| 637 | } else { |
| 638 | let gather = gather.as_deref_mut().ok_or("no gather net for an unfused text file")?; |
| 639 | gather.at(width)?.infer_raw_many(&[&hidden, &embedded])?.into_iter().next().ok_or("no combine")? |
| 640 | }; |
| 641 | times.combine += tick.elapsed().as_secs_f64() * 1000.0; |
| 642 | let tick = Instant::now(); |
| 643 | if let Some(thread) = building { |
| 644 | let plan = thread.join().map_err(|_| "the plan thread panicked".to_string())?; |
| 645 | net.adopt(mode, plan?); |
| 646 | } |
| 647 | times.plan_wait += tick.elapsed().as_secs_f64() * 1000.0; |
| 648 | let tick = Instant::now(); |
| 649 | let mut local = vec![0f32; (gemma4::HEAD_DIM * width) as usize]; |
| 650 | let mut global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize]; |
| 651 | for column in 0..width { |
| 652 | let position = start + column; |
| 653 | place(&mut local, &rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?, column, width); |
| 654 | place(&mut global, &rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?, column, width); |
| 655 | } |
| 656 | times.rotary += tick.elapsed().as_secs_f64() * 1000.0; |
| 657 | let tick = Instant::now(); |
| 658 | let at = net.at(mode)?; |
| 659 | times.record += tick.elapsed().as_secs_f64() * 1000.0; |
| 660 | let tick = Instant::now(); |
| 661 | at.set_params(StepParams { prefix: start, window_start: start.saturating_sub(gemma4::WINDOW - 1) })?; |
| 662 | let out = at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?; |
| 663 | times.gpu += tick.elapsed().as_secs_f64() * 1000.0; |
| 664 | let stamps = modelrunner::knobs::is_set("timestamps"); |
| 665 | times.reports = if stamps { at.op_times().map(|r| vec![("prefill", r)]).unwrap_or_default() } else { Vec::new() }; |
| 666 | if (index + 1) * CHUNK < prompt.len() { |
| 667 | continue; |
| 668 | } |
| 669 | // As `Gemma4Handle::tail`: the last real column through the layers that own no cache. |
| 670 | let tick = Instant::now(); |
| 671 | let last = chunk.len() - 1; |
| 672 | let residual = out.first().ok_or("a prefill returned nothing")?; |
| 673 | let mut inputs = gemma4::tail_inputs(residual, [&hidden, &per_layer, &local, &global], last, width as usize, fused()); |
| 674 | if let Some(rows) = tail_rows { |
| 675 | inputs[1] = rows; |
| 676 | } |
| 677 | let at = net.at(gemma4::Mode::Tail.at(TIER))?; |
| 678 | let position = start + last as u32; |
| 679 | at.set_params(StepParams { prefix: position, window_start: position.saturating_sub(gemma4::WINDOW - 1) })?; |
| 680 | let refs: Vec<&[f32]> = inputs.iter().map(Vec::as_slice).collect(); |
| 681 | times.state = at.infer_raw_many(&refs)?.into_iter().next().ok_or("the tail returned nothing")?; |
| 682 | times.tail += tick.elapsed().as_secs_f64() * 1000.0; |
| 683 | if let Some(report) = stamps.then(|| at.op_times().ok()).flatten() { |
| 684 | times.reports.push(("tail", report)); |
| 685 | } |
| 686 | } |
| 687 | Ok(times) |
| 688 | } |
| 689 | |
| 690 | /// TTFT as the app sees it: `prefill_app` for a prompt of each width (the golden's tokens cycled), |
| 691 | /// then the first greedy step (device combine, DecodeStep record, step, head). Each width runs |
| 692 | /// cold then warm, and the widths run back to back as consecutive prompts would. |
| 693 | fn time_prefill( |
| 694 | context: &Arc<context::Context>, |
| 695 | weights: &Streamed, |
| 696 | embed: &Streamed, |
| 697 | head: Option<&Streamed>, |
| 698 | tokens: &[u32], |
| 699 | widths: &[u32], |
| 700 | ) { |
| 701 | use std::time::Instant; |
| 702 | let mut net = match streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan) { |
| 703 | Ok(net) => net, |
| 704 | Err(why) => return println!("the net does not build: {why}"), |
| 705 | }; |
| 706 | let mut head_net = match build_head(context, head, HeadOut::Greedy) { |
| 707 | Ok(net) => net, |
| 708 | Err(why) => return println!("the head does not build: {why}"), |
| 709 | }; |
| 710 | let mut gather = match (!fused()).then(|| gather_plan(context, embed)).transpose() { |
| 711 | Ok(net) => net, |
| 712 | Err(why) => return println!("the gather net does not build: {why}"), |
| 713 | }; |
| 714 | // As `build_gemma4` warms at load: the arena at the widest chunk, then the decode step. |
| 715 | let tick = Instant::now(); |
| 716 | let warmed = (|| -> Result<(), String> { |
| 717 | net.at(gemma4::Mode::Prefill { tokens: 256 }.at(TIER))?; |
| 718 | net.at(gemma4::Mode::PrefillFresh { tokens: 256 }.at(TIER))?; |
| 719 | net.at(gemma4::Mode::Tail.at(TIER))?; |
| 720 | net.at(gemma4::Mode::DecodeStep.at(TIER))?; |
| 721 | for width in [256, 1] { |
| 722 | if let Some(gather) = gather.as_mut() { |
| 723 | gather.at(width)?; |
| 724 | } |
| 725 | } |
| 726 | if let Some(head) = head_net.as_mut() { |
| 727 | for out in [HeadOut::Logits, HeadOut::TopK, HeadOut::Greedy] { |
| 728 | head.at(out)?; |
| 729 | } |
| 730 | } |
| 731 | Ok(()) |
| 732 | })(); |
| 733 | if let Err(why) = warmed { |
| 734 | return println!("the warm-up failed: {why}"); |
| 735 | } |
| 736 | println!("load-time warm-up {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0); |
| 737 | let reader = embed.reader(); |
| 738 | let rotary = weights.reader(); |
| 739 | let stamps = modelrunner::knobs::is_set("timestamps"); |
| 740 | let mut prefill_report = None; |
| 741 | for &width in widths { |
| 742 | if width == 0 || width >= TIER { |
| 743 | println!("a {width}-token prompt does not fit the {TIER}-position cache"); |
| 744 | continue; |
| 745 | } |
| 746 | let prompt: Vec<u32> = tokens.iter().copied().cycle().take(width as usize).collect(); |
| 747 | let next = tokens[width as usize % tokens.len()]; |
| 748 | // The app's flow: Kotlin pushes the prompt, then steps its last token; native runs them as |
| 749 | // one prefill and the head reads the last column (`Gemma4Handle::fold_pending`). |
| 750 | let folded: Vec<u32> = prompt.iter().copied().chain([next]).collect(); |
| 751 | for run in 0..2 { |
| 752 | let start = Instant::now(); |
| 753 | let mut p = match prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &folded, true) { |
| 754 | Ok(p) => p, |
| 755 | Err(why) => return println!("the prefill failed: {why}"), |
| 756 | }; |
| 757 | let prefill_ms = start.elapsed().as_secs_f64() * 1000.0; |
| 758 | if stamps && run == 1 { |
| 759 | prefill_report = Some(std::mem::take(&mut p.reports)); |
| 760 | } |
| 761 | let tick = Instant::now(); |
| 762 | let id = match head_net.as_mut().map(|h| h.at(HeadOut::Greedy).and_then(|at| at.infer_raw_many(&[&p.state]))) { |
| 763 | Some(Ok(out)) => out.last().filter(|id| id.len() == 2).map(|id| id[1] as u32 * 2048 + id[0] as u32), |
| 764 | Some(Err(why)) => return println!("the head failed: {why}"), |
| 765 | None => None, |
| 766 | }; |
| 767 | let head_ms = tick.elapsed().as_secs_f64() * 1000.0; |
| 768 | println!( |
| 769 | "{} prefill {width}+1 tokens: rows {:.0} + plan wait {:.0} + combine {:.0} + rotary {:.0} + record {:.0} + gpu {:.0} + tail {:.0} = {prefill_ms:.0} ms; \ |
| 770 | head {head_ms:.0} ms (id {id:?}); TTFT {:.0} ms", |
| 771 | if run == 0 { "cold" } else { "warm" }, |
| 772 | p.rows, p.plan_wait, p.combine, p.rotary, p.record, p.gpu, p.tail, |
| 773 | prefill_ms + head_ms, |
| 774 | ); |
| 775 | } |
| 776 | // The old flow once (prefill the prompt, then a decode step), for the token to match. |
| 777 | let tick = Instant::now(); |
| 778 | let unfolded = prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &prompt, true).and_then(|_| { |
| 779 | let mut s = StepTimes::default(); |
| 780 | decode_one(&mut net, head_net.as_mut(), gather.as_mut(), &reader, &rotary, next, width, HeadOut::Greedy, &mut s) |
| 781 | }); |
| 782 | println!(" decode-step flow: id {unfolded:?}, {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0); |
| 783 | let margins = (|| -> Result<String, String> { |
| 784 | let head = head_net.as_mut().ok_or("no head")?; |
| 785 | let p = prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &folded, true)?; |
| 786 | let a = softcapped(&head.at(HeadOut::Logits)?.infer_raw_many(&[&p.state])?)?; |
| 787 | prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &prompt, true)?; |
| 788 | let b = last_logits(&mut net, head, &reader, &rotary, next, width)?; |
| 789 | let top3 = |l: &[f32]| top10(l).into_iter().take(3).map(|i| (i, l[i as usize])).collect::<Vec<_>>(); |
| 790 | Ok(format!("folded {:?} / decode-step {:?}", top3(&a), top3(&b))) |
| 791 | })(); |
| 792 | println!(" top3 {margins:?}"); |
| 793 | } |
| 794 | for (title, report) in prefill_report.unwrap_or_default() { |
| 795 | print_kinds(title, &report); |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | /// Feed `tokens` at positions `start..` without the head: one batched `Prefill` submit, or one |
| 800 | /// single-position pass each (the decode layer, which attends the cache). |
| 801 | fn feed( |
| 802 | net: &mut Reshaped<gemma4::Pass>, |
| 803 | embed: &modelrunner::weights::Reader<'_>, |
| 804 | rotary: &modelrunner::weights::Reader<'_>, |
| 805 | tokens: &[u32], |
| 806 | start: u32, |
| 807 | batched: bool, |
| 808 | ) -> Result<(), String> { |
| 809 | if tokens.is_empty() { |
| 810 | return Ok(()); |
| 811 | } |
| 812 | let params = |position: u32| StepParams { |
| 813 | prefix: position, |
| 814 | window_start: position.saturating_sub(gemma4::WINDOW - 1), |
| 815 | }; |
| 816 | if !batched { |
| 817 | for (offset, &token) in tokens.iter().enumerate() { |
| 818 | let position = start + offset as u32; |
| 819 | let (hidden, per_layer) = gather_in(embed, token)?; |
| 820 | let local = rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; |
| 821 | let global = rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; |
| 822 | let at = net.at(gemma4::Mode::Prefill { tokens: 1 }.at(TIER))?; |
| 823 | at.set_params(params(position))?; |
| 824 | at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?; |
| 825 | } |
| 826 | return Ok(()); |
| 827 | } |
| 828 | let width = tokens.len() as u32; |
| 829 | let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize]; |
| 830 | let mut per_layer = vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize]; |
| 831 | let mut local = vec![0f32; (gemma4::HEAD_DIM * width) as usize]; |
| 832 | let mut global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize]; |
| 833 | for (column, &token) in tokens.iter().enumerate() { |
| 834 | let column = column as u32; |
| 835 | let (h, p) = gather_in(embed, token)?; |
| 836 | place(&mut hidden, &h, column, width); |
| 837 | place(&mut per_layer, &p, column, width); |
| 838 | place(&mut local, &rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, start + column)?, column, width); |
| 839 | place( |
| 840 | &mut global, |
| 841 | &rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, start + column)?, |
| 842 | column, |
| 843 | width, |
| 844 | ); |
| 845 | } |
| 846 | // As the bridge does: a chunk at position 0 attends itself, any later one the cache. |
| 847 | let mode = if start == 0 { |
| 848 | gemma4::Mode::PrefillFresh { tokens: width } |
| 849 | } else { |
| 850 | gemma4::Mode::Prefill { tokens: width } |
| 851 | }; |
| 852 | let at = net.at(mode.at(TIER))?; |
| 853 | at.set_params(params(start))?; |
| 854 | at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?; |
| 855 | Ok(()) |
| 856 | } |
| 857 | |
| 858 | /// The last token as a decode step at `position`, then the logits head. |
| 859 | #[allow(clippy::too_many_arguments)] |
| 860 | fn last_logits( |
| 861 | net: &mut Reshaped<gemma4::Pass>, |
| 862 | head: &mut Reshaped<HeadOut>, |
| 863 | embed: &modelrunner::weights::Reader<'_>, |
| 864 | rotary: &modelrunner::weights::Reader<'_>, |
| 865 | token: u32, |
| 866 | position: u32, |
| 867 | ) -> Result<Vec<f32>, String> { |
| 868 | let (hidden, per_layer) = gather_in(embed, token)?; |
| 869 | let local = rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; |
| 870 | let global = rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; |
| 871 | let at = net.at(gemma4::Mode::DecodeStep.at(TIER))?; |
| 872 | at.set_params(StepParams { prefix: position, window_start: position.saturating_sub(gemma4::WINDOW - 1) })?; |
| 873 | let out = at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?; |
| 874 | let state = out.into_iter().next().ok_or("the step returned nothing")?; |
| 875 | softcapped(&head.at(HeadOut::Logits)?.infer_raw_many(&[&state])?) |
| 876 | } |
| 877 | |
| 878 | fn top10(logits: &[f32]) -> Vec<u32> { |
| 879 | let mut order: Vec<u32> = (0..logits.len() as u32).collect(); |
| 880 | order.sort_by(|&a, &b| logits[b as usize].total_cmp(&logits[a as usize])); |
| 881 | order.truncate(10); |
| 882 | order |
| 883 | } |
| 884 | |
| 885 | /// A prompt split `[0..k at 0][k..n-1 at k]` must give the next-token ranking the whole prompt |
| 886 | /// gives at 0. Variants: whole batched (reference), all sequential, the app's stopgap (batched |
| 887 | /// head + sequential tail), and a batched tail (correct only once prefill attends the cache). |
| 888 | fn split_check( |
| 889 | context: &Arc<context::Context>, |
| 890 | weights: &Streamed, |
| 891 | embed: &Streamed, |
| 892 | head: Option<&Streamed>, |
| 893 | prompt: &[u32], |
| 894 | k: u32, |
| 895 | ) -> Result<(), String> { |
| 896 | let n = prompt.len(); |
| 897 | let k = k as usize; |
| 898 | if n < 3 || k == 0 || k + 1 >= n || n as u32 >= TIER { |
| 899 | return Err(format!("need 0 < k < n - 1 and n < {TIER}; got k {k}, n {n}")); |
| 900 | } |
| 901 | let head = head.ok_or("the split check needs --head")?; |
| 902 | let mut net = streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan)?; |
| 903 | let mut head_net = streamed_net(context, head, HeadOut::Logits, head_plan)?; |
| 904 | let reader = embed.reader(); |
| 905 | let rotary = weights.reader(); |
| 906 | let last = prompt[n - 1]; |
| 907 | let body = &prompt[..n - 1]; |
| 908 | let (front, tail) = body.split_at(k); |
| 909 | let mut run = |label: &str, front_batched: bool, tail_batched: bool, whole: bool| -> Result<Vec<f32>, String> { |
| 910 | let tick = std::time::Instant::now(); |
| 911 | let mut tail_ms = 0.0; |
| 912 | if whole { |
| 913 | feed(&mut net, &reader, &rotary, body, 0, front_batched)?; |
| 914 | } else { |
| 915 | feed(&mut net, &reader, &rotary, front, 0, front_batched)?; |
| 916 | let tail_tick = std::time::Instant::now(); |
| 917 | feed(&mut net, &reader, &rotary, tail, k as u32, tail_batched)?; |
| 918 | tail_ms = tail_tick.elapsed().as_secs_f64() * 1000.0; |
| 919 | } |
| 920 | let logits = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?; |
| 921 | let caches = net.at(gemma4::Mode::DecodeStep.at(TIER))?.export_pinned(gemma4::CACHE_TENSORS, n as u32)?; |
| 922 | let hash = caches.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)); |
| 923 | println!( |
| 924 | " {label:<32} {:>7.0} ms (tail {tail_ms:.0} ms = {:.1} ms/token) caches {hash:016x} top10 {:?}", |
| 925 | tick.elapsed().as_secs_f64() * 1000.0, |
| 926 | tail_ms / tail.len().max(1) as f64, |
| 927 | top10(&logits) |
| 928 | ); |
| 929 | Ok(logits) |
| 930 | }; |
| 931 | println!("split check: {n} tokens, split at {k}"); |
| 932 | // Widest batch first so the arena grows before anything it holds matters. |
| 933 | let reference = run("whole batched at 0", true, true, true)?; |
| 934 | let variants = [ |
| 935 | ("all sequential", run("all sequential", false, false, true)?), |
| 936 | ("batched head + sequential tail", run("batched head + sequential tail", true, false, false)?), |
| 937 | ("batched head + batched tail", run("batched head + batched tail", true, true, false)?), |
| 938 | ]; |
| 939 | let want = top10(&reference); |
| 940 | let mut gather = if fused() { None } else { Some(gather_plan(context, embed)?) }; |
| 941 | prefill_app(&mut net, gather.as_mut(), &reader, &rotary, body, false)?; |
| 942 | let exact = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?; |
| 943 | println!(" {:<32} top10 {:?}", "app path, unpadded", top10(&exact)); |
| 944 | prefill_app(&mut net, gather.as_mut(), &reader, &rotary, body, true)?; |
| 945 | let app = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?; |
| 946 | println!(" {:<32} top10 {:?}", "app path (rows + device combine)", top10(&app)); |
| 947 | let pad_diff = app.iter().zip(&exact).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); |
| 948 | println!(" padding {} -> {}: max |logit diff| vs unpadded {pad_diff:.4}", body.len(), body.len().div_ceil(8) * 8); |
| 949 | let folded = prefill_app(&mut net, gather.as_mut(), &reader, &rotary, prompt, true)?; |
| 950 | let folded = softcapped(&head_net.at(HeadOut::Logits)?.infer_raw_many(&[&folded.state])?)?; |
| 951 | println!(" {:<32} top10 {:?}", "app path, last token folded", top10(&folded)); |
| 952 | let variants = [ |
| 953 | variants[0].clone(), |
| 954 | variants[1].clone(), |
| 955 | variants[2].clone(), |
| 956 | ("app path (rows + device combine)", app), |
| 957 | ("app path, last token folded", folded), |
| 958 | ]; |
| 959 | for (label, logits) in &variants { |
| 960 | let got = top10(logits); |
| 961 | let max_diff = logits.iter().zip(&reference).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); |
| 962 | let verdict = if got == want { |
| 963 | "SAME top10" |
| 964 | } else if got[0] == want[0] { |
| 965 | "same argmax, top10 reordered" |
| 966 | } else { |
| 967 | "ARGMAX DIFFERS" |
| 968 | }; |
| 969 | println!(" {label:<32} {verdict}, max |logit diff| {max_diff:.4}"); |
| 970 | } |
| 971 | Ok(()) |
| 972 | } |
| 973 | |
| 974 | /// The device combine (`gemma4_gather`, uploaded through `Reshaped::windowed` so only the |
| 975 | /// tensors it reads leave the 3.6 GB file) against the host `combine_cached`, per token. |
| 976 | fn gather_check(context: &Arc<context::Context>, embed: &Streamed, tokens: &[u32]) -> Result<(), String> { |
| 977 | use std::time::Instant; |
| 978 | let tick = Instant::now(); |
| 979 | let mut net = gather_plan(context, embed)?; |
| 980 | println!("gather net built in {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0); |
| 981 | let reader = embed.reader(); |
| 982 | let (mut host_ms, mut device_ms, mut worst) = (0.0, 0.0, 0f32); |
| 983 | let mut device_cols = Vec::new(); |
| 984 | let repeats = 4; |
| 985 | for pass in 0..repeats { |
| 986 | for &token in tokens { |
| 987 | let hidden = reader.int4_row( |
| 988 | gemma4::embed::TOKENS, |
| 989 | gemma4::embed::TOKENS + 1, |
| 990 | &[gemma4::VOCAB, gemma4::D_MODEL], |
| 991 | token, |
| 992 | )?; |
| 993 | let row = if gemma4::embed::PLACEHOLDERS.contains(&token) { 0 } else { token }; |
| 994 | let mut embedded = Vec::with_capacity((gemma4::PER_LAYER as usize) * gemma4::LAYERS); |
| 995 | for i in 0..gemma4::LAYERS { |
| 996 | let at = gemma4::embed::table(i); |
| 997 | embedded.extend(reader.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], row)?); |
| 998 | } |
| 999 | let tick = Instant::now(); |
| 1000 | let host = gemma4::combine_cached(&reader, &hidden, &embedded)?; |
| 1001 | let host_t = tick.elapsed().as_secs_f64() * 1000.0; |
| 1002 | let tick = Instant::now(); |
| 1003 | let out = net.at(1)?.infer_raw_many(&[&hidden, &embedded])?; |
| 1004 | let device_t = tick.elapsed().as_secs_f64() * 1000.0; |
| 1005 | let device = out.into_iter().next().ok_or("the gather net returned nothing")?; |
| 1006 | if pass == 0 { |
| 1007 | device_cols.push(device.clone()); |
| 1008 | } |
| 1009 | if device.len() != host.len() { |
| 1010 | return Err(format!("device {} values, host {}", device.len(), host.len())); |
| 1011 | } |
| 1012 | let scale = host.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); |
| 1013 | let diff = device.iter().zip(&host).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max) / scale; |
| 1014 | worst = worst.max(diff); |
| 1015 | if pass > 0 { |
| 1016 | host_ms += host_t; |
| 1017 | device_ms += device_t; |
| 1018 | } |
| 1019 | } |
| 1020 | } |
| 1021 | let n = (tokens.len() * (repeats - 1)) as f64; |
| 1022 | println!( |
| 1023 | "combine per token: host {:.2} ms, device {:.2} ms; worst max|diff|/max|host| {worst:.5}", |
| 1024 | host_ms / n, |
| 1025 | device_ms / n |
| 1026 | ); |
| 1027 | // The prefill's batched combine: every column at once, against the per-token device combine. |
| 1028 | use modelrunner::nets::gemma4_gather as g; |
| 1029 | let width = tokens.len(); |
| 1030 | let tick = Instant::now(); |
| 1031 | let hidden = g::token_rows(&reader, tokens)?; |
| 1032 | let embedded = g::layer_rows(&reader, tokens)?; |
| 1033 | let rows_ms = tick.elapsed().as_secs_f64() * 1000.0; |
| 1034 | let mut wide = Vec::new(); |
| 1035 | let mut wide_ms = 0.0; |
| 1036 | for _ in 0..3 { |
| 1037 | let tick = Instant::now(); |
| 1038 | wide = net.at(width as u32)?.infer_raw_many(&[&hidden, &embedded])?.into_iter().next().ok_or("no wide combine")?; |
| 1039 | wide_ms = tick.elapsed().as_secs_f64() * 1000.0; |
| 1040 | } |
| 1041 | let (mut identical, mut worst) = (0, 0f32); |
| 1042 | for (at, single) in device_cols.iter().enumerate() { |
| 1043 | let col = g::column(&wide, at, width); |
| 1044 | identical += usize::from(col == *single); |
| 1045 | let scale = single.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); |
| 1046 | worst = worst.max(col.iter().zip(single).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max) / scale); |
| 1047 | } |
| 1048 | println!( |
| 1049 | "wide combine over {width} columns: rows {rows_ms:.1} ms, combine {wide_ms:.1} ms; \ |
| 1050 | {identical}/{width} columns bit-identical to per-token, worst {worst:.5}" |
| 1051 | ); |
| 1052 | Ok(()) |
| 1053 | } |
| 1054 | |
| 1055 | /// Soft tokens after text: `prompt[..2]` batched at 0, then `prompt[2..n-1]` as soft rows |
| 1056 | /// (embedding row + pad-token per-layer inputs, as `pushSoftGemma4` builds them) batched at 2 |
| 1057 | /// versus one pass each, then the last token. The two next-token rankings must agree. |
| 1058 | fn soft_check( |
| 1059 | context: &Arc<context::Context>, |
| 1060 | weights: &Streamed, |
| 1061 | embed: &Streamed, |
| 1062 | head: Option<&Streamed>, |
| 1063 | prompt: &[u32], |
| 1064 | ) -> Result<(), String> { |
| 1065 | let n = prompt.len(); |
| 1066 | if n < 4 { |
| 1067 | return Err("the soft check needs at least 4 tokens".into()); |
| 1068 | } |
| 1069 | let head = head.ok_or("the soft check needs --head")?; |
| 1070 | let mut net = streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan)?; |
| 1071 | let mut head_net = streamed_net(context, head, HeadOut::Logits, head_plan)?; |
| 1072 | let reader = embed.reader(); |
| 1073 | let rotary = weights.reader(); |
| 1074 | let mut rows = Vec::new(); |
| 1075 | for &token in &prompt[2..n - 1] { |
| 1076 | let hidden = reader.int4_row( |
| 1077 | gemma4::embed::TOKENS, |
| 1078 | gemma4::embed::TOKENS + 1, |
| 1079 | &[gemma4::VOCAB, gemma4::D_MODEL], |
| 1080 | token, |
| 1081 | )?; |
| 1082 | let per_layer = gemma4::gather_soft_input(&reader, &hidden, 0, fused())?; |
| 1083 | rows.push((hidden, per_layer)); |
| 1084 | } |
| 1085 | let mut run = |batched: bool| -> Result<Vec<f32>, String> { |
| 1086 | feed(&mut net, &reader, &rotary, &prompt[..2], 0, true)?; |
| 1087 | if batched { |
| 1088 | let width = rows.len() as u32; |
| 1089 | let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize]; |
| 1090 | let mut per_layer = vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize]; |
| 1091 | let mut local = vec![0f32; (gemma4::HEAD_DIM * width) as usize]; |
| 1092 | let mut global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize]; |
| 1093 | for (column, (h, p)) in rows.iter().enumerate() { |
| 1094 | let column = column as u32; |
| 1095 | place(&mut hidden, h, column, width); |
| 1096 | place(&mut per_layer, p, column, width); |
| 1097 | place(&mut local, &rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, 2 + column)?, column, width); |
| 1098 | place(&mut global, &rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, 2 + column)?, column, width); |
| 1099 | } |
| 1100 | let at = net.at(gemma4::Mode::Prefill { tokens: width }.at(TIER))?; |
| 1101 | at.set_params(StepParams { prefix: 2, window_start: 0 })?; |
| 1102 | at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?; |
| 1103 | } else { |
| 1104 | for (offset, (h, p)) in rows.iter().enumerate() { |
| 1105 | let position = 2 + offset as u32; |
| 1106 | let local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; |
| 1107 | let global = rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; |
| 1108 | let at = net.at(gemma4::Mode::Prefill { tokens: 1 }.at(TIER))?; |
| 1109 | at.set_params(StepParams { prefix: position, window_start: position.saturating_sub(gemma4::WINDOW - 1) })?; |
| 1110 | at.infer_raw_many(&[h, p, &local, &global])?; |
| 1111 | } |
| 1112 | } |
| 1113 | last_logits(&mut net, &mut head_net, &reader, &rotary, prompt[n - 1], (n - 1) as u32) |
| 1114 | }; |
| 1115 | let batched = run(true)?; |
| 1116 | let sequential = run(false)?; |
| 1117 | let max_diff = batched.iter().zip(&sequential).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); |
| 1118 | println!("soft rows batched top10 {:?}", top10(&batched)); |
| 1119 | println!("soft rows sequential top10 {:?}", top10(&sequential)); |
| 1120 | println!( |
| 1121 | "soft check: {}, max |logit diff| {max_diff:.4}", |
| 1122 | if top10(&batched) == top10(&sequential) { "SAME top10" } else if top10(&batched)[0] == top10(&sequential)[0] { "same argmax, top10 reordered" } else { "ARGMAX DIFFERS" } |
| 1123 | ); |
| 1124 | Ok(()) |
| 1125 | } |
| 1126 | |
| 1127 | /// Per-kind GPU table for one submit, plus its ten hottest dispatches. |
| 1128 | fn print_kinds(title: &str, report: &[(String, f64, f64)]) { |
| 1129 | let mut per_kind: Vec<(String, usize, f64)> = Vec::new(); |
| 1130 | let (mut total, mut gaps) = (0.0, 0.0); |
| 1131 | for (label, us, gap) in report { |
| 1132 | total += us; |
| 1133 | gaps += gap; |
| 1134 | let kind = label.split(':').nth(1).unwrap_or("?").trim().to_string(); |
| 1135 | match per_kind.iter_mut().find(|(k, _, _)| *k == kind) { |
| 1136 | Some((_, n, t)) => { |
| 1137 | *n += 1; |
| 1138 | *t += us; |
| 1139 | } |
| 1140 | None => per_kind.push((kind, 1, *us)), |
| 1141 | } |
| 1142 | } |
| 1143 | per_kind.sort_by(|a, b| b.2.total_cmp(&a.2)); |
| 1144 | println!(); |
| 1145 | println!("{title}: {} dispatches, {:.1} ms timestamped, {:.1} ms gaps", report.len(), total / 1000.0, gaps / 1000.0); |
| 1146 | println!("{:>6} {:>10} {:>10} kind", "count", "total-ms", "mean-us"); |
| 1147 | for (kind, n, us) in &per_kind { |
| 1148 | println!("{n:>6} {:>10.1} {:>10.1} {kind}", us / 1000.0, us / *n as f64); |
| 1149 | } |
| 1150 | let mut hottest: Vec<&(String, f64, f64)> = report.iter().collect(); |
| 1151 | hottest.sort_by(|a, b| b.1.total_cmp(&a.1)); |
| 1152 | for (label, us, _) in hottest.into_iter().take(10) { |
| 1153 | println!(" {us:>9.1} us {label}"); |
| 1154 | } |
| 1155 | } |
| 1156 | |
| 1157 | /// Per-(kind, in_c, out_c) GPU time for the weight-streaming kinds, with the weight bandwidth. |
| 1158 | fn print_shapes(report: &[(String, f64, f64)], plan: &modelrunner::nets::Plan) { |
| 1159 | use modelrunner::nets::{Kind, Op}; |
| 1160 | let mut rows: Vec<(String, u32, u32, usize, f64, f64)> = Vec::new(); |
| 1161 | let dispatches = plan.ops.iter().filter_map(|op| match op { Op::Dispatch { kind, push, .. } => Some((*kind, *push)), _ => None }); |
| 1162 | for ((kind, push), (_, us, _)) in dispatches.zip(report) { |
| 1163 | let bits = match kind { Kind::ConvVecInt4 => 4.0, Kind::ConvVecInt8 => 8.0, Kind::RmsNorm => 16.0, _ => continue }; |
| 1164 | let (in_c, out_c) = if kind == Kind::RmsNorm { (push.in_c, push.group.max(1)) } else { (push.in_c, push.out_c) }; |
| 1165 | let bytes = if kind == Kind::RmsNorm { f64::from(in_c) * 2.0 } else { f64::from(in_c) * f64::from(out_c) * bits / 8.0 }; |
| 1166 | let name = format!("{kind:?}"); |
| 1167 | let push = modelrunner::nets::Push { in_c, out_c, ..push }; |
| 1168 | match rows.iter_mut().find(|r| r.0 == name && r.1 == push.in_c && r.2 == push.out_c) { |
| 1169 | Some(r) => { r.3 += 1; r.4 += us; r.5 += bytes; } |
| 1170 | None => rows.push((name, push.in_c, push.out_c, 1, *us, bytes)), |
| 1171 | } |
| 1172 | } |
| 1173 | rows.sort_by(|a, b| b.4.total_cmp(&a.4)); |
| 1174 | println!("{:>6} {:>10} {:>10} {:>8} kind in_c -> out_c", "count", "total-ms", "mean-us", "GB/s"); |
| 1175 | for (kind, in_c, out_c, n, us, bytes) in rows { |
| 1176 | println!("{n:>6} {:>10.2} {:>10.1} {:>8.1} {kind} {in_c} -> {out_c}", us / 1000.0, us / n as f64, bytes / us / 1000.0); |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | /// Host RSS high-water mark and current RSS (Linux/Android only). |
| 1181 | fn print_memory() { |
| 1182 | let Ok(status) = std::fs::read_to_string("/proc/self/status") else { return }; |
| 1183 | for line in status.lines().filter(|l| l.starts_with("VmHWM") || l.starts_with("VmRSS")) { |
| 1184 | println!("{line}"); |
| 1185 | } |
| 1186 | } |
| 1187 | |
| 1188 | /// Feed every token in order and return the last step's logits. |
| 1189 | /// |
| 1190 | /// The device returns the normed hidden state; the logits are |
| 1191 | /// `hidden @ H^T` over the raw-scale head table (see |
| 1192 | /// `gemma4::embed::HEAD_TABLE`), softcapped, computed on the host exactly as |
| 1193 | /// the bridge does it. So a parity pass here covers the gather, the whole |
| 1194 | /// transformer, AND the tied-head path the app actually uses. |
| 1195 | fn run( |
| 1196 | context: &Arc<context::Context>, |
| 1197 | weights: &Streamed, |
| 1198 | embed: &Streamed, |
| 1199 | head: Option<&Streamed>, |
| 1200 | tokens: &[u32], |
| 1201 | ) -> Result<Vec<f32>, String> { |
| 1202 | let mut net = streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan)?; |
| 1203 | let reader = embed.reader(); |
| 1204 | let rotary = weights.reader(); |
| 1205 | let mut hidden = Vec::new(); |
| 1206 | for (step, &token) in tokens.iter().enumerate() { |
| 1207 | let position = u32::try_from(step).map_err(|_| "a step past u32")?; |
| 1208 | if position >= gemma4::MAX_CONTEXT { |
| 1209 | return Err(format!("position {position} is past MAX_CONTEXT")); |
| 1210 | } |
| 1211 | let (hidden_in, per_layer) = gather_in(&reader, token)?; |
| 1212 | let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; |
| 1213 | let angles_global = |
| 1214 | rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; |
| 1215 | |
| 1216 | let at = net.at(gemma4::Mode::DecodeStep.at(TIER))?; |
| 1217 | // The sliding layers attend `[position - WINDOW + 1, position]`; the full ones want the |
| 1218 | // whole prefix. One `window_start` serves both only while the prefix is inside the |
| 1219 | // window, which it is for a golden this short - a longer one needs the per-layer window |
| 1220 | // this runtime does not carry yet. |
| 1221 | at.set_params(StepParams { |
| 1222 | prefix: position, |
| 1223 | window_start: position.saturating_sub(gemma4::WINDOW - 1), |
| 1224 | })?; |
| 1225 | let out = at.infer_raw_many(&[&hidden_in, &per_layer, &angles_local, &angles_global])?; |
| 1226 | if out.len() != 1 { |
| 1227 | return Err(format!("a step returned {} tensors, not the hidden state", out.len())); |
| 1228 | } |
| 1229 | hidden = out.into_iter().next().unwrap_or_default(); |
| 1230 | } |
| 1231 | if hidden.len() != gemma4::D_MODEL as usize { |
| 1232 | return Err(format!("hidden state of {} values, not {}", hidden.len(), gemma4::D_MODEL)); |
| 1233 | } |
| 1234 | gpu_logits(context, head, &hidden) |
| 1235 | } |
| 1236 | |
| 1237 | /// Logits for `hidden` from the standalone head file (~402 MB upload). |
| 1238 | /// |
| 1239 | /// There is no fallback: the EMBED-resident chunks would mean a net over the |
| 1240 | /// 3.6 GB EMBED file, and the host tied head holds a ~400 MB fp32 quarter. |
| 1241 | fn gpu_logits( |
| 1242 | context: &Arc<context::Context>, |
| 1243 | head: Option<&Streamed>, |
| 1244 | hidden: &[f32], |
| 1245 | ) -> Result<Vec<f32>, String> { |
| 1246 | let head = head.ok_or("no head file: pass --head gemma4_head.maml")?; |
| 1247 | let mut net = streamed_net(context, head, HeadOut::Logits, head_plan)?; |
| 1248 | softcapped(&net.at(HeadOut::Logits)?.infer_raw_many(&[hidden])?) |
| 1249 | } |
| 1250 | |
| 1251 | /// The 16 head splits concatenated and softcapped, as the bridge does it. |
| 1252 | fn softcapped(out: &[Vec<f32>]) -> Result<Vec<f32>, String> { |
| 1253 | use modelrunner::nets::gemma4_head; |
| 1254 | let splits = out.get(..gemma4_head::HEAD_CHUNKS).ok_or("the head returned too few splits")?; |
| 1255 | let mut logits = Vec::with_capacity(gemma4::VOCAB as usize); |
| 1256 | for split in splits { |
| 1257 | if split.len() != gemma4_head::CLASSES_PER_CHUNK as usize { |
| 1258 | return Err(format!("a head split of {} values", split.len())); |
| 1259 | } |
| 1260 | logits.extend(split.iter().map(|&v| gemma4::LOGIT_CAP * (v / gemma4::LOGIT_CAP).tanh())); |
| 1261 | } |
| 1262 | Ok(logits) |
| 1263 | } |
| 1264 | |
| 1265 | /// One position's angles from a rotary table, which is plain fp16. |
| 1266 | /// |
| 1267 | /// A single-row `fp16_rows` read (512 B local, 1 KB global) rather than the |
| 1268 | /// whole `[MAX_CONTEXT, width]` table: the old `fp16` call held the full |
| 1269 | /// 8/16 MB blob as ~16/33 MB of fp32 transient per step, twice a step. |
| 1270 | fn rotary_row( |
| 1271 | reader: &modelrunner::weights::Reader<'_>, |
| 1272 | index: usize, |
| 1273 | width: u32, |
| 1274 | position: u32, |
| 1275 | ) -> Result<Vec<f32>, String> { |
| 1276 | if position >= gemma4::MAX_CONTEXT { |
| 1277 | return Err(format!("position {position} is past the rotary table")); |
| 1278 | } |
| 1279 | reader.fp16_rows(index, &[gemma4::MAX_CONTEXT, width], position, 1) |
| 1280 | } |
| 1281 | |
| 1282 | /// Print the comparison, and say plainly whether it passed. |
| 1283 | fn report(got: &[f32], want_ids: &[u32], want_logits: &[f32]) { |
| 1284 | let mut order: Vec<u32> = (0..got.len() as u32).collect(); |
| 1285 | order.sort_by(|&a, &b| got[b as usize].total_cmp(&got[a as usize])); |
| 1286 | let top: Vec<u32> = order.iter().copied().take(10).collect(); |
| 1287 | |
| 1288 | println!(); |
| 1289 | println!(" reference top10 {want_ids:?}"); |
| 1290 | println!(" device top10 {top:?}"); |
| 1291 | println!(); |
| 1292 | println!(" {:>8} {:>12} {:>12}", "id", "reference", "device"); |
| 1293 | for (rank, &id) in want_ids.iter().enumerate().take(10) { |
| 1294 | println!( |
| 1295 | " {id:>8} {:>12.4} {:>12.4}", |
| 1296 | want_logits.get(rank).copied().unwrap_or(f32::NAN), |
| 1297 | got.get(id as usize).copied().unwrap_or(f32::NAN), |
| 1298 | ); |
| 1299 | } |
| 1300 | println!(); |
| 1301 | let argmax_ok = top.first() == want_ids.first(); |
| 1302 | let overlap = top.iter().filter(|id| want_ids.contains(id)).count(); |
| 1303 | println!(" argmax {}", if argmax_ok { "MATCHES" } else { "DIFFERS" }); |
| 1304 | println!(" {overlap} of the reference's top 10 are in the device's top 10"); |
| 1305 | if argmax_ok && overlap >= 8 { |
| 1306 | println!(); |
| 1307 | println!("PASS: the forward pass agrees with onnxruntime within quantisation noise"); |
| 1308 | } else { |
| 1309 | println!(); |
| 1310 | println!("FAIL: this is a composition error, not quantisation - the ranking moved"); |
| 1311 | } |
| 1312 | } |
| 1313 | |
| 1314 | /// `{"tokens": [...], "top_ids": [...], "top_logits": [...]}`. |
| 1315 | fn parse_golden(text: &str) -> (Vec<u32>, Vec<u32>, Vec<f32>) { |
| 1316 | let numbers = |key: &str| -> String { |
| 1317 | let Some(at) = text.find(key) else { return String::new() }; |
| 1318 | let rest = &text[at + key.len()..]; |
| 1319 | let Some(open) = rest.find('[') else { return String::new() }; |
| 1320 | let Some(close) = rest[open..].find(']') else { return String::new() }; |
| 1321 | rest[open + 1..open + close].to_string() |
| 1322 | }; |
| 1323 | let ints = |s: String| -> Vec<u32> { |
| 1324 | s.split(',').filter_map(|p| p.trim().parse().ok()).collect() |
| 1325 | }; |
| 1326 | let floats = |s: String| -> Vec<f32> { |
| 1327 | s.split(',').filter_map(|p| p.trim().parse().ok()).collect() |
| 1328 | }; |
| 1329 | ( |
| 1330 | ints(numbers("\"tokens\"")), |
| 1331 | ints(numbers("\"top_ids\"")), |
| 1332 | floats(numbers("\"top_logits\"")), |
| 1333 | ) |
| 1334 | } |