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