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

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

report_gemv_overhead.rs171 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.
31use std::sync::Arc;
32
33use modelrunner::nets::{Act, Builder, Shape, WeightSource};
34use modelrunner::preprocess::RESCALE_ONLY;
35use modelrunner::vulkan::context;
36use modelrunner::vulkan::run::Net;
37use modelrunner::weights::{Blob, Dtype, Tensor};
38
39/// A blob of identical bytes with a matching tensor table.
40struct Filler {
41 bytes: Vec<u8>,
42 table: Vec<Tensor>,
43}
44
45impl 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.
63struct Invented;
64
65impl 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
77fn 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] =
85 [64, 128, 256, 512, 1024, 1536, 3072, 6144, 12288, 24576, 65536];
86
87 println!(" {:>7} {:>9} {:>9} {:>9}", "out", "MB", "ms", "GB/s");
88 let mut samples: Vec<(f64, f64)> = Vec::new();
89 for out in shapes {
90 match measure(&context, out, 1536) {
91 Ok((bytes, seconds)) => {
92 let mb = bytes as f64 / 1e6;
93 println!(
94 " {out:>7} {mb:>9.3} {:>9.3} {:>9.2}",
95 seconds * 1000.0,
96 bytes as f64 / seconds / 1e9
97 );
98 samples.push((bytes as f64, seconds));
99 }
100 Err(why) => println!(" {out:>7} {why}"),
101 }
102 }
103
104 // The smallest shape moves 49 kB. Whatever it costs is overhead, not streaming.
105 let Some(&(small_bytes, floor)) = samples.first() else {
106 return println!("nothing measured");
107 };
108 let Some(&(big_bytes, big_seconds)) = samples.last() else {
109 return println!("nothing measured");
110 };
111
112 println!();
113 println!("fixed cost {:.3} ms (wall time of a {:.0} kB gemv, which is almost all round trip)", floor * 1000.0, small_bytes / 1e3);
114
115 let corrected = big_seconds - floor;
116 if corrected > 0.0 {
117 println!(
118 "streaming {:.2} GB/s (largest shape, {:.1} MB, with that fixed cost subtracted)",
119 big_bytes / corrected / 1e9,
120 big_bytes / 1e6
121 );
122 println!(
123 "uncorrected {:.2} GB/s (the number report_gemv_scaling prints)",
124 big_bytes / big_seconds / 1e9
125 );
126 }
127 println!();
128 println!("Compare the streaming figure against report_read_path's storage-buffer column.");
129 println!("That comparison is the one that is NOT an artefact of per-call overhead.");
130}
131
132/// Time one int4 gemv of `out` by `inputs`, returning its weight bytes and the best seconds.
133fn measure(
134 context: &Arc<context::Context>,
135 out: u32,
136 inputs: u32,
137) -> Result<(u64, f64), String> {
138 let source = Invented;
139 let mut builder = Builder::new(&source);
140 let input = builder.input(Shape::new(inputs, 1, 1));
141 let projected = builder.conv_int4(input, 0, out, Act::None);
142 let plan = builder.finish(&[projected])?;
143 let blocks = inputs.div_ceil(32);
144 let weight_bytes = (u64::from(out) * u64::from(inputs)) / 2;
145 let scale_bytes = u64::from(out) * u64::from(blocks) * 2;
146 let bias_bytes = u64::from(out) * 2;
147 let total = weight_bytes + scale_bytes + bias_bytes + 4096;
148 let table = vec![
149 Tensor {
150 rank: 1,
151 dims: [(total / 2) as u32, 0, 0, 0],
152 offset: 0,
153 len: (total / 2) as u32,
154 dtype: Dtype::F16,
155 };
156 3
157 ];
158 let data = Filler { bytes: vec![0x11u8; total as usize], table };
159 let mut net = Net::new(Arc::clone(context), plan, &data, RESCALE_ONLY)?;
160 let feed = vec![0.5f32; inputs as usize];
161 // One warm pass, then the best of nine. More repeats than the scaling probe because the
162 // small shapes are short enough that a single scheduling hiccup dominates a best-of-five.
163 net.infer_raw(&feed)?;
164 let mut best = f64::MAX;
165 for _ in 0..9 {
166 let started = std::time::Instant::now();
167 net.infer_raw(&feed)?;
168 best = best.min(started.elapsed().as_secs_f64());
169 }
170 Ok((weight_bytes, best))
171}