Compare commits

..
2 Commits
Author SHA1 Message Date
octagonal d9df73abab Radix sort working ! 2026-10-03 00:02:47 +02:00
octagonal efd07fd53b Working 'fast' radix 2026-10-02 21:38:59 +02:00
11 changed files with 334 additions and 181 deletions
+31 -7
View File
@@ -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();
}
}
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+78 -25
View File
@@ -38,6 +38,11 @@ RWStructuredBuffer<uint32_t> dest_key_buffer;
[vk::binding(1, 2)]
RWStructuredBuffer<uint32_t> dest_value_buffer;
[vk::binding(0, 3)]
RWStructuredBuffer<uint32_t> indirect_element_count;
[vk::binding(1, 3)]
RWStructuredBuffer<IndirectArgs> 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]);
}
@@ -210,17 +216,25 @@ void scatter_pass(
uint32_t3 local_location: SV_GroupThreadID,
uint32_t3 group_location: SV_GroupID, )
{
uint32_t batch_index = 0;
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);
// uint32_t batch_index = 0;
uint32_t start = group_location.x * WG_HISTO_ELEMENT + local_location.x;
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)
{
uint32_t key = key_buffer[index];
uint32_t digit = extract_digit(key, params.pass_index, params.descending);
// local_histogram[digit].add(1);
uint32_t local_index = index - group_location.x * WG_HISTO_ELEMENT;
sort_tokens[local_index] = SortToken(digit, local_index);
if (index < end)
{
uint32_t key = key_buffer[index];
uint32_t digit = extract_digit(key, params.pass_index, params.descending);
sort_tokens[local_index] = SortToken(digit, local_index);
}
else
{
sort_tokens[local_index] = SortToken(0xFFFF, local_index);
}
}
GroupMemoryBarrierWithGroupSync();
@@ -240,9 +254,9 @@ void scatter_pass(
uint32_t sum = 0;
for (uint32_t i = 0; i < WE_HISTO_ELEMENTS; i++)
{
uint32_t bin_digit = ((thread_tokens[i].digit >> radix_pass) & 1) ^ 1;
uint32_t bin_digit = (thread_tokens[i].digit >> radix_pass) & 1;
thread_prefix[i] = sum;
sum += bin_digit;
sum += 1 - bin_digit; // Count number of zeroes
}
// Publish sum
@@ -262,39 +276,78 @@ void scatter_pass(
uint32_t total_zeroes = local_prefix[WG_THREAD_COUNT - 1];
// Scatter sort tokens
// Exclusive zero rank of block
uint32_t zero_rank = select(local_location.x == 0, 0, local_prefix[local_location.x - 1]);
for (uint32_t i = 0; i < WE_HISTO_ELEMENTS; i++)
{
uint32_t bin_digit = (thread_tokens[i].digit >> radix_pass) & 1;
uint32_t index = i + local_location.x * WE_HISTO_ELEMENTS;
uint32_t scatter_index = select(bin_digit == 0,
thread_prefix[i] + zero_rank,
total_zeroes + local_location.x - (thread_prefix[i] + zero_rank));
total_zeroes + index - (thread_prefix[i] + zero_rank));
sort_tokens[scatter_index] = thread_tokens[i];
}
GroupMemoryBarrierWithGroupSync();
}
// Scatter to main memory
// Compute local offset by boundary detection
if (local_location.x == 0 || sort_tokens[local_location.x].digit != sort_tokens[local_location.x - 1].digit)
// Tokens are now sorted in the LDS
// Boundary detection
for (
uint32_t i = local_location.x * WE_HISTO_ELEMENTS;
i < min((local_location.x + 1) * WE_HISTO_ELEMENTS, element_count);
i++)
{
local_prefix[sort_tokens[local_location.x].digit] = local_location.x;
SortToken token = sort_tokens[i];
uint32_t digit = token.digit;
if (i == 0 || sort_tokens[i - 1].digit != digit)
{
local_prefix[digit] = i;
}
}
// For each digit, we now know where it starts within the buffer
GroupMemoryBarrierWithGroupSync();
// Scatter keys
uint32_t offset = local_location.x * WE_HISTO_ELEMENTS;
for (uint32_t i = 0; i < WE_HISTO_ELEMENTS; i++)
for (
uint32_t i = local_location.x * WE_HISTO_ELEMENTS;
i < min((local_location.x + 1) * WE_HISTO_ELEMENTS, element_count);
i++)
{
uint32_t digit = sort_tokens[offset + i].digit;
uint32_t index = sort_tokens[offset + i].index;
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) + 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 + (local_location.x - local_prefix[digit]);
uint32_t destination_index = group_offset + digit_offset + (i - local_prefix[digit]);
// dest_key_buffer[i] = local_prefix[local_location.x];
// dest_key_buffer[i] = destination_index;
// dest_key_buffer[i] = local_prefix[local_location.x];
dest_key_buffer[destination_index] = key_buffer[index];
dest_value_buffer[destination_index] = value_buffer[index];
}
}
[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;
}
Binary file not shown.
BIN
View File
Binary file not shown.
+112 -7
View File
@@ -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::<u32>() 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::<wgpu::util::DispatchIndirectArgs>() 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::<wgpu::util::DispatchIndirectArgs>() 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::<PassParameters>() 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::<u64>() * 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(&parameters);
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::<wgpu::util::DispatchIndirectArgs>() 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
+32 -2
View File
@@ -195,10 +195,22 @@ impl State
.await
.unwrap();
/*
let mut encoder = device.create_command_encoder(&Default::default());
println!("Making elements");
let elt_count = (1 << 20) as u32;
//let elt_count = (1 << 20) as u32;
//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::<Vec<_>>();
let org_big_key_buffer = org_big_value_buffer
@@ -207,6 +219,22 @@ impl State
.map(|_| random_range(1..256))
.collect::<Vec<_>>();
// let mut prefix = org_big_key_buffer.iter().fold([0; 256], |acc, x| {
// let mut acc = acc;
// acc[x >> 24] += 1;
// acc
// });
//
// let mut sum = 0;
// for x in prefix.iter_mut()
// {
// let cur = *x;
// *x = sum;
// sum += cur;
// }
//
// println!("Counts : {:?}", prefix);
let sorted_values = org_big_key_buffer
.iter()
.zip(org_big_value_buffer.iter())
@@ -235,6 +263,7 @@ impl State
&device,
&big_key_buffer,
&big_value_buffer,
Some(&count_buffer),
&mut encoder,
radix_sort::RadixSortDirection::Ascending,
);
@@ -267,7 +296,7 @@ impl State
.chunks(4)
.map(|x| u32::from_ne_bytes([x[0], x[1], x[2], x[3]]))
.collect::<Vec<u32>>();
println!("{:?}", &data[0..256]);
println!("{:?}", &data[0..3000]);
},
);
@@ -291,6 +320,7 @@ impl State
device.poll(wgpu::wgt::PollType::Poll);
panic!();
*/
let size = window.inner_size();
+1 -1
View File
@@ -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,
);
+80 -139
View File
@@ -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::<u32>() * 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::<u32>() * 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::<u32>() * 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::<Vec<_>>(),
));
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::<u32>() 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<storage, read_write> usage_buffer: array<u32>;
@group(0) @binding(1) var<storage, read_write> sort_buffer: array<u32>;
var<immediate> both_phase: u32;
fn big_fusion(index: u32, phase_size: u32) -> vec2<u32>
{{
// 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<u32>(a, b);
}}
fn small_fusion(index: u32, phase: u32, sub_phase: u32) -> vec2<u32>
{{
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<u32>(a, b);
}}
@group(0) @binding(0) var<storage, read_write> index_buffer: array<u32>;
@compute
@workgroup_size(64)
@workgroup_size(256)
fn main(
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
)
{{
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<u32>(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::<u32>()) 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,
);
}
}