From d9df73abab2931cdf0c9e2a076d990461d3a5345 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Sat, 3 Oct 2026 00:02:47 +0200 Subject: [PATCH] Radix sort working ! --- shaders/compaction.slang | 38 +++++- shaders/compaction.spv | Bin 4552 -> 5592 bytes shaders/radix_sort.slang | 39 +++++- shaders/radix_sort.spv | Bin 10428 -> 11768 bytes src/gpu/radix_sort.rs | 119 +++++++++++++++- src/main.rs | 10 ++ src/voxel_cache/request_buffer.rs | 2 +- src/voxel_cache/usage_buffer.rs | 219 +++++++++++------------------- 8 files changed, 266 insertions(+), 161 deletions(-) diff --git a/shaders/compaction.slang b/shaders/compaction.slang index 3ed1b15..a973b4b 100644 --- a/shaders/compaction.slang +++ b/shaders/compaction.slang @@ -87,7 +87,9 @@ void block_sum( sum_buffer[2 * thread_index + 1] = local_data[2 * local_thread_index + 1]; } -[numthreads(1, 1, 1)] +groupshared uint32_t local_prefix[256]; + +[numthreads(256, 1, 1)] [shader("compute")] void linear_reduced_sum( uint32_t3 workgroup_id: SV_GroupID, @@ -96,13 +98,35 @@ void linear_reduced_sum( { let size = reduced_buffer.getCount(); - // Perform exclusive sum - var running_sum : uint32_t = 0; - for (uint32_t i = 0; i < size; i++) + uint32_t running_sum = 0; + for (uint32_t slice = 0; slice < size; slice += 256) { - let value = reduced_buffer[i]; - reduced_buffer[i] = running_sum; - running_sum += value; + let index = slice + local_thread_id.x; + if (index < size) + { + local_prefix[local_thread_id.x] = reduced_buffer[index]; + } + else + { + local_prefix[local_thread_id.x] = 0; + } + + GroupMemoryBarrierWithGroupSync(); + + for (uint32_t offset = 1; offset < 256; offset *= 2) + { + uint32_t offset_value = select(local_thread_id.x >= offset, local_prefix[local_thread_id.x - offset], 0); + GroupMemoryBarrierWithGroupSync(); + local_prefix[local_thread_id.x] += offset_value; + GroupMemoryBarrierWithGroupSync(); + } + + if (index < size) + { + reduced_buffer[index] = select(local_thread_id.x == 0, 0, local_prefix[local_thread_id.x - 1]) + running_sum; + } + running_sum += local_prefix[255]; + GroupMemoryBarrierWithGroupSync(); } } diff --git a/shaders/compaction.spv b/shaders/compaction.spv index aed71d52ff6c9fbd06fba3afbe3dc3fa28134036..45d92dd98c4c72ce158f3c7bfac2afb31256d5d4 100644 GIT binary patch literal 5592 zcmZ{niFce;8OA@7Nm|-sX@M3HYHA`N1$Pleu!U+XC_<~Cq7Kt!QX*-BlNqRrS`h)o zeL+D*+yxX7S6l)2ec$yQ{|VP~Jox*4bDub8PQ9GB@AK~WKKFjpGCDH3q8dA-s;ZN! zzwoDPT{TkaSyipBc3*H&^SqtAnoHfqPHS(wxu-Wf+wLrz)AOyRC2Jm1jjHOpwbfzO zSiyVd7pE_8F7@_dk053>5aZ*>3S=d+mRb4^Mds%g+O1Br)1K)~w`cmr)~rIzPwr~) z(sZlaZFlP4>AMEMz3qEA$g`|N1Y$+MvkvCB@34QAo$I%Dj9nat-gWWrZl^ch?XlCd zYhIi?UdISm&E~%LzCG>EW9pjmdXLkKy@hUJ(VQ{YVYKvk=n1gMO`?!R~TL`?<$K-pAOJ-1TQ%(P_`l?Z+f@94@PBadvj8-ECgkn(wvy z{s#QS-=8BNo!-L2+```aLfqqed`t6l(-z6e|GPWqcqelUGwuD$JGG`!bDBHcf$g2i z^Kpo__pSZVVjqF_ZoTUrFy}q^u6EK*?3(PWy5894A^YJ2_L1QK^=s7FdB-Bocg|qF zw)JvsT>gy@+JkY=Js8){{3F=;QFVN@+JF`xMbC}s3B{)?!dTv z^&F=n4vqaN%m*288l8MI&T{#N{z>Aa(PvWYyYRQi^IS--y&hY9sO6l;fjwh#9uL;% z+Ft6O0QTIjYm4uRVEg$N@5U#Ory=^y{|C%G3GMnf`!RMp@?^w)s?+N!VCULv8@+r( zXCQKG>@1M>6!I@>?Q0MFrN>jj!#&Q#XAfiB__}?2XCa=&H|bvGN^YKp7`wBaWoz*{ z^LA?e4z?j%5#OivSC`te!N%ODGqnfz>3$Cs-p&C#*Eb#BwuAMDx2J<$@@DKA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ZCF@Ldw zx2@n-#Csc$x4R82$A0(0|+7;k+C*gF|JkY@Bw zuzvFnCEs1(;4bp+#%HdvnB{wtFF3jv+a*WF?nCr>HgVju4ECP(3*Y_8=RR@w3Rr*G zJz#6&j#aQe^W?;sKIbL&Rmc6Efwb_VN_nb z3vDm;u{2YCVC$VpXX*j8OTLV0+s8U}%*$?Y32|QhJ&F7DgYD%z2af|_xiuEN4TAN{ zk-fB|_YgRG`wa)T4}$ICTtx4O!1gv4z3X88_O_Sy-~21+9lTHU8wPt$`^EViVEHf> zbJhgwH!tQ#`KA;a}Vb%&ZIusTsmW(S#7@axB`yj{{@qD0NNaN%=FXX1;~D63UUyM*fZdW9ZE6h{n><3dEe*I_EpDwJP)?s zGx#1apk2O)F>U);r;fSNAM^Pl*z-I4_6n|F0vnS{wRZ^Ky@R$n;q&a)J6H1H9o<(Q zyc9W|jNcWUz6=gdUjerpWO<%h=vR@6Nc`@-_Z*@4?#$wjK0DCXrrkHaW z+gYB2{t{V)*vEY9-SaE7%RSBc8qw#T;<(c{VBg(4xtFu2Pu|=!YSdBlEjV~6a(D#4 zvEbo5u)g5oDA?thjD3&%fOsag` dest_key_buffer; [vk::binding(1, 2)] RWStructuredBuffer dest_value_buffer; +[vk::binding(0, 3)] +RWStructuredBuffer indirect_element_count; +[vk::binding(1, 3)] +RWStructuredBuffer indirect_workgroup_count; + [vk::push_constant] uniform PassParams params; @@ -68,7 +73,7 @@ void histogram_pass( // 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 < min(indirect_element_count[0], (group_location.x + 1) * WG_HISTO_ELEMENT); index += WG_THREAD_COUNT) { uint32_t key = key_buffer[index]; @@ -106,7 +111,8 @@ void prefix_sum_pass( uint32_t running_prefix = 0; uint32_t start_offset = group_location.x * params.histogram_count; - uint32_t end_offset = start_offset + params.histogram_count; + // uint32_t end_offset = start_offset + params.histogram_count; + uint32_t end_offset = start_offset + indirect_workgroup_count[0].x + 1; for ( uint32_t slice_offset = start_offset; @@ -160,7 +166,7 @@ void total_prefix_sum_pass( } // Load last histogram into lds - local_prefix[local_location.x] = histograms[(params.histogram_count - 1) + params.histogram_count * local_location.x]; + local_prefix[local_location.x] = histograms[indirect_workgroup_count[0].x + params.histogram_count * local_location.x]; GroupMemoryBarrierWithGroupSync(); // Perform hillis steele for (uint32_t offset = 1; offset < WG_THREAD_COUNT; offset *= 2) @@ -171,7 +177,7 @@ void total_prefix_sum_pass( GroupMemoryBarrierWithGroupSync(); } - histograms[(params.histogram_count - 1) + params.histogram_count * local_location.x] = + histograms[indirect_workgroup_count[0].x + params.histogram_count * local_location.x] = select(local_location.x == 0, 0, local_prefix[local_location.x - 1]); } @@ -212,8 +218,8 @@ void scatter_pass( { // uint32_t batch_index = 0; uint32_t start = group_location.x * WG_HISTO_ELEMENT + local_location.x; - uint32_t end = min(key_buffer.getCount(), (group_location.x + 1) * WG_HISTO_ELEMENT); - uint32_t element_count = key_buffer.getCount() - group_location.x * WG_HISTO_ELEMENT; + uint32_t end = min(indirect_element_count[0], (group_location.x + 1) * WG_HISTO_ELEMENT); + uint32_t element_count = indirect_element_count[0] - group_location.x * WG_HISTO_ELEMENT; for (uint32_t index = start; index < (group_location.x + 1) * WG_HISTO_ELEMENT; index += WG_THREAD_COUNT) @@ -313,7 +319,7 @@ void scatter_pass( uint32_t digit = sort_tokens[i].digit; uint32_t index = sort_tokens[i].index + group_location.x * WG_HISTO_ELEMENT; uint32_t group_offset = histograms[group_location.x + digit * params.histogram_count]; - uint32_t digit_offset = histograms[(params.histogram_count - 1) + digit * params.histogram_count]; + uint32_t digit_offset = histograms[indirect_workgroup_count[0].x + digit * params.histogram_count]; uint32_t destination_index = group_offset + digit_offset + (i - local_prefix[digit]); @@ -326,3 +332,22 @@ void scatter_pass( } } +[shader("compute")] +[numthreads(1, 1, 1)] +void compute_counts_pass( + uint32_t3 location: SV_DispatchThreadID, + uint32_t3 local_location: SV_GroupThreadID, + uint32_t3 group_location: SV_GroupID, ) +{ + uint32_t element_count = indirect_element_count[0]; + if (params.pass_index != 0) + { + element_count = params.pass_index; + indirect_element_count[0] = params.pass_index; + } + + indirect_workgroup_count[0].x = div_ceil(element_count, WG_HISTO_ELEMENT); + indirect_workgroup_count[0].y = 1; + indirect_workgroup_count[0].z = 1; +} + diff --git a/shaders/radix_sort.spv b/shaders/radix_sort.spv index b6d35290a13dd501f7136d745d039c64239a0efd..b66222222755f0500cb1df5abd94797cff5fb52d 100644 GIT binary patch literal 11768 zcmZ{o2b|qimB(K)Eg?XFfb=9l=nz_ngqmO=L;@s)rUH-2%u5)P%)~cuXrdw_ioJ_s z?|>rq-dNGy)$P5rtJ~aO?Caw9`+xU0^Urhm!}*-w`JH>uJ@?#m@64oc?omUHfjNyv z$jxI!+}0l6+1yn{a8y5{e-If$<{|Tug^j%` zeh=`jc5Ca{ZOzH4GBINp;M)_KnbTcsFSyP`XLv`mcjnAG^|=chi>kHuX5Qq;aHqp& zyBYp!ewnwBvHKwVBKsjTIV`ARErJ`F*tu(}(`t@POpSLYyCL1L`5R{+kaaPJ#j^g2 zy!)PwcW<-t<~|#59`cE;?&Ck#7Z0$O=dfd9gnCV%5d2VMfA}k}-P~zUjdZ5ktCB+|p`$@B>uA{f&)}j(^>b_pGKXR64}^9mLql&TzZaoY=Z`vem(?A{>lfUuvFQMb=~Z>j4oosPTvdPhw2#+}D2@zi(Sb379N=81Oas)_Bbaj>aW7bRfVYqF z!fMkIRlN8v3HNt-&hVe zv({ka6zsf$hRgtW8=e}v5E0q=_-HU zR(;LdW8ppUEvxvd3#XrvYL4%44_)!Iz3awW#Q53X=ylZF_uMzq`=Ra6ByI1S_6oFb zi0_^DnY-D2)%)oEy@U*WNB!(4KgT=IUiOP^U-}kn`%c#V+WO~I{=VuhO#HlyiSL?n zj+Jw*aL$o)f3D*@S6@flb^M%@cd8y+t~a(^Z|s$D*2tgHuJ!cY?7pg&*+bs2tmAm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(wctJL?*7C%XBN_Qcy2SzG4yTClO4*TlOH zS$#F$^~i~*J@IzKPg{I%0K13!)bU1i&X0M=?!9V%>>eo3Zp&POi?Z`R84Bew{bD LbGroYzh(X(y`PuR diff --git a/src/gpu/radix_sort.rs b/src/gpu/radix_sort.rs index 7c5702f..3f8f0f7 100644 --- a/src/gpu/radix_sort.rs +++ b/src/gpu/radix_sort.rs @@ -45,10 +45,16 @@ pub struct RadixSorter double_buffer_values: Buffer, double_buffer_bind_group: BindGroup, + // Counts buffer + element_counts_buffer: Buffer, + indirect_counts_storage: Buffer, + indirect_counts: Buffer, + histogram_pass: ComputePipeline, prefix_sum_pass: ComputePipeline, total_prefix_sum_pass: ComputePipeline, scatter_pass: ComputePipeline, + compute_counts_pass: ComputePipeline, timing_query_set: QuerySet, pub timing_buffer: Buffer, @@ -136,6 +142,27 @@ impl RadixSorter mapped_at_creation: false, }); + let element_counts_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("RadixSorter::element_counts_buffer"), + size: size_of::() as u64, + usage: BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let indirect_counts_storage = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("RadixSorter::element_counts_buffer"), + size: size_of::() as u64, + usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + + let indirect_counts = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("RadixSorter::element_counts_buffer"), + size: size_of::() as u64, + usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let data_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("RadixSorter::data_bind_group_layout"), @@ -191,9 +218,8 @@ impl RadixSorter Some(&data_bind_group_layout), // Dest buffer Some(&data_bind_group_layout), - // (Two buffers same layout as histograms) - // Sort count buffer, indirect buffer - //Some(&data_bind_group_layout), + // Counts buffer + Some(&data_bind_group_layout), ], immediate_size: size_of::() as u32, // for the pass number }); @@ -243,6 +269,16 @@ impl RadixSorter cache: None, }); + let compute_counts_pass = + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("RadixSorter::compute_counts_pass"), + layout: Some(&pipelines_layout), + module: &radix_sort_shader_module, + entry_point: Some("compute_counts_pass"), + 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, @@ -269,10 +305,15 @@ impl RadixSorter double_buffer_values, double_buffer_bind_group, + element_counts_buffer, + indirect_counts_storage, + indirect_counts, + histogram_pass, prefix_sum_pass, total_prefix_sum_pass, scatter_pass, + compute_counts_pass, timing_buffer, timing_query_set, @@ -284,11 +325,11 @@ impl RadixSorter device: &Device, keys: &Buffer, values: &Buffer, + indirect: 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::data_buffer_bind_group"), layout: &self.data_bind_group_layout, @@ -306,8 +347,69 @@ impl RadixSorter ], }); + let counts_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("RadixSorter::double_buffer_bind_group"), + layout: &self.data_bind_group_layout, + entries: &[ + // Keys + wgpu::BindGroupEntry { + binding: 0, + resource: indirect + .unwrap_or(&self.element_counts_buffer) + .as_entire_binding(), + }, + // Values + wgpu::BindGroupEntry { + binding: 1, + resource: self.indirect_counts_storage.as_entire_binding(), + }, + ], + }); + let bg = [&data_buffer_bind_group, &self.double_buffer_bind_group]; + // Compute counts + { + let mut counts_compute_pass = + encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("RadixSorter::counts_compute_pass"), + timestamp_writes: None, + }); + + let parameters = PassParameters { + pass_index: if indirect.is_some() + { + 0 + } + else + { + self.max_size as u32 + }, + descending: 0, + digit_stride: 0, + }; + let bytes = bytemuck::bytes_of(¶meters); + + counts_compute_pass.set_pipeline(&self.compute_counts_pass); + + counts_compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]); + counts_compute_pass.set_bind_group(1, bg[0], &[]); + counts_compute_pass.set_bind_group(2, bg[1], &[]); + counts_compute_pass.set_bind_group(3, &counts_bind_group, &[]); + + counts_compute_pass.set_immediates(0, bytes); + counts_compute_pass.dispatch_workgroups(1, 1, 1); + } + + // Copy indrect counts to indrect compatible buffer + encoder.copy_buffer_to_buffer( + &self.indirect_counts_storage, + 0, + &self.indirect_counts, + 0, + size_of::() as u64, + ); + let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("RadixSorter::compute_pass"), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { @@ -333,11 +435,13 @@ impl RadixSorter 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_bind_group, &[]); // ~~ Histogram pass compute_pass.set_pipeline(&self.histogram_pass); compute_pass.set_immediates(0, bytes); - compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1); + compute_pass.dispatch_workgroups_indirect(&self.indirect_counts, 0); + //compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1); // ~~ Prefix sum pass compute_pass.set_pipeline(&self.prefix_sum_pass); @@ -348,10 +452,11 @@ impl RadixSorter compute_pass.set_immediates(0, bytes); compute_pass.dispatch_workgroups(1, 1, 1); - //compute_pass.dispatch_workgroups_indirect(&self., 0); + // ~~ Scatter pass compute_pass.set_pipeline(&self.scatter_pass); compute_pass.set_immediates(0, bytes); - compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1); + compute_pass.dispatch_workgroups_indirect(&self.indirect_counts, 0); + //compute_pass.dispatch_workgroups(self.histo_block_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 e3baaaa..d2d75f8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -195,6 +195,7 @@ impl State .await .unwrap(); + /* let mut encoder = device.create_command_encoder(&Default::default()); println!("Making elements"); @@ -202,6 +203,13 @@ impl State //let elt_count = 100_000; //let elt_count = (21 * 4096) as u32; //let elt_count = 3000 as u32; + let elt_count_real = 1_000_000; + let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("count_buffer"), + usage: wgpu::BufferUsages::STORAGE, + contents: bytemuck::bytes_of(&elt_count_real), + }); + let elt_count = 1_000_000; //let elt_count = 256 as u32; let org_big_value_buffer = (0..(elt_count as u32)).collect::>(); @@ -255,6 +263,7 @@ impl State &device, &big_key_buffer, &big_value_buffer, + Some(&count_buffer), &mut encoder, radix_sort::RadixSortDirection::Ascending, ); @@ -311,6 +320,7 @@ impl State 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 0961ccf..ac2dedd 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, ); diff --git a/src/voxel_cache/usage_buffer.rs b/src/voxel_cache/usage_buffer.rs index 64b1cac..d2ee664 100644 --- a/src/voxel_cache/usage_buffer.rs +++ b/src/voxel_cache/usage_buffer.rs @@ -1,3 +1,5 @@ +use std::ops::Div; + use bytemuck::bytes_of; use wgpu::BindGroup; use wgpu::BindGroupEntry; @@ -8,14 +10,21 @@ use wgpu::ComputePipeline; use wgpu::Device; use wgpu::ShaderStages; +use crate::gpu::radix_sort::RadixSorter; + pub struct UsageBuffer { pub cache_size: usize, pub current_timestamp: u32, + pub usage_buffer: Buffer, - pub sort_buffer: Buffer, - pub sort_pipeline: ComputePipeline, - pub bindgroup: BindGroup, + pub key_buffer: Buffer, + pub index_buffer: Buffer, + + pub index_bind_group: BindGroup, + pub init_indices_pass: ComputePipeline, + + pub sorter: RadixSorter, pub device: Device, } @@ -25,16 +34,24 @@ impl UsageBuffer { let initial_timestamp = 0; let usage_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("Usage buffer"), + label: Some("UsageBuffer::usage_buffer"), size: (size_of::() * cache_size) as u64, usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC, mapped_at_creation: true, }); - let sort_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("usage_sort_buffer"), + + let key_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("UsageBuffer::key_buffer"), + size: (size_of::() * cache_size) as u64, + usage: BufferUsages::STORAGE | BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + let index_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("UsageBuffer::key_buffer"), size: (size_of::() * cache_size) as u64, usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC, - mapped_at_creation: true, + mapped_at_creation: false, }); usage_buffer @@ -45,138 +62,54 @@ impl UsageBuffer )); usage_buffer.unmap(); - sort_buffer - .get_mapped_range_mut(0..) - .unwrap() - .copy_from_slice(bytemuck::cast_slice( - &(0..(cache_size as u32)).collect::>(), - )); - sort_buffer.unmap(); - let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("usage_sort_pipeline_bing_group_layout"), - entries: &[ - 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, + label: Some("UsageBuffer::bindgroup_layout"), + entries: &[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, }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], + count: None, + }], }); - let bindgroup = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("usage_sort_pipeline_bindgroup"), + let index_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("UsageBuffer::index_bindgroup"), layout: &bindgroup_layout, - entries: &[ - BindGroupEntry { - binding: 0, - resource: usage_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 1, - resource: sort_buffer.as_entire_binding(), - }, - ], + entries: &[BindGroupEntry { + binding: 0, + resource: index_buffer.as_entire_binding(), + }], }); - let pipeline_layouts = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("usage_buffer_pipeline_layout"), + let pipeline_layout = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("UsageBuffer::pipeline_layout"), bind_group_layouts: &[Some(&bindgroup_layout)], - immediate_size: size_of::() as u32, + immediate_size: 0, }); - let sort_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("Sort node request"), - layout: Some(pipeline_layouts), + let init_indices_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("UsageBuffer::init_indices_pass"), + layout: Some(pipeline_layout), module: &device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("clear_chunk_requests shader module"), source: wgpu::ShaderSource::Wgsl( " - - @group(0) @binding(0) var usage_buffer: array; - @group(0) @binding(1) var sort_buffer: array; - var both_phase: u32; - - fn big_fusion(index: u32, phase_size: u32) -> vec2 - {{ - // Find out in which block index this invocation pertains - let block_index = index / (phase_size / 2); - let element_index = index % (phase_size / 2); - - let offset = block_index * phase_size; - let a = offset + element_index; - let b = offset + phase_size - 1 - element_index; - return vec2(a, b); - }} - - fn small_fusion(index: u32, phase: u32, sub_phase: u32) -> vec2 - {{ - let phase_size = u32(1 << (phase - sub_phase + 1)); - - let block_index = index / (phase_size / 2); - let element_index = index % (phase_size / 2); - - let offset = block_index * phase_size; - let a = offset + element_index; - let b = a + (phase_size / 2); - return vec2(a, b); - }} - + @group(0) @binding(0) var index_buffer: array; @compute - @workgroup_size(64) + @workgroup_size(256) fn main( @builtin(global_invocation_id) global_invocation_id: vec3 ) {{ - - let length = arrayLength(&sort_buffer); - let index = global_invocation_id.x; - let sub_phase = (both_phase >> 16) & 0xFFFF; - let phase = both_phase & 0xFFFF; - let phase_total_width = u32(1 << (phase + 1)); - - var swap_indices = vec2(0, 0); - - if(sub_phase == 0) + let total = arrayLength(&index_buffer); + if(global_invocation_id.x < total) {{ - // Bitonic fusion - swap_indices = big_fusion(index, phase_total_width); - }}else - {{ - swap_indices = small_fusion(index, phase, sub_phase); - }} - - // Do swap - if(swap_indices.y >= length) - {{ - // Suppose that swap_indices.y is -inf, dont swap - return; - }} - - let av = usage_buffer[sort_buffer[swap_indices.x]]; - let bv = usage_buffer[sort_buffer[swap_indices.y]]; - - if(bv < av) - {{ - let temp = sort_buffer[swap_indices.x]; - sort_buffer[swap_indices.x] = sort_buffer[swap_indices.y]; - sort_buffer[swap_indices.y] = temp; + index_buffer[global_invocation_id.x] = global_invocation_id.x; }} }} " @@ -192,9 +125,11 @@ impl UsageBuffer cache_size, current_timestamp: initial_timestamp, usage_buffer, - sort_buffer, - sort_pipeline, - bindgroup, + key_buffer, + index_buffer, + index_bind_group, + init_indices_pass, + sorter: RadixSorter::new(&device, cache_size), device, } } @@ -217,33 +152,39 @@ impl UsageBuffer pub fn sort_buffer(&self) -> &Buffer { - &self.sort_buffer + &self.index_buffer } pub fn sort_usage(&self, encoder: &mut CommandEncoder) { + // Copy keys to sort buffer + encoder.copy_buffer_to_buffer( + &self.usage_buffer, + 0, + &self.key_buffer, + 0, + (self.cache_size * size_of::()) as u64, + ); + + // Compute pass to initialize sorting indices let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("usage_buffer_sort_compute_pass"), + label: Some("UsageBuffer::compute_pass"), timestamp_writes: None, }); - compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]); - compute_pass.set_pipeline(&self.sort_pipeline); + compute_pass.set_bind_group(0, &self.index_bind_group, &[]); + compute_pass.set_pipeline(&self.init_indices_pass); + compute_pass.dispatch_workgroups(self.cache_size.div_ceil(256) as u32, 1, 1); - // Compute required shader invocations - let sort_steps = self.cache_size.next_power_of_two().ilog2(); // Each element is sorted - let shader_invocations = self.cache_size.div_ceil(2); // bitonic sorting : - // half as many shaders - // per element - let workgroup_invocations = shader_invocations.div_ceil(64); + drop(compute_pass); - for i in 0..=sort_steps - { - for j in 0..=i - { - compute_pass.set_immediates(0, bytes_of(&(j << 16 | i))); - compute_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1); - } - } + self.sorter.sort( + &self.device, + &self.key_buffer, + &self.index_buffer, + None, + encoder, + crate::gpu::radix_sort::RadixSortDirection::Ascending, + ); } }