Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / report_gemv_bottleneck.rs
report_gemv_bottleneck.rs801 lines · 35.7 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 | |
| 45 | use std::sync::Arc; |
| 46 | use std::time::Instant; |
| 47 | |
| 48 | use ash::vk; |
| 49 | |
| 50 | use modelrunner::vulkan::buffers::Buffer; |
| 51 | use 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. |
| 57 | const A: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_a_control.comp.spv")); |
| 58 | const B: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_b_unpack.comp.spv")); |
| 59 | const C: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_c_full.comp.spv")); |
| 60 | const D: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_d_deep.comp.spv")); |
| 61 | const E: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_e_deep_full.comp.spv")); |
| 62 | const F: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_f_shape.comp.spv")); |
| 63 | const G: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_g_shape_full.comp.spv")); |
| 64 | const H: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_h_rows8.comp.spv")); |
| 65 | const I: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_i_kloop16.comp.spv")); |
| 66 | const J: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_j_split8x8.comp.spv")); |
| 67 | const 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`]. |
| 77 | fn 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) |
| 97 | fn 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. |
| 102 | fn 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. |
| 108 | const BYTES: u64 = 256 * 1024 * 1024; |
| 109 | |
| 110 | /// Workgroups. Matches `imageprobe::GROUPS`. |
| 111 | const 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. |
| 124 | fn 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. |
| 129 | const 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. |
| 141 | const 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. |
| 147 | const WARMUP: usize = 3; |
| 148 | |
| 149 | fn 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 | |
| 159 | fn 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 = [binding(0), binding(1), binding(2)]; |
| 201 | let layout = unsafe { |
| 202 | context |
| 203 | .device |
| 204 | .create_descriptor_set_layout( |
| 205 | &vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings), |
| 206 | None, |
| 207 | ) |
| 208 | .map_err(|e| format!("descriptor layout: {e:?}"))? |
| 209 | }; |
| 210 | let sizes = |
| 211 | [vk::DescriptorPoolSize { ty: vk::DescriptorType::STORAGE_BUFFER, descriptor_count: 3 }]; |
| 212 | let pool = unsafe { |
| 213 | context |
| 214 | .device |
| 215 | .create_descriptor_pool( |
| 216 | &vk::DescriptorPoolCreateInfo::default().max_sets(1).pool_sizes(&sizes), |
| 217 | None, |
| 218 | ) |
| 219 | .map_err(|e| format!("descriptor pool: {e:?}"))? |
| 220 | }; |
| 221 | let layouts = [layout]; |
| 222 | let set = unsafe { |
| 223 | context |
| 224 | .device |
| 225 | .allocate_descriptor_sets( |
| 226 | &vk::DescriptorSetAllocateInfo::default() |
| 227 | .descriptor_pool(pool) |
| 228 | .set_layouts(&layouts), |
| 229 | ) |
| 230 | .map_err(|e| format!("descriptor set: {e:?}"))? |
| 231 | .first() |
| 232 | .copied() |
| 233 | .ok_or("allocate_descriptor_sets returned nothing")? |
| 234 | }; |
| 235 | write_set(context, set, &source, &sink, &acts); |
| 236 | |
| 237 | let push = [vk::PushConstantRange::default() |
| 238 | .stage_flags(vk::ShaderStageFlags::COMPUTE) |
| 239 | .offset(0) |
| 240 | .size(12)]; |
| 241 | let pipeline_layout = unsafe { |
| 242 | context |
| 243 | .device |
| 244 | .create_pipeline_layout( |
| 245 | &vk::PipelineLayoutCreateInfo::default() |
| 246 | .set_layouts(&layouts) |
| 247 | .push_constant_ranges(&push), |
| 248 | None, |
| 249 | ) |
| 250 | .map_err(|e| format!("pipeline layout: {e:?}"))? |
| 251 | }; |
| 252 | |
| 253 | let command_pool = unsafe { |
| 254 | context |
| 255 | .device |
| 256 | .create_command_pool( |
| 257 | &vk::CommandPoolCreateInfo::default() |
| 258 | .queue_family_index(context.queue_family_index) |
| 259 | .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER), |
| 260 | None, |
| 261 | ) |
| 262 | .map_err(|e| format!("command pool: {e:?}"))? |
| 263 | }; |
| 264 | let command_buffer = unsafe { |
| 265 | context |
| 266 | .device |
| 267 | .allocate_command_buffers( |
| 268 | &vk::CommandBufferAllocateInfo::default() |
| 269 | .command_pool(command_pool) |
| 270 | .level(vk::CommandBufferLevel::PRIMARY) |
| 271 | .command_buffer_count(1), |
| 272 | ) |
| 273 | .map_err(|e| format!("command buffer: {e:?}"))? |
| 274 | .first() |
| 275 | .copied() |
| 276 | .ok_or("allocate_command_buffers returned nothing")? |
| 277 | }; |
| 278 | let fence = unsafe { |
| 279 | context |
| 280 | .device |
| 281 | .create_fence(&vk::FenceCreateInfo::default(), None) |
| 282 | .map_err(|e| format!("fence: {e:?}"))? |
| 283 | }; |
| 284 | |
| 285 | // name, spirv, note, workgroups, bytes swept. |
| 286 | // |
| 287 | // A-E sweep the whole 256 MB with a grid-stride loop, so a lane runs ~128 iterations. |
| 288 | // F and G are dispatched as a real gemv - one workgroup per two output channels - so a |
| 289 | // lane runs the loop **once** at `in_c` 1536, which is what `conv_vec_int4.comp` does. |
| 290 | // That difference is the point of the pair; see `gemv_f_shape.comp`. |
| 291 | let gemv_out = gemv_out(); |
| 292 | let gemv_in = gemv_in(); |
| 293 | // Weight bytes F and G sweep: `out * in / 2` at four bits. |
| 294 | let gemv_bytes: u64 = u64::from(gemv_out) * u64::from(gemv_in) / 2; |
| 295 | |
| 296 | // HARD BOUND. The gemv-shaped variants index `weights128[(channel * in_c + base) / 32]` |
| 297 | // into the same 256 MiB source allocation the streaming variants sweep. If |
| 298 | // `out * in_c / 2` exceeds it they read past the end — and under `robustBufferAccess` |
| 299 | // that does not fault, it returns zeros. The kernel still runs, still finishes, and |
| 300 | // reports a plausible GB/s computed from bytes it never actually read. |
| 301 | // |
| 302 | // Refusing is the only safe behaviour: a silently wrong number here would be |
| 303 | // indistinguishable from a real result and would be acted on. |
| 304 | if gemv_bytes > BYTES { |
| 305 | println!( |
| 306 | "REFUSING TO RUN: GEMV_OUT={gemv_out} x GEMV_IN={gemv_in} needs {:.1} MB", |
| 307 | gemv_bytes as f64 / 1e6 |
| 308 | ); |
| 309 | println!(" but the source allocation is {:.1} MB.", BYTES as f64 / 1e6); |
| 310 | println!(); |
| 311 | println!(" The gemv variants would read past the buffer. Under robustBufferAccess that"); |
| 312 | println!(" returns zeros rather than faulting, so you would get a plausible number"); |
| 313 | println!(" computed from bytes that were never read."); |
| 314 | println!(); |
| 315 | println!( |
| 316 | " Keep GEMV_OUT * GEMV_IN <= {}. Max GEMV_OUT for this GEMV_IN is {}.", |
| 317 | BYTES * 2, |
| 318 | (BYTES * 2) / u64::from(gemv_in) |
| 319 | ); |
| 320 | return Ok(()); |
| 321 | } |
| 322 | |
| 323 | // A lane starts at `lane * 32` and strides 2048, so this is how many times its loop runs |
| 324 | // and how many of the 64 lanes enter it at all. Printed because it is the variable under |
| 325 | // test, and reading it off `in_c` in your head is exactly the step everyone got wrong. |
| 326 | let iterations = gemv_in.div_ceil(2048); |
| 327 | let active_lanes = gemv_in.div_ceil(32).min(64); |
| 328 | |
| 329 | let variants: [(&str, &[u8], &str, u32, u64); 11] = [ |
| 330 | ("A control ", A, "stream, 1 XOR / 16 B", GROUPS, BYTES), |
| 331 | ("B unpack ", B, "stream, + int4 unpack", GROUPS, BYTES), |
| 332 | ("C full dequant ", C, "stream, + activations + FMA", GROUPS, BYTES), |
| 333 | ("D deep ", D, "stream, 16 loads in flight", GROUPS, BYTES), |
| 334 | ("E deep + full ", E, "stream, deep + full dequant", GROUPS, BYTES), |
| 335 | ("F real shape ", F, "gemv shape, trivial ALU", gemv_out / 2, gemv_bytes), |
| 336 | ("G real shape+ ", G, "K=1 ROWS 2 64 lanes, READONLY acts", gemv_out / 2, gemv_bytes), |
| 337 | ("H ROWS 8 ", H, "K=1 ROWS 8 64 lanes (row-ILP only)", gemv_out / 8, gemv_bytes), |
| 338 | ("I K-loop x16 ", I, "K=3 ROWS 2 16 lanes", gemv_out / 2, gemv_bytes), |
| 339 | ("J split 8x8 ", J, "K=6 ROWS 8 64 lanes", gemv_out / 8, gemv_bytes), |
| 340 | // G with a read-write activation buffer and a store into it, as production's `arena` |
| 341 | // is (`common.glsl:38`, `conv_vec_int4.comp:179`). K vs G is the aliasing cost. |
| 342 | ("K rw-arena ", K, "= G but READ-WRITE acts + store", gemv_out / 2, gemv_bytes), |
| 343 | ]; |
| 344 | |
| 345 | // Warm the clocks on the control before anything is recorded as a measurement. |
| 346 | { |
| 347 | let warm = Pipeline::new(context, pipeline_layout, A)?; |
| 348 | for _ in 0..WARMUP { |
| 349 | let _ = time_pass( |
| 350 | Pass { |
| 351 | context, |
| 352 | cb: command_buffer, |
| 353 | fence, |
| 354 | layout: pipeline_layout, |
| 355 | set, |
| 356 | pipeline: &warm, |
| 357 | }, |
| 358 | quads, |
| 359 | GROUPS, |
| 360 | )?; |
| 361 | } |
| 362 | warm.destroy(context); |
| 363 | } |
| 364 | |
| 365 | println!(" A-E: 256 MB per pass, {GROUPS} workgroups, grid-stride (~128 iterations a lane)"); |
| 366 | println!( |
| 367 | " F-G: {:.1} MB per pass, {} workgroups, gemv shape [{gemv_out}, {gemv_in}]", |
| 368 | gemv_bytes as f64 / 1e6, |
| 369 | gemv_out / 2, |
| 370 | ); |
| 371 | println!(" -> {iterations} loop iteration(s) a lane, {active_lanes} of 64 lanes active"); |
| 372 | println!(" {RUNS} timed passes each, INTERLEAVED round-robin"); |
| 373 | println!(); |
| 374 | println!(" variant raw GB/s corr GB/s min max what changed"); |
| 375 | |
| 376 | // Every variant is built up front and then timed ROUND-ROBIN: one pass of A, one of B, ... |
| 377 | // one of J, and repeat. Not seven passes of A, then seven of B. |
| 378 | // |
| 379 | // This is not fastidiousness. lead measured `ROWS=4` at 3.63 vs 3.19 - an apparent 14% win - |
| 380 | // running baseline-then-candidate sequentially, and it evaporated to 0.88x (a LOSS) when the |
| 381 | // same two were interleaved in one session. GPU DVFS drifts over the tens of seconds a full |
| 382 | // sweep takes, so a sequential schedule confounds "which variant" with "when in the session |
| 383 | // it ran". With ten variants the first and last are minutes apart, and F/G/I - the |
| 384 | // comparisons this whole document rests on - sit at the far end of that drift. |
| 385 | // |
| 386 | // Round-robin makes every variant share the same clock trajectory: whatever the clocks are |
| 387 | // doing in round k, all ten see it. |
| 388 | let mut built = Vec::with_capacity(variants.len()); |
| 389 | for (name, spirv, note, groups, bytes) in variants { |
| 390 | built.push((name, Pipeline::new(context, pipeline_layout, spirv)?, note, groups, bytes)); |
| 391 | } |
| 392 | |
| 393 | // One discarded pass each, so no variant's first timed pass pays for driver setup. |
| 394 | for (_, pipeline, _, groups, _) in &built { |
| 395 | let _ = time_pass( |
| 396 | Pass { context, cb: command_buffer, fence, layout: pipeline_layout, set, pipeline }, |
| 397 | quads, |
| 398 | *groups, |
| 399 | )?; |
| 400 | } |
| 401 | |
| 402 | let mut rates: Vec<Vec<f64>> = vec![Vec::with_capacity(RUNS); built.len()]; |
| 403 | let mut times: Vec<Vec<f64>> = vec![Vec::with_capacity(RUNS); built.len()]; |
| 404 | for _ in 0..RUNS { |
| 405 | for (index, (_, pipeline, _, groups, bytes)) in built.iter().enumerate() { |
| 406 | let seconds = time_pass( |
| 407 | Pass { context, cb: command_buffer, fence, layout: pipeline_layout, set, pipeline }, |
| 408 | quads, |
| 409 | *groups, |
| 410 | )?; |
| 411 | if let Some(slot) = rates.get_mut(index) { |
| 412 | slot.push(*bytes as f64 / seconds / 1e9); |
| 413 | } |
| 414 | if let Some(slot) = times.get_mut(index) { |
| 415 | slot.push(seconds); |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | let mut medians = Vec::new(); |
| 421 | let mut overhead_flagged = false; |
| 422 | for (index, (name, pipeline, note, _, bytes)) in built.iter().enumerate() { |
| 423 | pipeline.destroy(context); |
| 424 | let (Some(rate_samples), Some(time_samples)) = (rates.get_mut(index), times.get_mut(index)) |
| 425 | else { |
| 426 | continue; |
| 427 | }; |
| 428 | rate_samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 429 | time_samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 430 | let median = rate_samples.get(rate_samples.len() / 2).copied().unwrap_or(0.0); |
| 431 | let low = rate_samples.first().copied().unwrap_or(0.0); |
| 432 | let high = rate_samples.last().copied().unwrap_or(0.0); |
| 433 | |
| 434 | // Overhead share is judged on measured WALL TIME, not on bytes. |
| 435 | // |
| 436 | // A byte threshold is calibrated against one rate and goes quiet at every other. 20 MB |
| 437 | // 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 |
| 438 | // and 39% overhead - so a byte guard stays silent exactly when a successful fix would |
| 439 | // be under-reported by 40%. Wall time is rate-independent and self-correcting. |
| 440 | let median_time = time_samples.get(time_samples.len() / 2).copied().unwrap_or(0.0); |
| 441 | let share = if median_time > 0.0 { CALL_FLOOR_S / median_time } else { 1.0 }; |
| 442 | let mark = if share > 0.10 { |
| 443 | overhead_flagged = true; |
| 444 | " <-- OVERHEAD" |
| 445 | } else { |
| 446 | "" |
| 447 | }; |
| 448 | |
| 449 | // The corrected rate, so the subtraction is not left as a manual step for whoever reads |
| 450 | // the table. Every cross-shape comparison wants this column, because two shapes with |
| 451 | // different wall times carry different overhead shares and the raw figures are not |
| 452 | // directly comparable. The raw column stays because it is what `report_gemv_scaling` |
| 453 | // prints, and dropping it would break comparability with every number already recorded. |
| 454 | let corrected = if median_time > CALL_FLOOR_S * 1.05 { |
| 455 | *bytes as f64 / (median_time - CALL_FLOOR_S) / 1e9 |
| 456 | } else { |
| 457 | // Below ~1.05x the floor the subtraction is meaningless and would print a wild |
| 458 | // number. Say so rather than emit one. |
| 459 | f64::NAN |
| 460 | }; |
| 461 | if corrected.is_nan() { |
| 462 | println!(" {name} {median:10.2} -- {low:6.2} {high:6.2} {note}{mark}"); |
| 463 | } else { |
| 464 | println!(" {name} {median:10.2} {corrected:8.2} {low:6.2} {high:6.2} {note}{mark}"); |
| 465 | } |
| 466 | // The analysis below is entirely cross-shape (F against A, G against C, and so on), so |
| 467 | // it reads the corrected column. Where correction is impossible the raw value is used |
| 468 | // and the row will already be flagged. |
| 469 | medians.push((*name, if corrected.is_nan() { median } else { corrected })); |
| 470 | } |
| 471 | |
| 472 | if overhead_flagged { |
| 473 | println!(); |
| 474 | println!( |
| 475 | " OVERHEAD: rows marked above ran in under {:.1} ms, so the measured {:.2} ms", |
| 476 | CALL_FLOOR_S * 10.0 * 1000.0, |
| 477 | CALL_FLOOR_S * 1000.0, |
| 478 | ); |
| 479 | println!(" per-call host round trip is >10% of their time. Prefer the corrected column,"); |
| 480 | println!( |
| 481 | " and treat differences between flagged rows as weak. Raising GEMV_OUT is better." |
| 482 | ); |
| 483 | } |
| 484 | println!(); |
| 485 | println!(" raw = bytes / t comparable with report_gemv_scaling, which also does not correct"); |
| 486 | println!( |
| 487 | " corr = bytes / (t - {:.2} ms) host round trip removed; the analysis below uses this", |
| 488 | CALL_FLOOR_S * 1000.0 |
| 489 | ); |
| 490 | |
| 491 | report(&medians); |
| 492 | |
| 493 | unsafe { |
| 494 | let device = &context.device; |
| 495 | device.destroy_fence(fence, None); |
| 496 | device.destroy_command_pool(command_pool, None); |
| 497 | device.destroy_pipeline_layout(pipeline_layout, None); |
| 498 | device.destroy_descriptor_pool(pool, None); |
| 499 | device.destroy_descriptor_set_layout(layout, None); |
| 500 | } |
| 501 | Ok(()) |
| 502 | } |
| 503 | |
| 504 | /// Read the 2x2 out loud, so the log says which hypothesis it supports rather than leaving |
| 505 | /// it to whoever pastes the table into a message. |
| 506 | fn report(medians: &[(&str, f64)]) { |
| 507 | let get = |i: usize| medians.get(i).map(|(_, v)| *v).unwrap_or(0.0); |
| 508 | let (a, b, c, d, e, f, g) = (get(0), get(1), get(2), get(3), get(4), get(5), get(6)); |
| 509 | println!(); |
| 510 | println!(" A -> B unpack costs {:.2}x (inside a stream)", ratio(a, b)); |
| 511 | println!(" B -> C activations cost {:.2}x (inside a stream)", ratio(b, c)); |
| 512 | println!(" A -> D depth is worth {:.2}x (light ALU)", ratio(a, d)); |
| 513 | println!(" C -> E depth is worth {:.2}x (full ALU)", ratio(c, e)); |
| 514 | println!( |
| 515 | " A -> F the SHAPE costs {:.2}x (same trivial ALU, one-shot vs stream)", |
| 516 | ratio(a, f) |
| 517 | ); |
| 518 | println!(" F -> G the ALU costs {:.2}x (inside the real shape)", ratio(f, g)); |
| 519 | println!(); |
| 520 | |
| 521 | // Deliberately coarse thresholds. This is a discriminating experiment, not a measurement |
| 522 | // of an effect size, and a 1.3x is not something to build a plan on. |
| 523 | let shape_costs = a > 0.0 && f < a * 0.5; |
| 524 | let alu_costs_in_shape = f > 0.0 && g < f * 0.6; |
| 525 | let alu_costs_in_stream = a > 0.0 && c < a * 0.6; |
| 526 | let depth_helps = d > a * 1.3; |
| 527 | |
| 528 | match (shape_costs, alu_costs_in_shape) { |
| 529 | (true, false) => println!( |
| 530 | " READS AS: THE SHAPE. A one-iteration loop with 16 idle lanes accounts for it, and\n \ |
| 531 | the dequant arithmetic is nearly free. Fix = give each lane a stream of work:\n \ |
| 532 | more taps per lane, no idle lanes, a loop that actually iterates. Integer dot\n \ |
| 533 | product and W4A8 would buy little." |
| 534 | ), |
| 535 | (true, true) => println!( |
| 536 | " READS AS: BOTH. The shape costs {:.1}x and the arithmetic a further {:.1}x on top\n \ |
| 537 | of it. Fix the shape first - it is the larger term and it is a loop-bounds change,\n \ |
| 538 | not a numerics change.", |
| 539 | ratio(a, f), |
| 540 | ratio(f, g), |
| 541 | ), |
| 542 | (false, true) => println!( |
| 543 | " READS AS: THE ALU. The shape is nearly free and the dequant is the limiter.\n \ |
| 544 | This revives VK_KHR_shader_integer_dot_product and possibly W4A8." |
| 545 | ), |
| 546 | (false, false) => println!( |
| 547 | " READS AS: NEITHER, which means G did not reproduce the real kernel. Check G against\n \ |
| 548 | report_gemv_scaling's [65536, 1536] row before reading anything else here." |
| 549 | ), |
| 550 | } |
| 551 | if alu_costs_in_stream && !alu_costs_in_shape { |
| 552 | println!( |
| 553 | " NOTE: the dequant is expensive inside a stream (A->C) but not inside the real\n \ |
| 554 | shape (F->G). That is consistent with the shape already being the bottleneck -\n \ |
| 555 | there is no throughput left for the arithmetic to take away." |
| 556 | ); |
| 557 | } |
| 558 | if depth_helps { |
| 559 | println!(" NOTE: deep prefetch beat the control by {:.2}x with light ALU.", ratio(d, a)); |
| 560 | } |
| 561 | println!(); |
| 562 | println!(" TWO ANCHORS, check both before trusting anything above:"); |
| 563 | println!(" A should match report_read_path's SSBO figure (~20 G715, ~28 G4)."); |
| 564 | println!(" G should match report_gemv_scaling's [65536, 1536] row (~3.4-4.0)."); |
| 565 | println!(" If either is off, the harness is not reproducing what it claims to."); |
| 566 | } |
| 567 | |
| 568 | fn ratio(from: f64, to: f64) -> f64 { |
| 569 | if to <= 0.0 { |
| 570 | return 0.0; |
| 571 | } |
| 572 | from / to |
| 573 | } |
| 574 | |
| 575 | fn binding(at: u32) -> vk::DescriptorSetLayoutBinding<'static> { |
| 576 | vk::DescriptorSetLayoutBinding::default() |
| 577 | .binding(at) |
| 578 | .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) |
| 579 | .descriptor_count(1) |
| 580 | .stage_flags(vk::ShaderStageFlags::COMPUTE) |
| 581 | } |
| 582 | |
| 583 | fn write_set( |
| 584 | context: &Arc<Context>, |
| 585 | set: vk::DescriptorSet, |
| 586 | source: &Buffer, |
| 587 | sink: &Buffer, |
| 588 | acts: &Buffer, |
| 589 | ) { |
| 590 | let infos = [ |
| 591 | vk::DescriptorBufferInfo { buffer: source.buffer, offset: 0, range: vk::WHOLE_SIZE }, |
| 592 | vk::DescriptorBufferInfo { buffer: sink.buffer, offset: 0, range: vk::WHOLE_SIZE }, |
| 593 | vk::DescriptorBufferInfo { buffer: acts.buffer, offset: 0, range: vk::WHOLE_SIZE }, |
| 594 | ]; |
| 595 | let writes: Vec<_> = infos |
| 596 | .iter() |
| 597 | .enumerate() |
| 598 | .map(|(at, info)| { |
| 599 | vk::WriteDescriptorSet::default() |
| 600 | .dst_set(set) |
| 601 | .dst_binding(at as u32) |
| 602 | .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) |
| 603 | .buffer_info(std::slice::from_ref(info)) |
| 604 | }) |
| 605 | .collect(); |
| 606 | // SAFETY: the set is live and nothing is in flight against it yet. |
| 607 | unsafe { context.device.update_descriptor_sets(&writes, &[]) }; |
| 608 | } |
| 609 | |
| 610 | /// Fill the activation buffer with ordinary finite fp16, through a staging copy. |
| 611 | fn upload_activations(context: &Arc<Context>, acts: &Buffer) -> Result<(), String> { |
| 612 | // 0.5, 1.0, 1.5 ... as fp16 bit patterns, cycling. Any finite spread does; what matters |
| 613 | // is that none of them is NaN, Inf or denormal. |
| 614 | let values: Vec<u16> = |
| 615 | (0..act_elems()).map(|i| f32_to_f16(0.5 + (i % 8) as f32 * 0.25)).collect(); |
| 616 | let mut bytes = Vec::with_capacity(values.len() * 2); |
| 617 | for value in &values { |
| 618 | bytes.extend_from_slice(&value.to_le_bytes()); |
| 619 | } |
| 620 | let staging = Buffer::staging(context, bytes.len() as vk::DeviceSize)?; |
| 621 | staging.write(&bytes)?; |
| 622 | one_shot(context, |device, cb| { |
| 623 | let region = vk::BufferCopy::default().size(bytes.len() as vk::DeviceSize); |
| 624 | // SAFETY: both buffers are live and the region is exactly the staging size. |
| 625 | unsafe { |
| 626 | device.cmd_copy_buffer(cb, staging.buffer, acts.buffer, std::slice::from_ref(®ion)) |
| 627 | }; |
| 628 | }) |
| 629 | } |
| 630 | |
| 631 | /// Round to fp16, for the handful of constants above. Round-to-nearest is not needed here. |
| 632 | fn f32_to_f16(value: f32) -> u16 { |
| 633 | let bits = value.to_bits(); |
| 634 | let sign = ((bits >> 16) & 0x8000) as u16; |
| 635 | let exponent = ((bits >> 23) & 0xFF) as i32 - 127 + 15; |
| 636 | let mantissa = ((bits >> 13) & 0x3FF) as u16; |
| 637 | if exponent <= 0 || exponent >= 31 { |
| 638 | return sign; |
| 639 | } |
| 640 | sign | ((exponent as u16) << 10) | mantissa |
| 641 | } |
| 642 | |
| 643 | /// Record, submit and wait for one throwaway command buffer. |
| 644 | fn one_shot( |
| 645 | context: &Arc<Context>, |
| 646 | record: impl FnOnce(&ash::Device, vk::CommandBuffer), |
| 647 | ) -> Result<(), String> { |
| 648 | let device = &context.device; |
| 649 | // SAFETY: every handle is created, used and destroyed inside this call, and the fence is |
| 650 | // waited on before anything is torn down. |
| 651 | unsafe { |
| 652 | let pool = device |
| 653 | .create_command_pool( |
| 654 | &vk::CommandPoolCreateInfo::default() |
| 655 | .queue_family_index(context.queue_family_index), |
| 656 | None, |
| 657 | ) |
| 658 | .map_err(|e| format!("one-shot pool: {e:?}"))?; |
| 659 | let cb = device |
| 660 | .allocate_command_buffers( |
| 661 | &vk::CommandBufferAllocateInfo::default() |
| 662 | .command_pool(pool) |
| 663 | .level(vk::CommandBufferLevel::PRIMARY) |
| 664 | .command_buffer_count(1), |
| 665 | ) |
| 666 | .map_err(|e| format!("one-shot buffer: {e:?}"))? |
| 667 | .first() |
| 668 | .copied() |
| 669 | .ok_or("allocate_command_buffers returned nothing")?; |
| 670 | device |
| 671 | .begin_command_buffer( |
| 672 | cb, |
| 673 | &vk::CommandBufferBeginInfo::default() |
| 674 | .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT), |
| 675 | ) |
| 676 | .map_err(|e| format!("one-shot begin: {e:?}"))?; |
| 677 | record(device, cb); |
| 678 | device.end_command_buffer(cb).map_err(|e| format!("one-shot end: {e:?}"))?; |
| 679 | let fence = device |
| 680 | .create_fence(&vk::FenceCreateInfo::default(), None) |
| 681 | .map_err(|e| format!("one-shot fence: {e:?}"))?; |
| 682 | let buffers = [cb]; |
| 683 | let submit = vk::SubmitInfo::default().command_buffers(&buffers); |
| 684 | let guard = context.lock_queue(); |
| 685 | let sent = device.queue_submit(context.queue, std::slice::from_ref(&submit), fence); |
| 686 | drop(guard); |
| 687 | sent.map_err(|e| format!("one-shot submit: {e:?}"))?; |
| 688 | device |
| 689 | .wait_for_fences(&[fence], true, 20_000_000_000) |
| 690 | .map_err(|e| format!("one-shot wait: {e:?}"))?; |
| 691 | device.destroy_fence(fence, None); |
| 692 | device.destroy_command_pool(pool, None); |
| 693 | } |
| 694 | Ok(()) |
| 695 | } |
| 696 | |
| 697 | struct Pipeline { |
| 698 | module: vk::ShaderModule, |
| 699 | pipeline: vk::Pipeline, |
| 700 | } |
| 701 | |
| 702 | impl Pipeline { |
| 703 | fn new( |
| 704 | context: &Arc<Context>, |
| 705 | layout: vk::PipelineLayout, |
| 706 | spirv: &[u8], |
| 707 | ) -> Result<Pipeline, String> { |
| 708 | if spirv.len() % (4) != 0 || spirv.len() < 20 { |
| 709 | return Err(format!( |
| 710 | "{} bytes is not a SPIR-V module - did the glslc step run? See analysis/gemv_probe/README.md", |
| 711 | spirv.len() |
| 712 | )); |
| 713 | } |
| 714 | let words: Vec<u32> = |
| 715 | spirv.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect(); |
| 716 | // SAFETY: both handles are destroyed by `destroy`, and the module outlives the |
| 717 | // pipeline creation that reads it. |
| 718 | unsafe { |
| 719 | let module = context |
| 720 | .device |
| 721 | .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words), None) |
| 722 | .map_err(|e| format!("shader module: {e:?}"))?; |
| 723 | let name = std::ffi::CString::new("main").map_err(|e| format!("{e}"))?; |
| 724 | let stage = vk::PipelineShaderStageCreateInfo::default() |
| 725 | .stage(vk::ShaderStageFlags::COMPUTE) |
| 726 | .module(module) |
| 727 | .name(&name); |
| 728 | let pipeline = context |
| 729 | .device |
| 730 | .create_compute_pipelines( |
| 731 | vk::PipelineCache::null(), |
| 732 | &[vk::ComputePipelineCreateInfo::default().stage(stage).layout(layout)], |
| 733 | None, |
| 734 | ) |
| 735 | .map_err(|(_, e)| format!("compute pipeline: {e:?}"))? |
| 736 | .first() |
| 737 | .copied() |
| 738 | .ok_or("create_compute_pipelines returned nothing")?; |
| 739 | Ok(Pipeline { module, pipeline }) |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | fn destroy(&self, context: &Arc<Context>) { |
| 744 | // SAFETY: called after the last fence wait, so nothing references either handle. |
| 745 | unsafe { |
| 746 | context.device.destroy_pipeline(self.pipeline, None); |
| 747 | context.device.destroy_shader_module(self.module, None); |
| 748 | } |
| 749 | } |
| 750 | } |
| 751 | |
| 752 | /// The Vulkan handles one timed pass binds, bundled so `time_pass` takes |
| 753 | /// the pass plus its two sizes. |
| 754 | struct Pass<'a> { |
| 755 | context: &'a Arc<Context>, |
| 756 | cb: vk::CommandBuffer, |
| 757 | fence: vk::Fence, |
| 758 | layout: vk::PipelineLayout, |
| 759 | set: vk::DescriptorSet, |
| 760 | pipeline: &'a Pipeline, |
| 761 | } |
| 762 | |
| 763 | /// Seconds for one pass. |
| 764 | fn time_pass(pass: Pass<'_>, quads: u32, groups: u32) -> Result<f64, String> { |
| 765 | let Pass { context, cb, fence, layout, set, pipeline } = pass; |
| 766 | let device = &context.device; |
| 767 | // `quads` for the streaming variants, `in_c` and `count` for the gemv-shaped ones. All |
| 768 | // three are pushed for every variant; a shader that does not declare a field ignores it. |
| 769 | // For F and G, `groups` **is** `count` — one workgroup per `ROWS` output channels. |
| 770 | let mut push = [0u8; 12]; |
| 771 | for (slot, value) in [quads, gemv_in(), groups].iter().enumerate() { |
| 772 | if let Some(dst) = push.get_mut(slot * 4..slot * 4 + 4) { |
| 773 | dst.copy_from_slice(&value.to_le_bytes()); |
| 774 | } |
| 775 | } |
| 776 | // SAFETY: the buffer is reset and re-recorded here and the fence is waited on before |
| 777 | // this returns, so nothing is ever in flight across two calls. |
| 778 | unsafe { |
| 779 | device |
| 780 | .begin_command_buffer(cb, &vk::CommandBufferBeginInfo::default()) |
| 781 | .map_err(|e| format!("begin: {e:?}"))?; |
| 782 | device.cmd_bind_pipeline(cb, vk::PipelineBindPoint::COMPUTE, pipeline.pipeline); |
| 783 | device.cmd_bind_descriptor_sets(cb, vk::PipelineBindPoint::COMPUTE, layout, 0, &[set], &[]); |
| 784 | device.cmd_push_constants(cb, layout, vk::ShaderStageFlags::COMPUTE, 0, &push); |
| 785 | device.cmd_dispatch(cb, groups, 1, 1); |
| 786 | device.end_command_buffer(cb).map_err(|e| format!("end: {e:?}"))?; |
| 787 | |
| 788 | let started = Instant::now(); |
| 789 | device.reset_fences(&[fence]).map_err(|e| format!("reset: {e:?}"))?; |
| 790 | let buffers = [cb]; |
| 791 | let submit = vk::SubmitInfo::default().command_buffers(&buffers); |
| 792 | let guard = context.lock_queue(); |
| 793 | let sent = device.queue_submit(context.queue, std::slice::from_ref(&submit), fence); |
| 794 | drop(guard); |
| 795 | sent.map_err(|e| format!("submit: {e:?}"))?; |
| 796 | device |
| 797 | .wait_for_fences(&[fence], true, 20_000_000_000) |
| 798 | .map_err(|e| format!("wait: {e:?}"))?; |
| 799 | Ok(started.elapsed().as_secs_f64()) |
| 800 | } |
| 801 | } |