Skip to main content

spatialrust_gpu/kernels/
gicp_covariances.rs

1use super::{invalid, plan, GpuGicpInput};
2use crate::{GpuIcpInput, GpuKdTree, WgpuRuntime, MAX_GPU_K_NEIGHBORS};
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialResult, TransferDirection};
5use spatialrust_search::KdTree;
6use wgpu::util::DeviceExt;
7
8#[repr(C)]
9#[derive(Clone, Copy, Pod, Zeroable)]
10struct Params {
11    sources: u32,
12    targets: u32,
13    neighbors: u32,
14    epsilon: f32,
15    radius_squared: f32,
16    radius_mode: u32,
17    padding: [u32; 2],
18}
19
20#[derive(Clone, Copy)]
21enum Preparation {
22    Knn(u32),
23    Radius { radius: f32, capacity: u32 },
24}
25
26fn covariance_plan(
27    source: u64,
28    target: u64,
29    k: u32,
30    epsilon: f32,
31    limits: &wgpu::Limits,
32) -> SpatialResult<u64> {
33    if !(3..=MAX_GPU_K_NEIGHBORS).contains(&k) {
34        return Err(invalid());
35    }
36    bounded_covariance_plan(source, target, k, epsilon, limits)
37}
38
39fn bounded_covariance_plan(
40    source: u64,
41    target: u64,
42    capacity: u32,
43    epsilon: f32,
44    limits: &wgpu::Limits,
45) -> SpatialResult<u64> {
46    if source == 0 || target == 0 || capacity == 0 || !(1e-4..=1.0).contains(&epsilon) {
47        return Err(invalid());
48    }
49    let total = source.checked_add(target).and_then(|v| v.checked_add(1)).ok_or_else(invalid)?;
50    plan(source, total, limits)?;
51    let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
52    let stride = 8 + 8 * u64::from(capacity);
53    for count in [source, target] {
54        if count > u64::from(u32::MAX)
55            || count.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
56            || count
57                .checked_mul(stride)
58                .map_or(true, |v| v > bound || v / 4 > u64::from(u32::MAX) || v > isize::MAX as u64)
59        {
60            return Err(invalid());
61        }
62    }
63    if (total - 1).div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
64        || total.checked_mul(8).map_or(true, |v| v > u64::from(u32::MAX))
65    {
66        return Err(invalid());
67    }
68    Ok(total * 32)
69}
70
71fn valid_radius(radius: f32) -> bool {
72    radius.is_finite() && radius > 0.0 && (radius * radius).is_normal()
73}
74
75impl GpuGicpInput {
76    /// Explicitly uploads finite source/target trees and original-order positions,
77    /// then computes both k-NN plane-regularized covariances entirely on GPU.
78    /// Query positions and target tree are shared with the registration passes.
79    /// Payload upload is 32*(S+T) + 32*(source_nodes+target_nodes) bytes; no
80    /// neighborhoods/covariances are downloaded or re-uploaded. Three submissions
81    /// prepare bounded neighborhoods, covariance eigenvectors and global status,
82    /// without a host wait. Prepared covariance rows remain owned by this input.
83    /// Both trees must be nonempty; k=3..=64 and epsilon=1e-4..=1 are supported.
84    /// Eigenvectors use centered/scaled compensated f32 covariance and the CPU
85    /// 32-step/physical 1e-12 Jacobi stopping convention. f32 arithmetic, ties,
86    /// repeated eigenvalues and CPU raw-product rounding can change covariances.
87    /// Invalid preparation makes ALL subsequent equation downloads fail (status
88    /// bit 16); no CPU fallback occurs. CPU tree construction is external.
89    pub fn upload_with_gpu_covariances(
90        runtime: &WgpuRuntime,
91        source: &KdTree,
92        target: &KdTree,
93        k: u32,
94        epsilon: f32,
95    ) -> SpatialResult<Self> {
96        Self::upload_prepared(runtime, source, target, Preparation::Knn(k), epsilon)
97    }
98
99    /// Uploads original positions/trees and prepares complete inclusive radius
100    /// neighborhoods and plane covariances on GPU, without payload readback.
101    /// `capacity` is a positive per-point bound, including self and duplicates.
102    /// Overflow invalidates both covariance sets and every equation download;
103    /// rows are never silently truncated. Radius must be finite/positive with
104    /// a normal f32 square; epsilon must be in 1e-4..=1.
105    /// Fewer than three neighbors use epsilon*I, as in the existing grid route.
106    /// Other rows use centered/scaled compensated sums and 32 max-pivot Jacobi
107    /// steps with physical 1e-20 stopping on the unnormalized central sum.
108    /// f32 arithmetic, traversal order and repeated eigenvalues can differ
109    /// from the legacy grid's raw means and 16 three-pivot sweeps.
110    /// Transfers, ownership and CPU solve boundaries match the k-NN method.
111    pub fn upload_with_gpu_radius_covariances(
112        runtime: &WgpuRuntime,
113        source: &KdTree,
114        target: &KdTree,
115        radius: f32,
116        capacity: u32,
117        epsilon: f32,
118    ) -> SpatialResult<Self> {
119        if !valid_radius(radius) {
120            return Err(invalid());
121        }
122        Self::upload_prepared(
123            runtime,
124            source,
125            target,
126            Preparation::Radius { radius, capacity },
127            epsilon,
128        )
129    }
130
131    fn upload_prepared(
132        runtime: &WgpuRuntime,
133        source: &KdTree,
134        target: &KdTree,
135        preparation: Preparation,
136        epsilon: f32,
137    ) -> SpatialResult<Self> {
138        let (x, y, z) = source.layout().positions();
139        let targets = target.layout().positions().0.len();
140        let (capacity, radius) = match preparation {
141            Preparation::Knn(k) => (k, None),
142            Preparation::Radius { radius, capacity } => (capacity, Some(radius)),
143        };
144        let planner = if radius.is_some() { bounded_covariance_plan } else { covariance_plan };
145        let bytes =
146            planner(x.len() as u64, targets as u64, capacity, epsilon, &runtime.device().limits())?;
147        let bound = runtime
148            .device()
149            .limits()
150            .max_buffer_size
151            .min(u64::from(runtime.device().limits().max_storage_buffer_binding_size));
152        for nodes in [source.layout().nodes().len(), target.layout().nodes().len()] {
153            if (nodes as u64).checked_mul(32).map_or(true, |v| v > bound) {
154                return Err(invalid());
155            }
156        }
157        let points: Vec<_> = (0..x.len()).map(|i| [x[i], y[i], z[i]]).collect();
158        let positions = GpuIcpInput::upload(runtime, &points, target)?;
159        let source_tree = GpuKdTree::upload(runtime, source)?;
160        let (source_neighbors, target_neighbors) = if let Some(radius) = radius {
161            (
162                source_tree.radius_neighbors_resident(
163                    runtime,
164                    &positions.source,
165                    radius,
166                    capacity,
167                )?,
168                positions.tree.radius_neighbors_resident(
169                    runtime,
170                    &positions.target,
171                    radius,
172                    capacity,
173                )?,
174            )
175        } else {
176            (
177                source_tree.nearest_k_resident(runtime, &positions.source, capacity)?,
178                positions.tree.nearest_k_resident(runtime, &positions.target, capacity)?,
179            )
180        };
181        let covariances = runtime.device().create_buffer(&wgpu::BufferDescriptor {
182            label: Some("gicp-resident-covariances"),
183            size: bytes,
184            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
185            mapped_at_creation: false,
186        });
187        let params = Params {
188            sources: x.len() as u32,
189            targets: targets as u32,
190            neighbors: capacity,
191            epsilon,
192            radius_squared: radius.map_or(0.0, |r| r * r),
193            radius_mode: u32::from(radius.is_some()),
194            padding: [0; 2],
195        };
196        encode_covariances(
197            runtime,
198            &positions,
199            [&source_neighbors, &target_neighbors],
200            &covariances,
201            params,
202        );
203        let mut transfers = positions.upload_transfers();
204        transfers.record(
205            TransferDirection::HostToDevice,
206            source_tree.upload_transfers().host_to_device_bytes(),
207        );
208        // I + (epsilon-1)nn^T has lambda_min >= epsilon up to bounded f32
209        // rounding. Factor two slack covers <= 1e-6 component errors at epsilon
210        // >= 1e-4. The shader additionally rejects non-SPD packed rows.
211        let weight_scale = 6.0 / epsilon;
212        Ok(Self { positions, covariances, weight_scale, covariance_offset: 1, transfers })
213    }
214}
215
216fn encode_covariances(
217    runtime: &WgpuRuntime,
218    positions: &GpuIcpInput,
219    neighbors: [&crate::GpuNeighborhoods; 2],
220    covariances: &wgpu::Buffer,
221    params: Params,
222) {
223    let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
224        label: Some("gicp-covariance-params"),
225        contents: bytemuck::bytes_of(&params),
226        usage: wgpu::BufferUsages::UNIFORM,
227    });
228    let cache = runtime
229        .gicp_covariance_pipelines
230        .get_or_init(|| GicpCovariancePipelines::new(runtime.device()));
231    let buffers = [
232        &uniform,
233        positions.source.buffer().unwrap(),
234        positions.target.buffer().unwrap(),
235        neighbors[0].buffer(),
236        neighbors[1].buffer(),
237        covariances,
238    ];
239    let entries: Vec<_> = buffers
240        .iter()
241        .enumerate()
242        .map(|(binding, buffer)| wgpu::BindGroupEntry {
243            binding: binding as u32,
244            resource: buffer.as_entire_binding(),
245        })
246        .collect();
247    let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
248        label: Some("gicp-covariance-bindings"),
249        layout: &cache.layout,
250        entries: &entries,
251    });
252    let mut encoder = runtime.device().create_command_encoder(&Default::default());
253    for pipeline in &cache.pipelines {
254        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
255            label: Some("gicp-covariance"),
256            timestamp_writes: None,
257        });
258        pass.set_pipeline(pipeline);
259        pass.set_bind_group(0, &group, &[]);
260        pass.dispatch_workgroups((params.sources + params.targets).div_ceil(64), 1, 1);
261    }
262    runtime.queue().submit(Some(encoder.finish()));
263}
264
265pub(crate) struct GicpCovariancePipelines {
266    layout: wgpu::BindGroupLayout,
267    pipelines: [wgpu::ComputePipeline; 2],
268}
269impl GicpCovariancePipelines {
270    fn new(device: &wgpu::Device) -> Self {
271        let entries: Vec<_> = (0..6)
272            .map(|binding| wgpu::BindGroupLayoutEntry {
273                binding,
274                visibility: wgpu::ShaderStages::COMPUTE,
275                ty: wgpu::BindingType::Buffer {
276                    ty: if binding == 0 {
277                        wgpu::BufferBindingType::Uniform
278                    } else {
279                        wgpu::BufferBindingType::Storage { read_only: binding != 5 }
280                    },
281                    has_dynamic_offset: false,
282                    min_binding_size: None,
283                },
284                count: None,
285            })
286            .collect();
287        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
288            label: Some("gicp-covariance-layout"),
289            entries: &entries,
290        });
291        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
292            label: Some("gicp-covariance-layout"),
293            bind_group_layouts: &[&layout],
294            push_constant_ranges: &[],
295        });
296        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
297            label: Some("gicp-covariance"),
298            source: wgpu::ShaderSource::Wgsl(
299                include_str!("../shaders/gicp_covariances.wgsl").into(),
300            ),
301        });
302        let pipelines = ["build_covariances", "finalize"].map(|entry| {
303            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
304                label: Some("gicp-covariance-pipeline"),
305                layout: Some(&pipeline_layout),
306                module: &shader,
307                entry_point: Some(entry),
308                compilation_options: Default::default(),
309                cache: None,
310            })
311        });
312        Self { layout, pipelines }
313    }
314}
315
316#[cfg(all(test, not(target_arch = "wasm32")))]
317#[path = "gicp_covariance_tests.rs"]
318mod tests;