From 6dedbbdb750ba88f3fcc433e19692f106d4d6ec4 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Sun, 8 Nov 2026 01:59:07 +0100 Subject: [PATCH] Now selecting exactly K in top-k selection --- src/gpu/shaders/top_k.wgsl | 32 +++++++-- src/gpu/top_k.rs | 133 ++++++++++++++++++++++++++++++------- 2 files changed, 136 insertions(+), 29 deletions(-) diff --git a/src/gpu/shaders/top_k.wgsl b/src/gpu/shaders/top_k.wgsl index b962dba..cddd317 100644 --- a/src/gpu/shaders/top_k.wgsl +++ b/src/gpu/shaders/top_k.wgsl @@ -12,6 +12,11 @@ @group(0) @binding(3) var selected_count: atomic; @group(0) @binding(4) var selected_indices: array; +// 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 fill_state: array>; + struct TopKParams { element_count: u32, @@ -68,6 +73,10 @@ fn histogram_pass(@builtin(global_invocation_id) global_id: vec3) // 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() @@ -89,11 +98,14 @@ fn threshold_pass() } 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 the indices whose quantized bin is strictly above the -// threshold. The order of the output list is arbitrary. +// 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) @@ -110,10 +122,22 @@ fn select_pass(@builtin(global_invocation_id) global_id: vec3) return; } - let bin = quantize(count); - if (i32(bin) > threshold) + 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; + } + } } diff --git a/src/gpu/top_k.rs b/src/gpu/top_k.rs index 38c8298..c589f8e 100644 --- a/src/gpu/top_k.rs +++ b/src/gpu/top_k.rs @@ -5,13 +5,13 @@ //! 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 the indices of the elements whose bin is strictly above the -//! 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 at most `k` (in practice it is -//! strictly less than `k` when `k > 0`, because the whole threshold bin is -//! excluded). The threshold bin and the selected count are exposed so a later -//! pass can fill the remaining slots to reach exactly `k`. +//! 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. //! @@ -66,6 +66,8 @@ pub struct TopKSelector 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, @@ -115,6 +117,14 @@ impl TopKSelector 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: &[ @@ -173,6 +183,17 @@ impl TopKSelector }, 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, + }, ], }); @@ -236,6 +257,7 @@ impl TopKSelector threshold, selected_count, selected_indices, + fill_state, bind_group_layout, histogram_pass, threshold_pass, @@ -249,7 +271,8 @@ impl TopKSelector /// `max_selected` capacity given to [`TopKSelector::new`]. /// /// After this call: - /// - [`Self::selected_count_buffer`] contains the number of emitted indices. + /// - [`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 @@ -297,6 +320,10 @@ impl TopKSelector binding: 4, resource: self.selected_indices.as_entire_binding(), }, + wgpu::BindGroupEntry { + binding: 5, + resource: self.fill_state.as_entire_binding(), + }, ], }); @@ -408,12 +435,35 @@ mod tests sum += count; } - let selected = counts + 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(); + .collect::>(); + + // 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) } @@ -463,7 +513,7 @@ mod tests } #[test] - fn selection_never_exceeds_k() + fn selection_selects_exactly_min_k_and_non_zero() { let mut state = 0x0ddc_0ffe_e15e_beefu64; @@ -474,11 +524,13 @@ mod tests .map(|_| next_random(&mut state) % 64) .collect::>(); + let non_zero = counts.iter().filter(|&&count| count != 0).count(); + for k in 0..=20 { let (selected, threshold) = select_cpu(&counts, k); - assert!(selected.len() <= k as usize); + assert_eq!(selected.len(), (k as usize).min(non_zero)); let mut sorted = selected.clone(); sorted.sort_unstable(); @@ -489,22 +541,22 @@ mod tests { let count = counts[index as usize]; assert!(count != 0); - assert!(quantize_cpu(count) as i32 > threshold); + assert!(quantize_cpu(count) as i32 >= threshold); } } } } #[test] - fn selection_excludes_the_threshold_bin() + 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 is in the threshold - // bin and is therefore excluded. - assert_eq!(selected.len(), 2); - assert!(selected.iter().all(|&index| counts[index as usize] == 5)); + // 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] @@ -527,12 +579,14 @@ mod tests } #[test] - fn selection_with_all_equal_counts_selects_nothing() + fn selection_with_all_equal_counts_selects_k() { let counts = [7, 7, 7, 7]; - let (selected, _) = select_cpu(&counts, 2); + let (selected, threshold) = select_cpu(&counts, 2); - assert!(selected.is_empty()); + // 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] @@ -572,8 +626,8 @@ mod tests let selector = TopKSelector::new(&device, 8); - // Run the selection twice to verify that the histogram is cleared and - // `selected_count` is reset between calls. + // 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 { @@ -584,10 +638,39 @@ mod tests let (count, indices) = read_selection(&device, &queue, &selector); - // The two 5s are above the threshold bin, which contains the 3. - assert_eq!(count, 2); - assert_eq!(indices, vec![1, 3]); + // 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.