Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / report_gemv_overhead.rs
report_gemv_overhead.rs170 lines · 6.5 KiBRaw
| 1 | //! Separates fixed per-call cost from streaming rate in the int4 gemv, by measurement. |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! cargo run --offline --release -p modelrunner --example report_gemv_overhead |
| 5 | //! ``` |
| 6 | //! |
| 7 | //! # Why this exists |
| 8 | //! |
| 9 | //! `report_gemv_scaling` sweeps six matrix shapes and its smallest is 1.18 MB, which is large |
| 10 | //! enough that fixed cost and streaming cost are entangled. Fitting `time = fixed + bytes/rate` |
| 11 | //! to those six points recovers the split, but a two-parameter fit to six noisy points is weak |
| 12 | //! evidence and the intercept it produces varies by 2x depending on which points are included. |
| 13 | //! |
| 14 | //! This measures the intercept instead. It sweeps down to a `[64, 1536]` projection - 49 kB of |
| 15 | //! weights, which even a slow kernel streams in tens of microseconds - so the wall time of the |
| 16 | //! smallest shapes *is* the fixed cost, near enough, with no fit involved. |
| 17 | //! |
| 18 | //! # What the fixed cost is, and is not |
| 19 | //! |
| 20 | //! Each timed iteration is one `Net::infer_raw`: a host staging write of the input vector, one |
| 21 | //! `queue_submit`, a fence wait, and a readback. It is a **host round trip**, of which the GPU |
| 22 | //! dispatch is one part. |
| 23 | //! |
| 24 | //! That matters for how the number should be read. A real decode step issues on the order of a |
| 25 | //! thousand dispatches inside a single submit, so it pays this round trip roughly once per |
| 26 | //! token rather than once per projection. **The intercept measured here is therefore mostly an |
| 27 | //! artefact of the harness, not a per-projection cost the decoder actually pays** - which is |
| 28 | //! exactly why it has to be measured and subtracted rather than left in the headline number. |
| 29 | //! |
| 30 | //! The figure that survives the subtraction is the streaming rate, and that one is real. |
| 31 | use std::sync::Arc; |
| 32 | |
| 33 | use modelrunner::nets::{Act, Builder, Shape, WeightSource}; |
| 34 | use modelrunner::preprocess::RESCALE_ONLY; |
| 35 | use modelrunner::vulkan::context; |
| 36 | use modelrunner::vulkan::run::Net; |
| 37 | use modelrunner::weights::{Blob, Dtype, Tensor}; |
| 38 | |
| 39 | /// A blob of identical bytes with a matching tensor table. |
| 40 | struct Filler { |
| 41 | bytes: Vec<u8>, |
| 42 | table: Vec<Tensor>, |
| 43 | } |
| 44 | |
| 45 | impl Blob for Filler { |
| 46 | fn data_len(&self) -> u64 { |
| 47 | self.bytes.len() as u64 |
| 48 | } |
| 49 | fn tensors(&self) -> &[Tensor] { |
| 50 | &self.table |
| 51 | } |
| 52 | fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> { |
| 53 | let from = offset as usize; |
| 54 | let span = self.bytes.get(from..from + into.len()).ok_or_else(|| { |
| 55 | format!("a read of {} at {offset} past {}", into.len(), self.bytes.len()) |
| 56 | })?; |
| 57 | into.copy_from_slice(span); |
| 58 | Ok(()) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// Lays tensors out back to back in the order they are asked for, so no model file is needed. |
| 63 | struct Invented; |
| 64 | |
| 65 | impl WeightSource for Invented { |
| 66 | fn shaped(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> { |
| 67 | Ok(0) |
| 68 | } |
| 69 | fn shaped_words(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> { |
| 70 | Ok(0) |
| 71 | } |
| 72 | fn count(&self) -> usize { |
| 73 | 3 |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn main() { |
| 78 | let context = match context::shared() { |
| 79 | Ok(context) => context, |
| 80 | Err(why) => return println!("no Vulkan device: {why}"), |
| 81 | }; |
| 82 | |
| 83 | // Small shapes first. The first few are dominated by the round trip, which is the point. |
| 84 | let shapes: [u32; 11] = [64, 128, 256, 512, 1024, 1536, 3072, 6144, 12288, 24576, 65536]; |
| 85 | |
| 86 | println!(" {:>7} {:>9} {:>9} {:>9}", "out", "MB", "ms", "GB/s"); |
| 87 | let mut samples: Vec<(f64, f64)> = Vec::new(); |
| 88 | for out in shapes { |
| 89 | match measure(&context, out, 1536) { |
| 90 | Ok((bytes, seconds)) => { |
| 91 | let mb = bytes as f64 / 1e6; |
| 92 | println!( |
| 93 | " {out:>7} {mb:>9.3} {:>9.3} {:>9.2}", |
| 94 | seconds * 1000.0, |
| 95 | bytes as f64 / seconds / 1e9 |
| 96 | ); |
| 97 | samples.push((bytes as f64, seconds)); |
| 98 | } |
| 99 | Err(why) => println!(" {out:>7} {why}"), |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // The smallest shape moves 49 kB. Whatever it costs is overhead, not streaming. |
| 104 | let Some(&(small_bytes, floor)) = samples.first() else { |
| 105 | return println!("nothing measured"); |
| 106 | }; |
| 107 | let Some(&(big_bytes, big_seconds)) = samples.last() else { |
| 108 | return println!("nothing measured"); |
| 109 | }; |
| 110 | |
| 111 | println!(); |
| 112 | println!( |
| 113 | "fixed cost {:.3} ms (wall time of a {:.0} kB gemv, which is almost all round trip)", |
| 114 | floor * 1000.0, |
| 115 | small_bytes / 1e3 |
| 116 | ); |
| 117 | |
| 118 | let corrected = big_seconds - floor; |
| 119 | if corrected > 0.0 { |
| 120 | println!( |
| 121 | "streaming {:.2} GB/s (largest shape, {:.1} MB, with that fixed cost subtracted)", |
| 122 | big_bytes / corrected / 1e9, |
| 123 | big_bytes / 1e6 |
| 124 | ); |
| 125 | println!( |
| 126 | "uncorrected {:.2} GB/s (the number report_gemv_scaling prints)", |
| 127 | big_bytes / big_seconds / 1e9 |
| 128 | ); |
| 129 | } |
| 130 | println!(); |
| 131 | println!("Compare the streaming figure against report_read_path's storage-buffer column."); |
| 132 | println!("That comparison is the one that is NOT an artefact of per-call overhead."); |
| 133 | } |
| 134 | |
| 135 | /// Time one int4 gemv of `out` by `inputs`, returning its weight bytes and the best seconds. |
| 136 | fn measure(context: &Arc<context::Context>, out: u32, inputs: u32) -> Result<(u64, f64), String> { |
| 137 | let source = Invented; |
| 138 | let mut builder = Builder::new(&source); |
| 139 | let input = builder.input(Shape::new(inputs, 1, 1)); |
| 140 | let projected = builder.conv_int4(input, 0, out, Act::None); |
| 141 | let plan = builder.finish(&[projected])?; |
| 142 | let blocks = inputs.div_ceil(32); |
| 143 | let weight_bytes = (u64::from(out) * u64::from(inputs)) / 2; |
| 144 | let scale_bytes = u64::from(out) * u64::from(blocks) * 2; |
| 145 | let bias_bytes = u64::from(out) * 2; |
| 146 | let total = weight_bytes + scale_bytes + bias_bytes + 4096; |
| 147 | let table = vec![ |
| 148 | Tensor { |
| 149 | rank: 1, |
| 150 | dims: [(total / 2) as u32, 0, 0, 0], |
| 151 | offset: 0, |
| 152 | len: (total / 2) as u32, |
| 153 | dtype: Dtype::F16, |
| 154 | }; |
| 155 | 3 |
| 156 | ]; |
| 157 | let data = Filler { bytes: vec![0x11u8; total as usize], table }; |
| 158 | let mut net = Net::new(Arc::clone(context), plan, &data, RESCALE_ONLY)?; |
| 159 | let feed = vec![0.5f32; inputs as usize]; |
| 160 | // One warm pass, then the best of nine. More repeats than the scaling probe because the |
| 161 | // small shapes are short enough that a single scheduling hiccup dominates a best-of-five. |
| 162 | net.infer_raw(&feed)?; |
| 163 | let mut best = f64::MAX; |
| 164 | for _ in 0..9 { |
| 165 | let started = std::time::Instant::now(); |
| 166 | net.infer_raw(&feed)?; |
| 167 | best = best.min(started.elapsed().as_secs_f64()); |
| 168 | } |
| 169 | Ok((weight_bytes, best)) |
| 170 | } |