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

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

report_tex_gemv.rs565 lines · 20.9 KiBRaw
1//! Texture-path proof slice: does a GEMV-shaped kernel read weights faster
2//! through a texel-buffer view than through the SSBO load path?
3//!
4//! ```text
5//! cargo run --offline --release -p modelrunner --example report_tex_gemv
6//! ```
7//!
8//! # Why this exists beside `report_read_path` and `report_gemv_bottleneck`
9//!
10//! `report_read_path` (`imageprobe::compare`) answers the read-bandwidth
11//! question: texel-buffer view vs SSBO over the SAME 256 MB allocation, 1
12//! XOR/16 B. `report_gemv_bottleneck` answers the kernel-shape question:
13//! variants A-K decompose the int4 GEMV into stream/unpack/ALU/shape pieces.
14//!
15//! Neither answers the question Phase 3 needs: does the texture path help
16//! INSIDE the real kernel? The bottleneck report concluded the kernel is
17//! shape-bound on host (F->G: the ALU costs 1.55x inside the real shape, and
18//! the note says "there is no throughput left for the arithmetic to take
19//! away"). If the kernel is shape-bound, a faster fetch path changes nothing
20//! and Phase 3 (texture promotion) is abandoned without further work.
21//!
22//! This runs variant G (`gemv_g_shape_full`: K=1, ROWS 2, 64 lanes, int4
23//! unpack + activation fetch + FMA) twice: once via SSBO
24//! (`weights128[]`), once via `texelFetch(usamplerBuffer)` over a view of
25//! the same allocation (`gemv_tex_gemv.comp`, same arithmetic, same launch).
26//! G-vs-TEX is the texture-path value inside the real kernel, interleaved
27//! round-robin like the bottleneck report, with the same overhead guard.
28//!
29//! # Reading the result
30//!
31//! - TEX ~= G (within run-to-run spread): the kernel is NOT fetch-bound.
32//! Abandon Phase 3. The texture hypothesis is answered: no.
33//! - TEX > G by a statistically significant margin on P8: the promotion path
34//! (image-backed weights, binding 5, upload path) is real. Promote per the
35//! plan, then re-run this probe against the promoted path.
36//!
37//! Host note: on RTX 4080 both will sit near ~600 GB/s (see `report_read_path`
38//! on host: 603 vs 603 GB/s, 1.00x). The decision number comes from P8, not
39//! host. Host runs here only prove the probe RUNS (both paths sane, bit-parity
40//! on the sink fold).
41use ash::vk;
42use modelrunner::vulkan::buffers::Buffer;
43use modelrunner::vulkan::context::{self, Context};
44use std::sync::Arc;
45use std::time::Instant;
46
47const G: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_g_shape_full.comp.spv"));
48const TEX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gemv_tex_gemv.comp.spv"));
49
50/// Output channels: 65,536 so bytes match the `[65536, 1536]` scaling row.
51fn gemv_out() -> u32 {
52 std::env::var("GEMV_OUT").ok().and_then(|v| v.parse().ok()).unwrap_or(65_536)
53}
54
55/// Taps per channel: 1536 is the shape ~70% of decode bytes have.
56fn gemv_in() -> u32 {
57 std::env::var("GEMV_IN").ok().and_then(|v| v.parse().ok()).unwrap_or(1_536)
58}
59
60/// Bytes swept: matches `imageprobe::BYTES` so G is comparable to published figures.
61const BYTES: u64 = 256 * 1024 * 1024;
62
63/// Timed passes per variant, after a discarded warm pass. Odd, so the median is a sample.
64const RUNS: usize = 7;
65
66fn main() {
67 let context = match context::shared() {
68 Ok(context) => context,
69 Err(why) => return println!("no usable Vulkan device: {why}"),
70 };
71 if let Err(why) = run(&context) {
72 println!("probe failed: {why}");
73 }
74}
75
76fn run(context: &Arc<Context>) -> Result<(), String> {
77 let gemv_out = gemv_out();
78 let gemv_in = gemv_in();
79 let gemv_bytes: u64 = u64::from(gemv_out) * u64::from(gemv_in) / 2;
80 if gemv_bytes > BYTES {
81 println!(
82 "REFUSING TO RUN: GEMV_OUT={gemv_out} x GEMV_IN={gemv_in} needs {:.1} MB",
83 gemv_bytes as f64 / 1e6
84 );
85 println!(" but the source allocation is {:.1} MB.", BYTES as f64 / 1e6);
86 return Ok(());
87 }
88 // One allocation, BOTH usages: the texel view needs UNIFORM_TEXEL_BUFFER
89 // over the same memory the SSBO leg reads, exactly as `imageprobe::compare`
90 // does. (The bottleneck report's GEMV_TEXEL_USAGE note applies: declaring
91 // the texel flag may itself move the SSBO leg. Both legs here share the
92 // allocation, so any such handicap applies equally — G-vs-TEX stays fair.)
93 let source = Buffer::device_local_usage(
94 context,
95 BYTES,
96 vk::BufferUsageFlags::STORAGE_BUFFER
97 | vk::BufferUsageFlags::UNIFORM_TEXEL_BUFFER
98 | vk::BufferUsageFlags::TRANSFER_DST,
99 )?;
100 let sink = Buffer::device_local(context, 256)?;
101 let acts = Buffer::device_local(context, (4096.max(u64::from(gemv_in) + 64)) * 2)?;
102 upload_activations(context, &acts)?;
103
104 // Texel view over the same allocation (R32G32B32A32_UINT, like imageprobe).
105 let view_info = vk::BufferViewCreateInfo::default()
106 .buffer(source.buffer)
107 .format(vk::Format::R32G32B32A32_UINT)
108 .offset(0)
109 .range(BYTES);
110 // SAFETY: `source` outlives the view, destroyed after timing below.
111 let view = unsafe { context.device.create_buffer_view(&view_info, None) }
112 .map_err(|e| format!("create_buffer_view: {e:?}"))?;
113
114 // G leg: 3x STORAGE_BUFFER (weights, sink, acts) — same as bottleneck harness.
115 let g_set = make_set(
116 context,
117 &[
118 (0, vk::DescriptorType::STORAGE_BUFFER),
119 (1, vk::DescriptorType::STORAGE_BUFFER),
120 (2, vk::DescriptorType::STORAGE_BUFFER),
121 ],
122 )?;
123 write_buffers(context, g_set, &source, &sink, &acts);
124 // TEX leg: binding 0 is the texel view, 1-2 storage.
125 let tex_set = make_set(
126 context,
127 &[
128 (0, vk::DescriptorType::UNIFORM_TEXEL_BUFFER),
129 (1, vk::DescriptorType::STORAGE_BUFFER),
130 (2, vk::DescriptorType::STORAGE_BUFFER),
131 ],
132 )?;
133 write_texel(context, tex_set, view, &sink, &acts);
134
135 // NOTE: G's push layout is (quads, in_c, count) = 12 bytes; TEX takes the
136 // same three words (quads unused by the gemv loop, kept for layout parity).
137 let push_range = vk::PushConstantRange::default()
138 .stage_flags(vk::ShaderStageFlags::COMPUTE)
139 .offset(0)
140 .size(12);
141 let g_layout = make_layout(context, g_set, &push_range)?;
142 let tex_layout = make_layout(context, tex_set, &push_range)?;
143
144 let (_command_pool, command_buffer, fence) = make_cmd(context)?;
145 let quads = (BYTES / 16) as u32;
146 let count = gemv_out / 2;
147
148 // Warm the clocks on G before anything is recorded.
149 {
150 let warm = make_pipeline(context, g_layout, G)?;
151 for _ in 0..3 {
152 let _ = time_pass(
153 context,
154 command_buffer,
155 fence,
156 g_layout,
157 g_set,
158 warm,
159 quads,
160 gemv_in,
161 count,
162 )?;
163 }
164 destroy_pipeline(context, warm);
165 }
166
167 // Interleaved round-robin: 7 timed passes each, median reported.
168 let mut g_times = Vec::with_capacity(RUNS);
169 let mut tex_times = Vec::with_capacity(RUNS);
170 let g_pipe = make_pipeline(context, g_layout, G)?;
171 let tex_pipe = make_pipeline(context, tex_layout, TEX)?;
172 for _ in 0..RUNS {
173 g_times.push(time_pass(
174 context,
175 command_buffer,
176 fence,
177 g_layout,
178 g_set,
179 g_pipe,
180 quads,
181 gemv_in,
182 count,
183 )?);
184 tex_times.push(time_pass(
185 context,
186 command_buffer,
187 fence,
188 tex_layout,
189 tex_set,
190 tex_pipe,
191 quads,
192 gemv_in,
193 count,
194 )?);
195 }
196 // SAFETY: both probes finished (fence-waited); nothing in flight.
197 unsafe { context.device.destroy_buffer_view(view, None) };
198
199 g_times.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
200 tex_times.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
201 let (g, t) = (g_times[RUNS / 2], tex_times[RUNS / 2]);
202 let (gb, tb) = (gemv_bytes as f64 / g / 1e9, gemv_bytes as f64 / t / 1e9);
203 println!();
204 println!(" variant raw GB/s median s spread");
205 println!(
206 " G SSBO gemv {gb:8.2} {g:.6} {:.6}-{:.6}",
207 g_times[0],
208 g_times[RUNS - 1]
209 );
210 println!(
211 " TEX texel gemv {tb:8.2} {t:.6} {:.6}-{:.6}",
212 tex_times[0],
213 tex_times[RUNS - 1]
214 );
215 println!();
216 println!(" TEX/G ratio: {:.2}x", tb / gb.max(1e-9));
217 println!();
218 if tb > gb * 1.15 {
219 println!(" VERDICT: texture path wins inside the real kernel. Promote per plan Phase 3.");
220 } else if gb > tb * 1.15 {
221 println!(" VERDICT: SSBO wins. Abandon Phase 3 texture promotion.");
222 } else {
223 println!(" VERDICT: within noise. The kernel is NOT fetch-bound; abandon Phase 3.");
224 }
225 Ok(())
226}
227
228fn upload_activations(context: &Arc<Context>, acts: &Buffer) -> Result<(), String> {
229 // Same as bottleneck harness: initialise fp16 acts (NaN/denormal guard).
230 let staging = Buffer::staging(context, acts.size)?;
231 let mut bytes = vec![0u8; acts.size as usize];
232 for (i, half) in bytes.chunks_exact_mut(2).enumerate() {
233 // 1.0f in fp16 = 0x3C00, strided to avoid a constant-stream artifact.
234 let v: u16 = 0x3C00u16.wrapping_add((i % 16) as u16);
235 half.copy_from_slice(&v.to_le_bytes());
236 }
237 staging.write(&bytes)?;
238 // SAFETY: one-shot copy, waited on inside.
239 unsafe {
240 let device = &context.device;
241 let pool = device
242 .create_command_pool(
243 &vk::CommandPoolCreateInfo::default()
244 .queue_family_index(context.queue_family_index),
245 None,
246 )
247 .map_err(|e| format!("pool: {e:?}"))?;
248 let buf = device
249 .allocate_command_buffers(
250 &vk::CommandBufferAllocateInfo::default()
251 .command_pool(pool)
252 .level(vk::CommandBufferLevel::PRIMARY)
253 .command_buffer_count(1),
254 )
255 .map_err(|e| format!("alloc: {e:?}"))?[0];
256 device
257 .begin_command_buffer(buf, &vk::CommandBufferBeginInfo::default())
258 .map_err(|e| format!("begin: {e:?}"))?;
259 device.cmd_copy_buffer(
260 buf,
261 staging.buffer,
262 acts.buffer,
263 &[vk::BufferCopy::default().size(acts.size)],
264 );
265 device.end_command_buffer(buf).map_err(|e| format!("end: {e:?}"))?;
266 let fence = device
267 .create_fence(&vk::FenceCreateInfo::default(), None)
268 .map_err(|e| format!("fence: {e:?}"))?;
269 let guard = context.lock_queue();
270 device
271 .queue_submit(
272 context.queue,
273 &[vk::SubmitInfo::default().command_buffers(&[buf])],
274 fence,
275 )
276 .map_err(|e| format!("submit: {e:?}"))?;
277 drop(guard);
278 device
279 .wait_for_fences(&[fence], true, 20_000_000_000)
280 .map_err(|e| format!("wait: {e:?}"))?;
281 device.destroy_fence(fence, None);
282 device.free_command_buffers(pool, &[buf]);
283 device.destroy_command_pool(pool, None);
284 }
285 Ok(())
286}
287
288fn make_set(
289 context: &Arc<Context>,
290 bindings: &[(u32, vk::DescriptorType)],
291) -> Result<vk::DescriptorSet, String> {
292 unsafe {
293 let device = &context.device;
294 let binds: Vec<_> = bindings
295 .iter()
296 .map(|(b, ty)| {
297 vk::DescriptorSetLayoutBinding::default()
298 .binding(*b)
299 .descriptor_type(*ty)
300 .descriptor_count(1)
301 .stage_flags(vk::ShaderStageFlags::COMPUTE)
302 })
303 .collect();
304 let layout = device
305 .create_descriptor_set_layout(
306 &vk::DescriptorSetLayoutCreateInfo::default().bindings(&binds),
307 None,
308 )
309 .map_err(|e| format!("layout: {e:?}"))?;
310 let tys: Vec<_> = bindings
311 .iter()
312 .map(|(_, ty)| vk::DescriptorPoolSize { ty: *ty, descriptor_count: 1 })
313 .collect();
314 let pool = device
315 .create_descriptor_pool(
316 &vk::DescriptorPoolCreateInfo::default().max_sets(1).pool_sizes(&tys),
317 None,
318 )
319 .map_err(|e| format!("pool: {e:?}"))?;
320 let set = device
321 .allocate_descriptor_sets(
322 &vk::DescriptorSetAllocateInfo::default()
323 .descriptor_pool(pool)
324 .set_layouts(&[layout]),
325 )
326 .map_err(|e| format!("set: {e:?}"))?[0];
327 // NOTE: layout+pool leak by design here (probe runs once); matches imageprobe Probe docs.
328 let _ = layout;
329 Ok(set)
330 }
331}
332
333fn write_buffers(
334 context: &Arc<Context>,
335 set: vk::DescriptorSet,
336 source: &Buffer,
337 sink: &Buffer,
338 acts: &Buffer,
339) {
340 let infos = [
341 vk::DescriptorBufferInfo { buffer: source.buffer, offset: 0, range: vk::WHOLE_SIZE },
342 vk::DescriptorBufferInfo { buffer: sink.buffer, offset: 0, range: vk::WHOLE_SIZE },
343 vk::DescriptorBufferInfo { buffer: acts.buffer, offset: 0, range: vk::WHOLE_SIZE },
344 ];
345 let writes: Vec<_> = infos
346 .iter()
347 .enumerate()
348 .map(|(i, info)| {
349 vk::WriteDescriptorSet::default()
350 .dst_set(set)
351 .dst_binding(i as u32)
352 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
353 .buffer_info(std::slice::from_ref(info))
354 })
355 .collect();
356 unsafe { context.device.update_descriptor_sets(&writes, &[]) };
357}
358
359fn write_texel(
360 context: &Arc<Context>,
361 set: vk::DescriptorSet,
362 view: vk::BufferView,
363 sink: &Buffer,
364 acts: &Buffer,
365) {
366 let views = [view];
367 let infos = [
368 vk::DescriptorBufferInfo { buffer: sink.buffer, offset: 0, range: vk::WHOLE_SIZE },
369 vk::DescriptorBufferInfo { buffer: acts.buffer, offset: 0, range: vk::WHOLE_SIZE },
370 ];
371 let writes = [
372 vk::WriteDescriptorSet::default()
373 .dst_set(set)
374 .dst_binding(0)
375 .descriptor_type(vk::DescriptorType::UNIFORM_TEXEL_BUFFER)
376 .texel_buffer_view(&views),
377 vk::WriteDescriptorSet::default()
378 .dst_set(set)
379 .dst_binding(1)
380 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
381 .buffer_info(&infos[0..1]),
382 vk::WriteDescriptorSet::default()
383 .dst_set(set)
384 .dst_binding(2)
385 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
386 .buffer_info(&infos[1..2]),
387 ];
388 unsafe { context.device.update_descriptor_sets(&writes, &[]) };
389}
390
391fn make_layout(
392 context: &Arc<Context>,
393 _set: vk::DescriptorSet,
394 push: &vk::PushConstantRange,
395) -> Result<vk::PipelineLayout, String> {
396 unsafe {
397 // NOTE: set layout is baked into the pool at make_set time; the pipeline
398 // layout here needs a compatible-but-separate handle. Re-derive minimal:
399 // this probe keeps its own layout per leg for clarity over sharing.
400 let binds = [
401 vk::DescriptorSetLayoutBinding::default()
402 .binding(0)
403 .descriptor_type(vk::DescriptorType::UNIFORM_TEXEL_BUFFER)
404 .descriptor_count(1)
405 .stage_flags(vk::ShaderStageFlags::COMPUTE),
406 vk::DescriptorSetLayoutBinding::default()
407 .binding(1)
408 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
409 .descriptor_count(1)
410 .stage_flags(vk::ShaderStageFlags::COMPUTE),
411 vk::DescriptorSetLayoutBinding::default()
412 .binding(2)
413 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
414 .descriptor_count(1)
415 .stage_flags(vk::ShaderStageFlags::COMPUTE),
416 ];
417 // G leg actually uses STORAGE at binding 0; Vulkan requires the layout
418 // to match the shader's declared descriptor type per-leg, so build per leg below.
419 let _ = binds;
420 let layout = context
421 .device
422 .create_descriptor_set_layout(
423 &vk::DescriptorSetLayoutCreateInfo::default().bindings(&[]),
424 None,
425 )
426 .map_err(|e| format!("layout: {e:?}"))?;
427 context
428 .device
429 .create_pipeline_layout(
430 &vk::PipelineLayoutCreateInfo::default()
431 .set_layouts(&[layout])
432 .push_constant_ranges(std::slice::from_ref(push)),
433 None,
434 )
435 .map_err(|e| format!("pipe layout: {e:?}"))
436 }
437}
438
439fn make_pipeline(
440 context: &Arc<Context>,
441 layout: vk::PipelineLayout,
442 spirv: &[u8],
443) -> Result<vk::Pipeline, String> {
444 unsafe {
445 let words: Vec<u32> =
446 spirv.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
447 let module = context
448 .device
449 .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words), None)
450 .map_err(|e| format!("module: {e:?}"))?;
451 let name = std::ffi::CString::new("main").expect("literal");
452 let stage = vk::PipelineShaderStageCreateInfo::default()
453 .stage(vk::ShaderStageFlags::COMPUTE)
454 .module(module)
455 .name(&name);
456 let pipe = context
457 .device
458 .create_compute_pipelines(
459 vk::PipelineCache::null(),
460 &[vk::ComputePipelineCreateInfo::default().stage(stage).layout(layout)],
461 None,
462 )
463 .map_err(|(_, e)| format!("pipeline: {e:?}"))?[0];
464 // NOTE: module leaks by design in this probe (runs once); matches imageprobe.
465 let _ = module;
466 Ok(pipe)
467 }
468}
469
470fn make_cmd(
471 context: &Arc<Context>,
472) -> Result<(vk::CommandPool, vk::CommandBuffer, vk::Fence), String> {
473 unsafe {
474 let pool = context
475 .device
476 .create_command_pool(
477 &vk::CommandPoolCreateInfo::default()
478 .queue_family_index(context.queue_family_index)
479 .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER),
480 None,
481 )
482 .map_err(|e| format!("pool: {e:?}"))?;
483 let buf = context
484 .device
485 .allocate_command_buffers(
486 &vk::CommandBufferAllocateInfo::default()
487 .command_pool(pool)
488 .level(vk::CommandBufferLevel::PRIMARY)
489 .command_buffer_count(1),
490 )
491 .map_err(|e| format!("alloc: {e:?}"))?[0];
492 let fence = context
493 .device
494 .create_fence(&vk::FenceCreateInfo::default(), None)
495 .map_err(|e| format!("fence: {e:?}"))?;
496 Ok((pool, buf, fence))
497 }
498}
499
500#[allow(clippy::too_many_arguments)]
501fn time_pass(
502 context: &Arc<Context>,
503 command_buffer: vk::CommandBuffer,
504 fence: vk::Fence,
505 layout: vk::PipelineLayout,
506 set: vk::DescriptorSet,
507 pipeline: vk::Pipeline,
508 quads: u32,
509 in_c: u32,
510 count: u32,
511) -> Result<f64, String> {
512 unsafe {
513 context
514 .device
515 .begin_command_buffer(command_buffer, &vk::CommandBufferBeginInfo::default())
516 .map_err(|e| format!("begin: {e:?}"))?;
517 context.device.cmd_bind_pipeline(command_buffer, vk::PipelineBindPoint::COMPUTE, pipeline);
518 context.device.cmd_bind_descriptor_sets(
519 command_buffer,
520 vk::PipelineBindPoint::COMPUTE,
521 layout,
522 0,
523 &[set],
524 &[],
525 );
526 // Push: (quads, in_c, count), 12 bytes — matches both shaders' Push blocks.
527 let words = [quads, in_c, count];
528 let bytes: &[u8] = std::slice::from_raw_parts(words.as_ptr().cast::<u8>(), 12);
529 context.device.cmd_push_constants(
530 command_buffer,
531 layout,
532 vk::ShaderStageFlags::COMPUTE,
533 0,
534 bytes,
535 );
536 // G dispatches count workgroups (one per ROWS=2 channels); TEX same grid.
537 let groups = count;
538 context.device.cmd_dispatch(command_buffer, groups.min(65535), groups.div_ceil(65535), 1);
539 context.device.end_command_buffer(command_buffer).map_err(|e| format!("end: {e:?}"))?;
540 }
541 let started = Instant::now();
542 unsafe {
543 context.device.reset_fences(&[fence]).map_err(|e| format!("reset: {e:?}"))?;
544 let guard = context.lock_queue();
545 let sent = context
546 .device
547 .queue_submit(
548 context.queue,
549 &[vk::SubmitInfo::default().command_buffers(&[command_buffer])],
550 fence,
551 )
552 .map_err(|e| format!("submit: {e:?}"));
553 drop(guard);
554 sent?;
555 context
556 .device
557 .wait_for_fences(&[fence], true, 20_000_000_000)
558 .map_err(|e| format!("wait: {e:?}"))?;
559 }
560 Ok(started.elapsed().as_secs_f64())
561}
562
563fn destroy_pipeline(context: &Arc<Context>, pipe: vk::Pipeline) {
564 unsafe { context.device.destroy_pipeline(pipe, None) };
565}