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_bottleneck.rs

report_gemv_bottleneck.rs770 lines · 35.1 KiBRaw
1//! Which of three hypotheses explains the int4 gemv running at 3-17% of streaming bandwidth.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example report_gemv_bottleneck
5//! ```
6//!
7//! # The question
8//!
9//! `probe_ssbo.comp` sweeps 256 MB at ~20 GB/s on a Mali-G715 doing **one XOR per 16 bytes**
10//! with one load in flight. `conv_vec_int4.comp` reads the same width from the same kind of
11//! buffer with the same workgroup size and a comparable load depth, and reaches 0.64-3.37
12//! GB/s. Three explanations have been offered and they imply opposite fixes:
13//!
14//! * **H1, memory-level parallelism.** ml_drift bulk-prefetches into subgroup registers
15//! (`__wave Type weights_cache[16]`, `ucl::WaveLoad(..., 16)`); we keep 1-2 loads in
16//! flight. Fix: restructure the loads.
17//! * **H2, dequant ALU.** ~160 ops per 16 bytes against the control's one. Fix: cut the
18//! arithmetic, which would revive `VK_KHR_shader_integer_dot_product` (reported
19//! accelerated on both test devices, currently unused) and possibly W4A8 activations.
20//! * **H3, access pattern.** Something about the indexing rather than the width.
21//!
22//! # The design
23//!
24//! Five shaders over one 256 MB allocation, differing in one axis at a time:
25//!
26//! | | shallow loads | 16 loads in flight |
27//! | :--- | :--- | :--- |
28//! | 1 XOR / 16 B | **A** (control) | **D** |
29//! | + int4 unpack | **B** | |
30//! | + unpack, activation fetch, FMA | **C** | **E** |
31//!
32//! `A-B` is the unpack, `B-C` the activation stream, `A-D` prefetch depth without
33//! arithmetic, `C-E` prefetch depth with it. A being anything other than ~20 GB/s means the
34//! harness is not comparable to `imageprobe::compare` and nothing else should be read.
35//!
36//! All five sweep the same bytes with the same grid, so the reported GB/s are directly
37//! comparable to each other and to the SSBO figure from `report_read_path`.
38//!
39//! # Deliberately not in `shaders/`
40//!
41//! These are probes, not runtime kernels, so they live in `analysis/gemv_probe/` and are
42//! compiled by hand rather than by `build.rs`, which would pull them into every build of
43//! the shipped runtime. See the README beside them for the `glslc` line.
44
45use std::sync::Arc;
46use std::time::Instant;
47
48use ash::vk;
49
50use modelrunner::vulkan::buffers::Buffer;
51use modelrunner::vulkan::context::{self, Context};
52
53// Compiled by `build.rs` from `shaders/gemv_*.comp` into OUT_DIR, the same path
54// `imageprobe.rs` uses for its two probe shaders. The sources of truth are in
55// `analysis/gemv_probe/`; `shaders/` holds build-visible copies because `build.rs` is the
56// only glslc access available in this environment.
57const A: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_a_control.comp.spv"));
58const B: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_b_unpack.comp.spv"));
59const C: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_c_full.comp.spv"));
60const D: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_d_deep.comp.spv"));
61const E: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_e_deep_full.comp.spv"));
62const F: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_f_shape.comp.spv"));
63const G: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_g_shape_full.comp.spv"));
64const H: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_h_rows8.comp.spv"));
65const I: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_i_kloop16.comp.spv"));
66const J: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_j_split8x8.comp.spv"));
67const K: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_k_rwarena.comp.spv"));
68
69/// Output channels for the gemv-shaped variants F and G.
70///
71/// 65,536 so their bytes match the `[65536, 1536]` row of `report_gemv_scaling`, which is the
72/// figure G has to reproduce. `count` is half of it because `ROWS` is 2, giving 32,768
73/// workgroups - inside the 65,535 per-dimension floor, so no 2D split is needed.
74///
75/// `GEMV_OUT` overrides it, so the byte total can be held roughly constant while `GEMV_IN`
76/// sweeps. See [`gemv_out`].
77fn gemv_out() -> u32 {
78 env_u32("GEMV_OUT").unwrap_or(65_536)
79}
80
81/// Taps per output channel for F and G. 1,536 is the shape ~70% of the model's bytes have,
82/// and the shape whose loop runs exactly once with 16 lanes idle.
83///
84/// # Why this is overridable
85///
86/// It is the single variable that decides how many times `conv_vec_int4.comp`'s loop runs per
87/// lane: the stride is `64 * I4_BLOCK` = 2048 taps, so a lane runs `ceil(in_c / 2048)` times
88/// and lanes with `lane * 32 >= in_c` do not run at all. Sweeping it with everything else held
89/// fixed isolates iterations-per-lane from occupancy, ALU mix and dispatch count - which is the
90/// question left open after the A-G run, and it needs no new shader because both F and G
91/// already take `in_c` as a push constant.
92///
93/// 1536 -> 1 iteration, 48 of 64 lanes (q, k, v, gate_up, head splits: 71% of decode bytes)
94/// 2048 -> 1 iteration, 64 of 64 lanes (o_proj on sliding layers)
95/// 4096 -> 2 iterations, 64 lanes
96/// 12288 -> 6 iterations, 64 lanes (down, shared-cache layers)
97fn gemv_in() -> u32 {
98 env_u32("GEMV_IN").unwrap_or(1_536)
99}
100
101/// A positive `u32` from the environment, or `None` if unset or unparseable.
102fn env_u32(key: &str) -> Option<u32> {
103 std::env::var(key).ok()?.parse::<u32>().ok().filter(|v| *v > 0)
104}
105
106/// Bytes swept per pass. Matches `imageprobe::BYTES` so A is comparable to the published
107/// SSBO figure.
108const BYTES: u64 = 256 * 1024 * 1024;
109
110/// Workgroups. Matches `imageprobe::GROUPS`.
111const GROUPS: u32 = 2048;
112
113/// `float16_t` in the activation buffer.
114///
115/// 4,096 (8 KB) is the floor — cache-resident, as the real kernel's 3 KB activation vector is,
116/// and it is all variants A–E ever index (C's `abase` tops out at 4,095).
117///
118/// The gemv-shaped variants need `in_c` elements, because their activation index runs to
119/// `base + 31` where `base` reaches `in_c`. Sizing to that rather than masking is deliberate:
120/// masking every access cost **32 extra ALU ops per `uvec4`** in the loop these variants exist
121/// to measure, which the real kernel does not pay (`conv_vec_int4.comp:114`), and which made
122/// this probe 1.6–1.8x slower than the production kernel it models. Sizing to `in_c` also
123/// reproduces the real cache footprint (3 KB at 1536, 24 KB at 12288) instead of a fixed 8 KB.
124fn act_elems() -> u64 {
125 4096.max(u64::from(gemv_in()) + 64)
126}
127
128/// Timed passes per variant, after a discarded warm pass. Odd, so the median is a sample.
129const RUNS: usize = 7;
130
131/// The per-call host round trip, in seconds, as measured by `report_gemv_overhead`.
132///
133/// Directly measured rather than fitted: a `[64, 1536]` gemv moves 49 kB, which even a slow
134/// kernel streams in tens of microseconds, so its wall time is the round trip. Three runs on a
135/// Mali-G715 gave 0.312 / 0.655 / 0.638 ms; the larger figure is used so the guard errs toward
136/// warning. An earlier two-parameter curve fit put this at 1.5-2.9 ms and was wrong.
137///
138/// Used only to judge whether a variant's measurement is overhead-dominated. It is **not**
139/// subtracted from the reported GB/s - those stay raw, so they remain comparable with
140/// `report_gemv_scaling`, which does not subtract either.
141const CALL_FLOOR_S: f64 = 0.000_64;
142
143/// Passes of variant A run before any timing starts, to bring the clocks up.
144///
145/// bench-builder found cold-clock artifacts large enough to halve a reading, so the first
146/// variant measured must not also be the thing that warms the device.
147const WARMUP: usize = 3;
148
149fn main() {
150 let context = match context::shared() {
151 Ok(context) => context,
152 Err(why) => return println!("no usable Vulkan device: {why}"),
153 };
154 if let Err(why) = run(&context) {
155 println!("probe failed: {why}");
156 }
157}
158
159fn run(context: &Arc<Context>) -> Result<(), String> {
160 let quads = (BYTES / 16) as u32;
161 // The source allocation's USAGE FLAGS are a variable, not a detail.
162 //
163 // `imageprobe` allocates its 256 MB with `STORAGE_BUFFER | UNIFORM_TEXEL_BUFFER |
164 // TRANSFER_DST`, because it needs a texel view over the same memory. This runner allocates
165 // with `Buffer::device_local`, i.e. `STORAGE_BUFFER | TRANSFER_DST | TRANSFER_SRC` - no
166 // texel usage.
167 //
168 // That difference is suspicious: variant A is byte-for-byte `probe_ssbo.comp`, reads the
169 // same 256 MB with the same 2,048 groups, and measures **28.6 GB/s on the G710** where
170 // `report_read_path`'s SSBO leg measures **17.4** on the same device. Same shader, 1.64x
171 // apart, and the allocation flags are the only difference.
172 //
173 // `GEMV_TEXEL_USAGE=1` adds the texel flag so the two can be compared directly. If A drops
174 // to ~17.4, then declaring `UNIFORM_TEXEL_BUFFER` depresses SSBO throughput - which would
175 // mean `report_read_path`'s SSBO leg is handicapped, its ceilings are understated, and its
176 // texel-vs-SSBO ratio is measuring the handicap rather than a texel advantage.
177 let source = if std::env::var("GEMV_TEXEL_USAGE").is_ok() {
178 Buffer::device_local_usage(
179 context,
180 BYTES,
181 vk::BufferUsageFlags::STORAGE_BUFFER
182 | vk::BufferUsageFlags::UNIFORM_TEXEL_BUFFER
183 | vk::BufferUsageFlags::TRANSFER_DST,
184 )?
185 } else {
186 Buffer::device_local(context, BYTES)?
187 };
188 let sink = Buffer::device_local(context, 256)?;
189 let acts = Buffer::device_local(context, act_elems() * 2)?;
190
191 // The activation buffer is initialised, unlike the source.
192 //
193 // The source feeds `bitfieldExtract`, so whatever bits it holds become a finite integer
194 // and uninitialised memory cannot change the arithmetic's cost. fp16 is different: an
195 // uninitialised pattern can be NaN or a denormal, and a device that handles those on a
196 // slow path would make variants C and E look expensive for a reason that has nothing to
197 // do with the hypothesis under test.
198 upload_activations(context, &acts)?;
199
200 let bindings = [
201 binding(0),
202 binding(1),
203 binding(2),
204 ];
205 let layout = unsafe {
206 context
207 .device
208 .create_descriptor_set_layout(
209 &vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings),
210 None,
211 )
212 .map_err(|e| format!("descriptor layout: {e:?}"))?
213 };
214 let sizes = [vk::DescriptorPoolSize {
215 ty: vk::DescriptorType::STORAGE_BUFFER,
216 descriptor_count: 3,
217 }];
218 let pool = unsafe {
219 context
220 .device
221 .create_descriptor_pool(
222 &vk::DescriptorPoolCreateInfo::default().max_sets(1).pool_sizes(&sizes),
223 None,
224 )
225 .map_err(|e| format!("descriptor pool: {e:?}"))?
226 };
227 let layouts = [layout];
228 let set = unsafe {
229 context
230 .device
231 .allocate_descriptor_sets(
232 &vk::DescriptorSetAllocateInfo::default()
233 .descriptor_pool(pool)
234 .set_layouts(&layouts),
235 )
236 .map_err(|e| format!("descriptor set: {e:?}"))?
237 .first()
238 .copied()
239 .ok_or("allocate_descriptor_sets returned nothing")?
240 };
241 write_set(context, set, &source, &sink, &acts);
242
243 let push = [vk::PushConstantRange::default()
244 .stage_flags(vk::ShaderStageFlags::COMPUTE)
245 .offset(0)
246 .size(12)];
247 let pipeline_layout = unsafe {
248 context
249 .device
250 .create_pipeline_layout(
251 &vk::PipelineLayoutCreateInfo::default()
252 .set_layouts(&layouts)
253 .push_constant_ranges(&push),
254 None,
255 )
256 .map_err(|e| format!("pipeline layout: {e:?}"))?
257 };
258
259 let command_pool = unsafe {
260 context
261 .device
262 .create_command_pool(
263 &vk::CommandPoolCreateInfo::default()
264 .queue_family_index(context.queue_family_index)
265 .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER),
266 None,
267 )
268 .map_err(|e| format!("command pool: {e:?}"))?
269 };
270 let command_buffer = unsafe {
271 context
272 .device
273 .allocate_command_buffers(
274 &vk::CommandBufferAllocateInfo::default()
275 .command_pool(command_pool)
276 .level(vk::CommandBufferLevel::PRIMARY)
277 .command_buffer_count(1),
278 )
279 .map_err(|e| format!("command buffer: {e:?}"))?
280 .first()
281 .copied()
282 .ok_or("allocate_command_buffers returned nothing")?
283 };
284 let fence = unsafe {
285 context
286 .device
287 .create_fence(&vk::FenceCreateInfo::default(), None)
288 .map_err(|e| format!("fence: {e:?}"))?
289 };
290
291 // name, spirv, note, workgroups, bytes swept.
292 //
293 // A-E sweep the whole 256 MB with a grid-stride loop, so a lane runs ~128 iterations.
294 // F and G are dispatched as a real gemv - one workgroup per two output channels - so a
295 // lane runs the loop **once** at `in_c` 1536, which is what `conv_vec_int4.comp` does.
296 // That difference is the point of the pair; see `gemv_f_shape.comp`.
297 let gemv_out = gemv_out();
298 let gemv_in = gemv_in();
299 // Weight bytes F and G sweep: `out * in / 2` at four bits.
300 let gemv_bytes: u64 = u64::from(gemv_out) * u64::from(gemv_in) / 2;
301
302 // HARD BOUND. The gemv-shaped variants index `weights128[(channel * in_c + base) / 32]`
303 // into the same 256 MiB source allocation the streaming variants sweep. If
304 // `out * in_c / 2` exceeds it they read past the end — and under `robustBufferAccess`
305 // that does not fault, it returns zeros. The kernel still runs, still finishes, and
306 // reports a plausible GB/s computed from bytes it never actually read.
307 //
308 // Refusing is the only safe behaviour: a silently wrong number here would be
309 // indistinguishable from a real result and would be acted on.
310 if gemv_bytes > BYTES {
311 println!("REFUSING TO RUN: GEMV_OUT={gemv_out} x GEMV_IN={gemv_in} needs {:.1} MB", gemv_bytes as f64 / 1e6);
312 println!(" but the source allocation is {:.1} MB.", BYTES as f64 / 1e6);
313 println!();
314 println!(" The gemv variants would read past the buffer. Under robustBufferAccess that");
315 println!(" returns zeros rather than faulting, so you would get a plausible number");
316 println!(" computed from bytes that were never read.");
317 println!();
318 println!(" Keep GEMV_OUT * GEMV_IN <= {}. Max GEMV_OUT for this GEMV_IN is {}.", BYTES * 2, (BYTES * 2) / u64::from(gemv_in));
319 return Ok(());
320 }
321
322 // A lane starts at `lane * 32` and strides 2048, so this is how many times its loop runs
323 // and how many of the 64 lanes enter it at all. Printed because it is the variable under
324 // test, and reading it off `in_c` in your head is exactly the step everyone got wrong.
325 let iterations = gemv_in.div_ceil(2048);
326 let active_lanes = gemv_in.div_ceil(32).min(64);
327
328 let variants: [(&str, &[u8], &str, u32, u64); 11] = [
329 ("A control ", A, "stream, 1 XOR / 16 B", GROUPS, BYTES),
330 ("B unpack ", B, "stream, + int4 unpack", GROUPS, BYTES),
331 ("C full dequant ", C, "stream, + activations + FMA", GROUPS, BYTES),
332 ("D deep ", D, "stream, 16 loads in flight", GROUPS, BYTES),
333 ("E deep + full ", E, "stream, deep + full dequant", GROUPS, BYTES),
334 ("F real shape ", F, "gemv shape, trivial ALU", gemv_out / 2, gemv_bytes),
335 ("G real shape+ ", G, "K=1 ROWS 2 64 lanes, READONLY acts", gemv_out / 2, gemv_bytes),
336 ("H ROWS 8 ", H, "K=1 ROWS 8 64 lanes (row-ILP only)", gemv_out / 8, gemv_bytes),
337 ("I K-loop x16 ", I, "K=3 ROWS 2 16 lanes", gemv_out / 2, gemv_bytes),
338 ("J split 8x8 ", J, "K=6 ROWS 8 64 lanes", gemv_out / 8, gemv_bytes),
339 // G with a read-write activation buffer and a store into it, as production's `arena`
340 // is (`common.glsl:38`, `conv_vec_int4.comp:179`). K vs G is the aliasing cost.
341 ("K rw-arena ", K, "= G but READ-WRITE acts + store", gemv_out / 2, gemv_bytes),
342 ];
343
344 // Warm the clocks on the control before anything is recorded as a measurement.
345 {
346 let warm = Pipeline::new(context, pipeline_layout, A)?;
347 for _ in 0..WARMUP {
348 let _ = time_pass(context, command_buffer, fence, pipeline_layout, set, &warm, quads, GROUPS)?;
349 }
350 warm.destroy(context);
351 }
352
353 println!(" A-E: 256 MB per pass, {GROUPS} workgroups, grid-stride (~128 iterations a lane)");
354 println!(
355 " F-G: {:.1} MB per pass, {} workgroups, gemv shape [{gemv_out}, {gemv_in}]",
356 gemv_bytes as f64 / 1e6,
357 gemv_out / 2,
358 );
359 println!(
360 " -> {iterations} loop iteration(s) a lane, {active_lanes} of 64 lanes active"
361 );
362 println!(" {RUNS} timed passes each, INTERLEAVED round-robin");
363 println!();
364 println!(" variant raw GB/s corr GB/s min max what changed");
365
366 // Every variant is built up front and then timed ROUND-ROBIN: one pass of A, one of B, ...
367 // one of J, and repeat. Not seven passes of A, then seven of B.
368 //
369 // This is not fastidiousness. lead measured `ROWS=4` at 3.63 vs 3.19 - an apparent 14% win -
370 // running baseline-then-candidate sequentially, and it evaporated to 0.88x (a LOSS) when the
371 // same two were interleaved in one session. GPU DVFS drifts over the tens of seconds a full
372 // sweep takes, so a sequential schedule confounds "which variant" with "when in the session
373 // it ran". With ten variants the first and last are minutes apart, and F/G/I - the
374 // comparisons this whole document rests on - sit at the far end of that drift.
375 //
376 // Round-robin makes every variant share the same clock trajectory: whatever the clocks are
377 // doing in round k, all ten see it.
378 let mut built = Vec::with_capacity(variants.len());
379 for (name, spirv, note, groups, bytes) in variants {
380 built.push((name, Pipeline::new(context, pipeline_layout, spirv)?, note, groups, bytes));
381 }
382
383 // One discarded pass each, so no variant's first timed pass pays for driver setup.
384 for (_, pipeline, _, groups, _) in &built {
385 let _ = time_pass(context, command_buffer, fence, pipeline_layout, set, pipeline, quads, *groups)?;
386 }
387
388 let mut rates: Vec<Vec<f64>> = vec![Vec::with_capacity(RUNS); built.len()];
389 let mut times: Vec<Vec<f64>> = vec![Vec::with_capacity(RUNS); built.len()];
390 for _ in 0..RUNS {
391 for (index, (_, pipeline, _, groups, bytes)) in built.iter().enumerate() {
392 let seconds =
393 time_pass(context, command_buffer, fence, pipeline_layout, set, pipeline, quads, *groups)?;
394 if let Some(slot) = rates.get_mut(index) {
395 slot.push(*bytes as f64 / seconds / 1e9);
396 }
397 if let Some(slot) = times.get_mut(index) {
398 slot.push(seconds);
399 }
400 }
401 }
402
403 let mut medians = Vec::new();
404 let mut overhead_flagged = false;
405 for (index, (name, pipeline, note, _, bytes)) in built.iter().enumerate() {
406 pipeline.destroy(context);
407 let (Some(rate_samples), Some(time_samples)) = (rates.get_mut(index), times.get_mut(index))
408 else {
409 continue;
410 };
411 rate_samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
412 time_samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
413 let median = rate_samples.get(rate_samples.len() / 2).copied().unwrap_or(0.0);
414 let low = rate_samples.first().copied().unwrap_or(0.0);
415 let high = rate_samples.last().copied().unwrap_or(0.0);
416
417 // Overhead share is judged on measured WALL TIME, not on bytes.
418 //
419 // A byte threshold is calibrated against one rate and goes quiet at every other. 20 MB
420 // at 2.77 GB/s is 7.2 ms and only 9% overhead, but the same 20 MB at 20 GB/s is 1.0 ms
421 // and 39% overhead - so a byte guard stays silent exactly when a successful fix would
422 // be under-reported by 40%. Wall time is rate-independent and self-correcting.
423 let median_time = time_samples.get(time_samples.len() / 2).copied().unwrap_or(0.0);
424 let share = if median_time > 0.0 { CALL_FLOOR_S / median_time } else { 1.0 };
425 let mark = if share > 0.10 {
426 overhead_flagged = true;
427 " <-- OVERHEAD"
428 } else {
429 ""
430 };
431
432 // The corrected rate, so the subtraction is not left as a manual step for whoever reads
433 // the table. Every cross-shape comparison wants this column, because two shapes with
434 // different wall times carry different overhead shares and the raw figures are not
435 // directly comparable. The raw column stays because it is what `report_gemv_scaling`
436 // prints, and dropping it would break comparability with every number already recorded.
437 let corrected = if median_time > CALL_FLOOR_S * 1.05 {
438 *bytes as f64 / (median_time - CALL_FLOOR_S) / 1e9
439 } else {
440 // Below ~1.05x the floor the subtraction is meaningless and would print a wild
441 // number. Say so rather than emit one.
442 f64::NAN
443 };
444 if corrected.is_nan() {
445 println!(" {name} {median:10.2} -- {low:6.2} {high:6.2} {note}{mark}");
446 } else {
447 println!(" {name} {median:10.2} {corrected:8.2} {low:6.2} {high:6.2} {note}{mark}");
448 }
449 // The analysis below is entirely cross-shape (F against A, G against C, and so on), so
450 // it reads the corrected column. Where correction is impossible the raw value is used
451 // and the row will already be flagged.
452 medians.push((*name, if corrected.is_nan() { median } else { corrected }));
453 }
454
455 if overhead_flagged {
456 println!();
457 println!(
458 " OVERHEAD: rows marked above ran in under {:.1} ms, so the measured {:.2} ms",
459 CALL_FLOOR_S * 10.0 * 1000.0,
460 CALL_FLOOR_S * 1000.0,
461 );
462 println!(" per-call host round trip is >10% of their time. Prefer the corrected column,");
463 println!(" and treat differences between flagged rows as weak. Raising GEMV_OUT is better.");
464 }
465 println!();
466 println!(" raw = bytes / t comparable with report_gemv_scaling, which also does not correct");
467 println!(" corr = bytes / (t - {:.2} ms) host round trip removed; the analysis below uses this", CALL_FLOOR_S * 1000.0);
468
469 report(&medians);
470
471
472 unsafe {
473 let device = &context.device;
474 device.destroy_fence(fence, None);
475 device.destroy_command_pool(command_pool, None);
476 device.destroy_pipeline_layout(pipeline_layout, None);
477 device.destroy_descriptor_pool(pool, None);
478 device.destroy_descriptor_set_layout(layout, None);
479 }
480 Ok(())
481}
482
483/// Read the 2x2 out loud, so the log says which hypothesis it supports rather than leaving
484/// it to whoever pastes the table into a message.
485fn report(medians: &[(&str, f64)]) {
486 let get = |i: usize| medians.get(i).map(|(_, v)| *v).unwrap_or(0.0);
487 let (a, b, c, d, e, f, g) = (get(0), get(1), get(2), get(3), get(4), get(5), get(6));
488 println!();
489 println!(" A -> B unpack costs {:.2}x (inside a stream)", ratio(a, b));
490 println!(" B -> C activations cost {:.2}x (inside a stream)", ratio(b, c));
491 println!(" A -> D depth is worth {:.2}x (light ALU)", ratio(a, d));
492 println!(" C -> E depth is worth {:.2}x (full ALU)", ratio(c, e));
493 println!(" A -> F the SHAPE costs {:.2}x (same trivial ALU, one-shot vs stream)", ratio(a, f));
494 println!(" F -> G the ALU costs {:.2}x (inside the real shape)", ratio(f, g));
495 println!();
496
497 // Deliberately coarse thresholds. This is a discriminating experiment, not a measurement
498 // of an effect size, and a 1.3x is not something to build a plan on.
499 let shape_costs = a > 0.0 && f < a * 0.5;
500 let alu_costs_in_shape = f > 0.0 && g < f * 0.6;
501 let alu_costs_in_stream = a > 0.0 && c < a * 0.6;
502 let depth_helps = d > a * 1.3;
503
504 match (shape_costs, alu_costs_in_shape) {
505 (true, false) => println!(
506 " READS AS: THE SHAPE. A one-iteration loop with 16 idle lanes accounts for it, and\n \
507 the dequant arithmetic is nearly free. Fix = give each lane a stream of work:\n \
508 more taps per lane, no idle lanes, a loop that actually iterates. Integer dot\n \
509 product and W4A8 would buy little."
510 ),
511 (true, true) => println!(
512 " READS AS: BOTH. The shape costs {:.1}x and the arithmetic a further {:.1}x on top\n \
513 of it. Fix the shape first - it is the larger term and it is a loop-bounds change,\n \
514 not a numerics change.",
515 ratio(a, f),
516 ratio(f, g),
517 ),
518 (false, true) => println!(
519 " READS AS: THE ALU. The shape is nearly free and the dequant is the limiter.\n \
520 This revives VK_KHR_shader_integer_dot_product and possibly W4A8."
521 ),
522 (false, false) => println!(
523 " READS AS: NEITHER, which means G did not reproduce the real kernel. Check G against\n \
524 report_gemv_scaling's [65536, 1536] row before reading anything else here."
525 ),
526 }
527 if alu_costs_in_stream && !alu_costs_in_shape {
528 println!(
529 " NOTE: the dequant is expensive inside a stream (A->C) but not inside the real\n \
530 shape (F->G). That is consistent with the shape already being the bottleneck -\n \
531 there is no throughput left for the arithmetic to take away."
532 );
533 }
534 if depth_helps {
535 println!(" NOTE: deep prefetch beat the control by {:.2}x with light ALU.", ratio(d, a));
536 }
537 println!();
538 println!(" TWO ANCHORS, check both before trusting anything above:");
539 println!(" A should match report_read_path's SSBO figure (~20 G715, ~28 G4).");
540 println!(" G should match report_gemv_scaling's [65536, 1536] row (~3.4-4.0).");
541 println!(" If either is off, the harness is not reproducing what it claims to.");
542}
543
544fn ratio(from: f64, to: f64) -> f64 {
545 if to <= 0.0 {
546 return 0.0;
547 }
548 from / to
549}
550
551fn binding(at: u32) -> vk::DescriptorSetLayoutBinding<'static> {
552 vk::DescriptorSetLayoutBinding::default()
553 .binding(at)
554 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
555 .descriptor_count(1)
556 .stage_flags(vk::ShaderStageFlags::COMPUTE)
557}
558
559fn write_set(context: &Arc<Context>, set: vk::DescriptorSet, source: &Buffer, sink: &Buffer, acts: &Buffer) {
560 let infos = [
561 vk::DescriptorBufferInfo { buffer: source.buffer, offset: 0, range: vk::WHOLE_SIZE },
562 vk::DescriptorBufferInfo { buffer: sink.buffer, offset: 0, range: vk::WHOLE_SIZE },
563 vk::DescriptorBufferInfo { buffer: acts.buffer, offset: 0, range: vk::WHOLE_SIZE },
564 ];
565 let writes: Vec<_> = infos
566 .iter()
567 .enumerate()
568 .map(|(at, info)| {
569 vk::WriteDescriptorSet::default()
570 .dst_set(set)
571 .dst_binding(at as u32)
572 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
573 .buffer_info(std::slice::from_ref(info))
574 })
575 .collect();
576 // SAFETY: the set is live and nothing is in flight against it yet.
577 unsafe { context.device.update_descriptor_sets(&writes, &[]) };
578}
579
580/// Fill the activation buffer with ordinary finite fp16, through a staging copy.
581fn upload_activations(context: &Arc<Context>, acts: &Buffer) -> Result<(), String> {
582 // 0.5, 1.0, 1.5 ... as fp16 bit patterns, cycling. Any finite spread does; what matters
583 // is that none of them is NaN, Inf or denormal.
584 let values: Vec<u16> = (0..act_elems())
585 .map(|i| f32_to_f16(0.5 + (i % 8) as f32 * 0.25))
586 .collect();
587 let mut bytes = Vec::with_capacity(values.len() * 2);
588 for value in &values {
589 bytes.extend_from_slice(&value.to_le_bytes());
590 }
591 let staging = Buffer::staging(context, bytes.len() as vk::DeviceSize)?;
592 staging.write(&bytes)?;
593 one_shot(context, |device, cb| {
594 let region = vk::BufferCopy::default().size(bytes.len() as vk::DeviceSize);
595 // SAFETY: both buffers are live and the region is exactly the staging size.
596 unsafe { device.cmd_copy_buffer(cb, staging.buffer, acts.buffer, std::slice::from_ref(&region)) };
597 })
598}
599
600/// Round to fp16, for the handful of constants above. Round-to-nearest is not needed here.
601fn f32_to_f16(value: f32) -> u16 {
602 let bits = value.to_bits();
603 let sign = ((bits >> 16) & 0x8000) as u16;
604 let exponent = ((bits >> 23) & 0xFF) as i32 - 127 + 15;
605 let mantissa = ((bits >> 13) & 0x3FF) as u16;
606 if exponent <= 0 || exponent >= 31 {
607 return sign;
608 }
609 sign | ((exponent as u16) << 10) | mantissa
610}
611
612/// Record, submit and wait for one throwaway command buffer.
613fn one_shot(
614 context: &Arc<Context>,
615 record: impl FnOnce(&ash::Device, vk::CommandBuffer),
616) -> Result<(), String> {
617 let device = &context.device;
618 // SAFETY: every handle is created, used and destroyed inside this call, and the fence is
619 // waited on before anything is torn down.
620 unsafe {
621 let pool = device
622 .create_command_pool(
623 &vk::CommandPoolCreateInfo::default().queue_family_index(context.queue_family_index),
624 None,
625 )
626 .map_err(|e| format!("one-shot pool: {e:?}"))?;
627 let cb = device
628 .allocate_command_buffers(
629 &vk::CommandBufferAllocateInfo::default()
630 .command_pool(pool)
631 .level(vk::CommandBufferLevel::PRIMARY)
632 .command_buffer_count(1),
633 )
634 .map_err(|e| format!("one-shot buffer: {e:?}"))?
635 .first()
636 .copied()
637 .ok_or("allocate_command_buffers returned nothing")?;
638 device
639 .begin_command_buffer(
640 cb,
641 &vk::CommandBufferBeginInfo::default()
642 .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
643 )
644 .map_err(|e| format!("one-shot begin: {e:?}"))?;
645 record(device, cb);
646 device.end_command_buffer(cb).map_err(|e| format!("one-shot end: {e:?}"))?;
647 let fence = device
648 .create_fence(&vk::FenceCreateInfo::default(), None)
649 .map_err(|e| format!("one-shot fence: {e:?}"))?;
650 let buffers = [cb];
651 let submit = vk::SubmitInfo::default().command_buffers(&buffers);
652 let guard = context.lock_queue();
653 let sent = device.queue_submit(context.queue, std::slice::from_ref(&submit), fence);
654 drop(guard);
655 sent.map_err(|e| format!("one-shot submit: {e:?}"))?;
656 device
657 .wait_for_fences(&[fence], true, 20_000_000_000)
658 .map_err(|e| format!("one-shot wait: {e:?}"))?;
659 device.destroy_fence(fence, None);
660 device.destroy_command_pool(pool, None);
661 }
662 Ok(())
663}
664
665struct Pipeline {
666 module: vk::ShaderModule,
667 pipeline: vk::Pipeline,
668}
669
670impl Pipeline {
671 fn new(context: &Arc<Context>, layout: vk::PipelineLayout, spirv: &[u8]) -> Result<Pipeline, String> {
672 if !spirv.len().is_multiple_of(4) || spirv.len() < 20 {
673 return Err(format!(
674 "{} bytes is not a SPIR-V module - did the glslc step run? See analysis/gemv_probe/README.md",
675 spirv.len()
676 ));
677 }
678 let words: Vec<u32> = spirv
679 .chunks_exact(4)
680 .map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]]))
681 .collect();
682 // SAFETY: both handles are destroyed by `destroy`, and the module outlives the
683 // pipeline creation that reads it.
684 unsafe {
685 let module = context
686 .device
687 .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words), None)
688 .map_err(|e| format!("shader module: {e:?}"))?;
689 let name = std::ffi::CString::new("main").map_err(|e| format!("{e}"))?;
690 let stage = vk::PipelineShaderStageCreateInfo::default()
691 .stage(vk::ShaderStageFlags::COMPUTE)
692 .module(module)
693 .name(&name);
694 let pipeline = context
695 .device
696 .create_compute_pipelines(
697 vk::PipelineCache::null(),
698 &[vk::ComputePipelineCreateInfo::default().stage(stage).layout(layout)],
699 None,
700 )
701 .map_err(|(_, e)| format!("compute pipeline: {e:?}"))?
702 .first()
703 .copied()
704 .ok_or("create_compute_pipelines returned nothing")?;
705 Ok(Pipeline { module, pipeline })
706 }
707 }
708
709 fn destroy(&self, context: &Arc<Context>) {
710 // SAFETY: called after the last fence wait, so nothing references either handle.
711 unsafe {
712 context.device.destroy_pipeline(self.pipeline, None);
713 context.device.destroy_shader_module(self.module, None);
714 }
715 }
716}
717
718/// Seconds for one pass.
719fn time_pass(
720 context: &Arc<Context>,
721 cb: vk::CommandBuffer,
722 fence: vk::Fence,
723 layout: vk::PipelineLayout,
724 set: vk::DescriptorSet,
725 pipeline: &Pipeline,
726 quads: u32,
727 groups: u32,
728) -> Result<f64, String> {
729 let device = &context.device;
730 // `quads` for the streaming variants, `in_c` and `count` for the gemv-shaped ones. All
731 // three are pushed for every variant; a shader that does not declare a field ignores it.
732 // For F and G, `groups` **is** `count` — one workgroup per `ROWS` output channels.
733 let mut push = [0u8; 12];
734 for (slot, value) in [quads, gemv_in(), groups].iter().enumerate() {
735 if let Some(dst) = push.get_mut(slot * 4..slot * 4 + 4) {
736 dst.copy_from_slice(&value.to_le_bytes());
737 }
738 }
739 // SAFETY: the buffer is reset and re-recorded here and the fence is waited on before
740 // this returns, so nothing is ever in flight across two calls.
741 unsafe {
742 device
743 .begin_command_buffer(cb, &vk::CommandBufferBeginInfo::default())
744 .map_err(|e| format!("begin: {e:?}"))?;
745 device.cmd_bind_pipeline(cb, vk::PipelineBindPoint::COMPUTE, pipeline.pipeline);
746 device.cmd_bind_descriptor_sets(cb, vk::PipelineBindPoint::COMPUTE, layout, 0, &[set], &[]);
747 device.cmd_push_constants(
748 cb,
749 layout,
750 vk::ShaderStageFlags::COMPUTE,
751 0,
752 &push,
753 );
754 device.cmd_dispatch(cb, groups, 1, 1);
755 device.end_command_buffer(cb).map_err(|e| format!("end: {e:?}"))?;
756
757 let started = Instant::now();
758 device.reset_fences(&[fence]).map_err(|e| format!("reset: {e:?}"))?;
759 let buffers = [cb];
760 let submit = vk::SubmitInfo::default().command_buffers(&buffers);
761 let guard = context.lock_queue();
762 let sent = device.queue_submit(context.queue, std::slice::from_ref(&submit), fence);
763 drop(guard);
764 sent.map_err(|e| format!("submit: {e:?}"))?;
765 device
766 .wait_for_fences(&[fence], true, 20_000_000_000)
767 .map_err(|e| format!("wait: {e:?}"))?;
768 Ok(started.elapsed().as_secs_f64())
769 }
770}