Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / report_prefill_cost.rs
report_prefill_cost.rs205 lines · 8.6 KiBRaw
| 1 | //! What the discarded logits head costs on every prefill position. |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! cargo run --offline --release -p modelrunner --example report_prefill_cost -- <gemma4_text.maml> |
| 5 | //! ``` |
| 6 | //! |
| 7 | //! # What this measures |
| 8 | //! |
| 9 | //! A prompt is pushed one position at a time and the logits are kept only for the last of them. |
| 10 | //! `bridge.rs:2484` selects [`gemma4::Mode::DecodeStep.at(TIER)`] unconditionally, and `want_logits` is |
| 11 | //! checked at :2491 — *after* the pass — so the head runs for every position of the prompt and |
| 12 | //! the host throws the result away. |
| 13 | //! |
| 14 | //! [`gemma4::Mode::Prefill`] is the same pass without the head. This times both against the same |
| 15 | //! device and reports the difference, which is the saving available with no batching at all. |
| 16 | //! |
| 17 | //! # Why it needs measuring rather than deriving |
| 18 | //! |
| 19 | //! The head is 9 of the plan's ~1,094 ops but 227 MB of its 1.30 GB of weights — 0.8% by dispatch |
| 20 | //! and 17.5% by bytes, a factor of twenty apart. Which figure predicts the time depends on whether |
| 21 | //! these particular ops are dispatch-bound or bandwidth-bound, and the profile that established |
| 22 | //! "283 us per op" is an average over ops spanning four orders of magnitude in size. Four int4 |
| 23 | //! projections over 262,144 classes are not average ops. So the derivation goes both ways and only |
| 24 | //! a stopwatch settles it. |
| 25 | //! |
| 26 | //! Build with `--release`. A debug build measures `rustc -O0`, not the runtime. |
| 27 | use std::path::PathBuf; |
| 28 | use std::time::Instant; |
| 29 | |
| 30 | use modelrunner::nets::gemma4; |
| 31 | use modelrunner::preprocess::RESCALE_ONLY; |
| 32 | use modelrunner::vulkan::context; |
| 33 | use modelrunner::vulkan::run::{Net, StepParams}; |
| 34 | use modelrunner::weights::{graph, Weights}; |
| 35 | |
| 36 | /// Positions to time in each mode. Enough to average out submit jitter. |
| 37 | const STEPS: u32 = 12; |
| 38 | |
| 39 | /// The cache these examples record against: the top tier, so a long prompt fits. |
| 40 | const TIER: u32 = gemma4::MAX_CONTEXT; |
| 41 | |
| 42 | fn main() { |
| 43 | let Some(path) = std::env::args().nth(1).map(PathBuf::from) else { |
| 44 | println!("usage: report_prefill_cost <gemma4_text.maml>"); |
| 45 | return; |
| 46 | }; |
| 47 | let bytes = match std::fs::read(&path) { |
| 48 | Ok(bytes) => bytes, |
| 49 | Err(why) => { |
| 50 | println!("cannot read {}: {why}", path.display()); |
| 51 | return; |
| 52 | } |
| 53 | }; |
| 54 | let weights = match Weights::parse(&bytes, graph::GEMMA4_TEXT) { |
| 55 | Ok(weights) => weights, |
| 56 | Err(why) => { |
| 57 | println!("cannot parse it: {why}"); |
| 58 | return; |
| 59 | } |
| 60 | }; |
| 61 | println!("weights {:.2} GB", weights.data().len() as f64 / 1e9); |
| 62 | |
| 63 | let context = match context::shared() { |
| 64 | Ok(context) => context, |
| 65 | Err(why) => { |
| 66 | println!("no usable Vulkan device: {why}"); |
| 67 | return; |
| 68 | } |
| 69 | }; |
| 70 | |
| 71 | let decode = match gemma4::build(&weights, gemma4::Mode::DecodeStep.at(TIER)) { |
| 72 | Ok(plan) => plan, |
| 73 | Err(why) => { |
| 74 | println!("the decode plan does not build: {why}"); |
| 75 | return; |
| 76 | } |
| 77 | }; |
| 78 | let prefill = match gemma4::build(&weights, gemma4::Mode::Prefill { tokens: 1 }.at(TIER)) { |
| 79 | Ok(plan) => plan, |
| 80 | Err(why) => { |
| 81 | println!("the prefill plan does not build: {why}"); |
| 82 | return; |
| 83 | } |
| 84 | }; |
| 85 | println!( |
| 86 | "decode {:>5} ops, {:>6.1} MB arena", |
| 87 | decode.ops.len(), |
| 88 | f64::from(decode.arena_elems) * 2.0 / 1e6 |
| 89 | ); |
| 90 | println!( |
| 91 | "prefill {:>5} ops, {:>6.1} MB arena ({} ops fewer)", |
| 92 | prefill.ops.len(), |
| 93 | f64::from(prefill.arena_elems) * 2.0 / 1e6, |
| 94 | decode.ops.len() - prefill.ops.len() |
| 95 | ); |
| 96 | println!(); |
| 97 | |
| 98 | // Constructed at `DecodeStep`, exactly as `bridge.rs:2605` does, so the arena is sized for the |
| 99 | // larger of the two and the switch to prefill cannot grow it. Growing is what would drop the |
| 100 | // KV caches, and doing it in the same order as the shipping code is the point. |
| 101 | let mut net = match Net::whole(context, decode, &weights, RESCALE_ONLY) { |
| 102 | Ok(net) => net, |
| 103 | Err(why) => { |
| 104 | println!("the decode plan does not record: {why}"); |
| 105 | return; |
| 106 | } |
| 107 | }; |
| 108 | |
| 109 | // The values are irrelevant to timing; only the shapes reach the device. |
| 110 | let hidden = vec![0.01f32; gemma4::D_MODEL as usize]; |
| 111 | let per_layer = vec![0.01f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32) as usize]; |
| 112 | let local = vec![0.01f32; gemma4::HEAD_DIM as usize]; |
| 113 | let global = vec![0.01f32; gemma4::GLOBAL_HEAD_DIM as usize]; |
| 114 | |
| 115 | let run = |net: &mut Net, label: &str| -> Option<f64> { |
| 116 | // One discarded pass: the first submit pays for pipeline warm-up and for faulting 1.3 GB |
| 117 | // of weights into device memory, neither of which is per-position cost. |
| 118 | if let Err(why) = step(net, 0, &hidden, &per_layer, &local, &global) { |
| 119 | println!("{label}: warm-up failed: {why}"); |
| 120 | return None; |
| 121 | } |
| 122 | let start = Instant::now(); |
| 123 | for position in 0..STEPS { |
| 124 | if let Err(why) = step(net, position, &hidden, &per_layer, &local, &global) { |
| 125 | println!("{label}: step {position} failed: {why}"); |
| 126 | return None; |
| 127 | } |
| 128 | } |
| 129 | Some(start.elapsed().as_secs_f64() * 1e3 / f64::from(STEPS)) |
| 130 | }; |
| 131 | |
| 132 | let Some(decode_ms) = run(&mut net, "decode") else { return }; |
| 133 | println!("decode {decode_ms:>7.2} ms per position, head computed and discarded"); |
| 134 | |
| 135 | // Switching plans is a `Reshaped::at` mode change, which is a `Net::rebuild`: a |
| 136 | // `device_wait_idle` under the process-wide queue lock and every dispatch emitted again. It |
| 137 | // happens once per turn in the shipping path — the prompt is pushed headless and the first |
| 138 | // sampled token wants logits — so it is charged once against the whole prefill, not per |
| 139 | // position. Timed because a saving of a few ms a position would be worth nothing if the |
| 140 | // switch that unlocks it cost more than the prompt saves. |
| 141 | let switch = Instant::now(); |
| 142 | if let Err(why) = net.rebuild(prefill) { |
| 143 | println!("the prefill plan does not record: {why}"); |
| 144 | return; |
| 145 | } |
| 146 | let switch_ms = switch.elapsed().as_secs_f64() * 1e3; |
| 147 | println!("switch {switch_ms:>7.2} ms to re-record, once per turn"); |
| 148 | let Some(prefill_ms) = run(&mut net, "prefill") else { return }; |
| 149 | println!("prefill {prefill_ms:>7.2} ms per position, no head"); |
| 150 | println!(); |
| 151 | |
| 152 | let saved = decode_ms - prefill_ms; |
| 153 | println!("saved {saved:>7.2} ms per position, {:.1}%", 100.0 * saved / decode_ms); |
| 154 | // The prompt measured on device was 1,871 tokens, all but the last of them headless. |
| 155 | let over_prompt = saved * 1870.0 - switch_ms; |
| 156 | println!( |
| 157 | " {:>7.1} s over a 1,871-token prompt, net of the one switch", |
| 158 | over_prompt / 1e3 |
| 159 | ); |
| 160 | println!(); |
| 161 | |
| 162 | // How much of a position is attention, and does attention cost anything at all? |
| 163 | // |
| 164 | // `Mode::Prefill { tokens: N }` is refused above one, so the N-sweep that would answer "does a |
| 165 | // pass over N tokens cost one pass or N passes" cannot be run without first building the |
| 166 | // batched path it is meant to de-risk. This is the closest probe that needs no new plan. |
| 167 | // |
| 168 | // `prefix` is the only thing that changes how much work the attention ops do: every cached |
| 169 | // score and value op sums over `prefix + 1` keys, so at prefix 0 they touch one key and at |
| 170 | // 2047 they touch 2048. Same plan, same dispatch count, same weights, same bytes read for |
| 171 | // every projection - 2048x the attention arithmetic and 2048x the KV cache traffic. |
| 172 | // |
| 173 | // If the time is flat across this sweep, attention is free at these sizes and the pass is |
| 174 | // paying for something fixed per dispatch or per weight byte. Both of those amortise over a |
| 175 | // batch. If it climbs, attention is real per-token work and batching amortises less of the |
| 176 | // pass than the op count suggests. |
| 177 | println!("prefix sweep, same plan, attention work only:"); |
| 178 | for prefix in [0u32, 63, 255, 1023, 2047] { |
| 179 | let start = Instant::now(); |
| 180 | for _ in 0..STEPS { |
| 181 | if let Err(why) = step(&mut net, prefix, &hidden, &per_layer, &local, &global) { |
| 182 | println!(" prefix {prefix}: {why}"); |
| 183 | return; |
| 184 | } |
| 185 | } |
| 186 | let ms = start.elapsed().as_secs_f64() * 1e3 / f64::from(STEPS); |
| 187 | println!(" prefix {prefix:>5} -> {ms:>7.2} ms ({} keys attended)", prefix + 1); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | /// One position, with the step parameters the decode loop would set. |
| 192 | fn step( |
| 193 | net: &mut Net, |
| 194 | position: u32, |
| 195 | hidden: &[f32], |
| 196 | per_layer: &[f32], |
| 197 | local: &[f32], |
| 198 | global: &[f32], |
| 199 | ) -> Result<(), String> { |
| 200 | net.set_params(StepParams { |
| 201 | prefix: position, |
| 202 | window_start: position.saturating_sub(gemma4::WINDOW - 1), |
| 203 | })?; |
| 204 | net.infer_raw_many(&[hidden, per_layer, local, global]).map(|_| ()) |
| 205 | } |