From 41feb52ab59caf4eed52abe199ce2d739f7fadcd Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Tue, 29 Sep 2026 23:57:48 +0200 Subject: [PATCH] Starting faster radix --- shaders/radix_sort.slang | 238 ++++---------- shaders/radix_sort.spv | Bin 8908 -> 3732 bytes src/gpu/radix_sort.rs | 519 +++++------------------------- src/main.rs | 82 ++--- src/voxel_cache/request_buffer.rs | 2 +- 5 files changed, 185 insertions(+), 656 deletions(-) diff --git a/shaders/radix_sort.slang b/shaders/radix_sort.slang index 57f17c7..dfff66b 100644 --- a/shaders/radix_sort.slang +++ b/shaders/radix_sort.slang @@ -1,6 +1,15 @@ -const static uint32_t digit_count = 4; +const static uint32_t digit_count = 8; const static uint32_t value_count = 1 << digit_count; +// Thread count per work group +static const uint32_t WG_THREAD_COUNT = 256; + +// Elements managed per thread for histo build +static const uint32_t WE_HISTO_ELEMENTS = 16; + +// Elements managed per workgroup for histo build +static const uint32_t WG_HISTO_ELEMENT = WG_THREAD_COUNT * WE_HISTO_ELEMENTS; + struct Histogram { uint32_t[value_count] histogram; @@ -34,100 +43,59 @@ RWStructuredBuffer dest_key_buffer; [vk::binding(1, 2)] RWStructuredBuffer dest_value_buffer; +/* [vk::binding(0, 3)] RWStructuredBuffer sort_count; [vk::binding(1, 3)] RWStructuredBuffer block_count; +*/ [vk::push_constant] uniform PassParams params; -uint32_t get_digit(uint32_t value, uint32_t digit_id, uint32_t descending) +uint32_t extract_digit(uint32_t value, uint32_t digit_id, uint32_t descending) { let mask = ~(0xFFFFFFFF << digit_count); let digit = (value >> (digit_id * digit_count)) & mask; return select(descending != 0, digit ^ mask, digit); } -static const uint32_t split_size = 16; -static const uint32_t thread_count = 256; -static const uint32_t local_histo_count = thread_count / split_size; +groupshared Atomic local_histogram[value_count]; -struct LocalHistogram -{ - Atomic[value_count] histogram; -} - -groupshared LocalHistogram[local_histo_count] local_histograms; - -uint32_t histogram_index(uint32_t digit, uint32_t histo_index) -{ - return digit * params.digit_stride + histo_index; -} +// groupshared uint32_t local_histogram[value_count]; [shader("compute")] -[numthreads(256, 1, 1)] +[numthreads(WG_THREAD_COUNT, 1, 1)] void histogram_pass( uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID, uint32_t3 group_location: SV_GroupID, ) { + // First element managed by this thread in the data + uint32_t base_offset = group_location.x * WG_HISTO_ELEMENT + local_location.x; - let element_count = sort_count[0]; - // Reset histogram - let split_index = local_location.x / split_size; - for (uint32_t i = 0; i < value_count; i++) + // Zero out local_histogram + if (local_location.x < value_count) { - local_histograms[split_index].histogram[i].store(0); - } - if (location.x >= element_count) - { - - return; + local_histogram[local_location.x] = 0; } - GroupMemoryBarrierWithGroupSync(); // Sync histo reset + GroupMemoryBarrierWithGroupSync(); - var value = key_buffer[location.x]; - value = get_digit(value, params.pass_index, params.descending); - local_histograms[split_index].histogram[value].add(1); - - GroupMemoryBarrierWithGroupSync(); // Sync histo build - - // Aggregate all histograms and send to local memory - // Binary tree sum - /* - var amount = 2; - for (uint32_t d = local_histo_count / 2; d > 0; d >>= 1) + for (var load = 0; load < WE_HISTO_ELEMENTS; load++) { - if (local_location.x < d) - { - let a = location.x * amount; - let b = a + amount - 1; - - for (var v = 0; v < value_count; v++) - { - local_histograms[a * value_count + v].add(local_histograms[b * value_count + v].load()); - } - } - GroupMemoryBarrierWithGroupSync(); - amount >>= 1; + // This access pattern coaleces reads + uint32_t index = base_offset + load * WE_HISTO_ELEMENTS; + uint32_t key = key_buffer[index]; + uint32_t digit = extract_digit(key, params.pass_index, params.descending); + local_histogram[digit] += 1; + GroupMemoryBarrierWithGroupSync(); // useful ? } - */ - // thread 0 sends to local memory - if (local_location.x == 0) + + // Write histogram out + if (local_location.x < value_count) { - - for (uint32_t v = 0; v < value_count; v++) - { - var sum = 0; - for (uint32_t i = 0; i < local_histo_count; i++) - { - - sum += local_histograms[i].histogram[v].load(); - } - histograms[histogram_index(v, group_location.x)] = sum; - } + histograms[local_location.x + group_location.x * params.digit_stride] = local_histogram[local_location.x].load(); } } @@ -136,122 +104,60 @@ uint32_t div_ceil(uint32_t n, uint32_t q) return (n / q) + select(n % q == 0, 0, 1); } -groupshared uint32_t[16][16] block_sums; - -void scan_digit(uint32_t lid_digit, uint32_t lid_histo) -{ - let thread_block_size = div_ceil(block_count[0].x, 16); - var running_sum = 0; - for (uint32_t i = lid_histo * thread_block_size; i < min(thread_block_size * (lid_histo + 1), block_count[0].x); i++) - { - let current = histograms[histogram_index(lid_digit, i)]; - histograms[histogram_index(lid_digit, i)] = running_sum; - running_sum += current; - } - - if (lid_histo == 15) - { - histograms[histogram_index(lid_digit, block_count[0].x)] = running_sum; - } - block_sums[lid_digit][lid_histo] = running_sum; -} - -void apply_digit(uint32_t lid_digit, uint32_t lid_histo) -{ - let thread_block_size = div_ceil(block_count[0].x + 1, 16); - var running_sum = 0; - for (uint32_t i = lid_histo * thread_block_size; i < min(thread_block_size * (lid_histo + 1), block_count[0].x + 1); i++) - { - histograms[histogram_index(lid_digit, i)] += block_sums[lid_digit][lid_histo]; - } -} +groupshared uint32_t local_total_histogram[value_count]; [shader("compute")] -[numthreads(16, 16, 1)] -void running_sum_pass( +[numthreads(256, 1, 1)] +void prefix_sum_pass( uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID, uint32_t3 group_location: SV_GroupID, ) { - scan_digit(local_location.x, local_location.y); - - AllMemoryBarrierWithGroupSync(); - if (local_location.y == 0) + if (local_location.x < value_count) { - var running_sum = 0; - for (uint32_t i = 0; i < 16; i++) - { - let current = block_sums[local_location.x][i]; - block_sums[local_location.x][i] = running_sum; - running_sum += current; - } + return; } - AllMemoryBarrierWithGroupSync(); - apply_digit(local_location.x, local_location.y); - - AllMemoryBarrierWithGroupSync(); - - if (local_location.x == 0 && local_location.y == 0) + uint32_t running_sum = 0; + for (uint32_t i = local_location.x; i < params.digit_stride - 1; i += value_count) { - var running_sum = 0; - for (uint32_t i = 0; i < value_count; i++) - { - let current = histograms[histogram_index(i, block_count[0].x)]; - histograms[histogram_index(i, block_count[0].x)] = running_sum; - running_sum += current; - } + uint32_t current = histograms[i]; + histograms[i] = running_sum; + running_sum += current; } + + // Last histogram : into lds + local_total_histogram[local_location.x] = running_sum; + + GroupMemoryBarrierWithGroupSync(); + + // hillis-steel totaling + for (uint32_t offset = 1; offset < value_count; offset *= 2) + { + if (local_location.x >= offset) + { + local_total_histogram[local_location.x] += local_total_histogram[local_location.x - offset]; + } + GroupMemoryBarrierWithGroupSync(); + } + + // Save last histogram in memory + histograms[params.digit_stride - 1 + local_location.x] = local_total_histogram[local_location.x]; } -groupshared uint32_t[256] keys; -groupshared uint32_t[256] values; -groupshared uint32_t[256] digit; +static const uint32_t WE_SCATTER_ELEMENTS = 1; + +groupshared uint32_t scatter_keys[WG_THREAD_COUNT * WG_HISTO_ELEMENT]; +groupshared uint32_t scatter_values[WG_THREAD_COUNT * WG_HISTO_ELEMENT]; +groupshared uint32_t scatter_values[WG_THREAD_COUNT * WG_HISTO_ELEMENT]; [shader("compute")] -[numthreads(256, 1, 1)] +[numthreads(WG_THREAD_COUNT, 1, 1)] void scatter_pass( uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID, uint32_t3 group_location: SV_GroupID, ) { - - let element_count = sort_count[0]; - // Load kv - if (location.x >= element_count) - { - return; - } - - // Gather - keys[local_location.x] = key_buffer[location.x]; - values[local_location.x] = value_buffer[location.x]; - - // Compute digit - digit[local_location.x] = get_digit(keys[local_location.x], params.pass_index, params.descending); - - GroupMemoryBarrierWithGroupSync(); - - // Compute local offset - var local_offset = 0; - var local_digit = digit[local_location.x]; - for (uint32_t i = 0; i < local_location.x; i++) - { - - if (digit[i] == local_digit) - { - - local_offset += 1; - } - } - - // Scatter - // Compute global offset - let digit_offset = local_digit * (block_count[0].x + 1); - let global_loc = histograms[histogram_index(local_digit, block_count[0].x)] + histograms[histogram_index(local_digit, group_location.x)] + local_offset; - - dest_key_buffer[global_loc] = keys[local_location.x]; - dest_value_buffer[global_loc] = values[local_location.x]; } [shader("compute")] @@ -261,15 +167,5 @@ void indirect_count_pass( uint32_t3 local_location: SV_GroupThreadID, uint32_t3 group_location: SV_GroupID, ) { - - let indirect = params.pass_index; - if (indirect == 0) - { - sort_count[0] = key_buffer.getCount(); - } - let div_ceil = (sort_count[0] / 256) + select(sort_count[0] % 256 == 0, 0, 1); - block_count[0].x = div_ceil; - block_count[0].y = 1; - block_count[0].z = 1; } diff --git a/shaders/radix_sort.spv b/shaders/radix_sort.spv index 2705fd5b37cebacd601d27796e61e2f12ec8a55b..9e50c3f4921645376107705ae510025bf29242fd 100644 GIT binary patch literal 3732 zcmZ{m*>V(R6o4BhAuKApph8R}CIvSwDFuS8ngBJ%5ph!Er$SY zRsbWwT5`#+1m=r;s(q>6?IowMU4>5jwRmW|8t66~Wl2H(=;~Hhx;5z9omRWZn`ON@ z*XxvhlXXO}xAlO8w4mJFOUcc%l-wN3BZj!fALY`+#I)a;xn^UgzAy>oL)i_;sV~1& z*^MxT+Q)femU*Ld^PrvWyqjM zm_?RNGWE#@^Y5~=*1o;^8dIImxz$r4A-DEc-fia0uQRQEKbF0;+SBclP({0y>u)da zXTHiI@1HDN=$7kn4#r%NrETfE4tcXz6nUqtJe_CJ>vTx$0U)bo8<4euVK(Fq^ygX5 zmDf$RU&}`Hb5m2@yzJ*)>Yl7;soQa8|93aXsMR}Fe=8vGEy~}P_)TDC&O`m?>-bu= zM`w7PPTaR|M;}%8ei!45_&ea8-7)6i&cZ+T7yianrmZq-2$??0oP~9{pTRux=J9PL z!_DAv@@)Z2Z^maUcnmPU{4I$GVK-FGM43H|!8;Reoz?DSzYW@jZz9L`0r{wMjI}e* z?TOz8KL%}FWyT!`+uK;;ty^B3$YZa|2KWhRU+8y2JCoq=gkFh5)OW`Q3@vCTiIOO=%0Y+zagFyC1N(gT!+O-mLz?d!NCNLu>2&)LXOrvu=6oQ)i8#_f|r$zdCL9)1$XyY@fID zJJJ2UIfR9G@E~A4C$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ND`rdTwR+=bbpav>Q*mvi*+zoYL;^ LmfDrIr{50&+PRwD diff --git a/src/gpu/radix_sort.rs b/src/gpu/radix_sort.rs index e838343..84198b6 100644 --- a/src/gpu/radix_sort.rs +++ b/src/gpu/radix_sort.rs @@ -9,6 +9,7 @@ use wgpu::CommandEncoder; use wgpu::ComputePass; use wgpu::ComputePipeline; use wgpu::Device; +use wgpu::QuerySet; use wgpu::ShaderStages; use wgpu::include_spirv; use wgpu::util::DeviceExt; @@ -29,311 +30,14 @@ struct PassParameters digit_stride: u32, } -struct HistogramScanner -{ - // Used to perform the base case : dumb pass - direct_sum_pass: ComputePipeline, - slot_bind_group_layout: BindGroupLayout, - - // Recursive running - reduce_pass: ComputePipeline, - apply_pass: ComputePipeline, - compute_invocation_count: ComputePipeline, - - group_counts_storage: Buffer, - group_counts: Buffer, - group_counts_storage_bind_group: BindGroup, - buffers: Vec<(usize, Buffer, BindGroup)>, -} - -impl HistogramScanner -{ - const THREAD_COUNT: usize = 256; - const BLOCK_COUNT: usize = Self::THREAD_COUNT / 2; - const DIGIT_COUNT: usize = 4; - const VALUE_COUNT: usize = 1 << Self::DIGIT_COUNT; - - pub fn new(device: &Device, histogram_count: usize) -> Self - { - let mut buffers = vec![]; - - let mut pass_histogram_count = histogram_count; - - let indirect_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("HistogramScanner::indirect_count"), - usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, - contents: bytemuck::bytes_of(&wgpu::util::DispatchIndirectArgs { x: 1, y: 1, z: 1 }), - }); - - let slot_bind_group_layout = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("HistogramScanner::slot_bind_group_layout"), - entries: &[ - // Data buffer - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - }); - - println!("Creating histo buffer with {}", histogram_count); - while pass_histogram_count >= Self::BLOCK_COUNT - { - let block_count = pass_histogram_count.div_ceil(Self::BLOCK_COUNT); - println!("Creating block with {}", block_count); - let data_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("HistogramScanner::buffers (sum)"), - size: (block_count * size_of::() * Self::VALUE_COUNT) as u64, - usage: BufferUsages::STORAGE, - mapped_at_creation: false, - }); - let step_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("HistogramScanner::bind_group"), - layout: &slot_bind_group_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: data_buffer.as_entire_binding(), - }], - }); - buffers.push((pass_histogram_count, data_buffer, step_bind_group)); - - // Each reduced block becomes a histogram for the next pass - pass_histogram_count = block_count; - } - - println!("Using {} histogram reduce passes !", buffers.len()); - - let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("HistogramScanner::pipelines_layout"), - bind_group_layouts: &[ - // Count slot - Some(&slot_bind_group_layout), - // Reduced slot - Some(&slot_bind_group_layout), - ], - immediate_size: 0, // for the pass number - }); - - let radix_reduce_shader_module = - device.create_shader_module(include_spirv!("../../shaders/radix_reduce.spv")); - - let compilation_options = wgpu::PipelineCompilationOptions { - zero_initialize_workgroup_memory: false, - ..Default::default() - }; - - let reduce_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("HistogramScanner::reduce_pass"), - layout: Some(&pipelines_layout), - module: &radix_reduce_shader_module, - entry_point: Some("reduce_pass"), - compilation_options: compilation_options.clone(), - cache: None, - }); - - let apply_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("HistogramScanner::apply_pass"), - layout: Some(&pipelines_layout), - module: &radix_reduce_shader_module, - entry_point: Some("apply_pass"), - compilation_options: compilation_options.clone(), - cache: None, - }); - - let direct_sum_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("HistogramScanner::direct_sum_pass"), - layout: Some(&pipelines_layout), - module: &radix_reduce_shader_module, - entry_point: Some("direct_pass"), - compilation_options: compilation_options.clone(), - cache: None, - }); - - let compute_invocation_count = - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("HistogramScanner::compute_invocation_count"), - layout: Some(&pipelines_layout), - module: &radix_reduce_shader_module, - entry_point: Some("compute_invocation_count"), - compilation_options: compilation_options.clone(), - cache: None, - }); - - let group_counts = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("HistogramScanner::group_counts"), - size: (size_of::() * buffers.len().max(1)) as u64, - usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - - let group_counts_storage = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("HistogramScanner::group_counts_storage"), - size: (size_of::() * buffers.len().max(1)) as u64, - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - - let group_counts_storage_bind_group = - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("HistogramScanner::group_counts_storage_bind_group"), - layout: &slot_bind_group_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: group_counts_storage.as_entire_binding(), - }], - }); - - Self { - group_counts_storage, - group_counts, - group_counts_storage_bind_group, - reduce_pass, - slot_bind_group_layout, - direct_sum_pass, - apply_pass, - buffers, - compute_invocation_count, - } - } - - pub fn precompute_counts( - &self, - device: &Device, - count_buffer: &Buffer, - encoder: &mut CommandEncoder, - ) - { - // ~~ Compute invocation counts - let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("HistogramScanner::compute_group_count"), - timestamp_writes: None, - }); - let count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("HistogramScanner::bind_group"), - layout: &self.slot_bind_group_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - resource: count_buffer.as_entire_binding(), - }], - }); - - pass.set_bind_group(0, &count_bind_group, &[]); - pass.set_bind_group(1, &self.group_counts_storage_bind_group, &[]); - pass.set_pipeline(&self.compute_invocation_count); - pass.dispatch_workgroups(1, 1, 1); - drop(pass); - - encoder.copy_buffer_to_buffer( - &self.group_counts_storage, - 0, - &self.group_counts, - 0, - (self.buffers.len() * size_of::()) as u64, - ); - } - - pub fn sum( - &self, - device: &Device, - pass: &mut ComputePass, - data_buffer: &Buffer, - offset: u64, - size: u64, - ) - { - // ~~ Compute invocation counts - let out_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("HistogramScanner::bind_group"), - layout: &self.slot_bind_group_layout, - entries: &[wgpu::BindGroupEntry { - binding: 0, - //resource: data_buffer.as_entire_binding(), - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: data_buffer, - offset, - size: Some(NonZero::new(size).unwrap()), - }), - }], - }); - - let out_pass = (0usize, data_buffer.clone(), out_bind_group.clone()); - - let passes = std::iter::once(&out_pass) - .chain(self.buffers.iter()) - .collect::>(); - let pass_count = self.buffers.len(); - - for (i, (count, reduced)) in passes.iter().tuple_windows().enumerate() - { - // Reduce to destination - //pass.set_bind_group(0, &count.2, &[if i == 0 { offset as u32 } else { 0 }]); - pass.set_bind_group(0, &count.2, &[]); - pass.set_bind_group(1, &reduced.2, &[]); - pass.set_pipeline(&self.reduce_pass); - pass.dispatch_workgroups_indirect( - &self.group_counts, - (size_of::() * i) as u64, - ); - } - - if passes.len() == 1 - { - pass.set_bind_group(0, &out_bind_group, &[]); - pass.set_bind_group(1, &out_bind_group, &[]); - } - - // Last bindgroups are still bound - pass.set_pipeline(&self.direct_sum_pass); - pass.dispatch_workgroups(1, 1, 1); - - // Perform apply back up - for (i, (reduced, count)) in passes.iter().rev().tuple_windows().enumerate() - { - // pass.set_bind_group( - // 0, - // &count.2, - // &[ - // if i == pass_count - 1 - // { - // offset as u32 - // } - // else - // { - // 0 - // }, - // ], - // ); - pass.set_bind_group(0, &count.2, &[]); - pass.set_bind_group(1, &reduced.2, &[]); - pass.set_pipeline(&self.apply_pass); - pass.dispatch_workgroups_indirect( - &self.group_counts, - (size_of::() * (pass_count - 1 - i)) as u64, - ); - } - } -} - pub struct RadixSorter { max_size: usize, - block_count: usize, + histogram_count: usize, + histo_block_count: usize, + histograms: Buffer, histograms_bind_group: BindGroup, - digit_stride: u32, - - // For indirect dispatch - sort_count_buffer: Buffer, - group_count_buffer: Buffer, - counts_bind_group: BindGroup, - indirect_buffer: Buffer, data_bind_group_layout: BindGroupLayout, @@ -341,53 +45,51 @@ pub struct RadixSorter double_buffer_values: Buffer, double_buffer_bind_group: BindGroup, - histogram_reduce: HistogramScanner, histogram_pass: ComputePipeline, - running_sum_pass: ComputePipeline, - scatter_pass: ComputePipeline, - indirect_count_pass: ComputePipeline, + prefix_sum_pass: ComputePipeline, + + timing_query_set: QuerySet, + pub timing_buffer: Buffer, } impl RadixSorter { - const TOTAL_DIGIT_COUNT: usize = 32; - const THREAD_COUNT: usize = 256; - const DIGIT_COUNT: usize = 4; - const VALUE_COUNT: usize = 1 << Self::DIGIT_COUNT; - const PASS_COUNT: usize = Self::TOTAL_DIGIT_COUNT / Self::DIGIT_COUNT; + // How many total digits u32 => 32 + const TOTAL_BIN_DIGIT_COUNT: usize = 32; + + // The size of a digit sorted per pass + const DIGIT_SIZE: usize = 8; + + // The amounts of value for this digit size : base + const VALUE_COUNT: usize = 1 << Self::DIGIT_SIZE; + + // Numbers of passes for full sort + const PASS_COUNT: usize = Self::TOTAL_BIN_DIGIT_COUNT / Self::DIGIT_SIZE; + + // Thread count per work group + const WG_THREAD_COUNT: usize = 256; + + // Elements managed per thread for histo build + const WE_HISTO_ELEMENTS: usize = 16; + + // Elements managed per workgroup for histo build + const WG_HISTO_ELEMENTS: usize = Self::WG_THREAD_COUNT * Self::WE_HISTO_ELEMENTS; pub fn new(device: &Device, max_size: usize) -> Self { - let block_count = max_size.div_ceil(Self::THREAD_COUNT); - let histogram_count = block_count + 1; - let digit_stride = (histogram_count * size_of::()).next_multiple_of(256); - //let digit_stride = histogram_count * size_of::(); + // How many blocks (workgroups) for histobuild + let histo_block_count = max_size.div_ceil(Self::WG_HISTO_ELEMENTS); + + // Number of histograms to allocate + let histogram_count = histo_block_count + 1; let histograms = device.create_buffer(&wgpu::BufferDescriptor { label: Some("histograms_buffer"), - size: (digit_stride * Self::VALUE_COUNT) as u64, + size: (histogram_count * size_of::() * Self::VALUE_COUNT) as u64, usage: BufferUsages::STORAGE, mapped_at_creation: false, }); - let sort_count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("sort_count_buffer"), - contents: bytemuck::bytes_of(&0), - usage: BufferUsages::STORAGE, - }); - - let group_count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("group_count_buffer"), - contents: bytemuck::bytes_of(&wgpu::util::DispatchIndirectArgs { x: 1, y: 1, z: 1 }), - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - }); - - let indirect_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("indirect_buffer"), - contents: bytemuck::bytes_of(&wgpu::util::DispatchIndirectArgs { x: 0, y: 1, z: 1 }), - usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, - }); - let histograms_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("RadixSorter::histograms_bind_group_layout"), @@ -478,21 +180,6 @@ impl RadixSorter ], }); - let counts_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("RadixSorter::counts_bind_group"), - layout: &data_bind_group_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: sort_count_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: group_count_buffer.as_entire_binding(), - }, - ], - }); - let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("RadixSorter::pipelines_layout"), bind_group_layouts: &[ @@ -504,7 +191,7 @@ impl RadixSorter Some(&data_bind_group_layout), // (Two buffers same layout as histograms) // Sort count buffer, indirect buffer - Some(&data_bind_group_layout), + //Some(&data_bind_group_layout), ], immediate_size: size_of::() as u32, // for the pass number }); @@ -526,15 +213,16 @@ impl RadixSorter cache: None, }); - let running_sum_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("RadixSorter::running_sum_pass"), + let prefix_sum_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("RadixSorter::prefix_sum_pass"), layout: Some(&pipelines_layout), module: &radix_sort_shader_module, - entry_point: Some("running_sum_pass"), + entry_point: Some("prefix_sum_pass"), compilation_options: compilation_options.clone(), cache: None, }); + /* let scatter_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("RadixSorter::scatter_pass"), layout: Some(&pipelines_layout), @@ -553,18 +241,27 @@ impl RadixSorter compilation_options: compilation_options.clone(), cache: None, }); + */ + + let timing_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("RadixSorter::timing_buffer"), + size: (size_of::() * 2) as u64, + usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + + let timing_query_set = device.create_query_set(&wgpu::QuerySetDescriptor { + label: Some("RadixSorter::timing_query_set"), + ty: wgpu::QueryType::Timestamp, + count: 2, + }); RadixSorter { max_size, - block_count, + histo_block_count, + histogram_count, histograms, histograms_bind_group, - digit_stride: digit_stride as u32, - - sort_count_buffer, - group_count_buffer, - counts_bind_group, - indirect_buffer, data_bind_group_layout, @@ -572,11 +269,11 @@ impl RadixSorter double_buffer_values, double_buffer_bind_group, - histogram_reduce: HistogramScanner::new(device, histogram_count), histogram_pass, - running_sum_pass, - scatter_pass, - indirect_count_pass, + prefix_sum_pass, + + timing_buffer, + timing_query_set, } } @@ -585,11 +282,11 @@ impl RadixSorter device: &Device, keys: &Buffer, values: &Buffer, - indirect_count: Option<&Buffer>, encoder: &mut CommandEncoder, sort_direction: RadixSortDirection, ) { + dbg!(self.histogram_count); let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("RadixSorter::double_buffer_bind_group"), layout: &self.data_bind_group_layout, @@ -607,69 +304,17 @@ impl RadixSorter ], }); - let counts_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("RadixSorter::sort_count_bind_group"), - layout: &self.data_bind_group_layout, - entries: &[ - // Sort count - wgpu::BindGroupEntry { - binding: 0, - resource: indirect_count - .unwrap_or(&self.sort_count_buffer) - .as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: self.group_count_buffer.as_entire_binding(), - }, - ], - }); - let bg = [&data_buffer_bind_group, &self.double_buffer_bind_group]; - // Compute how many workgroups to dispatch - let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("RadixSorter::indirect_compute_pass"), - timestamp_writes: None, - }); - //compute_pass.set_bind_group(0, &hi, &[]); - compute_pass.set_pipeline(&self.indirect_count_pass); - compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); - compute_pass.set_bind_group(1, &data_buffer_bind_group, &[]); - compute_pass.set_bind_group(2, &self.double_buffer_bind_group, &[]); - compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); - compute_pass.set_immediates( - 0, - bytemuck::bytes_of(&PassParameters { - pass_index: if indirect_count.is_some() { 1u32 } else { 0 }, - descending: 0, - digit_stride: self.digit_stride / (size_of::() as u32), - }), - ); - compute_pass.dispatch_workgroups(1, 1, 1); - drop(compute_pass); - - // self.histogram_reduce.precompute_counts( - // device, - // indirect_count.unwrap_or(&self.sort_count_buffer), - // encoder, - // ); - - // Copy computed count over to indirect buffer - encoder.copy_buffer_to_buffer( - &self.group_count_buffer, - 0, - &self.indirect_buffer, - 0, - size_of::() as u64, - ); - let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("RadixSorter::compute_pass"), - timestamp_writes: None, + timestamp_writes: Some(wgpu::ComputePassTimestampWrites { + query_set: &self.timing_query_set, + beginning_of_pass_write_index: Some(0), + end_of_pass_write_index: Some(1), + }), }); compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); - compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); for i in 0..Self::PASS_COUNT { @@ -680,50 +325,30 @@ impl RadixSorter RadixSortDirection::Ascending => 0, RadixSortDirection::Descending => 1, }, - digit_stride: self.digit_stride / (size_of::() as u32), + digit_stride: self.histogram_count as u32, }; let bytes = bytemuck::bytes_of(¶meters); compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); compute_pass.set_bind_group(1, bg[i % 2], &[]); compute_pass.set_bind_group(2, bg[1 - (i % 2)], &[]); - compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); // ~~ Histogram pass compute_pass.set_pipeline(&self.histogram_pass); compute_pass.set_immediates(0, bytes); - compute_pass.dispatch_workgroups_indirect(&self.indirect_buffer, 0); + compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1); - /* - for digit in 0..Self::VALUE_COUNT - { - self.histogram_reduce.sum( - device, - &mut compute_pass, - &self.histograms, - (digit * self.digit_stride as usize) as u64, - self.digit_stride as u64, - ); - } - */ - - compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); - compute_pass.set_bind_group(1, bg[i % 2], &[]); - compute_pass.set_bind_group(2, bg[1 - (i % 2)], &[]); - compute_pass.set_bind_group(3, &counts_buffer_bind_group, &[]); - - // ~~ Running sum pass - compute_pass.set_pipeline(&self.running_sum_pass); + // ~~ Prefix sum pass + compute_pass.set_pipeline(&self.prefix_sum_pass); compute_pass.set_immediates(0, bytes); compute_pass.dispatch_workgroups(1, 1, 1); - // ~~ Scatter pass - compute_pass.set_pipeline(&self.scatter_pass); - compute_pass.set_immediates(0, bytes); - compute_pass.dispatch_workgroups_indirect(&self.indirect_buffer, 0); + //compute_pass.dispatch_workgroups_indirect(&self., 0); } // Even number of passes => data is in the user buffer drop(compute_pass); + + encoder.resolve_query_set(&self.timing_query_set, 0..2, &self.timing_buffer, 0); } } diff --git a/src/main.rs b/src/main.rs index 7a851ab..7b1ce0e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,7 @@ use glam::Mat4; use glam::Vec3; use glam::Vec4; use itertools::Itertools; +use rand::random; use rand::random_range; use rayon::iter::IndexedParallelIterator; use rayon::iter::IntoParallelRefIterator; @@ -196,20 +197,12 @@ impl State let mut encoder = device.create_command_encoder(&Default::default()); - /* + println!("Making elements"); let elt_count = 1_000_000u32; - //let elt_count = 1 << 20; - let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("count_buffer"), - contents: bytemuck::bytes_of(&elt_count), - usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - }); - //let elt_count = 1 << 20; - //let elt_count = 512; let org_big_value_buffer = (0..(elt_count as u32)).collect::>(); let org_big_key_buffer = org_big_value_buffer .iter() - .map(|_| random_range(0..2_000_000u32)) + .map(|_| random::()) .collect::>(); let sorted_values = org_big_key_buffer @@ -218,6 +211,7 @@ impl State .sorted_by_key(|(key, _)| *key) .map(|(_, val)| *val) .collect::>(); + println!("Upload data"); let big_key_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("big_key_buffer"), @@ -231,56 +225,70 @@ impl State usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, }); - let sorter = RadixSorter::new(&device, 1 << 20); + let sorter = RadixSorter::new(&device, elt_count as usize); //let sorter = RadixSorter::new(&device, 1_000_000); //let sorter = RadixSorter::new(&device, 512); + println!("Sorting"); sorter.sort( &device, &big_key_buffer, &big_value_buffer, - //Some(&count_buffer), - None, &mut encoder, radix_sort::RadixSortDirection::Ascending, ); queue.submit([encoder.finish()]); + let q = queue.get_timestamp_period(); wgpu::util::DownloadBuffer::read_buffer( &device, &queue, - &big_key_buffer.slice(..), - |clbk| { - let data_bytes = clbk.unwrap().to_vec(); - let data = data_bytes - .chunks(4) - .map(|x| u32::from_ne_bytes([x[0], x[1], x[2], x[3]])) - .collect::>(); - println!("{:?}", &data[0..512]); - }, - ); - - wgpu::util::DownloadBuffer::read_buffer( - &device, - &queue, - &big_value_buffer.slice(..), + &sorter.timing_buffer.slice(..), move |clbk| { let data_bytes = clbk.unwrap().to_vec(); let data = data_bytes - .chunks(4) - .map(|x| u32::from_ne_bytes([x[0], x[1], x[2], x[3]])) - .collect::>(); - for (gpu_key, key) in data.iter().zip(sorted_values.iter()) - { - assert_eq!(gpu_key, key, "FUCK YOU"); - } - println!("Finished check !"); + .chunks(8) + .map(|x| u64::from_ne_bytes([x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7]])) + .collect::>(); + let off = (data[1] - data[0]) as f32 * q / 1_000_000.; + println!("sort time {}ms", off); }, ); + // wgpu::util::DownloadBuffer::read_buffer( + // &device, + // &queue, + // &big_key_buffer.slice(..), + // |clbk| { + // let data_bytes = clbk.unwrap().to_vec(); + // let data = data_bytes + // .chunks(4) + // .map(|x| u32::from_ne_bytes([x[0], x[1], x[2], x[3]])) + // .collect::>(); + // println!("{:?}", &data[0..512]); + // }, + // ); + // + // wgpu::util::DownloadBuffer::read_buffer( + // &device, + // &queue, + // &big_value_buffer.slice(..), + // move |clbk| { + // let data_bytes = clbk.unwrap().to_vec(); + // let data = data_bytes + // .chunks(4) + // .map(|x| u32::from_ne_bytes([x[0], x[1], x[2], x[3]])) + // .collect::>(); + // for (gpu_key, key) in data.iter().zip(sorted_values.iter()) + // { + // assert_eq!(gpu_key, key, "FUCK YOU"); + // } + // println!("Finished check !"); + // }, + // ); + device.poll(wgpu::wgt::PollType::Poll); panic!(); - */ let size = window.inner_size(); diff --git a/src/voxel_cache/request_buffer.rs b/src/voxel_cache/request_buffer.rs index ac2dedd..0961ccf 100644 --- a/src/voxel_cache/request_buffer.rs +++ b/src/voxel_cache/request_buffer.rs @@ -286,7 +286,7 @@ where &self.device, &self.keys_buffer, &self.index_buffer, - Some(&self.request_count), + //Some(&self.request_count), encoder, radix_sort::RadixSortDirection::Descending, );