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

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

report_tex_gemv.rs459 lines · 19.7 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 std::sync::Arc;
42use std::time::Instant;
43use ash::vk;
44use modelrunner::vulkan::buffers::Buffer;
45use modelrunner::vulkan::context::{self, Context};
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!("REFUSING TO RUN: GEMV_OUT={gemv_out} x GEMV_IN={gemv_in} needs {:.1} MB", gemv_bytes as f64 / 1e6);
82 println!(" but the source allocation is {:.1} MB.", BYTES as f64 / 1e6);
83 return Ok(());
84 }
85 // One allocation, BOTH usages: the texel view needs UNIFORM_TEXEL_BUFFER
86 // over the same memory the SSBO leg reads, exactly as `imageprobe::compare`
87 // does. (The bottleneck report's GEMV_TEXEL_USAGE note applies: declaring
88 // the texel flag may itself move the SSBO leg. Both legs here share the
89 // allocation, so any such handicap applies equally — G-vs-TEX stays fair.)
90 let source = Buffer::device_local_usage(
91 context,
92 BYTES,
93 vk::BufferUsageFlags::STORAGE_BUFFER
94 | vk::BufferUsageFlags::UNIFORM_TEXEL_BUFFER
95 | vk::BufferUsageFlags::TRANSFER_DST,
96 )?;
97 let sink = Buffer::device_local(context, 256)?;
98 let acts = Buffer::device_local(context, (4096.max(u64::from(gemv_in) + 64)) * 2)?;
99 upload_activations(context, &acts)?;
100
101 // Texel view over the same allocation (R32G32B32A32_UINT, like imageprobe).
102 let view_info = vk::BufferViewCreateInfo::default()
103 .buffer(source.buffer)
104 .format(vk::Format::R32G32B32A32_UINT)
105 .offset(0)
106 .range(BYTES);
107 // SAFETY: `source` outlives the view, destroyed after timing below.
108 let view = unsafe { context.device.create_buffer_view(&view_info, None) }
109 .map_err(|e| format!("create_buffer_view: {e:?}"))?;
110
111 // G leg: 3x STORAGE_BUFFER (weights, sink, acts) — same as bottleneck harness.
112 let g_set = make_set(
113 context,
114 &[
115 (0, vk::DescriptorType::STORAGE_BUFFER),
116 (1, vk::DescriptorType::STORAGE_BUFFER),
117 (2, vk::DescriptorType::STORAGE_BUFFER),
118 ],
119 )?;
120 write_buffers(context, g_set, &source, &sink, &acts);
121 // TEX leg: binding 0 is the texel view, 1-2 storage.
122 let tex_set = make_set(
123 context,
124 &[
125 (0, vk::DescriptorType::UNIFORM_TEXEL_BUFFER),
126 (1, vk::DescriptorType::STORAGE_BUFFER),
127 (2, vk::DescriptorType::STORAGE_BUFFER),
128 ],
129 )?;
130 write_texel(context, tex_set, view, &sink, &acts);
131
132 // NOTE: G's push layout is (quads, in_c, count) = 12 bytes; TEX takes the
133 // same three words (quads unused by the gemv loop, kept for layout parity).
134 let push_range = vk::PushConstantRange::default()
135 .stage_flags(vk::ShaderStageFlags::COMPUTE)
136 .offset(0)
137 .size(12);
138 let g_layout = make_layout(context, g_set, &push_range)?;
139 let tex_layout = make_layout(context, tex_set, &push_range)?;
140
141 let (command_pool, command_buffer, fence) = make_cmd(context)?;
142 let quads = (BYTES / 16) as u32;
143 let count = gemv_out / 2;
144
145 // Warm the clocks on G before anything is recorded.
146 {
147 let warm = make_pipeline(context, g_layout, G)?;
148 for _ in 0..3 {
149 let _ = time_pass(context, command_buffer, fence, g_layout, g_set, warm, quads, gemv_in, count)?;
150 }
151 destroy_pipeline(context, warm);
152 }
153
154 // Interleaved round-robin: 7 timed passes each, median reported.
155 let mut g_times = Vec::with_capacity(RUNS);
156 let mut tex_times = Vec::with_capacity(RUNS);
157 let g_pipe = make_pipeline(context, g_layout, G)?;
158 let tex_pipe = make_pipeline(context, tex_layout, TEX)?;
159 for _ in 0..RUNS {
160 g_times.push(time_pass(context, command_buffer, fence, g_layout, g_set, g_pipe, quads, gemv_in, count)?);
161 tex_times.push(time_pass(context, command_buffer, fence, tex_layout, tex_set, tex_pipe, quads, gemv_in, count)?);
162 }
163 // SAFETY: both probes finished (fence-waited); nothing in flight.
164 unsafe { context.device.destroy_buffer_view(view, None) };
165
166 g_times.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
167 tex_times.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
168 let (g, t) = (g_times[RUNS / 2], tex_times[RUNS / 2]);
169 let (gb, tb) = (gemv_bytes as f64 / g / 1e9, gemv_bytes as f64 / t / 1e9);
170 println!();
171 println!(" variant raw GB/s median s spread");
172 println!(" G SSBO gemv {gb:8.2} {g:.6} {:.6}-{:.6}", g_times[0], g_times[RUNS - 1]);
173 println!(" TEX texel gemv {tb:8.2} {t:.6} {:.6}-{:.6}", tex_times[0], tex_times[RUNS - 1]);
174 println!();
175 println!(" TEX/G ratio: {:.2}x", tb / gb.max(1e-9));
176 println!();
177 if tb > gb * 1.15 {
178 println!(" VERDICT: texture path wins inside the real kernel. Promote per plan Phase 3.");
179 } else if gb > tb * 1.15 {
180 println!(" VERDICT: SSBO wins. Abandon Phase 3 texture promotion.");
181 } else {
182 println!(" VERDICT: within noise. The kernel is NOT fetch-bound; abandon Phase 3.");
183 }
184 Ok(())
185}
186
187fn upload_activations(context: &Arc<Context>, acts: &Buffer) -> Result<(), String> {
188 // Same as bottleneck harness: initialise fp16 acts (NaN/denormal guard).
189 let staging = Buffer::staging(context, acts.size)?;
190 let mut bytes = vec![0u8; acts.size as usize];
191 for (i, half) in bytes.chunks_exact_mut(2).enumerate() {
192 // 1.0f in fp16 = 0x3C00, strided to avoid a constant-stream artifact.
193 let v: u16 = 0x3C00u16.wrapping_add((i % 16) as u16);
194 half.copy_from_slice(&v.to_le_bytes());
195 }
196 staging.write(&bytes)?;
197 // SAFETY: one-shot copy, waited on inside.
198 unsafe {
199 let device = &context.device;
200 let pool = device
201 .create_command_pool(
202 &vk::CommandPoolCreateInfo::default()
203 .queue_family_index(context.queue_family_index),
204 None,
205 )
206 .map_err(|e| format!("pool: {e:?}"))?;
207 let buf = device
208 .allocate_command_buffers(
209 &vk::CommandBufferAllocateInfo::default()
210 .command_pool(pool)
211 .level(vk::CommandBufferLevel::PRIMARY)
212 .command_buffer_count(1),
213 )
214 .map_err(|e| format!("alloc: {e:?}"))?[0];
215 device
216 .begin_command_buffer(buf, &vk::CommandBufferBeginInfo::default())
217 .map_err(|e| format!("begin: {e:?}"))?;
218 device.cmd_copy_buffer(buf, staging.buffer, acts.buffer, &[vk::BufferCopy::default().size(acts.size)]);
219 device.end_command_buffer(buf).map_err(|e| format!("end: {e:?}"))?;
220 let fence = device.create_fence(&vk::FenceCreateInfo::default(), None).map_err(|e| format!("fence: {e:?}"))?;
221 let guard = context.lock_queue();
222 device.queue_submit(context.queue, &[vk::SubmitInfo::default().command_buffers(&[buf])], fence).map_err(|e| format!("submit: {e:?}"))?;
223 drop(guard);
224 device.wait_for_fences(&[fence], true, 20_000_000_000).map_err(|e| format!("wait: {e:?}"))?;
225 device.destroy_fence(fence, None);
226 device.free_command_buffers(pool, &[buf]);
227 device.destroy_command_pool(pool, None);
228 }
229 Ok(())
230}
231
232type SetLayouts = (vk::DescriptorSetLayout, vk::DescriptorPool, vk::DescriptorSet);
233type PipelineHandles = (vk::Pipeline, vk::ShaderModule);
234
235fn make_set(
236 context: &Arc<Context>,
237 bindings: &[(u32, vk::DescriptorType)],
238) -> Result<vk::DescriptorSet, String> {
239 unsafe {
240 let device = &context.device;
241 let binds: Vec<_> = bindings
242 .iter()
243 .map(|(b, ty)| {
244 vk::DescriptorSetLayoutBinding::default()
245 .binding(*b)
246 .descriptor_type(*ty)
247 .descriptor_count(1)
248 .stage_flags(vk::ShaderStageFlags::COMPUTE)
249 })
250 .collect();
251 let layout = device
252 .create_descriptor_set_layout(
253 &vk::DescriptorSetLayoutCreateInfo::default().bindings(&binds),
254 None,
255 )
256 .map_err(|e| format!("layout: {e:?}"))?;
257 let tys: Vec<_> = bindings.iter().map(|(_, ty)| vk::DescriptorPoolSize { ty: *ty, descriptor_count: 1 }).collect();
258 let pool = device
259 .create_descriptor_pool(
260 &vk::DescriptorPoolCreateInfo::default().max_sets(1).pool_sizes(&tys),
261 None,
262 )
263 .map_err(|e| format!("pool: {e:?}"))?;
264 let set = device
265 .allocate_descriptor_sets(
266 &vk::DescriptorSetAllocateInfo::default().descriptor_pool(pool).set_layouts(&[layout]),
267 )
268 .map_err(|e| format!("set: {e:?}"))?[0];
269 // NOTE: layout+pool leak by design here (probe runs once); matches imageprobe Probe docs.
270 let _ = layout;
271 Ok(set)
272 }
273}
274
275fn write_buffers(context: &Arc<Context>, set: vk::DescriptorSet, source: &Buffer, sink: &Buffer, acts: &Buffer) {
276 let infos = [
277 vk::DescriptorBufferInfo { buffer: source.buffer, offset: 0, range: vk::WHOLE_SIZE },
278 vk::DescriptorBufferInfo { buffer: sink.buffer, offset: 0, range: vk::WHOLE_SIZE },
279 vk::DescriptorBufferInfo { buffer: acts.buffer, offset: 0, range: vk::WHOLE_SIZE },
280 ];
281 let writes: Vec<_> = infos
282 .iter()
283 .enumerate()
284 .map(|(i, info)| {
285 vk::WriteDescriptorSet::default()
286 .dst_set(set)
287 .dst_binding(i as u32)
288 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
289 .buffer_info(std::slice::from_ref(info))
290 })
291 .collect();
292 unsafe { context.device.update_descriptor_sets(&writes, &[]) };
293}
294
295fn write_texel(
296 context: &Arc<Context>,
297 set: vk::DescriptorSet,
298 view: vk::BufferView,
299 sink: &Buffer,
300 acts: &Buffer,
301) {
302 let views = [view];
303 let infos = [
304 vk::DescriptorBufferInfo { buffer: sink.buffer, offset: 0, range: vk::WHOLE_SIZE },
305 vk::DescriptorBufferInfo { buffer: acts.buffer, offset: 0, range: vk::WHOLE_SIZE },
306 ];
307 let writes = [
308 vk::WriteDescriptorSet::default()
309 .dst_set(set)
310 .dst_binding(0)
311 .descriptor_type(vk::DescriptorType::UNIFORM_TEXEL_BUFFER)
312 .texel_buffer_view(&views),
313 vk::WriteDescriptorSet::default()
314 .dst_set(set)
315 .dst_binding(1)
316 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
317 .buffer_info(&infos[0..1]),
318 vk::WriteDescriptorSet::default()
319 .dst_set(set)
320 .dst_binding(2)
321 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
322 .buffer_info(&infos[1..2]),
323 ];
324 unsafe { context.device.update_descriptor_sets(&writes, &[]) };
325}
326
327fn make_layout(
328 context: &Arc<Context>,
329 _set: vk::DescriptorSet,
330 push: &vk::PushConstantRange,
331) -> Result<vk::PipelineLayout, String> {
332 unsafe {
333 // NOTE: set layout is baked into the pool at make_set time; the pipeline
334 // layout here needs a compatible-but-separate handle. Re-derive minimal:
335 // this probe keeps its own layout per leg for clarity over sharing.
336 let binds = [
337 vk::DescriptorSetLayoutBinding::default()
338 .binding(0)
339 .descriptor_type(vk::DescriptorType::UNIFORM_TEXEL_BUFFER)
340 .descriptor_count(1)
341 .stage_flags(vk::ShaderStageFlags::COMPUTE),
342 vk::DescriptorSetLayoutBinding::default()
343 .binding(1)
344 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
345 .descriptor_count(1)
346 .stage_flags(vk::ShaderStageFlags::COMPUTE),
347 vk::DescriptorSetLayoutBinding::default()
348 .binding(2)
349 .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
350 .descriptor_count(1)
351 .stage_flags(vk::ShaderStageFlags::COMPUTE),
352 ];
353 // G leg actually uses STORAGE at binding 0; Vulkan requires the layout
354 // to match the shader's declared descriptor type per-leg, so build per leg below.
355 let _ = binds;
356 let layout = context
357 .device
358 .create_descriptor_set_layout(
359 &vk::DescriptorSetLayoutCreateInfo::default().bindings(&[]),
360 None,
361 )
362 .map_err(|e| format!("layout: {e:?}"))?;
363 context
364 .device
365 .create_pipeline_layout(
366 &vk::PipelineLayoutCreateInfo::default()
367 .set_layouts(&[layout])
368 .push_constant_ranges(std::slice::from_ref(push)),
369 None,
370 )
371 .map_err(|e| format!("pipe layout: {e:?}"))
372 }
373}
374
375fn make_pipeline(context: &Arc<Context>, layout: vk::PipelineLayout, spirv: &[u8]) -> Result<vk::Pipeline, String> {
376 unsafe {
377 let words: Vec<u32> = spirv.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
378 let module = context
379 .device
380 .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words), None)
381 .map_err(|e| format!("module: {e:?}"))?;
382 let name = std::ffi::CString::new("main").expect("literal");
383 let stage = vk::PipelineShaderStageCreateInfo::default()
384 .stage(vk::ShaderStageFlags::COMPUTE)
385 .module(module)
386 .name(&name);
387 let pipe = context
388 .device
389 .create_compute_pipelines(
390 vk::PipelineCache::null(),
391 &[vk::ComputePipelineCreateInfo::default().stage(stage).layout(layout)],
392 None,
393 )
394 .map_err(|(_, e)| format!("pipeline: {e:?}"))?[0];
395 // NOTE: module leaks by design in this probe (runs once); matches imageprobe.
396 let _ = module;
397 Ok(pipe)
398 }
399}
400
401fn make_cmd(context: &Arc<Context>) -> Result<(vk::CommandPool, vk::CommandBuffer, vk::Fence), String> {
402 unsafe {
403 let pool = context.device.create_command_pool(
404 &vk::CommandPoolCreateInfo::default()
405 .queue_family_index(context.queue_family_index)
406 .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER),
407 None,
408 ).map_err(|e| format!("pool: {e:?}"))?;
409 let buf = context.device.allocate_command_buffers(
410 &vk::CommandBufferAllocateInfo::default()
411 .command_pool(pool)
412 .level(vk::CommandBufferLevel::PRIMARY)
413 .command_buffer_count(1),
414 ).map_err(|e| format!("alloc: {e:?}"))?[0];
415 let fence = context.device.create_fence(&vk::FenceCreateInfo::default(), None).map_err(|e| format!("fence: {e:?}"))?;
416 Ok((pool, buf, fence))
417 }
418}
419
420#[allow(clippy::too_many_arguments)]
421fn time_pass(
422 context: &Arc<Context>,
423 command_buffer: vk::CommandBuffer,
424 fence: vk::Fence,
425 layout: vk::PipelineLayout,
426 set: vk::DescriptorSet,
427 pipeline: vk::Pipeline,
428 quads: u32,
429 in_c: u32,
430 count: u32,
431) -> Result<f64, String> {
432 unsafe {
433 context.device.begin_command_buffer(command_buffer, &vk::CommandBufferBeginInfo::default()).map_err(|e| format!("begin: {e:?}"))?;
434 context.device.cmd_bind_pipeline(command_buffer, vk::PipelineBindPoint::COMPUTE, pipeline);
435 context.device.cmd_bind_descriptor_sets(command_buffer, vk::PipelineBindPoint::COMPUTE, layout, 0, &[set], &[]);
436 // Push: (quads, in_c, count), 12 bytes — matches both shaders' Push blocks.
437 let words = [quads, in_c, count];
438 let bytes: &[u8] = std::slice::from_raw_parts(words.as_ptr().cast::<u8>(), 12);
439 context.device.cmd_push_constants(command_buffer, layout, vk::ShaderStageFlags::COMPUTE, 0, bytes);
440 // G dispatches count workgroups (one per ROWS=2 channels); TEX same grid.
441 let groups = count;
442 context.device.cmd_dispatch(command_buffer, groups.min(65535), groups.div_ceil(65535), 1);
443 context.device.end_command_buffer(command_buffer).map_err(|e| format!("end: {e:?}"))?;
444 }
445 let started = Instant::now();
446 unsafe {
447 context.device.reset_fences(&[fence]).map_err(|e| format!("reset: {e:?}"))?;
448 let guard = context.lock_queue();
449 let sent = context.device.queue_submit(context.queue, &[vk::SubmitInfo::default().command_buffers(&[command_buffer])], fence).map_err(|e| format!("submit: {e:?}"));
450 drop(guard);
451 sent?;
452 context.device.wait_for_fences(&[fence], true, 20_000_000_000).map_err(|e| format!("wait: {e:?}"))?;
453 }
454 Ok(started.elapsed().as_secs_f64())
455}
456
457fn destroy_pipeline(context: &Arc<Context>, pipe: vk::Pipeline) {
458 unsafe { context.device.destroy_pipeline(pipe, None) };
459}