refactor: Splitting into crates

This commit is contained in:
2026-11-15 20:36:43 +01:00
parent c13a04c8e2
commit 828806fbc8
68 changed files with 929 additions and 330 deletions
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "vxls-gpu"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
itertools.workspace = true
wgpu.workspace = true
[dev-dependencies]
pollster.workspace = true
+268
View File
@@ -0,0 +1,268 @@
use bytemuck::bytes_of;
use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferSlice;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::ShaderStages;
use wgpu::util::DeviceExt;
pub struct NonZeroBufferCompactor
{
size: usize,
block_count: usize,
reduced_buffer: Buffer,
sum_buffer: Buffer,
count_buffer_bg_layout: BindGroupLayout,
compaction_bg: BindGroup,
reduce_sum_pipeline: ComputePipeline,
partial_sum_pipeline: ComputePipeline,
scatter_pipeline: ComputePipeline,
}
impl NonZeroBufferCompactor
{
const THREAD_COUNT: usize = 256;
pub fn new(device: &Device, size: usize) -> Self
{
let block_count = size.div_ceil(Self::THREAD_COUNT * 2);
let reduced_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("indirect_buffer_reduced"),
contents: bytemuck::cast_slice(vec![0u32; block_count + 1].as_slice()),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
let sum_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("indirect_buffer_sum"),
contents: bytemuck::cast_slice(
vec![0u32; block_count * Self::THREAD_COUNT * 2].as_slice(),
),
usage: BufferUsages::STORAGE,
});
let count_buffer_bg_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("count_buffer_bg_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,
},
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,
},
// Optional compacted layout
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let compaction_bg_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("count_buffer_bg_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,
},
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,
},
],
});
let compaction_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("compaction_bg"),
layout: &compaction_bg_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: reduced_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: sum_buffer.as_entire_binding(),
},
],
});
let compaction_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("compaction_pipeline_layout"),
bind_group_layouts: &[Some(&count_buffer_bg_layout), Some(&compaction_bg_layout)],
immediate_size: size_of::<u32>() as u32, // Bool : Write to compacted buffer ?
});
let compaction_shader_module = unsafe {
device.create_shader_module_trusted(
wgpu::ShaderModuleDescriptor {
label: Some("compaction_shader_layout"),
source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed(
wgpu::include_spirv_source!("../../../shaders/out/compaction.spv"),
)),
},
wgpu::ShaderRuntimeChecks {
bounds_checks: false,
force_loop_bounding: false,
ray_query_initialization_tracking: false,
task_shader_dispatch_tracking: false,
mesh_shader_primitive_indices_clamp: false,
int_div_checks: false,
},
)
};
let reduce_sum_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("reduce_sum_pipeline"),
layout: Some(&compaction_pipeline_layout),
module: &compaction_shader_module,
entry_point: Some("block_sum"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let partial_sum_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("partial_sum_pipeline "),
layout: Some(&compaction_pipeline_layout),
module: &compaction_shader_module,
entry_point: Some("linear_reduced_sum"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let scatter_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("uniform_add_pipeline"),
layout: Some(&compaction_pipeline_layout),
module: &compaction_shader_module,
entry_point: Some("scatter"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
NonZeroBufferCompactor {
size,
block_count,
reduced_buffer,
sum_buffer,
count_buffer_bg_layout,
compaction_bg,
reduce_sum_pipeline,
partial_sum_pipeline,
scatter_pipeline,
}
}
pub fn total_sum_buffer(&self) -> BufferSlice<'_>
{
self.reduced_buffer
.slice(((size_of::<u32>() * self.block_count) as u64)..)
}
pub fn copy_count_to_buffer(&self, encoder: &mut CommandEncoder, target: &Buffer)
{
encoder.copy_buffer_to_buffer(
&self.reduced_buffer,
(size_of::<u32>() * self.block_count) as u64,
target,
0,
size_of::<u32>() as u64,
);
}
pub fn compact_buffer(
&self,
device: &Device,
encoder: &mut CommandEncoder,
count_buffer: &Buffer,
index_buffer: &Buffer,
compact_buffer: Option<&Buffer>,
)
{
let count_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("count_buffer_bind_group"),
layout: &self.count_buffer_bg_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: count_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: index_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: compact_buffer.unwrap_or(&count_buffer).as_entire_binding(),
},
],
});
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("buffer_compactor_compute_pass"),
timestamp_writes: None,
});
compute_pass.set_bind_group(0, &count_buffer_bind_group, &[]);
compute_pass.set_bind_group(1, &self.compaction_bg, &[]);
// Perform local running sum, then reduce
compute_pass.set_pipeline(&self.reduce_sum_pipeline);
compute_pass.dispatch_workgroups(self.block_count as u32, 1, 1);
// Partial sums are now in the reuced sum buffer. Perform linear naive runnig sum on it
compute_pass.set_pipeline(&self.partial_sum_pipeline);
compute_pass.dispatch_workgroups(1, 1, 1);
// We can now reapply the partial running sum on the subblocks
compute_pass.set_pipeline(&self.scatter_pipeline);
compute_pass.set_immediates(
0,
if compact_buffer.is_some()
{
bytes_of(&1)
}
else
{
bytes_of(&0)
},
);
compute_pass.dispatch_workgroups(self.block_count as u32, 1, 1);
}
}
+166
View File
@@ -0,0 +1,166 @@
use wgpu::Buffer;
use wgpu::CommandEncoder;
/// Provides utility object to manage indirect dispatches workgroup count computations on the GPU
/// Takes in a single u32, and computes the amount of workgroups to dispatch given a workgroup size
pub struct IndirectBuffer1D
{
/// Buffer used in the indirect dispatch command
indirect_buffer: wgpu::Buffer,
/// Buffer visible from compute shaders to compute the amount
indirect_storage: wgpu::Buffer,
indirect_storage_bind_group: wgpu::BindGroup,
bind_group_layout: wgpu::BindGroupLayout,
compute_pipeline: wgpu::ComputePipeline,
}
impl IndirectBuffer1D
{
pub fn new(device: &wgpu::Device) -> Self
{
let indirect_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("IndirectBuffer1D::indirect_buffer"),
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let indirect_storage = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("IndirectBuffer1D::indirect_storage"),
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("IndirectBuffer1D::bind_group_layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("IndirectBuffer1D::bind_group"),
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: indirect_storage.as_entire_binding(),
}],
});
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("IndirectBuffer1D::shader_module"),
source: wgpu::ShaderSource::Wgsl(
"
struct IndirectDispatchArgs
{
x: u32,
y: u32,
z: u32
}
@group(0) @binding(0) var<storage, read_write> indirect_storage: IndirectDispatchArgs;
@group(1) @binding(0) var<storage, read_write> user_count: u32;
var<immediate> workgroup_size: u32;
@compute
@workgroup_size(1, 1, 1)
fn main()
{
let workgroup_count = (user_count / workgroup_size) + select(u32(1), u32(0), user_count % workgroup_size == 0);
var args: IndirectDispatchArgs;
args.x = workgroup_count;
args.y = 1;
args.z = 1;
indirect_storage = args;
}
".into(),
),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("IndirectBuffer1D::pipeline_layout"),
bind_group_layouts: &[
// Group 0: indirect args buffer
Some(&bind_group_layout),
// Group 1: user count buffer
Some(&bind_group_layout),
],
// workgroup size
immediate_size: size_of::<u32>() as u32,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("IndirectBuffer1D::pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
Self {
indirect_buffer,
indirect_storage,
indirect_storage_bind_group: bind_group,
bind_group_layout,
compute_pipeline: pipeline,
}
}
pub fn workgroup_count(
&self,
device: &wgpu::Device,
encoder: &mut CommandEncoder,
count_buffer: &Buffer,
workgroup_size: u32,
) -> &Buffer
{
// Transient bind group
let user_count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("IndirectBuffer1D::bind_group"),
layout: &self.bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: count_buffer.as_entire_binding(),
}],
});
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("IndirectBuffer1D::compute_pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.compute_pipeline);
pass.set_bind_group(0, &self.indirect_storage_bind_group, &[]);
pass.set_bind_group(1, &user_count_bind_group, &[]);
pass.set_immediates(0, bytemuck::bytes_of(&workgroup_size));
pass.dispatch_workgroups(1, 1, 1);
}
encoder.copy_buffer_to_buffer(
&self.indirect_storage,
0,
&self.indirect_buffer,
0,
Some(self.indirect_storage.size()),
);
&self.indirect_buffer
}
}
+65
View File
@@ -0,0 +1,65 @@
// Main common gpu parallel algorithms
pub mod buffer_compactor;
pub mod indirect_buffer;
pub mod radix_sort;
pub mod top_k;
// Utilities
pub fn create_multi_buffers_bind_group_layout(
device: &wgpu::Device,
count: u32,
label: Option<&str>,
) -> wgpu::BindGroupLayout
{
let entries = (0..count)
.map(|i| wgpu::BindGroupLayoutEntry {
binding: i,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
})
.collect::<Vec<_>>();
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label,
entries: &entries,
})
}
pub fn create_multi_buffers_bind_group(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> wgpu::BindGroup
{
let entries = buffers
.iter()
.enumerate()
.map(|(i, buffer)| wgpu::BindGroupEntry {
binding: i as u32,
resource: buffer.as_entire_binding(),
})
.collect::<Vec<_>>();
device.create_bind_group(&wgpu::BindGroupDescriptor {
label,
layout,
entries: &entries,
})
}
pub fn create_multi_buffers_bg_bg_layout(
device: &wgpu::Device,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
{
let layout = create_multi_buffers_bind_group_layout(device, buffers.len() as u32, label);
let bg = create_multi_buffers_bind_group(device, &layout, buffers, label);
(layout, bg)
}
+473
View File
@@ -0,0 +1,473 @@
use std::num::NonZero;
use itertools::Itertools;
use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
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;
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum RadixSortDirection
{
Ascending,
Descending,
}
#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
struct PassParameters
{
pass_index: u32,
descending: u32,
digit_stride: u32,
}
pub struct RadixSorter
{
max_size: usize,
histogram_count: usize,
histo_block_count: usize,
histograms: Buffer,
histograms_bind_group: BindGroup,
data_bind_group_layout: BindGroupLayout,
double_buffer_keys: Buffer,
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,
}
impl RadixSorter
{
// 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
{
// 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: (histogram_count * size_of::<u32>() * Self::VALUE_COUNT) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let histograms_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("RadixSorter::histograms_bind_group_layout"),
entries: &[
// Histrograms
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let histograms_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::histograms_bind_group"),
layout: &histograms_bind_group_layout,
entries: &[
// Histrograms
wgpu::BindGroupEntry {
binding: 0,
resource: histograms.as_entire_binding(),
},
],
});
let double_buffer_keys = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::double_buffer_keys"),
size: (size_of::<u32>() * max_size) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let double_buffer_values = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::double_buffer_values"),
size: (size_of::<u32>() * max_size) as u64,
usage: BufferUsages::STORAGE,
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"),
entries: &[
// Keys
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Values
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let double_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::double_buffer_bind_group"),
layout: &data_bind_group_layout,
entries: &[
// Keys
wgpu::BindGroupEntry {
binding: 0,
resource: double_buffer_keys.as_entire_binding(),
},
// Values
wgpu::BindGroupEntry {
binding: 1,
resource: double_buffer_values.as_entire_binding(),
},
],
});
let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("RadixSorter::pipelines_layout"),
bind_group_layouts: &[
Some(&histograms_bind_group_layout),
// Double buffering :
// Source buffer
Some(&data_bind_group_layout),
// Dest buffer
Some(&data_bind_group_layout),
// Counts buffer
Some(&data_bind_group_layout),
],
immediate_size: size_of::<PassParameters>() as u32, // for the pass number
});
let radix_sort_shader_module =
device.create_shader_module(include_spirv!("../../../shaders/out/radix_sort.spv"));
let compilation_options = wgpu::PipelineCompilationOptions {
zero_initialize_workgroup_memory: false,
..Default::default()
};
let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::histogram_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("histogram_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
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("prefix_sum_pass"),
compilation_options: compilation_options.clone(),
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),
module: &radix_sort_shader_module,
entry_point: Some("scatter_pass"),
compilation_options: compilation_options.clone(),
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,
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,
histo_block_count,
histogram_count,
histograms,
histograms_bind_group,
data_bind_group_layout,
double_buffer_keys,
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,
}
}
/// Performs a radix sort on the `key` based on the `values`.
/// The keys are paired one-to-one with the values. At the end both keys and values are sorted.
/// An indirect count can be passed in `indirect` as a buffer of a single u32 on GPU.
/// A CPU side length can be passed in `direct_length`
/// `sort_direction` dictates the direction of the sort.
pub fn sort(
&self,
device: &Device,
keys: &Buffer,
values: &Buffer,
indirect: Option<&Buffer>,
direct_length: Option<usize>,
encoder: &mut CommandEncoder,
sort_direction: RadixSortDirection,
)
{
let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::data_buffer_bind_group"),
layout: &self.data_bind_group_layout,
entries: &[
// Keys
wgpu::BindGroupEntry {
binding: 0,
resource: keys.as_entire_binding(),
},
// Values
wgpu::BindGroupEntry {
binding: 1,
resource: values.as_entire_binding(),
},
],
});
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
{
direct_length.unwrap_or(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 {
query_set: &self.timing_query_set,
beginning_of_pass_write_index: Some(0),
end_of_pass_write_index: Some(1),
}),
});
for i in 0..Self::PASS_COUNT
{
let parameters = PassParameters {
pass_index: i as u32,
descending: match sort_direction
{
RadixSortDirection::Ascending => 0,
RadixSortDirection::Descending => 1,
},
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_bind_group, &[]);
// ~~ Histogram pass
compute_pass.set_pipeline(&self.histogram_pass);
compute_pass.set_immediates(0, bytes);
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);
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);
// ~~ Scatter pass
compute_pass.set_pipeline(&self.scatter_pass);
compute_pass.set_immediates(0, bytes);
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
drop(compute_pass);
encoder.resolve_query_set(&self.timing_query_set, 0..2, &self.timing_buffer, 0);
}
}
+143
View File
@@ -0,0 +1,143 @@
// Top-k selection over a dense array of u32 request counts.
//
// The Rust side prepends the following constants:
// const BIN_COUNT: u32;
// const SUB_BINS: u32;
// const LOG_SUB_BINS: u32;
// const WORKGROUP_SIZE: u32;
@group(0) @binding(0) var<storage, read> requests: array<u32>;
@group(0) @binding(1) var<storage, read_write> histogram: array<atomic<u32>>;
@group(0) @binding(2) var<storage, read_write> threshold: i32;
@group(0) @binding(3) var<storage, read_write> selected_count: atomic<u32>;
@group(0) @binding(4) var<storage, read_write> selected_indices: array<u32>;
// Threshold fill state:
// [0] = free slots for the threshold bin (k - above_count)
// [1] = threshold-bin candidates claimed so far
@group(0) @binding(5) var<storage, read_write> fill_state: array<atomic<u32>>;
struct TopKParams
{
element_count: u32,
k: u32,
}
var<immediate> params: TopKParams;
// Monotonic log-scale quantization. Counts of zero are never candidates, but
// the function is kept total so it is safe to call with any value.
fn quantize(count: u32) -> u32
{
if (count == 0u)
{
return 0u;
}
let exponent = 31u - countLeadingZeros(count);
var extra: u32;
if (exponent >= LOG_SUB_BINS)
{
extra = (count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1u);
}
else
{
extra = (count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1u);
}
return exponent * SUB_BINS + extra;
}
// Pass 1: quantize every non-zero count and accumulate the global histogram.
@compute
@workgroup_size(WORKGROUP_SIZE, 1, 1)
fn histogram_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
{
let index = global_id.x;
if (index >= params.element_count)
{
return;
}
let count = requests[index];
if (count == 0u)
{
return;
}
let bin = quantize(count);
atomicAdd(&histogram[bin], 1u);
}
// Pass 2: scan the histogram from the highest bin down until adding the
// current bin would reach k. The current bin becomes the threshold.
// A threshold of -1 means that every non-zero element is selected.
//
// `sum` is the number of elements in bins strictly above the threshold. It is
// also the number of slots already guaranteed, so the threshold bin has
// `k - sum` free slots left to fill.
@compute
@workgroup_size(1, 1, 1)
fn threshold_pass()
{
var sum: u32 = 0u;
var threshold_bin: i32 = -1;
for (var bin: u32 = BIN_COUNT; bin > 0u; bin = bin - 1u)
{
let count = atomicLoad(&histogram[bin - 1u]);
if (sum + count >= params.k)
{
threshold_bin = i32(bin - 1u);
break;
}
sum = sum + count;
}
threshold = threshold_bin;
atomicStore(&fill_state[0], params.k - min(params.k, sum));
atomicStore(&fill_state[1], 0u);
atomicStore(&selected_count, 0u);
}
// Pass 3: emit every index whose quantized bin is strictly above the
// threshold, then fill the remaining slots from the threshold bin in arbitrary
// order. Together these emit exactly `min(k, non-zero count)` indices.
@compute
@workgroup_size(WORKGROUP_SIZE, 1, 1)
fn select_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
{
let index = global_id.x;
if (index >= params.element_count)
{
return;
}
let count = requests[index];
if (count == 0u)
{
return;
}
let bin = i32(quantize(count));
if (bin > threshold)
{
// Unconditionally selected.
let slot = atomicAdd(&selected_count, 1u);
selected_indices[slot] = index;
}
else if (bin == threshold)
{
// Fill the remaining slots from the threshold bin, in arbitrary order.
let remaining = atomicLoad(&fill_state[0]);
let offset = atomicAdd(&fill_state[1], 1u);
if (offset < remaining)
{
let slot = atomicAdd(&selected_count, 1u);
selected_indices[slot] = index;
}
}
}
+718
View File
@@ -0,0 +1,718 @@
//! GPU top-k selection over a dense array of `u32` request counts.
//!
//! The selector runs three compute passes:
//! 1. Quantize every non-zero count into [`BIN_COUNT`] log-scale bins and build
//! a global histogram.
//! 2. Scan the histogram from the highest bin down until adding the current bin
//! would reach `k`, producing a threshold bin.
//! 3. Emit every index whose bin is strictly above the threshold bin, then fill
//! the remaining slots from the threshold bin.
//!
//! The number of selected elements is therefore exactly
//! `min(k, number of non-zero elements)`. Elements taken from the threshold bin
//! are chosen in arbitrary order; the caller is expected to sort the output if
//! an ordering is required.
//!
//! The output list is unordered: indices are appended with atomics.
//!
//! The selector uses shader immediates, so the device must enable
//! [`wgpu::Features::IMMEDIATES`] and expose a `max_immediate_size` of at least
//! `size_of::<TopKParams>()` (8 bytes).
use bytemuck::bytes_of;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::ShaderStages;
use wgpu::util::DeviceExt;
/// Number of quantization bins.
pub const BIN_COUNT: u32 = 256;
/// Number of sub-bins per power-of-two octave.
const SUB_BINS: u32 = BIN_COUNT / 32;
/// Number of mantissa bits kept by the quantizer.
const LOG_SUB_BINS: u32 = SUB_BINS.trailing_zeros();
/// Threads per workgroup for the histogram and selection passes.
const WORKGROUP_SIZE: u32 = 256;
const _: () = assert!(BIN_COUNT % 32 == 0);
const _: () = assert!(SUB_BINS.is_power_of_two());
/// Parameters passed to the shader through immediates.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct TopKParams
{
element_count: u32,
k: u32,
}
/// GPU top-k selector over a dense array of request counts.
///
/// The selector owns its scratch and output buffers, so a single instance
/// cannot be used for two overlapping selections. Create one instance per
/// concurrent selection, or copy the results before the next call.
pub struct TopKSelector
{
max_selected: u32,
histogram: Buffer,
threshold: Buffer,
selected_count: Buffer,
selected_indices: Buffer,
/// `[0]` free threshold-bin slots, `[1]` claimed threshold-bin candidates.
fill_state: Buffer,
bind_group_layout: BindGroupLayout,
histogram_pass: ComputePipeline,
threshold_pass: ComputePipeline,
select_pass: ComputePipeline,
}
impl TopKSelector
{
/// Creates a selector that can output at most `max_selected` indices.
pub fn new(device: &Device, max_selected: u32) -> Self
{
assert!(
device.features().contains(wgpu::Features::IMMEDIATES),
"TopKSelector requires the IMMEDIATES feature"
);
assert!(
device.limits().max_immediate_size >= size_of::<TopKParams>() as u32,
"TopKSelector requires a max_immediate_size of at least {} bytes",
size_of::<TopKParams>()
);
let histogram = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("TopKSelector::histogram"),
size: (BIN_COUNT as u64) * (size_of::<u32>() as u64),
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let threshold = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::threshold"),
contents: bytes_of(&-1i32),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
let selected_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::selected_count"),
contents: bytes_of(&0u32),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
// Avoid zero-sized buffers when `max_selected == 0`.
let selected_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("TopKSelector::selected_indices"),
size: (max_selected.max(1) as u64) * (size_of::<u32>() as u64),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
// [0] free threshold-bin slots, [1] claimed threshold-bin candidates.
// Both are reset by `threshold_pass` on every call.
let fill_state = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::fill_state"),
contents: bytemuck::cast_slice(&[0u32; 2]),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("TopKSelector::bind_group_layout"),
entries: &[
// Requests: read-only dense array of counts
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Histogram
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,
},
// Threshold bin
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Selected count
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Selected indices
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Threshold fill state
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("TopKSelector::pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: size_of::<TopKParams>() as u32,
});
// Inject the quantization constants so the Rust and WGSL sides cannot
// drift apart.
let header = format!(
"const BIN_COUNT: u32 = {}u;\n\
const SUB_BINS: u32 = {}u;\n\
const LOG_SUB_BINS: u32 = {}u;\n\
const WORKGROUP_SIZE: u32 = {}u;\n",
BIN_COUNT, SUB_BINS, LOG_SUB_BINS, WORKGROUP_SIZE
);
let mut shader_source = String::with_capacity(header.len() + 2048);
shader_source.push_str(&header);
shader_source.push_str(include_str!("./shaders/top_k.wgsl"));
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("TopKSelector::shader_module"),
source: wgpu::ShaderSource::Wgsl(shader_source.into()),
});
let compilation_options = wgpu::PipelineCompilationOptions::default();
let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("TopKSelector::histogram_pass"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("histogram_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let threshold_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("TopKSelector::threshold_pass"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("threshold_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let select_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("TopKSelector::select_pass"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("select_pass"),
compilation_options,
cache: None,
});
Self {
max_selected,
histogram,
threshold,
selected_count,
selected_indices,
fill_state,
bind_group_layout,
histogram_pass,
threshold_pass,
select_pass,
}
}
/// Runs the three top-k passes over `requests[0..element_count]`.
///
/// `k` is the requested number of elements and must not exceed the
/// `max_selected` capacity given to [`TopKSelector::new`].
///
/// After this call:
/// - [`Self::selected_count_buffer`] contains
/// `min(k, number of non-zero elements)`.
/// - [`Self::selected_indices_buffer`] contains that many indices, in an
/// arbitrary order.
/// - [`Self::threshold_buffer`] contains the threshold bin, or `-1` if all
/// non-zero elements were selected.
pub fn select(
&self,
device: &Device,
encoder: &mut CommandEncoder,
requests: &Buffer,
element_count: u32,
k: u32,
)
{
assert!(
k <= self.max_selected,
"TopKSelector: k ({k}) exceeds the max_selected capacity ({})",
self.max_selected
);
assert!(
requests.size() >= (element_count as u64) * (size_of::<u32>() as u64),
"TopKSelector: requests buffer is too small for {element_count} elements"
);
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("TopKSelector::bind_group"),
layout: &self.bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: requests.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: self.histogram.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.threshold.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: self.selected_count.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.selected_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: self.fill_state.as_entire_binding(),
},
],
});
// The histogram is rebuilt from scratch on every call.
encoder.clear_buffer(&self.histogram, 0, None);
let params = TopKParams { element_count, k };
let params_bytes = bytes_of(&params);
let workgroup_count = element_count.div_ceil(WORKGROUP_SIZE).max(1);
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("TopKSelector::select"),
timestamp_writes: None,
});
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.set_pipeline(&self.histogram_pass);
compute_pass.set_immediates(0, params_bytes);
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
compute_pass.set_pipeline(&self.threshold_pass);
compute_pass.set_immediates(0, params_bytes);
compute_pass.dispatch_workgroups(1, 1, 1);
compute_pass.set_pipeline(&self.select_pass);
compute_pass.set_immediates(0, params_bytes);
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
}
/// Number of indices emitted by the last [`Self::select`] call.
pub fn selected_count_buffer(&self) -> &Buffer
{
&self.selected_count
}
/// Indices emitted by the last [`Self::select`] call, in arbitrary order.
pub fn selected_indices_buffer(&self) -> &Buffer
{
&self.selected_indices
}
/// Threshold bin of the last [`Self::select`] call, or `-1` if every
/// non-zero element was selected.
pub fn threshold_buffer(&self) -> &Buffer
{
&self.threshold
}
/// Maximum number of indices this selector can emit.
pub fn max_selected(&self) -> u32
{
self.max_selected
}
}
#[cfg(test)]
mod tests
{
use super::*;
/// CPU mirror of the WGSL quantizer.
fn quantize_cpu(count: u32) -> u32
{
if count == 0
{
return 0;
}
let exponent = 31 - count.leading_zeros();
let extra = if exponent >= LOG_SUB_BINS
{
(count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1)
}
else
{
(count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1)
};
exponent * SUB_BINS + extra
}
/// CPU mirror of the three passes.
fn select_cpu(counts: &[u32], k: u32) -> (Vec<u32>, i32)
{
let mut histogram = vec![0u32; BIN_COUNT as usize];
for &count in counts
{
if count != 0
{
histogram[quantize_cpu(count) as usize] += 1;
}
}
let mut sum = 0u32;
let mut threshold = -1i32;
for bin in (0..BIN_COUNT as usize).rev()
{
let count = histogram[bin];
if sum + count >= k
{
threshold = bin as i32;
break;
}
sum += count;
}
let remaining = k.saturating_sub(sum);
let mut selected = counts
.iter()
.enumerate()
.filter(|&(_, &count)| count != 0 && quantize_cpu(count) as i32 > threshold)
.map(|(index, _)| index as u32)
.collect::<Vec<_>>();
// Fill the remaining slots from the threshold bin. The GPU picks these
// in arbitrary order; the CPU mirror fills them in index order so the
// tests stay deterministic.
if threshold >= 0
{
let mut slots = remaining;
for (index, &count) in counts.iter().enumerate()
{
if slots == 0
{
break;
}
if count != 0 && quantize_cpu(count) as i32 == threshold
{
selected.push(index as u32);
slots -= 1;
}
}
}
(selected, threshold)
}
fn next_random(state: &mut u64) -> u32
{
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
(*state >> 32) as u32
}
#[test]
fn quantize_is_monotonic()
{
let mut previous = 0;
for count in 1..100_000u32
{
let bin = quantize_cpu(count);
assert!(bin >= previous, "quantize({count}) = {bin} < {previous}");
assert!(bin < BIN_COUNT);
previous = bin;
}
let mut state = 0x1234_5678_9abc_def0u64;
let mut values = (0..10_000)
.map(|_| next_random(&mut state))
.collect::<Vec<_>>();
values.sort_unstable();
let mut previous = 0;
for count in values
{
let bin = quantize_cpu(count);
assert!(bin >= previous);
assert!(bin < BIN_COUNT);
previous = bin;
}
}
#[test]
fn quantize_handles_zero_and_max()
{
assert_eq!(quantize_cpu(0), 0);
assert!(quantize_cpu(u32::MAX) < BIN_COUNT);
}
#[test]
fn selection_selects_exactly_min_k_and_non_zero()
{
let mut state = 0x0ddc_0ffe_e15e_beefu64;
for _ in 0..100
{
let len = 1 + (next_random(&mut state) % 1000) as usize;
let counts = (0..len)
.map(|_| next_random(&mut state) % 64)
.collect::<Vec<_>>();
let non_zero = counts.iter().filter(|&&count| count != 0).count();
for k in 0..=20
{
let (selected, threshold) = select_cpu(&counts, k);
assert_eq!(selected.len(), (k as usize).min(non_zero));
let mut sorted = selected.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), selected.len(), "duplicate indices");
for &index in &selected
{
let count = counts[index as usize];
assert!(count != 0);
assert!(quantize_cpu(count) as i32 >= threshold);
}
}
}
}
#[test]
fn selection_fills_threshold_bin_to_exactly_k()
{
let counts = [1, 5, 3, 5, 2];
let (selected, _) = select_cpu(&counts, 3);
// The two 5s are above the threshold bin; the 3 fills the last slot.
let mut sorted = selected;
sorted.sort_unstable();
assert_eq!(sorted, vec![1, 2, 3]);
}
#[test]
fn selection_with_fewer_candidates_than_k()
{
let counts = [1, 0, 2, 0, 3];
let (selected, threshold) = select_cpu(&counts, 10);
assert_eq!(threshold, -1);
assert_eq!(selected.len(), 3);
}
#[test]
fn selection_with_k_zero()
{
let counts = [1, 2, 3];
let (selected, _) = select_cpu(&counts, 0);
assert!(selected.is_empty());
}
#[test]
fn selection_with_all_equal_counts_selects_k()
{
let counts = [7, 7, 7, 7];
let (selected, threshold) = select_cpu(&counts, 2);
// Every element is in the threshold bin, so the first two are taken.
assert_eq!(threshold, quantize_cpu(7) as i32);
assert_eq!(selected, vec![0, 1]);
}
#[test]
fn selection_with_all_zero_counts()
{
let counts = [0, 0, 0, 0];
let (selected, threshold) = select_cpu(&counts, 2);
assert_eq!(threshold, -1);
assert!(selected.is_empty());
}
#[test]
#[ignore = "requires a GPU adapter with the IMMEDIATES feature"]
fn gpu_selection_smoke_test()
{
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
.expect("no GPU adapter available");
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_features: wgpu::Features::IMMEDIATES,
required_limits: wgpu::Limits {
max_immediate_size: 112,
..Default::default()
},
..Default::default()
}))
.expect("failed to create GPU device");
let counts: [u32; 5] = [1, 5, 3, 5, 2];
let requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::test_requests"),
contents: bytemuck::cast_slice(&counts),
usage: BufferUsages::STORAGE,
});
let selector = TopKSelector::new(&device, 8);
// Run the selection twice to verify that the histogram and fill state
// are reset between calls.
for _ in 0..2
{
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("TopKSelector::test_encoder"),
});
selector.select(&device, &mut encoder, &requests, counts.len() as u32, 3);
queue.submit([encoder.finish()]);
let (count, indices) = read_selection(&device, &queue, &selector);
// The two 5s are above the threshold bin; the 3 fills the last slot.
assert_eq!(count, 3);
assert_eq!(indices, vec![1, 2, 3]);
}
// All-equal counts: the threshold bin must fill every slot.
let equal_counts: [u32; 4] = [7, 7, 7, 7];
let equal_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::test_equal_requests"),
contents: bytemuck::cast_slice(&equal_counts),
usage: BufferUsages::STORAGE,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("TopKSelector::test_encoder"),
});
selector.select(
&device,
&mut encoder,
&equal_requests,
equal_counts.len() as u32,
2,
);
queue.submit([encoder.finish()]);
let (count, indices) = read_selection(&device, &queue, &selector);
assert_eq!(count, 2);
assert_eq!(indices.len(), 2);
assert!(
indices
.iter()
.all(|&index| index < equal_counts.len() as u32)
);
}
/// Reads back the selected count and the sorted selected indices.
fn read_selection(
device: &wgpu::Device,
queue: &wgpu::Queue,
selector: &TopKSelector,
) -> (u32, Vec<u32>)
{
let count = std::sync::Arc::new(std::sync::Mutex::new(None));
let count_clone = count.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&selector.selected_count_buffer().slice(..),
move |buffer| {
let bytes = buffer.unwrap();
*count_clone.lock().unwrap() = Some(bytemuck::pod_read_unaligned::<u32>(&bytes));
},
);
let indices = std::sync::Arc::new(std::sync::Mutex::new(None));
let indices_clone = indices.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&selector.selected_indices_buffer().slice(..),
move |buffer| {
let bytes = buffer.unwrap();
*indices_clone.lock().unwrap() =
Some(bytemuck::pod_collect_to_vec::<u8, u32>(&bytes));
},
);
device
.poll(wgpu::wgt::PollType::wait_indefinitely())
.unwrap();
let count = *count.lock().unwrap().as_ref().unwrap();
let mut indices = indices.lock().unwrap().as_ref().unwrap()[0..count as usize].to_vec();
indices.sort_unstable();
(count, indices)
}
}