Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / probe_rmsnorm.rs
probe_rmsnorm.rs176 lines · 6.6 KiBRaw
| 1 | //! Single-norm microbenchmark: why is device RmsNorm 80x the sibling small ops? |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! cargo run --offline --release -p modelrunner --example probe_rmsnorm |
| 5 | //! ``` |
| 6 | //! |
| 7 | //! Phase 3b′ probe (read-only): one RmsNorm at decode shapes, sweeping channels, |
| 8 | //! groups, and count, best-of-5 wall plus per-op device times when |
| 9 | //! `MODELRUNNER_TIMESTAMPS=1` is set. Synthetic `Builder` plan + `Net::infer_raw` |
| 10 | //! over a kilobytes-large dummy blob — no model file, no whole-file upload, zero |
| 11 | //! OOM risk by construction. |
| 12 | //! |
| 13 | //! # The question this answers |
| 14 | //! |
| 15 | //! The per-op timestamp table puts 241 RmsNorm dispatches at ~830 µs mean each |
| 16 | //! (~200 ms a step) against Mul at 8.5 µs, Rotary at 11.5 µs, SoftmaxPrefix at |
| 17 | //! 14 µs. A norm over ≤1536 elements moves ~6 KB; at 830 µs that is ~7 MB/s |
| 18 | //! effective — so it is not fetch-bound. Candidate mechanisms and their |
| 19 | //! predictions: |
| 20 | //! |
| 21 | //! * single-workgroup launch/drain cost → flat vs channels, per-op cost drops |
| 22 | //! (or holds) when tiled, rises linearly with count; |
| 23 | //! * serial-reduction ALU → linear in channels; |
| 24 | //! * driver pathologies → cliffs at specific shapes. |
| 25 | //! |
| 26 | //! The sweep below is shaped to discriminate exactly these three. No fix is |
| 27 | //! designed until the numbers speak — the one-paragraph mechanism statement |
| 28 | //! this prints is the gate for all Phase 3b′ fix work. |
| 29 | //! |
| 30 | //! # Geometries (every RmsNorm the transformer actually runs) |
| 31 | //! |
| 32 | //! * plain 1536 (input / pre_ff / final norms, groups = 1); |
| 33 | //! * plain 256 (K norm: KV_HEADS = 1, so grouped-over-1; v norms); |
| 34 | //! * grouped 2048 = 8 heads × 256 (local Q norm, groups = 8); |
| 35 | //! * grouped 4096 = 8 heads × 512 (global Q norm, groups = 8); |
| 36 | //! * grouped 256 with groups = 8 (cross-cut: same channels as the K norm, |
| 37 | //! grouped like Q — isolates the grouping effect from the width effect). |
| 38 | |
| 39 | use modelrunner::nets::{Builder, Shape, WeightSource}; |
| 40 | use modelrunner::vulkan::{context, run::Net}; |
| 41 | use modelrunner::weights::{Blob, Tensor}; |
| 42 | |
| 43 | /// Channels × groups × chained-count to sweep: decode widths, the natural |
| 44 | /// grouping for each width, the 256-wide cross-cut, and 1 vs 35-chained (one |
| 45 | /// layer's worth of sequential norms in a single plan). |
| 46 | const SWEEP: [(u32, u32, usize); 10] = [ |
| 47 | (256, 1, 1), |
| 48 | (512, 1, 1), |
| 49 | (1536, 1, 1), |
| 50 | (2048, 8, 1), |
| 51 | (4096, 8, 1), |
| 52 | // Grouping cross-cut at fixed width. |
| 53 | (256, 8, 1), |
| 54 | (2048, 1, 1), |
| 55 | // Tiled: one layer's sequential norms in one plan. |
| 56 | (1536, 1, 35), |
| 57 | (2048, 8, 35), |
| 58 | (256, 1, 35), |
| 59 | ]; |
| 60 | |
| 61 | /// A weight source for the norm probe: every tensor at offset zero. |
| 62 | /// |
| 63 | /// Mirrors the `ProbeSource` in `bridge_part7.rs` (which examples cannot use: |
| 64 | /// it is private to the Android-gated bridge). They alias, which would be |
| 65 | /// nonsense for inference and is right here — the probe asks how fast a norm |
| 66 | /// runs, not what it computes. |
| 67 | struct NormSource; |
| 68 | |
| 69 | impl WeightSource for NormSource { |
| 70 | fn shaped(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> { |
| 71 | Ok(0) |
| 72 | } |
| 73 | fn shaped_words(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> { |
| 74 | Ok(0) |
| 75 | } |
| 76 | fn count(&self) -> usize { |
| 77 | 1 |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// A kilobytes-large blob of identical bytes with a one-tensor table beside it. |
| 82 | /// |
| 83 | /// The gamma the norms read is whatever these bytes decode to as fp16 — the |
| 84 | /// values do not matter for timing (no NaN: the input feed is nonzero and the |
| 85 | /// norm divides by the input's own magnitude, never by gamma). |
| 86 | struct NormFile { |
| 87 | bytes: Vec<u8>, |
| 88 | table: Vec<Tensor>, |
| 89 | } |
| 90 | |
| 91 | impl Blob for NormFile { |
| 92 | fn data_len(&self) -> u64 { |
| 93 | self.bytes.len() as u64 |
| 94 | } |
| 95 | fn tensors(&self) -> &[Tensor] { |
| 96 | &self.table |
| 97 | } |
| 98 | fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> { |
| 99 | let from = offset as usize; |
| 100 | let span = self.bytes.get(from..from + into.len()).ok_or_else(|| { |
| 101 | format!("a read of {} at {offset} past {}", into.len(), self.bytes.len()) |
| 102 | })?; |
| 103 | into.copy_from_slice(span); |
| 104 | Ok(()) |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | fn main() { |
| 109 | let context = match context::shared() { |
| 110 | Ok(context) => context, |
| 111 | Err(why) => return println!("no Vulkan device: {why}"), |
| 112 | }; |
| 113 | let stamps = modelrunner::knobs::is_set("timestamps"); |
| 114 | println!("channels groups count best-us per-op-us (best of 5)"); |
| 115 | for (channels, groups, count) in SWEEP { |
| 116 | match probe(&context, channels, groups, count, stamps) { |
| 117 | Ok((best, per_op)) => match per_op { |
| 118 | Some(op) => println!("{channels:>8} {groups:>6} {count:>5} {best:>7.1} {op:>9.1}"), |
| 119 | None => println!("{channels:>8} {groups:>6} {count:>5} {best:>7.1} (set MODELRUNNER_TIMESTAMPS=1 for per-op)"), |
| 120 | }, |
| 121 | Err(why) => println!("{channels:>8} {groups:>6} {count:>5} failed: {why}"), |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// Time `count` chained RmsNorms over `channels` inputs in `groups` groups. |
| 127 | /// |
| 128 | /// Returns best-of-5 wall µs plus, when `stamps` is set, the timestamped |
| 129 | /// per-op mean for the last iteration. Chained (each op reads the previous |
| 130 | /// output) so the dispatches serialize exactly as decode's interleaved norms do. |
| 131 | fn probe( |
| 132 | context: &std::sync::Arc<context::Context>, |
| 133 | channels: u32, |
| 134 | groups: u32, |
| 135 | count: usize, |
| 136 | stamps: bool, |
| 137 | ) -> Result<(f64, Option<f64>), String> { |
| 138 | let source = NormSource; |
| 139 | let mut builder = Builder::new(&source); |
| 140 | let input = builder.input(Shape::new(channels, 1, 1)); |
| 141 | let mut out = input; |
| 142 | for _ in 0..count { |
| 143 | out = builder.rms_norm_grouped(out, 0, modelrunner::nets::gemma4::EPSILON, groups); |
| 144 | } |
| 145 | let plan = builder.finish(&[out])?; |
| 146 | if plan.ops.len() != count { |
| 147 | return Err(format!("{} chained norms built {} ops", count, plan.ops.len())); |
| 148 | } |
| 149 | // Gamma needs per_group fp16 entries; 8 KB covers the widest point. |
| 150 | let bytes = vec![0x11u8; 8192]; |
| 151 | let table = vec![Tensor { |
| 152 | rank: 1, |
| 153 | dims: [4096, 0, 0, 0], |
| 154 | offset: 0, |
| 155 | len: 4096, |
| 156 | dtype: modelrunner::weights::Dtype::F16, |
| 157 | }]; |
| 158 | let file = NormFile { bytes, table }; |
| 159 | let mut net = Net::new(std::sync::Arc::clone(context), plan, &file, modelrunner::preprocess::RESCALE_ONLY)?; |
| 160 | let feed = vec![0.5f32; channels as usize]; |
| 161 | net.infer_raw(&feed)?; |
| 162 | let mut best = f64::MAX; |
| 163 | for _ in 0..5 { |
| 164 | let started = std::time::Instant::now(); |
| 165 | net.infer_raw(&feed)?; |
| 166 | best = best.min(started.elapsed().as_secs_f64()); |
| 167 | } |
| 168 | let per_op = if stamps { |
| 169 | let report = net.op_times()?; |
| 170 | let total: f64 = report.iter().map(|(_, us, _)| us).sum(); |
| 171 | Some(total / report.len().max(1) as f64) |
| 172 | } else { |
| 173 | None |
| 174 | }; |
| 175 | Ok((best * 1e6, per_op)) |
| 176 | } |