Skip to main content

spatialrust_gpu/kernels/
iss.rs

1use std::sync::Arc;
2
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
5use spatialrust_search::KdTree;
6use wgpu::util::DeviceExt;
7
8use crate::{GpuKdTree, GpuNeighborhoods, GpuQueryBatch, WgpuRuntime};
9
10#[repr(C)]
11#[derive(Clone, Copy, Pod, Zeroable)]
12struct Params {
13    count: u32,
14    salient_capacity: u32,
15    non_max_capacity: u32,
16    min_neighbors: u32,
17    gamma_21: f32,
18    gamma_32: f32,
19    radius: f32,
20    non_max_radius_squared: f32,
21}
22
23fn invalid() -> SpatialError {
24    SpatialError::InvalidArgument("GPU ISS requires matching input/runtime ownership, finite XYZ/extents, positive finite nonzero radius squares, finite gamma values in [0,1] and supported buffers/dispatch".to_owned())
25}
26
27fn valid_radius(radius: f32) -> bool {
28    radius.is_finite() && radius > 0.0 && (radius * radius).is_finite() && radius * radius > 0.0
29}
30
31fn plan(points: u64, limits: &wgpu::Limits) -> SpatialResult<u32> {
32    let bytes = points.checked_mul(16).ok_or_else(invalid)?;
33    let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
34    if points > u64::from(u32::MAX)
35        || bytes > bound
36        || bytes > isize::MAX as u64
37        || bound < 32
38        || limits.max_compute_workgroup_size_x < 64
39        || limits.max_compute_workgroup_size_y == 0
40        || limits.max_compute_workgroup_size_z == 0
41        || limits.max_compute_invocations_per_workgroup < 64
42        || points.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
43        || limits.max_storage_buffers_per_shader_stage < 6
44        || limits.max_bindings_per_bind_group < 7
45        || limits.max_bind_groups == 0
46        || limits.max_uniform_buffers_per_shader_stage == 0
47        || limits.max_uniform_buffer_binding_size < 32
48        || points
49            .checked_mul(16)
50            .and_then(|n| n.checked_add(32))
51            .map_or(true, |n| n > limits.max_buffer_size || n > isize::MAX as u64)
52    {
53        return Err(invalid());
54    }
55    Ok(points as u32)
56}
57
58/// Explicitly uploaded ISS positions/tree/queries, reusable on one runtime.
59/// CPU tree construction is external; subsequent search and selection run on GPU.
60pub struct GpuIssInput {
61    tree: GpuKdTree,
62    queries: GpuQueryBatch,
63    count: u32,
64    identity: Arc<()>,
65    input_identity: Arc<()>,
66    transfers: TransferStats,
67}
68
69impl GpuIssInput {
70    /// Uploads a finite CPU tree and original-order queries. The query buffer is
71    /// also the covariance position buffer: 32 bytes per point plus 32 per tree
72    /// node, with no duplicate sample upload. Finite f32 extent squares required.
73    pub fn upload(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
74        Self::upload_impl(runtime, tree, false)
75    }
76
77    /// Explicitly generates tree points and original-order query/position
78    /// records in one integer GPU pass. Host payload is 16*N + 32*M bytes,
79    /// compared with 32*N + 32*M for `upload`; device output bytes are 32*N.
80    /// No readback or completion wait. CPU partitioning, validation and node
81    /// staging remain. Removes 32*N host packing bytes, with 16*N transient
82    /// GPU input bytes beside owned outputs. Small inputs may be slower;
83    /// placement is explicit and existing ISS device requirements apply.
84    pub fn upload_with_gpu_gather(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
85        Self::upload_impl(runtime, tree, true)
86    }
87
88    fn upload_impl(runtime: &WgpuRuntime, tree: &KdTree, gpu_gather: bool) -> SpatialResult<Self> {
89        let layout = tree.layout();
90        let (x, y, z) = layout.positions();
91        let count = plan(x.len() as u64, &runtime.device().limits())?;
92        if !super::feature_validation::valid([x, y, z], None) {
93            return Err(invalid());
94        }
95        let (tree, queries) = if gpu_gather {
96            GpuKdTree::upload_and_queries_with_gpu_gather(runtime, tree)?
97        } else {
98            (GpuKdTree::upload(runtime, tree)?, GpuQueryBatch::upload_soa(runtime, [x, y, z])?)
99        };
100        let mut transfers = tree.upload_transfers();
101        transfers.record(
102            TransferDirection::HostToDevice,
103            queries.upload_transfers().host_to_device_bytes(),
104        );
105        transfers.record(
106            TransferDirection::DeviceToDevice,
107            queries.upload_transfers().device_to_device_bytes(),
108        );
109        Ok(Self {
110            tree,
111            queries,
112            count,
113            identity: runtime.profiling_identity(),
114            input_identity: Arc::new(()),
115            transfers,
116        })
117    }
118
119    /// Original point count.
120    #[must_use]
121    pub const fn point_count(&self) -> u32 {
122        self.count
123    }
124
125    /// Payload explicitly transferred at construction (zero for empty input),
126    /// including device output bytes for the GPU gather constructor.
127    #[must_use]
128    pub const fn upload_transfers(&self) -> TransferStats {
129        self.transfers
130    }
131
132    /// Computes both reusable radius graphs, including self, without readback
133    /// or a host wait. Every match is counted; selection rejects overflow.
134    pub fn neighborhoods_resident(
135        &self,
136        runtime: &WgpuRuntime,
137        salient_radius: f32,
138        non_max_radius: f32,
139        salient_capacity: u32,
140        non_max_capacity: u32,
141    ) -> SpatialResult<GpuIssNeighborhoods> {
142        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
143            || !valid_radius(salient_radius)
144            || !valid_radius(non_max_radius)
145        {
146            return Err(invalid());
147        }
148        let salient = self.tree.radius_neighbors_resident(
149            runtime,
150            &self.queries,
151            salient_radius,
152            salient_capacity,
153        )?;
154        let non_max = self.tree.radius_neighbors_resident(
155            runtime,
156            &self.queries,
157            non_max_radius,
158            non_max_capacity,
159        )?;
160        Ok(GpuIssNeighborhoods {
161            salient,
162            non_max,
163            salient_radius,
164            non_max_radius,
165            input_identity: Arc::clone(&self.input_identity),
166        })
167    }
168
169    /// Runs covariance/eigenvalue saliency then local-maximum selection in two
170    /// passes in one submission. Both graphs must be complete, even for rejected
171    /// candidates. Gamma values must be finite in [0,1]; min_neighbors includes
172    /// self. Equal computed maxima all survive. No payload transfer or host wait.
173    /// GPU f32 arithmetic can change threshold/NMS decisions versus CPU f64.
174    /// Nonzero local extents whose f32 square is subnormal/zero invalidate the
175    /// result with numerical status rather than evaluating underflowed covariance.
176    /// Bad graph status invalidates and zeros ALL scores/flags; GPU consumers
177    /// must check status and explicit download rejects invalid output.
178    pub fn keypoints_resident(
179        &self,
180        runtime: &WgpuRuntime,
181        neighbors: &GpuIssNeighborhoods,
182        gamma_21: f32,
183        gamma_32: f32,
184        min_neighbors: u32,
185    ) -> SpatialResult<GpuIssKeypoints> {
186        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
187            || !Arc::ptr_eq(&self.input_identity, &neighbors.input_identity)
188            || [gamma_21, gamma_32].iter().any(|g| !g.is_finite() || !(0.0..=1.0).contains(g))
189        {
190            return Err(invalid());
191        }
192        plan(u64::from(self.count), &runtime.device().limits())?;
193        let create = |label, size| {
194            runtime.device().create_buffer(&wgpu::BufferDescriptor {
195                label: Some(label),
196                size,
197                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
198                mapped_at_creation: false,
199            })
200        };
201        let result = GpuIssKeypoints {
202            scores: create("iss-eigenvalues", (u64::from(self.count) * 16).max(16)),
203            flags: create("iss-selection", (u64::from(self.count) * 4).max(4)),
204            status: create("iss-status", 32),
205            count: self.count,
206            identity: Arc::clone(&self.identity),
207        };
208        if self.count == 0 {
209            return Ok(result);
210        }
211        let cache = runtime.iss_pipelines.get_or_init(|| IssPipelines::new(runtime.device()));
212        let params = Params {
213            count: self.count,
214            salient_capacity: neighbors.salient.capacity(),
215            non_max_capacity: neighbors.non_max.capacity(),
216            min_neighbors,
217            gamma_21,
218            gamma_32,
219            radius: neighbors.salient_radius,
220            non_max_radius_squared: neighbors.non_max_radius * neighbors.non_max_radius,
221        };
222        let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
223            label: Some("iss-params"),
224            contents: bytemuck::bytes_of(&params),
225            usage: wgpu::BufferUsages::UNIFORM,
226        });
227        let buffers = [
228            &uniform,
229            self.queries.buffer().unwrap(),
230            neighbors.salient.buffer(),
231            neighbors.non_max.buffer(),
232            &result.scores,
233            &result.flags,
234            &result.status,
235        ];
236        let entries: Vec<_> = buffers
237            .iter()
238            .enumerate()
239            .map(|(binding, buffer)| wgpu::BindGroupEntry {
240                binding: binding as u32,
241                resource: buffer.as_entire_binding(),
242            })
243            .collect();
244        let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
245            label: Some("iss-bindings"),
246            layout: &cache.layout,
247            entries: &entries,
248        });
249        let mut encoder = runtime.device().create_command_encoder(&Default::default());
250        for pipeline in [&cache.saliency, &cache.selection] {
251            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
252                label: Some("iss-compute"),
253                timestamp_writes: None,
254            });
255            pass.set_pipeline(pipeline);
256            pass.set_bind_group(0, &group, &[]);
257            pass.dispatch_workgroups(self.count.div_ceil(64), 1, 1);
258        }
259        runtime.queue().submit(Some(encoder.finish()));
260        Ok(result)
261    }
262}
263
264/// Two radius graphs tied to exactly one immutable uploaded ISS input.
265pub struct GpuIssNeighborhoods {
266    salient: GpuNeighborhoods,
267    non_max: GpuNeighborhoods,
268    salient_radius: f32,
269    non_max_radius: f32,
270    input_identity: Arc<()>,
271}
272impl GpuIssNeighborhoods {
273    /// Covariance radius graph. Treat exposed storage as immutable.
274    #[must_use]
275    pub fn salient_rows(&self) -> &GpuNeighborhoods {
276        &self.salient
277    }
278    /// Non-maximum-suppression graph. Treat exposed storage as immutable.
279    #[must_use]
280    pub fn non_max_rows(&self) -> &GpuNeighborhoods {
281        &self.non_max
282    }
283}
284
285/// Owned resident ISS selection flags, eigenvalue/eligibility rows and validity
286/// status. No result storage is pooled. Custom consumers must inspect status.
287pub struct GpuIssKeypoints {
288    scores: wgpu::Buffer,
289    flags: wgpu::Buffer,
290    status: wgpu::Buffer,
291    count: u32,
292    identity: Arc<()>,
293}
294impl GpuIssKeypoints {
295    /// Original-order u32 flags (0 or 1), with 4 unused bytes for empty input.
296    #[must_use]
297    pub fn buffer(&self) -> &wgpu::Buffer {
298        &self.flags
299    }
300    /// Original-order vec4<f32>: ascending eigenvalues and eligibility (0 or 1).
301    /// Rejected ratio tests still expose eigenvalues; insufficient support is
302    /// zero. Empty input has 16 unused bytes. Invalid graph output is all zero.
303    #[must_use]
304    pub fn scores_buffer(&self) -> &wgpu::Buffer {
305        &self.scores
306    }
307    /// Eight u32 words: bad salient rows, bad NMS rows, required salient/NMS
308    /// capacity, malformed rows, last bad row plus one, numerical errors, reserved.
309    /// All zero means valid output. Consumers must reject any nonzero status.
310    #[must_use]
311    pub fn status_buffer(&self) -> &wgpu::Buffer {
312        &self.status
313    }
314    /// Original point/flag count.
315    #[must_use]
316    pub const fn point_count(&self) -> u32 {
317        self.count
318    }
319    /// Explicit flag/status readback payload; scores are not downloaded.
320    #[must_use]
321    pub const fn readback_bytes(&self) -> u64 {
322        if self.count == 0 {
323            0
324        } else {
325            self.count as u64 * 4 + 32
326        }
327    }
328    /// Explicitly downloads flags/status and returns ascending original indices.
329    /// Waits for completion; malformed/incomplete graphs reject before decoding.
330    /// Payload is 4 bytes per input point plus 32 status bytes, empty input zero.
331    /// CPU ordered flag compaction occurs here; no neighborhood/eigen readback.
332    pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<(Vec<u32>, TransferStats)> {
333        self.readback(runtime, false, |words| {
334            if words.iter().any(|&v| v > 1) {
335                return Err(invalid());
336            }
337            Ok(words
338                .iter()
339                .enumerate()
340                .filter_map(|(i, &flag)| (flag == 1).then_some(i as u32))
341                .collect())
342        })
343    }
344
345    /// Explicitly downloads eigenvalue/eligibility rows and status for diagnostics.
346    /// This separate opt-in transfer costs 16 bytes per point plus 32 status
347    /// bytes (empty input zero); the ordinary selection API does not call it.
348    /// Waits for completion and rejects invalid status/nonfinite or unsorted rows.
349    pub fn download_scores(
350        &self,
351        runtime: &WgpuRuntime,
352    ) -> SpatialResult<(Vec<[f32; 4]>, TransferStats)> {
353        self.readback(runtime, true, |words| {
354            let mut rows = Vec::with_capacity(self.count as usize);
355            for row in words.chunks_exact(4) {
356                let values: [f32; 4] = std::array::from_fn(|i| f32::from_bits(row[i]));
357                if values.iter().any(|v| !v.is_finite())
358                    || values[0] > values[1]
359                    || values[1] > values[2]
360                    || (values[3] != 0.0 && values[3] != 1.0)
361                {
362                    return Err(invalid());
363                }
364                rows.push(values);
365            }
366            Ok(rows)
367        })
368    }
369
370    fn readback<T: Default>(
371        &self,
372        runtime: &WgpuRuntime,
373        scores: bool,
374        decode: impl FnOnce(&[u32]) -> SpatialResult<T>,
375    ) -> SpatialResult<(T, TransferStats)> {
376        if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
377            return Err(invalid());
378        }
379        if self.count == 0 {
380            return Ok((T::default(), TransferStats::default()));
381        }
382        let bytes = u64::from(self.count) * if scores { 16 } else { 4 };
383        let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
384            label: Some("iss-readback"),
385            size: bytes + 32,
386            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
387            mapped_at_creation: false,
388        });
389        let mut encoder = runtime.device().create_command_encoder(&Default::default());
390        encoder.copy_buffer_to_buffer(
391            if scores { &self.scores } else { &self.flags },
392            0,
393            &staging,
394            0,
395            bytes,
396        );
397        encoder.copy_buffer_to_buffer(&self.status, 0, &staging, bytes, 32);
398        runtime.queue().submit(Some(encoder.finish()));
399        let slice = staging.slice(..);
400        let (sender, receiver) = std::sync::mpsc::channel();
401        slice.map_async(wgpu::MapMode::Read, move |r| {
402            let _ = sender.send(r);
403        });
404        runtime.device().poll(wgpu::Maintain::Wait);
405        receiver
406            .recv()
407            .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
408            .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
409        let mapped = slice.get_mapped_range();
410        let words: &[u32] = bytemuck::cast_slice(&mapped);
411        let payload_words = bytes as usize / 4;
412        let status = &words[payload_words..];
413        let decoded = if status.iter().any(|&v| v != 0) {
414            Err(SpatialError::InvalidArgument(format!("GPU ISS rejected incomplete/malformed neighborhoods or numerical output; status={status:?}")))
415        } else {
416            decode(&words[..payload_words])
417        };
418        drop(mapped);
419        staging.unmap();
420        let mut transfers = TransferStats::default();
421        transfers.record(TransferDirection::DeviceToHost, bytes + 32);
422        Ok((decoded?, transfers))
423    }
424}
425
426pub(crate) struct IssPipelines {
427    layout: wgpu::BindGroupLayout,
428    saliency: wgpu::ComputePipeline,
429    selection: wgpu::ComputePipeline,
430}
431impl IssPipelines {
432    fn new(device: &wgpu::Device) -> Self {
433        let entries: Vec<_> = (0..7)
434            .map(|binding| wgpu::BindGroupLayoutEntry {
435                binding,
436                visibility: wgpu::ShaderStages::COMPUTE,
437                ty: wgpu::BindingType::Buffer {
438                    ty: if binding == 0 {
439                        wgpu::BufferBindingType::Uniform
440                    } else {
441                        wgpu::BufferBindingType::Storage { read_only: binding < 4 }
442                    },
443                    has_dynamic_offset: false,
444                    min_binding_size: None,
445                },
446                count: None,
447            })
448            .collect();
449        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
450            label: Some("iss-layout"),
451            entries: &entries,
452        });
453        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
454            label: Some("iss-layout"),
455            bind_group_layouts: &[&layout],
456            push_constant_ranges: &[],
457        });
458        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
459            label: Some("iss-shader"),
460            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/iss.wgsl").into()),
461        });
462        let create = |entry| {
463            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
464                label: Some("iss-pipeline"),
465                layout: Some(&pipeline_layout),
466                module: &shader,
467                entry_point: Some(entry),
468                compilation_options: Default::default(),
469                cache: None,
470            })
471        };
472        Self { saliency: create("build_saliency"), selection: create("select_keypoints"), layout }
473    }
474}
475
476#[cfg(all(test, not(target_arch = "wasm32")))]
477#[path = "iss_tests.rs"]
478mod tests;
479
480#[cfg(all(test, not(target_arch = "wasm32")))]
481#[path = "iss_soa_upload_reference.rs"]
482pub(crate) mod soa_upload_reference;
483
484#[cfg(all(test, not(target_arch = "wasm32")))]
485#[path = "iss_validation_reference.rs"]
486pub(crate) mod validation_reference;