Fixing fast radix

This commit is contained in:
2026-10-01 22:55:04 +02:00
parent 41feb52ab5
commit 7dfcfe56e9
4 changed files with 184 additions and 110 deletions
+122 -62
View File
@@ -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<uint32_t> dest_key_buffer;
[vk::binding(1, 2)]
RWStructuredBuffer<uint32_t> dest_value_buffer;
/*
[vk::binding(0, 3)]
RWStructuredBuffer<uint32_t> sort_count;
[vk::binding(1, 3)]
RWStructuredBuffer<IndirectArgs> 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
}
Binary file not shown.
+27 -15
View File
@@ -47,6 +47,8 @@ pub struct RadixSorter
histogram_pass: ComputePipeline,
prefix_sum_pass: ComputePipeline,
total_prefix_sum_pass: ComputePipeline,
scatter_pass: ComputePipeline,
timing_query_set: QuerySet,
pub timing_buffer: Buffer,
@@ -70,7 +72,7 @@ impl RadixSorter
const WG_THREAD_COUNT: usize = 256;
// Elements managed per thread for histo build
const WE_HISTO_ELEMENTS: usize = 16;
const WE_HISTO_ELEMENTS: usize = 1;
// Elements managed per workgroup for histo build
const WG_HISTO_ELEMENTS: usize = Self::WG_THREAD_COUNT * Self::WE_HISTO_ELEMENTS;
@@ -222,7 +224,16 @@ impl RadixSorter
cache: None,
});
/*
let total_prefix_sum_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::total_prefix_sum_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("total_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),
@@ -232,17 +243,6 @@ impl RadixSorter
cache: None,
});
let indirect_count_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::indirect_count_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("indirect_count_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,
@@ -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
+35 -33
View File
@@ -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::<Vec<_>>();
let org_big_key_buffer = org_big_value_buffer
.iter()
.map(|_| random::<u32>())
//.map(|_| random::<u32>())
.map(|_| random_range(1..256))
.collect::<Vec<_>>();
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::<Vec<u32>>();
// 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::<Vec<u32>>();
// 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::<Vec<u32>>();
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::<Vec<u32>>();
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!();