From 7dfcfe56e9f333f90c5721f6eadd9bda63437b2b Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Thu, 1 Oct 2026 22:55:04 +0200 Subject: [PATCH] Fixing fast radix --- shaders/radix_sort.slang | 184 ++++++++++++++++++++++++++------------- shaders/radix_sort.spv | Bin 3732 -> 6884 bytes src/gpu/radix_sort.rs | 42 +++++---- src/main.rs | 68 ++++++++------- 4 files changed, 184 insertions(+), 110 deletions(-) diff --git a/shaders/radix_sort.slang b/shaders/radix_sort.slang index dfff66b..33634ed 100644 --- a/shaders/radix_sort.slang +++ b/shaders/radix_sort.slang @@ -5,16 +5,11 @@ const static uint32_t value_count = 1 << digit_count; static const uint32_t WG_THREAD_COUNT = 256; // Elements managed per thread for histo build -static const uint32_t WE_HISTO_ELEMENTS = 16; +static const uint32_t WE_HISTO_ELEMENTS = 1; // 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; -} - struct IndirectArgs { uint32_t x; @@ -26,7 +21,7 @@ struct PassParams { uint32_t pass_index; uint32_t descending; - uint32_t digit_stride; + uint32_t histogram_count; } [vk::binding(0, 0)] @@ -43,13 +38,6 @@ 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; @@ -71,10 +59,6 @@ void histogram_pass( 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; - - // Zero out local_histogram if (local_location.x < value_count) { local_histogram[local_location.x] = 0; @@ -82,20 +66,22 @@ void histogram_pass( GroupMemoryBarrierWithGroupSync(); - for (var load = 0; load < WE_HISTO_ELEMENTS; load++) + // This coalesces read + for (uint32_t index = group_location.x * WG_HISTO_ELEMENT + local_location.x; + index < min(key_buffer.getCount(), (group_location.x + 1) * WG_HISTO_ELEMENT); + index += WG_THREAD_COUNT) { - // 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 ? + local_histogram[digit].add(1); } - // Write histogram out + GroupMemoryBarrierWithGroupSync(); + if (local_location.x < value_count) { - histograms[local_location.x + group_location.x * params.digit_stride] = local_histogram[local_location.x].load(); + // histograms[local_location.x + group_location.x * value_count] = local_histogram[local_location.x].load(); + histograms[local_location.x * params.histogram_count + group_location.x] = local_histogram[local_location.x].load(); } } @@ -104,52 +90,95 @@ uint32_t div_ceil(uint32_t n, uint32_t q) return (n / q) + select(n % q == 0, 0, 1); } -groupshared uint32_t local_total_histogram[value_count]; +// groupshared uint32_t local_total_histogram[value_count]; +groupshared uint32_t local_prefix[WG_THREAD_COUNT]; [shader("compute")] -[numthreads(256, 1, 1)] +[numthreads(WG_THREAD_COUNT, 1, 1)] void prefix_sum_pass( uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID, uint32_t3 group_location: SV_GroupID, ) { - if (local_location.x < value_count) + // value_count is the number of possible values for a digit + uint32_t value = group_location.x; + uint32_t value_offset = value * params.histogram_count; + uint32_t running_prefix = 0; + + uint32_t start_offset = group_location.x * params.histogram_count; + uint32_t end_offset = start_offset + params.histogram_count; + + for ( + uint32_t slice_offset = start_offset; + slice_offset < end_offset; + slice_offset += WG_THREAD_COUNT) + { + uint32_t index = slice_offset + local_location.x; + // Load data into lds + if (index < end_offset - 1) + { + local_prefix[local_location.x] = histograms[index]; + } + else + { + local_prefix[local_location.x] = 0; + } + GroupMemoryBarrierWithGroupSync(); + + // Perform hillis steele + + for (uint32_t offset = 1; offset < WG_THREAD_COUNT; offset *= 2) + { + uint32_t offset_value = select(local_location.x >= offset, local_prefix[local_location.x - offset], 0); + GroupMemoryBarrierWithGroupSync(); + local_prefix[local_location.x] += offset_value; + GroupMemoryBarrierWithGroupSync(); + } + + // Accumulate runnig_prefix + + GroupMemoryBarrierWithGroupSync(); + if (index < end_offset) + { + histograms[index] = select(local_location.x == 0, 0, local_prefix[local_location.x - 1]) + running_prefix; + } + running_prefix += local_prefix[WG_THREAD_COUNT - 1]; + GroupMemoryBarrierWithGroupSync(); + } +} + +[shader("compute")] +[numthreads(WG_THREAD_COUNT, 1, 1)] +void total_prefix_sum_pass( + uint32_t3 location: SV_DispatchThreadID, + uint32_t3 local_location: SV_GroupThreadID, + uint32_t3 group_location: SV_GroupID, ) +{ + if (local_location.x >= value_count) { return; } - uint32_t running_sum = 0; - for (uint32_t i = local_location.x; i < params.digit_stride - 1; i += value_count) - { - uint32_t current = histograms[i]; - histograms[i] = running_sum; - running_sum += current; - } - - // Last histogram : into lds - local_total_histogram[local_location.x] = running_sum; - + // Load last histogram into lds + local_prefix[local_location.x] = histograms[(params.histogram_count - 1) + params.histogram_count * local_location.x]; GroupMemoryBarrierWithGroupSync(); - - // hillis-steel totaling - for (uint32_t offset = 1; offset < value_count; offset *= 2) + // Perform hillis steele + for (uint32_t offset = 1; offset < WG_THREAD_COUNT; offset *= 2) { - if (local_location.x >= offset) - { - local_total_histogram[local_location.x] += local_total_histogram[local_location.x - offset]; - } + uint32_t offset_value = select(local_location.x >= offset, local_prefix[local_location.x - offset], 0); + GroupMemoryBarrierWithGroupSync(); + local_prefix[local_location.x] += offset_value; GroupMemoryBarrierWithGroupSync(); } - // Save last histogram in memory - histograms[params.digit_stride - 1 + local_location.x] = local_total_histogram[local_location.x]; + histograms[(params.histogram_count - 1) + params.histogram_count * local_location.x] = + select(local_location.x == 0, 0, local_prefix[local_location.x - 1]); } -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]; +groupshared uint32_t keys[WG_THREAD_COUNT]; +groupshared uint32_t values[WG_THREAD_COUNT]; +groupshared uint32_t sub_radix[WG_THREAD_COUNT]; +groupshared uint32_t digits[WG_THREAD_COUNT]; [shader("compute")] [numthreads(WG_THREAD_COUNT, 1, 1)] @@ -158,14 +187,45 @@ void scatter_pass( uint32_t3 local_location: SV_GroupThreadID, uint32_t3 group_location: SV_GroupID, ) { -} - -[shader("compute")] -[numthreads(1, 1, 1)] -void indirect_count_pass( - uint32_t3 location: SV_DispatchThreadID, - uint32_t3 local_location: SV_GroupThreadID, - uint32_t3 group_location: SV_GroupID, ) -{ + uint32_t batch_index = 0; + + // Load up a batch of values + keys[local_location.x] = key_buffer[batch_index * WG_THREAD_COUNT + local_location.x]; + values[local_location.x] = value_buffer[batch_index * WG_THREAD_COUNT + local_location.x]; + digits[local_location.x] = extract_digit(keys[local_location.x], params.pass_index, params.descending); + + // Split radix sort on the batch + for (uint32_t split_index = 0; split_index < digit_count; split_index++) + { + // Set subradix value + sub_radix[local_location.x] = select(((digits[local_location.x] >> split_index) & 1) != 0, 1 << 16, 1); + GroupMemoryBarrierWithGroupSync(); + + for (uint32_t offset = 1; offset < WG_THREAD_COUNT; offset *= 2) + { + uint32_t offset_value = select(local_location.x >= offset, sub_radix[local_location.x - offset], 0); + GroupMemoryBarrierWithGroupSync(); + sub_radix[local_location.x] += offset_value; + GroupMemoryBarrierWithGroupSync(); + } + + // Now radix is ready, scatter split + uint32_t key = keys[local_location.x]; + uint32_t value = values[local_location.x]; + uint32_t digit = digits[local_location.x]; + uint32_t prefix = sub_radix[local_location.x]; + uint32_t destination = select(((digit >> split_index) & 1) != 0, prefix >> 16, prefix & 0xFFFF); + + GroupMemoryBarrierWithGroupSync(); + + // Scatter + keys[destination] = key; + values[destination] = value; + digits[destination] = digit; + + GroupMemoryBarrierWithGroupSync(); + } + + // Now values are sorted according to digit } diff --git a/shaders/radix_sort.spv b/shaders/radix_sort.spv index 9e50c3f4921645376107705ae510025bf29242fd..271d306c28e3cac0dc6a3f918962a7aa6cff0d84 100644 GIT binary patch literal 6884 zcmZ{o2bf(|5yx+`HFXn~7)lZrf(lEFg#;rZksz8VQA46&f4uCzUDj-N*H=NBKBU03ijS>6l~ZF)z43Vzx&R-+`V5s`6lx}|2b#QoS8Xyv+0_U9XPUD!W@_W3_r`Ix<;pG~BZw>&^FU-M(x4 z+D3D9?Yi~%l3$#4sdC#uwkYcX&qdCkz~gwmy0u9YpQkxo`m>QSw%h%8DgOTahR5Oply3XWh z7(;iqoOyD|+*=p=hwhV^?WZdjdxYY@9guA z>G1mP&wJqi_jflhEw5$%HqD`Zn_nR1%O1|>oocu9VqcF=j88Q4b=}!e%+colSaiGJ z>eZ<|?K>U^H(sA^&6MuAI`+=uyR+lvYmHQk-n_@1R|?H%5Bs)qz7(i=I@DX;$~}FD zz7Ol;+;50;>*)NhX#2-r-%5Y`PVAj++)eB-Zink#=barf_rCVD^Shyo{(J}FFWyA> z^9(un%IP~e_sAKqe)U;A*SY69v=5@amwo5ldb&R1a$bzn??};~bM2n%esf*i?>y{- zth#${@8YLKmg8mYIT1XBIF>UXM$2^}L(ES?&q3r5$HyAA;Xtx)%xA(SdEe>(b{g}@~>;vbgrnzgv=SDE0bYeRVY+ppIo524~ zb7R-U0-4MPTGuHyYclP#^_wTy%%=<`K>JavlqjkcE3Gg zcfPnV*Pp#v^yfDx)@xr{usgRGU4IIZ*@xcMVK3g!?EdIYc(Bh-N4)>ptTm@wkkb*z zwQy_DXCU(S;B92*0cgja_|SGHBByWh7WUa=4@AtRdvAhsZlBp(${nnaed+`Fv(FU! zD`I>Q*cwEPTfuUUOHYaX5W zSo4^)#`hR&9t)O_Ts#i!KHup6l*h+|Jx|*WiF*QA-nV--oPAh9^k?r}pVplRcCG8K zMZkS>b+pV~yIY|3l|( zK;ru_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qn|kH`~cb+JFl3*CFq!e`k29G zXy@q+w2`-$xG!^jji=ldW9aaUoqmGMovMpkK802u z{8eaci@rXq=q%GN?m(IKMqcsayNKTv=Wp#hlaITwR() * 2) as u64, @@ -271,6 +271,8 @@ impl RadixSorter histogram_pass, prefix_sum_pass, + total_prefix_sum_pass, + scatter_pass, timing_buffer, timing_query_set, @@ -288,7 +290,7 @@ impl RadixSorter { dbg!(self.histogram_count); let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("RadixSorter::double_buffer_bind_group"), + label: Some("RadixSorter::data_buffer_bind_group"), layout: &self.data_bind_group_layout, entries: &[ // Keys @@ -314,7 +316,6 @@ impl RadixSorter end_of_pass_write_index: Some(1), }), }); - compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); for i in 0..Self::PASS_COUNT { @@ -341,9 +342,20 @@ impl RadixSorter // ~~ Prefix sum pass compute_pass.set_pipeline(&self.prefix_sum_pass); compute_pass.set_immediates(0, bytes); + compute_pass.dispatch_workgroups(Self::VALUE_COUNT as u32, 1, 1); + + compute_pass.set_pipeline(&self.total_prefix_sum_pass); + compute_pass.set_immediates(0, bytes); compute_pass.dispatch_workgroups(1, 1, 1); //compute_pass.dispatch_workgroups_indirect(&self., 0); + compute_pass.set_pipeline(&self.scatter_pass); + compute_pass.set_immediates(0, bytes); + compute_pass.dispatch_workgroups( + self.max_size.div_ceil(Self::WG_THREAD_COUNT) as u32, + 1, + 1, + ); } // Even number of passes => data is in the user buffer diff --git a/src/main.rs b/src/main.rs index 7b1ce0e..adf531d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -198,11 +198,13 @@ 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) as u32; + //let elt_count = 256 as u32; let org_big_value_buffer = (0..(elt_count as u32)).collect::>(); let org_big_key_buffer = org_big_value_buffer .iter() - .map(|_| random::()) + //.map(|_| random::()) + .map(|_| random_range(1..256)) .collect::>(); let sorted_values = org_big_key_buffer @@ -255,37 +257,37 @@ impl State }, ); - // 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 !"); - // }, - // ); + 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..256]); + }, + ); + + 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!();