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

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

profile_gemma4_decode.rs127 lines · 5.1 KiBRaw
1//! Profile Gemma-4's decode step: op mix, weight traffic, and the two ceilings.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example profile_gemma4_decode
5//! ```
6//!
7//! # Why
8//!
9//! P8 measures 554 ms/token steady-state (1.80 tok/s) against LiteRT's ~10 tok/s.
10//! This attributes that number host-side (no device, no weights — the plan is
11//! built against synthetic shapes, exactly as `report_barriers` does): per-Kind
12//! op counts, per-Kind weight bytes read per step, total weight traffic per
13//! step, and the dispatch-rate ceiling the op count implies. What it cannot do
14//! is split a step into dispatch overhead vs kernel execution — that needs
15//! on-device timestamps the runtime does not emit yet.
16use modelrunner::nets::{gemma4, Kind, Op, WeightSource};
17
18/// A [`WeightSource`] that invents offsets and no data. Same trick as
19/// `report_barriers::Shapes`: plan-building never looks at a weight value.
20struct Shapes {
21 count: usize,
22 next: std::cell::Cell<u32>,
23}
24
25impl WeightSource for Shapes {
26 fn shaped(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {
27 let elements: u32 = dims.iter().copied().product::<u32>().max(1);
28 let at = self.next.get();
29 self.next.set(at + elements.next_multiple_of(8));
30 Ok(at)
31 }
32
33 fn shaped_words(&self, _index: usize, dims: &[u32]) -> Result<u32, String> {
34 let elements: u32 = dims.iter().copied().product::<u32>().max(1);
35 let at = self.next.get();
36 self.next.set(at + elements.div_ceil(4).next_multiple_of(8));
37 Ok(at)
38 }
39
40 fn count(&self) -> usize {
41 self.count
42 }
43}
44
45/// Weight bytes one op reads per decode step, from the geometry the builder
46/// resolved (`Push` carries in/out channels + positions; scales/biases are
47/// small beside the kernels and are folded into the per-kind factor).
48fn weight_bytes(kind: &Kind, push: &modelrunner::nets::Push) -> u64 {
49 let taps = u64::from(push.in_c) * u64::from(push.kh).max(1) * u64::from(push.kw).max(1);
50 let chans = u64::from(push.out_c);
51 let positions = u64::from(push.out_w).max(1);
52 // Decode: one position. Prefill shapes would multiply by positions —
53 // decode only, stated.
54 let _ = positions;
55 match kind {
56 Kind::ConvPointInt4 | Kind::ConvVecInt4 => chans * taps / 2 + chans * taps / 32,
57 Kind::ConvInt8 | Kind::ConvPointInt8 | Kind::ConvVecInt8 => chans * taps + chans * 2,
58 Kind::ConvQ2K | Kind::ConvPointQ2K | Kind::ConvVecQ2K => chans * taps / 4,
59 Kind::Conv | Kind::ConvPoint => chans * taps * 2,
60 // Norms/gammas: one vector of out_c fp16.
61 Kind::RmsNorm | Kind::LayerNorm => chans * 2,
62 // Everything else reads no weights (caches, softmaxes, elementwise).
63 _ => 0,
64 }
65}
66
67fn main() {
68 let source = Shapes { count: 1 << 20, next: std::cell::Cell::new(0) };
69 let plan = match gemma4::build(&source, gemma4::Mode::DecodeStep.at(4096)) {
70 Ok(plan) => plan,
71 Err(why) => {
72 // Same two-attempt dance as report_barriers::synthetic.
73 let wanted = why
74 .split("never reads tensor ")
75 .nth(1)
76 .and_then(|rest| rest.split(' ').next())
77 .and_then(|n| n.parse::<usize>().ok());
78 match wanted {
79 Some(n) => {
80 let retry = Shapes { count: n, next: std::cell::Cell::new(0) };
81 match gemma4::build(&retry, gemma4::Mode::DecodeStep.at(4096)) {
82 Ok(plan) => plan,
83 Err(why) => return println!("the decode plan does not build: {why}"),
84 }
85 }
86 None => return println!("the decode plan does not build: {why}"),
87 }
88 }
89 };
90 println!("decode plan: {} ops, {} barriers today", plan.ops.len(), plan.ops.len());
91 let mut per_kind: Vec<(Kind, usize, u64)> = Vec::new();
92 for op in &plan.ops {
93 let Op::Dispatch { kind, push, .. } = op else { continue };
94 let bytes = weight_bytes(kind, push);
95 match per_kind.iter_mut().find(|(k, _, _)| k == kind) {
96 Some((_, n, b)) => {
97 *n += 1;
98 *b += bytes;
99 }
100 None => per_kind.push((*kind, 1, bytes)),
101 }
102 }
103 per_kind.sort_by_key(|b| std::cmp::Reverse(b.2));
104 println!();
105 println!("{:>6} {:>10} {:?}", "count", "wt-bytes", "kind");
106 let mut total_bytes = 0u64;
107 for (kind, n, bytes) in &per_kind {
108 println!("{n:>6} {bytes:>10} {kind:?}");
109 total_bytes += bytes;
110 }
111 println!();
112 println!("total weight traffic per step: ~{:.1} MB", total_bytes as f64 / 1e6);
113 println!("arena: {:.1} MB", f64::from(plan.arena_elems) * 2.0 / 1e6);
114 println!();
115 println!("ceilings at P8-measured 587 us/dispatch (plan) vs 5 GB/s buffers:");
116 println!(
117 " dispatch ceiling: {} ops x 587 us = {:.0} ms",
118 plan.ops.len(),
119 plan.ops.len() as f64 * 0.587
120 );
121 println!(
122 " bandwidth ceiling: {:.1} MB / 5 GB/s = {:.0} ms",
123 total_bytes as f64 / 1e6,
124 total_bytes as f64 / 5e9 * 1e3
125 );
126 println!(" measured on-device: 554 ms/token steady-state");
127}