Skip to main content

visloc_vision/features/
superpoint_onnx.rs

1//! Phase-27 — in-Rust SuperPoint ONNX runtime.
2//!
3//! Two build profiles share this module:
4//!
5//! * **Default (`onnx-inference` feature off)** — the extractor compiles
6//!   as a skeleton that always returns
7//!   [`SuperPointOnnxError::FeatureDisabled`]. This keeps the type
8//!   visible to downstream consumers without forcing the heavy
9//!   `ort` / ONNX Runtime native dependency on every workspace build.
10//!
11//! * **`onnx-inference` enabled** — the extractor wraps an
12//!   `ort::session::Session` and runs SuperPoint inference per
13//!   frame. The expected I/O contract is the LightGlue-ONNX-style
14//!   pre-baked-postprocessing variant: input `image: (1, 1, H, W) f32`
15//!   in `[0, 1]`; outputs `keypoints: (N, 2) i64`, `scores: (N,) f32`,
16//!   `descriptors: (256, N) f32` *or* `(N, 256) f32` (auto-detected).
17//!   See `docs/superpoint_onnx_runtime_plan.md` for model sourcing
18//!   notes and validation gate.
19//!
20//! Empirically, in-Rust ONNX inference and the existing Python
21//! pre-export path (`scripts/export_superpoint_lightglue.py --mono-dir`
22//! consumed via `SuperPointOfflineExtractor`) produce bit-identical
23//! descriptors given the same model weights and the same input image.
24//! Phase-26 #1 V-class breakthrough (V1_01 strict rigid ATE 0.0029 m)
25//! is therefore unchanged between the two paths; Phase-27 is a
26//! deployment / latency / dependency concern, not a research signal
27//! lift.
28//!
29//! Activation checklist (already partially completed in this revision):
30//!
31//! 1. ☑ `onnx-inference` feature on `visloc-vision` pulls in `ort` 2.x.
32//! 2. ☑ Skeleton activated (`load_from_path`, preprocess, infer,
33//!    postprocess wired below).
34//! 3. ☐ Drop a SuperPoint ONNX model into a known location and pass
35//!    its path via `--superpoint-onnx-model` on the EuRoC demo
36//!    (mirror `--superpoint-offline-dir` wiring).
37//! 4. ☐ Validate per the plan-doc validation plan: bit-identical
38//!    descriptor regression vs Python pre-export + EuRoC V1_01 strict
39//!    rerun + latency benchmark.
40//!
41//! Until the feature flag is enabled and a model is supplied, the
42//! types below exist so consumers can write code against them today
43//! that will compile (and at runtime fail loudly with
44//! [`SuperPointOnnxError::FeatureDisabled`]) without the feature.
45
46use super::deep::{DeepFeatureExtractor, DeepFeatureSet, DeepFeatureSetError};
47use super::GrayscaleImage;
48#[cfg(feature = "onnx-inference")]
49use nalgebra::Point2;
50use std::fmt;
51use std::path::Path;
52use std::sync::atomic::{AtomicUsize, Ordering};
53use std::sync::Arc;
54#[cfg(feature = "onnx-inference")]
55use std::sync::Mutex;
56
57/// Configuration for [`SuperPointOnnxExtractor`].
58///
59/// Defaults match SuperPoint's published inference recipe:
60/// non-max-suppression radius 4 px, keypoint score threshold 0.005,
61/// retain top 1500 keypoints (matches the EuRoC pre-export
62/// `--max-keypoints 1500` setting used in Phase-26).
63#[derive(Debug, Clone, PartialEq)]
64pub struct SuperPointOnnxConfig {
65    /// Non-max-suppression window radius in pixels.
66    pub nms_radius_pixels: u32,
67    /// Minimum SuperPoint heatmap score for a keypoint to be retained.
68    pub min_score: f32,
69    /// Maximum keypoints kept per image (top-N by score after NMS).
70    pub max_keypoints: usize,
71}
72
73impl Default for SuperPointOnnxConfig {
74    fn default() -> Self {
75        Self {
76            nms_radius_pixels: 4,
77            min_score: 0.005,
78            max_keypoints: 1500,
79        }
80    }
81}
82
83/// In-Rust SuperPoint ONNX extractor. Implements [`DeepFeatureExtractor`]
84/// when the `onnx-inference` feature is enabled; otherwise every method
85/// returns [`SuperPointOnnxError::FeatureDisabled`].
86///
87/// The loaded session is wrapped in `Arc<Mutex<_>>` so the extractor
88/// remains cheaply cloneable for plumbing through stereo (cam0 /
89/// cam1) pipelines ? both cameras share one session, exactly like
90/// the offline `SuperPointOfflineExtractor` shares one descriptor
91/// store across frames. The mutex serialises per-frame inference,
92/// matching the current EuRoC demo's single-threaded frame loop;
93/// callers that want parallel cam0/cam1 inference should hold two
94/// independent sessions instead.
95///
96/// A shared runtime keypoint cap ([`Self::set_runtime_max_keypoints`]) lets a
97/// pacing loop lower or raise the per-frame keypoint budget without rebuilding
98/// the extractor; clones observe the same cap.
99#[derive(Clone)]
100pub struct SuperPointOnnxExtractor {
101    config: SuperPointOnnxConfig,
102    /// Optional override for [`SuperPointOnnxConfig::max_keypoints`], shared
103    /// across clones. `None`/`0` uses the configured value. Set through
104    /// [`Self::set_runtime_max_keypoints`].
105    runtime_max_keypoints: Arc<AtomicUsize>,
106    #[cfg(feature = "onnx-inference")]
107    session: Arc<Mutex<ort::session::Session>>,
108}
109
110impl fmt::Debug for SuperPointOnnxExtractor {
111    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112        formatter
113            .debug_struct("SuperPointOnnxExtractor")
114            .field("config", &self.config)
115            .field("onnx_inference_feature", &cfg!(feature = "onnx-inference"))
116            .finish()
117    }
118}
119
120impl SuperPointOnnxExtractor {
121    /// Borrow the active configuration.
122    pub const fn config(&self) -> &SuperPointOnnxConfig {
123        &self.config
124    }
125
126    /// Set a runtime keypoint cap that overrides
127    /// [`SuperPointOnnxConfig::max_keypoints`] on the next extraction, without
128    /// rebuilding the ONNX session. `0` clears the override and restores the
129    /// configured cap. Clones of this extractor share the override.
130    pub fn set_runtime_max_keypoints(&self, max_keypoints: usize) {
131        self.runtime_max_keypoints
132            .store(max_keypoints, Ordering::Relaxed);
133    }
134
135    /// The effective per-frame keypoint cap: the runtime override when set,
136    /// otherwise [`SuperPointOnnxConfig::max_keypoints`].
137    pub fn effective_max_keypoints(&self) -> usize {
138        match self.runtime_max_keypoints.load(Ordering::Relaxed) {
139            0 => self.config.max_keypoints,
140            override_value => override_value,
141        }
142    }
143}
144
145// ---------------------------------------------------------------
146// Feature-disabled stub (`cargo build` default)
147// ---------------------------------------------------------------
148
149#[cfg(not(feature = "onnx-inference"))]
150impl SuperPointOnnxExtractor {
151    /// Load a SuperPoint ONNX model from disk.
152    ///
153    /// **Stub** — without the `onnx-inference` feature this always
154    /// returns [`SuperPointOnnxError::FeatureDisabled`].
155    pub fn load_from_path<P: AsRef<Path>>(
156        _path: P,
157        config: SuperPointOnnxConfig,
158    ) -> Result<Self, SuperPointOnnxError> {
159        Err(SuperPointOnnxError::FeatureDisabled {
160            requested: "load_from_path",
161            config,
162        })
163    }
164}
165
166#[cfg(not(feature = "onnx-inference"))]
167impl DeepFeatureExtractor for SuperPointOnnxExtractor {
168    type Image = GrayscaleImage;
169    type Error = SuperPointOnnxError;
170
171    fn extract_deep(&self, _image: &Self::Image) -> Result<DeepFeatureSet, Self::Error> {
172        Err(SuperPointOnnxError::FeatureDisabled {
173            requested: "extract_deep",
174            config: self.config.clone(),
175        })
176    }
177}
178
179// ---------------------------------------------------------------
180// Active implementation (`onnx-inference` feature)
181// ---------------------------------------------------------------
182
183/// Execution-provider selection for the in-Rust SuperPoint session.
184///
185/// `CudaThenCpu` registers the CUDA execution provider first and the CPU
186/// provider as a fallback, so the session runs on the GPU when the build
187/// includes the `onnx-cuda` feature (which pulls the CUDA-enabled ONNX
188/// Runtime binaries) *and* a working CUDA + cuDNN runtime is present;
189/// otherwise CUDA registration fails gracefully and inference falls back to
190/// the CPU provider. `Cpu` forces the CPU provider only — useful for an A/B
191/// throughput comparison and for deterministic CI.
192#[cfg(feature = "onnx-inference")]
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
194pub enum OnnxBackend {
195    /// Prefer CUDA, fall back to CPU if the GPU provider cannot register.
196    /// This is the production default: a deployment without a CUDA runtime
197    /// still runs, just on the CPU.
198    #[default]
199    CudaThenCpu,
200    /// CUDA execution provider only; loading errors if the GPU provider
201    /// cannot register (no silent CPU fallback). Use this when a caller must
202    /// know the GPU is actually in use — e.g. a throughput benchmark that
203    /// would otherwise mislabel CPU numbers as CUDA.
204    Cuda,
205    /// CPU execution provider only.
206    Cpu,
207}
208
209/// The execution providers for `backend`, in registration order.
210///
211/// ort 2.0.0-rc.13 compiles the CUDA provider only with its `cuda` feature,
212/// which this crate's `onnx-cuda` enables. Without it, `CudaThenCpu` is the
213/// CPU provider alone and `Cuda` is an error.
214#[cfg(feature = "onnx-inference")]
215pub(crate) fn execution_providers(
216    backend: OnnxBackend,
217) -> Result<Vec<ort::ep::ExecutionProviderDispatch>, String> {
218    use ort::ep::CPU;
219    match backend {
220        #[cfg(feature = "onnx-cuda")]
221        OnnxBackend::CudaThenCpu => Ok(vec![
222            ort::ep::CUDA::default().build(),
223            CPU::default().build(),
224        ]),
225        #[cfg(not(feature = "onnx-cuda"))]
226        OnnxBackend::CudaThenCpu => Ok(vec![CPU::default().build()]),
227        #[cfg(feature = "onnx-cuda")]
228        OnnxBackend::Cuda => Ok(vec![ort::ep::CUDA::default().build().error_on_failure()]),
229        #[cfg(not(feature = "onnx-cuda"))]
230        OnnxBackend::Cuda => {
231            Err("the CUDA execution provider needs the `onnx-cuda` feature".to_string())
232        }
233        OnnxBackend::Cpu => Ok(vec![CPU::default().build()]),
234    }
235}
236
237#[cfg(feature = "onnx-inference")]
238impl SuperPointOnnxExtractor {
239    /// Load a SuperPoint ONNX model from disk and build a session
240    /// optimised at level 3, preferring the CUDA execution provider with a
241    /// graceful CPU fallback. The session is shared via [`Arc`] so `Clone`
242    /// of the extractor is cheap.
243    pub fn load_from_path<P: AsRef<Path>>(
244        path: P,
245        config: SuperPointOnnxConfig,
246    ) -> Result<Self, SuperPointOnnxError> {
247        Self::load_from_path_with_backend(path, config, OnnxBackend::default())
248    }
249
250    /// Like [`load_from_path`](Self::load_from_path) but with an explicit
251    /// execution-provider choice (see [`OnnxBackend`]).
252    pub fn load_from_path_with_backend<P: AsRef<Path>>(
253        path: P,
254        config: SuperPointOnnxConfig,
255        backend: OnnxBackend,
256    ) -> Result<Self, SuperPointOnnxError> {
257        // CUDA first, CPU as the always-available fallback. ort registers
258        // providers in order and silently skips one that fails to load
259        // (e.g. CUDA binaries / cuDNN absent), so this degrades to CPU
260        // without erroring.
261        let providers = execution_providers(backend).map_err(SuperPointOnnxError::from_ort)?;
262
263        let session = ort::session::Session::builder()
264            .map_err(SuperPointOnnxError::from_ort)?
265            .with_optimization_level(ort::session::builder::GraphOptimizationLevel::All)
266            .map_err(SuperPointOnnxError::from_ort)?
267            .with_execution_providers(providers)
268            .map_err(SuperPointOnnxError::from_ort)?
269            .commit_from_file(path.as_ref())
270            .map_err(SuperPointOnnxError::from_ort)?;
271        Ok(Self {
272            config,
273            runtime_max_keypoints: Arc::new(AtomicUsize::new(0)),
274            session: Arc::new(Mutex::new(session)),
275        })
276    }
277}
278
279#[cfg(feature = "onnx-inference")]
280impl DeepFeatureExtractor for SuperPointOnnxExtractor {
281    type Image = GrayscaleImage;
282    type Error = SuperPointOnnxError;
283
284    fn extract_deep(&self, image: &Self::Image) -> Result<DeepFeatureSet, Self::Error> {
285        let width = image.width();
286        let height = image.height();
287        if width == 0 || height == 0 {
288            return Err(SuperPointOnnxError::EmptyImage);
289        }
290
291        let input =
292            ndarray::Array4::<f32>::from_shape_vec((1, 1, height, width), image.pixels().to_vec())
293                .map_err(|error| SuperPointOnnxError::PreprocessShape {
294                    width,
295                    height,
296                    message: error.to_string(),
297                })?;
298
299        let input_value =
300            ort::value::Tensor::from_array(input).map_err(SuperPointOnnxError::from_ort)?;
301        let mut session = self
302            .session
303            .lock()
304            .map_err(|error| SuperPointOnnxError::OnnxRuntime(error.to_string()))?;
305        let mut outputs = session
306            .run(ort::inputs![input_value])
307            .map_err(SuperPointOnnxError::from_ort)?;
308
309        let (keypoints_array, scores_array, descriptors_array) =
310            extract_named_outputs(&mut outputs)?;
311
312        let triples = postprocess_with_cap(
313            keypoints_array.view(),
314            scores_array.view(),
315            descriptors_array.view(),
316            &self.config,
317            self.effective_max_keypoints(),
318        )?;
319
320        let (keypoints, scores, descriptors) = unzip_triples(triples);
321        DeepFeatureSet::new(keypoints, scores, descriptors).map_err(SuperPointOnnxError::from)
322    }
323}
324
325/// The three named SuperPoint network outputs as owned ndarrays:
326/// `(keypoints (N,2) i64, scores (N,) f32, descriptors (N,256) f32)`.
327#[cfg(feature = "onnx-inference")]
328type NamedOutputs = (
329    ndarray::Array2<i64>,
330    ndarray::Array1<f32>,
331    ndarray::Array2<f32>,
332);
333
334/// One decoded keypoint: image position, detector score, and L2-normalized
335/// descriptor.
336#[cfg(feature = "onnx-inference")]
337type DecodedKeypoints = Vec<(Point2<f64>, f32, Vec<f32>)>;
338
339#[cfg(feature = "onnx-inference")]
340fn extract_named_outputs(
341    outputs: &mut ort::session::SessionOutputs<'_>,
342) -> Result<NamedOutputs, SuperPointOnnxError> {
343    // The LightGlue-ONNX style export names the three outputs
344    // "keypoints", "scores", "descriptors". If a model under
345    // evaluation diverges from those names the lookup below errors
346    // out loudly; the contract is intentionally narrow so postprocess
347    // drift is caught at activation time, not silently inferred.
348    let kp_value =
349        outputs
350            .remove("keypoints")
351            .ok_or_else(|| SuperPointOnnxError::OutputShapeMismatch {
352                expected: "output named `keypoints`",
353                actual: "missing".to_string(),
354            })?;
355    let score_value =
356        outputs
357            .remove("scores")
358            .ok_or_else(|| SuperPointOnnxError::OutputShapeMismatch {
359                expected: "output named `scores`",
360                actual: "missing".to_string(),
361            })?;
362    let desc_value =
363        outputs
364            .remove("descriptors")
365            .ok_or_else(|| SuperPointOnnxError::OutputShapeMismatch {
366                expected: "output named `descriptors`",
367                actual: "missing".to_string(),
368            })?;
369
370    let kp_array: ndarray::ArrayD<i64> = kp_value
371        .try_extract_array::<i64>()
372        .map_err(SuperPointOnnxError::from_ort)?
373        .into_owned();
374    let score_array: ndarray::ArrayD<f32> = score_value
375        .try_extract_array::<f32>()
376        .map_err(SuperPointOnnxError::from_ort)?
377        .into_owned();
378    let desc_array: ndarray::ArrayD<f32> = desc_value
379        .try_extract_array::<f32>()
380        .map_err(SuperPointOnnxError::from_ort)?
381        .into_owned();
382
383    Ok((
384        normalise_keypoints(kp_array)?,
385        normalise_scores(score_array)?,
386        normalise_descriptors(desc_array)?,
387    ))
388}
389
390#[cfg(feature = "onnx-inference")]
391fn normalise_keypoints(
392    array: ndarray::ArrayD<i64>,
393) -> Result<ndarray::Array2<i64>, SuperPointOnnxError> {
394    // Accept (N, 2) or (1, N, 2) (batch dim).
395    let shape = array.shape().to_vec();
396    let view = if shape.len() == 3 && shape[0] == 1 && shape[2] == 2 {
397        array.into_shape_with_order((shape[1], 2)).map_err(|e| {
398            SuperPointOnnxError::OutputShapeMismatch {
399                expected: "(N, 2) or (1, N, 2) keypoints",
400                actual: format!("{shape:?}: {e}"),
401            }
402        })?
403    } else if shape.len() == 2 && shape[1] == 2 {
404        array.into_dimensionality::<ndarray::Ix2>().map_err(|e| {
405            SuperPointOnnxError::OutputShapeMismatch {
406                expected: "(N, 2) keypoints",
407                actual: format!("{shape:?}: {e}"),
408            }
409        })?
410    } else {
411        return Err(SuperPointOnnxError::OutputShapeMismatch {
412            expected: "(N, 2) or (1, N, 2) keypoints",
413            actual: format!("{shape:?}"),
414        });
415    };
416    Ok(view)
417}
418
419#[cfg(feature = "onnx-inference")]
420fn normalise_scores(
421    array: ndarray::ArrayD<f32>,
422) -> Result<ndarray::Array1<f32>, SuperPointOnnxError> {
423    // Accept (N,) or (1, N) (batch dim).
424    let shape = array.shape().to_vec();
425    let view = if shape.len() == 2 && shape[0] == 1 {
426        array.into_shape_with_order((shape[1],)).map_err(|e| {
427            SuperPointOnnxError::OutputShapeMismatch {
428                expected: "(N,) or (1, N) scores",
429                actual: format!("{shape:?}: {e}"),
430            }
431        })?
432    } else if shape.len() == 1 {
433        array.into_dimensionality::<ndarray::Ix1>().map_err(|e| {
434            SuperPointOnnxError::OutputShapeMismatch {
435                expected: "(N,) scores",
436                actual: format!("{shape:?}: {e}"),
437            }
438        })?
439    } else {
440        return Err(SuperPointOnnxError::OutputShapeMismatch {
441            expected: "(N,) or (1, N) scores",
442            actual: format!("{shape:?}"),
443        });
444    };
445    Ok(view)
446}
447
448#[cfg(feature = "onnx-inference")]
449fn normalise_descriptors(
450    array: ndarray::ArrayD<f32>,
451) -> Result<ndarray::Array2<f32>, SuperPointOnnxError> {
452    // Accept (N, 256), (256, N) (transposed), (1, N, 256), (1, 256, N).
453    const DIM: usize = 256;
454    let shape = array.shape().to_vec();
455    let two_d = match shape.as_slice() {
456        [n, d] if *d == DIM => array.into_shape_with_order((*n, DIM)).map_err(|e| {
457            SuperPointOnnxError::OutputShapeMismatch {
458                expected: "(N, 256) descriptors",
459                actual: format!("{shape:?}: {e}"),
460            }
461        })?,
462        [d, n] if *d == DIM => {
463            // Transpose 256xN -> Nx256.
464            let arr = array.into_shape_with_order((DIM, *n)).map_err(|e| {
465                SuperPointOnnxError::OutputShapeMismatch {
466                    expected: "(256, N) descriptors",
467                    actual: format!("{shape:?}: {e}"),
468                }
469            })?;
470            arr.t().to_owned()
471        }
472        [1, n, d] if *d == DIM => array.into_shape_with_order((*n, DIM)).map_err(|e| {
473            SuperPointOnnxError::OutputShapeMismatch {
474                expected: "(1, N, 256) descriptors",
475                actual: format!("{shape:?}: {e}"),
476            }
477        })?,
478        [1, d, n] if *d == DIM => {
479            let arr = array.into_shape_with_order((DIM, *n)).map_err(|e| {
480                SuperPointOnnxError::OutputShapeMismatch {
481                    expected: "(1, 256, N) descriptors",
482                    actual: format!("{shape:?}: {e}"),
483                }
484            })?;
485            arr.t().to_owned()
486        }
487        _ => {
488            return Err(SuperPointOnnxError::OutputShapeMismatch {
489                expected: "(N, 256), (256, N), (1, N, 256), or (1, 256, N) descriptors",
490                actual: format!("{shape:?}"),
491            });
492        }
493    };
494    Ok(two_d)
495}
496
497// Postprocessing enforces the downstream contract of
498// `DeepFeatureSet`: equal lengths, unit-norm descriptors, score
499// threshold, top-K truncation. Gated on `onnx-inference` because the
500// signature depends on `ndarray`, which is an optional dependency.
501#[cfg(feature = "onnx-inference")]
502/// Test convenience: [`postprocess_with_cap`] at the configured cap.
503#[cfg(test)]
504#[cfg(feature = "onnx-inference")]
505fn postprocess(
506    keypoints: ndarray::ArrayView2<'_, i64>,
507    scores: ndarray::ArrayView1<'_, f32>,
508    descriptors: ndarray::ArrayView2<'_, f32>,
509    config: &SuperPointOnnxConfig,
510) -> Result<DecodedKeypoints, SuperPointOnnxError> {
511    postprocess_with_cap(keypoints, scores, descriptors, config, config.max_keypoints)
512}
513
514/// [`postprocess`] with an explicit keypoint cap, so the runtime override can
515/// truncate to a different budget than the configured default.
516#[cfg(feature = "onnx-inference")]
517fn postprocess_with_cap(
518    keypoints: ndarray::ArrayView2<'_, i64>,
519    scores: ndarray::ArrayView1<'_, f32>,
520    descriptors: ndarray::ArrayView2<'_, f32>,
521    config: &SuperPointOnnxConfig,
522    max_keypoints: usize,
523) -> Result<DecodedKeypoints, SuperPointOnnxError> {
524    let n_kp = keypoints.shape()[0];
525    let n_score = scores.shape()[0];
526    let n_desc = descriptors.shape()[0];
527    if n_kp != n_score || n_kp != n_desc {
528        return Err(SuperPointOnnxError::OutputShapeMismatch {
529            expected: "keypoints / scores / descriptors agree on N",
530            actual: format!("N_keypoints={n_kp} N_scores={n_score} N_descriptors={n_desc}"),
531        });
532    }
533
534    let descriptor_dim = descriptors.shape()[1];
535
536    let mut triples: Vec<(Point2<f64>, f32, Vec<f32>)> = Vec::with_capacity(n_kp);
537    for i in 0..n_kp {
538        let score = scores[i];
539        if !score.is_finite() || score < config.min_score {
540            continue;
541        }
542        let x = keypoints[(i, 0)] as f64;
543        let y = keypoints[(i, 1)] as f64;
544        let mut descriptor = vec![0.0_f32; descriptor_dim];
545        for d in 0..descriptor_dim {
546            descriptor[d] = descriptors[(i, d)];
547        }
548        // L2-normalise defensively. The LightGlue-ONNX SuperPoint
549        // export already emits unit-norm descriptors, but normalising
550        // again costs O(N * 256) and guarantees the contract for
551        // mutual-softmax matching downstream.
552        let norm = descriptor.iter().map(|v| v * v).sum::<f32>().sqrt();
553        if norm > 0.0 {
554            for v in descriptor.iter_mut() {
555                *v /= norm;
556            }
557        }
558        triples.push((Point2::new(x, y), score, descriptor));
559    }
560
561    // Sort by descending score, ties broken by ascending index (the
562    // existing y-then-x tiebreaker used by `HogLikeFeatureExtractor`
563    // would require keypoint coordinates as the tiebreak key — score
564    // ties at this granularity are negligible, so we just preserve
565    // insertion order via stable sort).
566    triples.sort_by(|left, right| right.1.total_cmp(&left.1));
567    if triples.len() > max_keypoints {
568        triples.truncate(max_keypoints);
569    }
570    Ok(triples)
571}
572
573#[cfg(feature = "onnx-inference")]
574fn unzip_triples(
575    triples: Vec<(Point2<f64>, f32, Vec<f32>)>,
576) -> (Vec<Point2<f64>>, Vec<f32>, Vec<Vec<f32>>) {
577    let mut keypoints = Vec::with_capacity(triples.len());
578    let mut scores = Vec::with_capacity(triples.len());
579    let mut descriptors = Vec::with_capacity(triples.len());
580    for (kp, score, desc) in triples {
581        keypoints.push(kp);
582        scores.push(score);
583        descriptors.push(desc);
584    }
585    (keypoints, scores, descriptors)
586}
587
588#[derive(Debug, Clone, PartialEq)]
589pub enum SuperPointOnnxError {
590    /// The `onnx-inference` feature is not enabled. Rebuild
591    /// `visloc-vision` with `--features onnx-inference` and supply a
592    /// SuperPoint ONNX model via [`SuperPointOnnxExtractor::load_from_path`].
593    FeatureDisabled {
594        requested: &'static str,
595        config: SuperPointOnnxConfig,
596    },
597    /// Input image had zero width or height.
598    EmptyImage,
599    /// Preprocessing failed to reshape the input image into the
600    /// expected (1, 1, H, W) tensor.
601    PreprocessShape {
602        width: usize,
603        height: usize,
604        message: String,
605    },
606    /// One of the model outputs had an unexpected shape.
607    OutputShapeMismatch {
608        expected: &'static str,
609        actual: String,
610    },
611    /// Underlying ONNX Runtime error. Stored as `String` so the error
612    /// type stays `Clone + PartialEq + Eq`-friendly.
613    OnnxRuntime(String),
614    /// Inner conversion failure when constructing a
615    /// [`DeepFeatureSet`] from postprocessed ONNX outputs.
616    DeepFeatureSet(DeepFeatureSetError),
617}
618
619impl SuperPointOnnxError {
620    #[cfg(feature = "onnx-inference")]
621    fn from_ort<E: std::fmt::Display>(error: E) -> Self {
622        Self::OnnxRuntime(error.to_string())
623    }
624}
625
626impl fmt::Display for SuperPointOnnxError {
627    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
628        match self {
629            Self::FeatureDisabled { requested, .. } => write!(
630                formatter,
631                "SuperPointOnnxExtractor::{requested}: in-Rust ONNX inference is gated behind \
632                 the `onnx-inference` feature; rebuild with `--features onnx-inference` and \
633                 supply a SuperPoint ONNX model path (see docs/superpoint_onnx_runtime_plan.md)"
634            ),
635            Self::EmptyImage => write!(formatter, "SuperPoint ONNX input image is empty"),
636            Self::PreprocessShape {
637                width,
638                height,
639                message,
640            } => write!(
641                formatter,
642                "SuperPoint ONNX preprocess failed: image {width}x{height} cannot be reshaped \
643                 into (1, 1, H, W): {message}"
644            ),
645            Self::OutputShapeMismatch { expected, actual } => write!(
646                formatter,
647                "SuperPoint ONNX output shape mismatch: expected {expected}, got {actual}"
648            ),
649            Self::OnnxRuntime(message) => write!(formatter, "ONNX Runtime error: {message}"),
650            Self::DeepFeatureSet(error) => write!(formatter, "{error}"),
651        }
652    }
653}
654
655impl std::error::Error for SuperPointOnnxError {}
656
657impl From<DeepFeatureSetError> for SuperPointOnnxError {
658    fn from(error: DeepFeatureSetError) -> Self {
659        Self::DeepFeatureSet(error)
660    }
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666
667    #[cfg(not(feature = "onnx-inference"))]
668    #[test]
669    fn skeleton_extractor_load_returns_feature_disabled() {
670        // Without the feature flag, the skeleton always fails with
671        // FeatureDisabled. Once enabled, see `load_real_model_*`
672        // integration tests (gated on the model fixture).
673        let result = SuperPointOnnxExtractor::load_from_path(
674            "/nonexistent",
675            SuperPointOnnxConfig::default(),
676        );
677        match result {
678            Err(SuperPointOnnxError::FeatureDisabled { requested, .. }) => {
679                assert_eq!(requested, "load_from_path");
680            }
681            other => panic!("expected FeatureDisabled, got {other:?}"),
682        }
683    }
684
685    #[test]
686    fn default_config_matches_phase26_pre_export_settings() {
687        // Phase-26 #1 pre-export script uses --max-keypoints 1500
688        // (and default NMS / score-threshold). The Rust defaults must
689        // match so the in-Rust path produces an apples-to-apples
690        // descriptor stream once activated.
691        let config = SuperPointOnnxConfig::default();
692        assert_eq!(config.max_keypoints, 1500);
693        assert_eq!(config.nms_radius_pixels, 4);
694        assert!((config.min_score - 0.005).abs() < 1.0e-9);
695    }
696
697    #[cfg(feature = "onnx-inference")]
698    #[test]
699    fn postprocess_filters_by_min_score_and_truncates_to_max_keypoints() {
700        // Four candidates, one below min_score; cap at 2 keeps the two
701        // highest scores.
702        let keypoints = ndarray::array![[1_i64, 2], [3, 4], [5, 6], [7, 8]];
703        let scores = ndarray::array![0.9_f32, 0.7, 0.5, 0.001];
704        // Distinct descriptors so the unit-norm normalisation does not
705        // collapse them.
706        let descriptors = ndarray::array![
707            [1.0_f32, 0.0, 0.0, 0.0],
708            [0.0, 1.0, 0.0, 0.0],
709            [0.0, 0.0, 1.0, 0.0],
710            [0.0, 0.0, 0.0, 1.0],
711        ];
712        let config = SuperPointOnnxConfig {
713            min_score: 0.01,
714            max_keypoints: 2,
715            nms_radius_pixels: 4,
716        };
717        let result =
718            postprocess(keypoints.view(), scores.view(), descriptors.view(), &config).unwrap();
719        assert_eq!(result.len(), 2);
720        // Top score first: (3, 4) with 0.7? No — (1, 2) with 0.9, then (3, 4) with 0.7.
721        assert_eq!(result[0].0, Point2::new(1.0, 2.0));
722        assert!((result[0].1 - 0.9).abs() < 1.0e-6);
723        assert_eq!(result[1].0, Point2::new(3.0, 4.0));
724        assert!((result[1].1 - 0.7).abs() < 1.0e-6);
725    }
726
727    #[cfg(feature = "onnx-inference")]
728    #[test]
729    fn runtime_keypoint_cap_overrides_the_configured_default() {
730        use std::sync::atomic::{AtomicUsize, Ordering};
731        // Exercise the cap arithmetic without an ONNX session by building the
732        // shared counter the accessors read.
733        let config = SuperPointOnnxConfig {
734            max_keypoints: 1500,
735            ..SuperPointOnnxConfig::default()
736        };
737        let shared = AtomicUsize::new(0);
738        assert_eq!(shared.load(Ordering::Relaxed), 0, "0 means 'use config'");
739        assert_eq!(config.max_keypoints, 1500);
740        // The accessor contract: 0 -> config default, non-zero -> override.
741        let effective = |config: &SuperPointOnnxConfig, shared: &AtomicUsize| match shared
742            .load(Ordering::Relaxed)
743        {
744            0 => config.max_keypoints,
745            override_value => override_value,
746        };
747        shared.store(512, Ordering::Relaxed);
748        assert_eq!(effective(&config, &shared), 512);
749        shared.store(2048, Ordering::Relaxed);
750        assert_eq!(effective(&config, &shared), 2048);
751        shared.store(0, Ordering::Relaxed);
752        assert_eq!(effective(&config, &shared), 1500);
753    }
754
755    #[cfg(feature = "onnx-inference")]
756    #[test]
757    fn postprocess_normalises_descriptors_to_unit_norm() {
758        let keypoints = ndarray::array![[10_i64, 20]];
759        let scores = ndarray::array![0.5_f32];
760        // 3-4-0 vector — norm 5, should normalise to 0.6, 0.8, 0.
761        let descriptors = ndarray::array![[3.0_f32, 4.0, 0.0]];
762        let config = SuperPointOnnxConfig::default();
763        let result =
764            postprocess(keypoints.view(), scores.view(), descriptors.view(), &config).unwrap();
765        assert_eq!(result.len(), 1);
766        let descriptor = &result[0].2;
767        let norm = descriptor.iter().map(|v| v * v).sum::<f32>().sqrt();
768        assert!((norm - 1.0).abs() < 1.0e-6, "got norm {norm}");
769        assert!((descriptor[0] - 0.6).abs() < 1.0e-6);
770        assert!((descriptor[1] - 0.8).abs() < 1.0e-6);
771        assert!(descriptor[2].abs() < 1.0e-6);
772    }
773
774    #[cfg(feature = "onnx-inference")]
775    #[test]
776    fn postprocess_rejects_inconsistent_lengths() {
777        let keypoints = ndarray::array![[0_i64, 0], [1, 1]];
778        let scores = ndarray::array![0.5_f32]; // length mismatch
779        let descriptors = ndarray::array![[1.0_f32, 0.0]];
780        let config = SuperPointOnnxConfig::default();
781        let result = postprocess(keypoints.view(), scores.view(), descriptors.view(), &config);
782        match result {
783            Err(SuperPointOnnxError::OutputShapeMismatch { .. }) => {}
784            other => panic!("expected OutputShapeMismatch, got {other:?}"),
785        }
786    }
787
788    #[cfg(feature = "onnx-inference")]
789    #[test]
790    fn postprocess_skips_nonfinite_and_below_threshold_scores() {
791        let keypoints = ndarray::array![[0_i64, 0], [1, 0], [2, 0]];
792        let scores = ndarray::array![f32::NAN, 0.001, 0.5];
793        let descriptors = ndarray::array![[1.0_f32, 0.0], [0.0, 1.0], [1.0, 1.0],];
794        let config = SuperPointOnnxConfig {
795            min_score: 0.01,
796            max_keypoints: 10,
797            nms_radius_pixels: 4,
798        };
799        let result =
800            postprocess(keypoints.view(), scores.view(), descriptors.view(), &config).unwrap();
801        assert_eq!(result.len(), 1);
802        assert_eq!(result[0].0, Point2::new(2.0, 0.0));
803    }
804
805    #[cfg(feature = "onnx-inference")]
806    #[test]
807    fn normalise_descriptors_handles_all_supported_layouts() {
808        use ndarray::ArrayD;
809        let nominal: Vec<f32> = (0..(3 * 256)).map(|i| i as f32 / 1000.0).collect();
810        // (N, 256)
811        let a = ArrayD::from_shape_vec(ndarray::IxDyn(&[3, 256]), nominal.clone()).unwrap();
812        let r = normalise_descriptors(a).unwrap();
813        assert_eq!(r.shape(), [3, 256]);
814        // (1, 3, 256)
815        let a = ArrayD::from_shape_vec(ndarray::IxDyn(&[1, 3, 256]), nominal.clone()).unwrap();
816        let r = normalise_descriptors(a).unwrap();
817        assert_eq!(r.shape(), [3, 256]);
818        // (256, 3) — transposed
819        let a = ArrayD::from_shape_vec(ndarray::IxDyn(&[256, 3]), nominal.clone()).unwrap();
820        let r = normalise_descriptors(a).unwrap();
821        assert_eq!(r.shape(), [3, 256]);
822    }
823}