Starting faster radix

This commit is contained in:
2026-09-29 23:57:48 +02:00
parent 3124978e3f
commit 41feb52ab5
5 changed files with 185 additions and 656 deletions
+67 -171
View File
@@ -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<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;
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<uint32_t> local_histogram[value_count];
struct LocalHistogram
{
Atomic<uint32_t>[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;
}
Binary file not shown.
+72 -447
View File
@@ -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::<u32>() * 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::<wgpu::util::DispatchIndirectArgs>() * 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::<wgpu::util::DispatchIndirectArgs>() * 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::<wgpu::util::DispatchIndirectArgs>()) 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::<Vec<_>>();
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::<wgpu::util::DispatchIndirectArgs>() * 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::<wgpu::util::DispatchIndirectArgs>() * (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::<u32>()).next_multiple_of(256);
//let digit_stride = histogram_count * size_of::<u32>();
// 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::<u32>() * 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::<PassParameters>() 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::<u64>() * 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::<u32>() 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::<wgpu::util::DispatchIndirectArgs>() 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::<u32>() as u32),
digit_stride: self.histogram_count as u32,
};
let bytes = bytemuck::bytes_of(&parameters);
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);
}
}
+45 -37
View File
@@ -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::<Vec<_>>();
let org_big_key_buffer = org_big_value_buffer
.iter()
.map(|_| random_range(0..2_000_000u32))
.map(|_| random::<u32>())
.collect::<Vec<_>>();
let sorted_values = org_big_key_buffer
@@ -218,6 +211,7 @@ impl State
.sorted_by_key(|(key, _)| *key)
.map(|(_, val)| *val)
.collect::<Vec<u32>>();
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::<Vec<u32>>();
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::<Vec<u32>>();
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::<Vec<u64>>();
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::<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 !");
// },
// );
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,
);