Skip to main content

threecrate_gpu/
nearest_neighbor.rs

1//! GPU-accelerated nearest neighbor search
2
3use crate::device::workgroup_grid;
4use crate::spatial::{vec4s, GpuKdTree, KD_TREE_WGSL, MAX_K};
5use crate::GpuContext;
6use bytemuck::{Pod, Zeroable};
7use threecrate_core::{Point3f, Result};
8
9/// Parameters for nearest neighbor search
10#[repr(C)]
11#[derive(Copy, Clone, Pod, Zeroable)]
12pub struct NearestNeighborParams {
13    pub num_points: u32,
14    pub k_neighbors: u32,
15    pub max_distance: f32,
16    pub _padding: u32,
17}
18
19/// GPU representation of a point for nearest neighbor search
20#[repr(C)]
21#[derive(Copy, Clone, Pod, Zeroable)]
22#[repr(align(16))]
23pub struct GpuPoint {
24    pub position: [f32; 3],
25    pub _padding: f32,
26}
27
28/// Result of nearest neighbor search
29#[repr(C)]
30#[derive(Copy, Clone, Pod, Zeroable)]
31pub struct NeighborResult {
32    pub index: u32,
33    pub distance: f32,
34    pub _padding: [u32; 2],
35}
36
37/// k-NN kernel: one invocation per query point, walking the GPU kd-tree.
38fn knn_shader() -> String {
39    format!(
40        "{}{}",
41        KD_TREE_WGSL,
42        r#"
43struct KnnParams {
44    num_queries: u32,
45    k: u32,
46    limit_sq: f32,
47    _pad: u32,
48}
49
50@group(0) @binding(1) var<storage, read> queries: array<vec4<f32>>;
51// k slots per query: (original point index, distance bits). Unused slots have
52// index NO_NODE.
53@group(0) @binding(2) var<storage, read_write> results: array<vec2<u32>>;
54@group(0) @binding(3) var<uniform> params: KnnParams;
55
56@compute @workgroup_size(64)
57fn knn(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {
58    let q = gid.x + gid.y * nwg.x * 64u;
59    if (q >= params.num_queries) {
60        return;
61    }
62    find_k_nearest(queries[q].xyz, params.k, params.limit_sq);
63    let base = q * params.k;
64    for (var i = 0u; i < params.k; i++) {
65        if (i < knn_count) {
66            results[base + i] = vec2<u32>(nodes[knn_node[i]].index, bitcast<u32>(sqrt(knn_dist[i])));
67        } else {
68            results[base + i] = vec2<u32>(NO_NODE, 0u);
69        }
70    }
71}
72"#
73    )
74}
75
76impl GpuContext {
77    /// GPU-accelerated k-nearest neighbor search.
78    ///
79    /// Builds a kd-tree over `points` once, uploads it, and answers every query
80    /// on the GPU by walking the tree. Returns, for each query, up to `k`
81    /// `(point index, distance)` pairs closer than `max_distance`, closest
82    /// first. `k` is clamped to 1..=32.
83    pub async fn find_k_nearest_neighbors(
84        &self,
85        points: &[Point3f],
86        query_points: &[Point3f],
87        k: usize,
88        max_distance: f32,
89    ) -> Result<Vec<Vec<(usize, f32)>>> {
90        if points.is_empty() || query_points.is_empty() {
91            return Ok(vec![Vec::new(); query_points.len()]);
92        }
93        let k = k.clamp(1, MAX_K);
94
95        let tree = GpuKdTree::new(self, points)?;
96        if tree.is_empty() {
97            return Ok(vec![Vec::new(); query_points.len()]);
98        }
99
100        let queries = self.create_buffer_init(
101            "kNN Queries",
102            &vec4s(&tree.frame.points_to_local(query_points)),
103            wgpu::BufferUsages::STORAGE,
104        );
105        let results = self.create_buffer(
106            "kNN Results",
107            (query_points.len() * k * std::mem::size_of::<[u32; 2]>()) as u64,
108            wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
109        );
110        let params = KnnParams {
111            num_queries: query_points.len() as u32,
112            k: k as u32,
113            // Negative means nothing matches, as with the old brute-force
114            // search (squaring it would turn it into a valid range).
115            limit_sq: if max_distance < 0.0 {
116                0.0
117            } else {
118                max_distance * max_distance
119            },
120            _pad: 0,
121        };
122        let params_buffer =
123            self.create_buffer_init("kNN Params", &[params], wgpu::BufferUsages::UNIFORM);
124
125        let pipeline = self.cached_pipeline(&self.pipelines.knn, "kNN", knn_shader, "knn");
126        let bind_group = self.create_bind_group(
127            "kNN",
128            &pipeline.get_bind_group_layout(0),
129            &[
130                wgpu::BindGroupEntry {
131                    binding: 0,
132                    resource: tree.nodes.as_entire_binding(),
133                },
134                wgpu::BindGroupEntry {
135                    binding: 1,
136                    resource: queries.as_entire_binding(),
137                },
138                wgpu::BindGroupEntry {
139                    binding: 2,
140                    resource: results.as_entire_binding(),
141                },
142                wgpu::BindGroupEntry {
143                    binding: 3,
144                    resource: params_buffer.as_entire_binding(),
145                },
146            ],
147        );
148
149        let mut encoder = self
150            .device
151            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("kNN") });
152        {
153            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
154                label: Some("kNN"),
155                timestamp_writes: None,
156            });
157            pass.set_pipeline(pipeline);
158            pass.set_bind_group(0, &bind_group, &[]);
159            let (x, y) = workgroup_grid(query_points.len().div_ceil(64));
160            pass.dispatch_workgroups(x, y, 1);
161        }
162        self.queue.submit(std::iter::once(encoder.finish()));
163
164        let raw: Vec<[u32; 2]> = self.read_buffer(&results)?;
165        Ok(raw
166            .chunks_exact(k)
167            .map(|slots| {
168                slots
169                    .iter()
170                    .take_while(|slot| slot[0] != u32::MAX)
171                    .map(|slot| (slot[0] as usize, f32::from_bits(slot[1])))
172                    .collect()
173            })
174            .collect())
175    }
176}
177
178/// Uniform block of the k-NN kernel (`KnnParams` in WGSL).
179#[repr(C)]
180#[derive(Copy, Clone, Pod, Zeroable)]
181struct KnnParams {
182    num_queries: u32,
183    k: u32,
184    limit_sq: f32,
185    _pad: u32,
186}
187
188/// GPU-accelerated nearest neighbor search for single query point
189pub async fn gpu_find_k_nearest(
190    gpu_context: &GpuContext,
191    points: &[Point3f],
192    query: &Point3f,
193    k: usize,
194) -> Result<Vec<(usize, f32)>> {
195    let results = gpu_context
196        .find_k_nearest_neighbors(points, &[*query], k, f32::INFINITY)
197        .await?;
198    Ok(results.into_iter().next().unwrap_or_default())
199}
200
201/// GPU-accelerated nearest neighbor search for multiple query points
202pub async fn gpu_find_k_nearest_batch(
203    gpu_context: &GpuContext,
204    points: &[Point3f],
205    query_points: &[Point3f],
206    k: usize,
207) -> Result<Vec<Vec<(usize, f32)>>> {
208    gpu_context
209        .find_k_nearest_neighbors(points, query_points, k, f32::INFINITY)
210        .await
211}
212
213/// GPU-accelerated radius-based nearest neighbor search
214pub async fn gpu_find_radius_neighbors(
215    gpu_context: &GpuContext,
216    points: &[Point3f],
217    query: &Point3f,
218    radius: f32,
219) -> Result<Vec<(usize, f32)>> {
220    let results = gpu_context
221        .find_k_nearest_neighbors(points, &[*query], 32, radius)
222        .await?;
223    Ok(results.into_iter().next().unwrap_or_default())
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use crate::device::GpuContext;
230    use approx::assert_relative_eq;
231    use threecrate_core::Point3f;
232
233    /// Try to create a GPU context, return None if not available
234    async fn try_create_gpu_context() -> Option<GpuContext> {
235        match GpuContext::new().await {
236            Ok(gpu) => Some(gpu),
237            Err(_) => {
238                println!("⚠️  GPU not available, skipping GPU-dependent test");
239                None
240            }
241        }
242    }
243
244    /// Create a simple test point cloud
245    fn create_test_points() -> Vec<Point3f> {
246        vec![
247            Point3f::new(0.0, 0.0, 0.0),
248            Point3f::new(1.0, 0.0, 0.0),
249            Point3f::new(0.0, 1.0, 0.0),
250            Point3f::new(0.0, 0.0, 1.0),
251            Point3f::new(1.0, 1.0, 1.0),
252        ]
253    }
254
255    #[test]
256    fn test_gpu_nearest_neighbor_single() {
257        pollster::block_on(async {
258            let Some(gpu) = try_create_gpu_context().await else {
259                return;
260            };
261
262            let points = create_test_points();
263            let query = Point3f::new(0.1, 0.1, 0.1);
264
265            let neighbors = gpu_find_k_nearest(&gpu, &points, &query, 3).await.unwrap();
266
267            assert_eq!(neighbors.len(), 3);
268            assert_eq!(neighbors[0].0, 0); // Closest should be origin
269            assert!(neighbors[0].1 < 0.2); // Distance should be small
270
271            println!("✓ GPU single nearest neighbor test passed");
272        });
273    }
274
275    #[test]
276    fn test_gpu_nearest_neighbor_batch() {
277        pollster::block_on(async {
278            let Some(gpu) = try_create_gpu_context().await else {
279                return;
280            };
281
282            let points = create_test_points();
283            let queries = vec![Point3f::new(0.1, 0.1, 0.1), Point3f::new(0.9, 0.1, 0.1)];
284
285            let results = gpu_find_k_nearest_batch(&gpu, &points, &queries, 2)
286                .await
287                .unwrap();
288
289            assert_eq!(results.len(), 2);
290            assert_eq!(results[0].len(), 2);
291            assert_eq!(results[1].len(), 2);
292
293            // First query should find origin as closest
294            assert_eq!(results[0][0].0, 0);
295
296            // Second query should find (1,0,0) as closest
297            assert_eq!(results[1][0].0, 1);
298
299            println!("✓ GPU batch nearest neighbor test passed");
300        });
301    }
302
303    #[test]
304    fn test_gpu_radius_neighbors() {
305        pollster::block_on(async {
306            let Some(gpu) = try_create_gpu_context().await else {
307                return;
308            };
309
310            let points = create_test_points();
311            let query = Point3f::new(0.0, 0.0, 0.0);
312            let radius = 1.5;
313
314            let neighbors = gpu_find_radius_neighbors(&gpu, &points, &query, radius)
315                .await
316                .unwrap();
317
318            // Should find points within radius
319            assert!(!neighbors.is_empty());
320
321            // All distances should be within radius
322            for (_, distance) in &neighbors {
323                assert!(*distance <= radius);
324            }
325
326            println!(
327                "✓ GPU radius neighbors test passed: {} neighbors found",
328                neighbors.len()
329            );
330        });
331    }
332
333    #[test]
334    fn test_gpu_knn_matches_cpu_kd_tree() {
335        use threecrate_algorithms::KdTree;
336        use threecrate_core::NearestNeighborSearch;
337
338        pollster::block_on(async {
339            let Some(gpu) = try_create_gpu_context().await else {
340                return;
341            };
342
343            // Deterministic pseudo-random cloud, offset from the origin
344            let mut state = 12345u32;
345            let mut next = || {
346                state = state.wrapping_mul(1664525).wrapping_add(1013904223);
347                (state >> 8) as f32 / (1u32 << 24) as f32
348            };
349            let points: Vec<Point3f> = (0..20_000)
350                .map(|_| Point3f::new(100.0 + 20.0 * next(), -50.0 + 20.0 * next(), 5.0 * next()))
351                .collect();
352            let queries = &points[..2_000];
353            let k = 10;
354
355            let gpu_results = gpu_find_k_nearest_batch(&gpu, &points, queries, k)
356                .await
357                .unwrap();
358            let tree = KdTree::new(&points).unwrap();
359
360            for (query, gpu_neighbors) in queries.iter().zip(&gpu_results) {
361                let cpu_neighbors = tree.find_k_nearest(query, k);
362                assert_eq!(gpu_neighbors.len(), k);
363                for (g, c) in gpu_neighbors.iter().zip(&cpu_neighbors) {
364                    assert!((g.1 - c.1).abs() < 1e-3, "gpu {:?} vs cpu {:?}", g, c);
365                }
366            }
367        });
368    }
369
370    #[test]
371    fn test_gpu_negative_max_distance_matches_nothing() {
372        pollster::block_on(async {
373            let Some(gpu) = try_create_gpu_context().await else {
374                return;
375            };
376            let points = create_test_points();
377            let results = gpu
378                .find_k_nearest_neighbors(&points, &[Point3f::origin()], 3, -1.0)
379                .await
380                .unwrap();
381            assert!(results[0].is_empty());
382        });
383    }
384
385    #[test]
386    fn test_gpu_nearest_neighbor_accuracy() {
387        pollster::block_on(async {
388            let Some(gpu) = try_create_gpu_context().await else {
389                return;
390            };
391
392            let points = create_test_points();
393            let query = Point3f::new(0.5, 0.5, 0.5);
394
395            let neighbors = gpu_find_k_nearest(&gpu, &points, &query, 1).await.unwrap();
396
397            assert_eq!(neighbors.len(), 1);
398
399            // Manually verify the nearest neighbor
400            let min_dist = points
401                .iter()
402                .map(|p| (query - *p).magnitude())
403                .fold(f32::INFINITY, f32::min);
404
405            // Every point here is equally far from the query, so any of them is
406            // a correct answer; check the returned one is at the minimum.
407            let (index, distance) = neighbors[0];
408            assert_relative_eq!(
409                (query - points[index]).magnitude(),
410                min_dist,
411                epsilon = 0.001
412            );
413            assert_relative_eq!(distance, min_dist, epsilon = 0.001);
414
415            println!("✓ GPU nearest neighbor accuracy test passed");
416        });
417    }
418}