Skip to main content

visloc_vision/matching/
mod.rs

1mod hamming;
2pub mod ivf;
3pub mod mutual_softmax;
4mod quantized;
5
6pub use hamming::HammingMatcher;
7pub use ivf::{IvfConfig, IvfMatcher};
8pub use mutual_softmax::{MutualSoftmaxConfig, MutualSoftmaxMatcher};
9
10#[cfg(feature = "gpu-matcher")]
11pub mod gpu;
12#[cfg(feature = "gpu-matcher")]
13pub use gpu::GpuDescriptorMatcher;
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct DescriptorMatch {
17    pub query_index: usize,
18    pub train_index: usize,
19    pub distance: f32,
20    pub second_best_distance: Option<f32>,
21    pub ratio: Option<f32>,
22    /// Optional per-match confidence in `(0, 1]`. Populated by matchers that
23    /// have a probabilistic interpretation of the match (e.g.
24    /// [`mutual_softmax::MutualSoftmaxMatcher`] sets it to the dual-softmax
25    /// confidence). Classical matchers leave it `None`. Downstream consumers
26    /// (RANSAC sample weighting, scanner candidate ranking) treat `None` as
27    /// "no signal" and fall back to uniform / unweighted behaviour.
28    pub confidence: Option<f32>,
29}
30
31pub trait Matcher {
32    fn match_descriptors(&self, query: &[Vec<f32>], train: &[Vec<f32>]) -> Vec<DescriptorMatch>;
33
34    /// Match every query descriptor against the `train` rows named by
35    /// `train_indices`, returning matches whose `train_index` is the **global**
36    /// row index (an element of `train_indices`), not the position within
37    /// `train_indices`.
38    ///
39    /// This exists so an index-based matcher (an inverted-file / ANN matcher)
40    /// can evaluate candidate subsets — which differ per query — without
41    /// materialising a fresh `Vec<Vec<f32>>` for each subset. The default
42    /// implementation builds that subset once and delegates to
43    /// [`Matcher::match_descriptors`]; matchers whose kernel can consume the
44    /// borrowed rows directly should override it, because the subset copy
45    /// otherwise dominates and cancels the ANN's saving.
46    ///
47    /// `train_indices` must be strictly ascending and in range; callers that
48    /// violate this get the subset built in the given order (semantics are then
49    /// only guaranteed for well-formed input).
50    fn match_descriptors_indexed(
51        &self,
52        query: &[Vec<f32>],
53        train: &[Vec<f32>],
54        train_indices: &[usize],
55    ) -> Vec<DescriptorMatch> {
56        let subset: Vec<Vec<f32>> = train_indices
57            .iter()
58            .filter_map(|&index| train.get(index).cloned())
59            .collect();
60        let mut matches = self.match_descriptors(query, &subset);
61        for descriptor_match in &mut matches {
62            if let Some(&global) = train_indices.get(descriptor_match.train_index) {
63                descriptor_match.train_index = global;
64            }
65        }
66        matches
67    }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq)]
71pub struct BruteForceMatcher {
72    pub ratio: Option<f32>,
73}
74
75impl Default for BruteForceMatcher {
76    fn default() -> Self {
77        Self { ratio: Some(0.8) }
78    }
79}
80
81impl BruteForceMatcher {
82    pub fn l2_distance(lhs: &[f32], rhs: &[f32]) -> Option<f32> {
83        if lhs.len() != rhs.len() {
84            return None;
85        }
86        let squared = lhs
87            .iter()
88            .zip(rhs.iter())
89            .map(|(a, b)| {
90                let diff = a - b;
91                diff * diff
92            })
93            .sum::<f32>();
94        Some(squared.sqrt())
95    }
96
97    /// Match with a mutual-nearest-neighbour check using one descriptor
98    /// matrix product for both directions.
99    ///
100    /// This is equivalent to wrapping this matcher in [`CrossCheckMatcher`],
101    /// but avoids recomputing the transposed dot-product matrix.
102    pub fn match_descriptors_cross_checked(
103        &self,
104        query: &[Vec<f32>],
105        train: &[Vec<f32>],
106    ) -> Vec<DescriptorMatch> {
107        let n_query = query.len();
108        let n_train = train.len();
109        if n_query == 0 || n_train == 0 {
110            return Vec::new();
111        }
112        let dim = query[0].len();
113        let uniform = dim != 0
114            && query.iter().all(|descriptor| descriptor.len() == dim)
115            && train.iter().all(|descriptor| descriptor.len() == dim);
116        if !uniform {
117            let forward = self.match_descriptors_elementwise(query, train);
118            let reverse = self.match_descriptors_elementwise(train, query);
119            let mut reverse_best_query_by_train = vec![None; n_train];
120            for descriptor_match in reverse {
121                reverse_best_query_by_train[descriptor_match.query_index] =
122                    Some(descriptor_match.train_index);
123            }
124            return forward
125                .into_iter()
126                .filter(|descriptor_match| {
127                    reverse_best_query_by_train[descriptor_match.train_index]
128                        == Some(descriptor_match.query_index)
129                })
130                .collect();
131        }
132
133        let query_norm_sq: Vec<f32> = query
134            .iter()
135            .map(|descriptor| descriptor.iter().map(|value| value * value).sum())
136            .collect();
137        let train_norm_sq: Vec<f32> = train
138            .iter()
139            .map(|descriptor| descriptor.iter().map(|value| value * value).sum())
140            .collect();
141
142        // Byte-quantized descriptors take the integer kernel, which finds the
143        // same scores (see `quantized`).
144        let Top2 {
145            forward_best,
146            forward_second,
147            reverse_best,
148            reverse_second,
149        } = match quantized::byte_scale(query, train, dim) {
150            Some(scale) => {
151                quantized::top2(query, train, dim, scale, &query_norm_sq, &train_norm_sq)
152            }
153            None => Self::top2_f32(query, train, dim, &query_norm_sq, &train_norm_sq),
154        };
155
156        let mut reverse_best_query_by_train = vec![None; n_train];
157        for train_index in 0..n_train {
158            let Some((query_index, best_score)) = reverse_best[train_index] else {
159                continue;
160            };
161            let distance = (train_norm_sq[train_index] + best_score).max(0.0).sqrt();
162            let second_distance = reverse_second[train_index]
163                .map(|second_score| (train_norm_sq[train_index] + second_score).max(0.0).sqrt());
164            if self
165                .ratio
166                .zip(second_distance)
167                .is_some_and(|(ratio, second)| distance >= ratio * second)
168            {
169                continue;
170            }
171            reverse_best_query_by_train[train_index] = Some(query_index);
172        }
173
174        let mut matches = Vec::new();
175        for query_index in 0..n_query {
176            let Some((train_index, best_score)) = forward_best[query_index] else {
177                continue;
178            };
179            if reverse_best_query_by_train[train_index] != Some(query_index) {
180                continue;
181            }
182            let distance = (query_norm_sq[query_index] + best_score).max(0.0).sqrt();
183            let second_distance = forward_second[query_index].map(|(_, second_score)| {
184                (query_norm_sq[query_index] + second_score).max(0.0).sqrt()
185            });
186            if self
187                .ratio
188                .zip(second_distance)
189                .is_some_and(|(ratio, second)| distance >= ratio * second)
190            {
191                continue;
192            }
193            matches.push(DescriptorMatch {
194                query_index,
195                train_index,
196                distance,
197                second_best_distance: second_distance,
198                ratio: second_distance.map(|second| distance / second),
199                confidence: None,
200            });
201        }
202        matches
203    }
204
205    /// Top-2 scores in both directions from one f32 matrix product.
206    fn top2_f32(
207        query: &[Vec<f32>],
208        train: &[Vec<f32>],
209        dim: usize,
210        query_norm_sq: &[f32],
211        train_norm_sq: &[f32],
212    ) -> Top2 {
213        let (n_query, n_train) = (query.len(), train.len());
214        let q = nalgebra::DMatrix::from_fn(n_query, dim, |i, k| query[i][k]);
215        let t = nalgebra::DMatrix::from_fn(n_train, dim, |j, k| train[j][k]);
216        let dots = q * t.transpose();
217
218        // nalgebra matrices are column-major. Walk every dot product once in
219        // its contiguous order and update both directional top-2 states. The
220        // query index still increases within each train column, and each
221        // query observes train indices in increasing outer-loop order, so the
222        // original strict-`<` first-wins tie behavior is preserved.
223        let mut forward_best = vec![None; n_query];
224        let mut forward_second = vec![None; n_query];
225        let mut reverse_best = vec![None; n_train];
226        let mut reverse_second = vec![None; n_train];
227        for train_index in 0..n_train {
228            for query_index in 0..n_query {
229                let dot = dots[(query_index, train_index)];
230                let reverse_score = query_norm_sq[query_index] - 2.0 * dot;
231                if reverse_best[train_index]
232                    .is_none_or(|(_, best_score)| reverse_score < best_score)
233                {
234                    reverse_second[train_index] =
235                        reverse_best[train_index].map(|(_, best_score)| best_score);
236                    reverse_best[train_index] = Some((query_index, reverse_score));
237                } else if reverse_second[train_index]
238                    .is_none_or(|second_score| reverse_score < second_score)
239                {
240                    reverse_second[train_index] = Some(reverse_score);
241                }
242
243                let forward_score = train_norm_sq[train_index] - 2.0 * dot;
244                if forward_best[query_index]
245                    .is_none_or(|(_, best_score)| forward_score < best_score)
246                {
247                    forward_second[query_index] = forward_best[query_index];
248                    forward_best[query_index] = Some((train_index, forward_score));
249                } else if forward_second[query_index]
250                    .is_none_or(|(_, second_score)| forward_score < second_score)
251                {
252                    forward_second[query_index] = Some((train_index, forward_score));
253                }
254            }
255        }
256        Top2 {
257            forward_best,
258            forward_second,
259            reverse_best,
260            reverse_second,
261        }
262    }
263}
264
265/// Best `(index, score)` and second-best score per row in both directions,
266/// as [`BruteForceMatcher::match_descriptors_cross_checked`] tracks them
267/// (forward: per query row, reverse: per train row).
268#[derive(Debug, PartialEq)]
269struct Top2 {
270    forward_best: Vec<Option<(usize, f32)>>,
271    forward_second: Vec<Option<(usize, f32)>>,
272    reverse_best: Vec<Option<(usize, f32)>>,
273    reverse_second: Vec<Option<f32>>,
274}
275
276impl Matcher for BruteForceMatcher {
277    fn match_descriptors(&self, query: &[Vec<f32>], train: &[Vec<f32>]) -> Vec<DescriptorMatch> {
278        // Nearest-neighbour by L2 is equivalent to nearest-neighbour by the
279        // squared distance ‖q−t‖² = ‖q‖² + ‖t‖² − 2·q·t. The cross term q·t for
280        // every (query, train) pair is one matrix product Q·Tᵀ, which nalgebra
281        // dispatches to the blocked `matrixmultiply` kernel — orders of
282        // magnitude faster than the element-wise double loop on the
283        // 256-dimensional deep descriptors this matcher is fed. The selected
284        // best/second distances are recovered as the actual L2 (sqrt), so the
285        // returned `distance` / `ratio` fields are unchanged.
286        let n_query = query.len();
287        let n_train = train.len();
288        if n_query == 0 || n_train == 0 {
289            return Vec::new();
290        }
291        let dim = query[0].len();
292        // The GEMM path assumes a single uniform descriptor dimension. Mixed
293        // lengths (or a zero dimension) fall back to the exact element-wise
294        // path, which skips mismatched pairs via `l2_distance`.
295        let uniform = dim != 0
296            && query.iter().all(|q| q.len() == dim)
297            && train.iter().all(|t| t.len() == dim);
298        if !uniform {
299            return self.match_descriptors_elementwise(query, train);
300        }
301
302        let q = nalgebra::DMatrix::from_fn(n_query, dim, |i, k| query[i][k]);
303        let t = nalgebra::DMatrix::from_fn(n_train, dim, |j, k| train[j][k]);
304        let dots = q * t.transpose(); // (n_query × n_train), dots[(i, j)] = qᵢ·tⱼ
305        let query_norm_sq: Vec<f32> = query
306            .iter()
307            .map(|q| q.iter().map(|x| x * x).sum())
308            .collect();
309        let train_norm_sq: Vec<f32> = train
310            .iter()
311            .map(|t| t.iter().map(|x| x * x).sum())
312            .collect();
313
314        let mut matches = Vec::new();
315        for query_index in 0..n_query {
316            // Rank by score_j = ‖t‖² − 2·q·t = ‖q−t‖² − ‖q‖²; ‖q‖² is constant
317            // across the row, so this preserves the argmin and the strict-`<`
318            // first-wins tie-break of the original loop.
319            let mut best: Option<(usize, f32)> = None;
320            let mut second_best: Option<(usize, f32)> = None;
321            for train_index in 0..n_train {
322                let score = train_norm_sq[train_index] - 2.0 * dots[(query_index, train_index)];
323                if best.is_none_or(|(_, best_score)| score < best_score) {
324                    second_best = best;
325                    best = Some((train_index, score));
326                } else if second_best.is_none_or(|(_, second_score)| score < second_score) {
327                    second_best = Some((train_index, score));
328                }
329            }
330
331            let Some((train_index, best_score)) = best else {
332                continue;
333            };
334            let distance = (query_norm_sq[query_index] + best_score).max(0.0).sqrt();
335            let second_distance = second_best.map(|(_, second_score)| {
336                (query_norm_sq[query_index] + second_score).max(0.0).sqrt()
337            });
338
339            if let Some(ratio) = self.ratio {
340                if let Some(second_distance) = second_distance {
341                    if distance >= ratio * second_distance {
342                        continue;
343                    }
344                }
345            }
346
347            matches.push(DescriptorMatch {
348                query_index,
349                train_index,
350                distance,
351                second_best_distance: second_distance,
352                ratio: second_distance.map(|second_distance| distance / second_distance),
353                confidence: None,
354            });
355        }
356
357        matches
358    }
359
360    /// Clone-free indexed match: build the `(N_candidates x dim)` train matrix
361    /// directly from the referenced rows instead of materialising a
362    /// `Vec<Vec<f32>>` subset. This is what makes an index-based matcher pay
363    /// off — the subset copy would otherwise dominate the GEMM it saves.
364    fn match_descriptors_indexed(
365        &self,
366        query: &[Vec<f32>],
367        train: &[Vec<f32>],
368        train_indices: &[usize],
369    ) -> Vec<DescriptorMatch> {
370        if train_indices.is_empty() || query.is_empty() {
371            return Vec::new();
372        }
373        let Some(dim) = query.first().map(Vec::len).filter(|&dim| dim != 0) else {
374            return Vec::new();
375        };
376        // The GEMM path needs a single uniform dimension on both sides; anything
377        // else falls back to the element-wise reference through the default
378        // subset materialisation.
379        let uniform = query.iter().all(|descriptor| descriptor.len() == dim)
380            && train_indices
381                .iter()
382                .all(|&index| train.get(index).is_some_and(|row| row.len() == dim));
383        if !uniform {
384            let subset: Vec<Vec<f32>> = train_indices
385                .iter()
386                .filter_map(|&index| train.get(index).cloned())
387                .collect();
388            let mut matches = self.match_descriptors_elementwise(query, &subset);
389            for descriptor_match in &mut matches {
390                if let Some(&global) = train_indices.get(descriptor_match.train_index) {
391                    descriptor_match.train_index = global;
392                }
393            }
394            return matches;
395        }
396
397        let q = nalgebra::DMatrix::from_fn(query.len(), dim, |i, k| query[i][k]);
398        let t =
399            nalgebra::DMatrix::from_fn(train_indices.len(), dim, |j, k| train[train_indices[j]][k]);
400        let dots = q * t.transpose();
401        let query_norm_sq: Vec<f32> = query
402            .iter()
403            .map(|descriptor| descriptor.iter().map(|value| value * value).sum())
404            .collect();
405        let train_norm_sq: Vec<f32> = train_indices
406            .iter()
407            .map(|&index| train[index].iter().map(|value| value * value).sum::<f32>())
408            .collect();
409
410        let mut matches = Vec::new();
411        for query_index in 0..query.len() {
412            let mut best: Option<(usize, f32)> = None;
413            let mut second_best: Option<(usize, f32)> = None;
414            for candidate in 0..train_indices.len() {
415                let score = train_norm_sq[candidate] - 2.0 * dots[(query_index, candidate)];
416                if best.is_none_or(|(_, best_score)| score < best_score) {
417                    second_best = best;
418                    best = Some((candidate, score));
419                } else if second_best.is_none_or(|(_, second_score)| score < second_score) {
420                    second_best = Some((candidate, score));
421                }
422            }
423            let Some((candidate, best_score)) = best else {
424                continue;
425            };
426            let distance = (query_norm_sq[query_index] + best_score).max(0.0).sqrt();
427            let second_distance = second_best.map(|(_, second_score)| {
428                (query_norm_sq[query_index] + second_score).max(0.0).sqrt()
429            });
430            if let Some(ratio) = self.ratio {
431                if let Some(second_distance) = second_distance {
432                    if distance >= ratio * second_distance {
433                        continue;
434                    }
435                }
436            }
437            matches.push(DescriptorMatch {
438                query_index,
439                train_index: train_indices[candidate],
440                distance,
441                second_best_distance: second_distance,
442                ratio: second_distance.map(|second_distance| distance / second_distance),
443                confidence: None,
444            });
445        }
446        matches
447    }
448}
449
450impl BruteForceMatcher {
451    /// Exact element-wise nearest-neighbour matching — the reference path used
452    /// when descriptors have mixed dimensions (the GEMM path needs a uniform
453    /// dimension). Identical in behaviour to the pre-GEMM implementation.
454    fn match_descriptors_elementwise(
455        &self,
456        query: &[Vec<f32>],
457        train: &[Vec<f32>],
458    ) -> Vec<DescriptorMatch> {
459        let mut matches = Vec::new();
460
461        for (query_index, query_descriptor) in query.iter().enumerate() {
462            let mut best: Option<(usize, f32)> = None;
463            let mut second_best: Option<(usize, f32)> = None;
464
465            for (train_index, train_descriptor) in train.iter().enumerate() {
466                let Some(distance) = Self::l2_distance(query_descriptor, train_descriptor) else {
467                    continue;
468                };
469
470                if best.is_none_or(|(_, best_distance)| distance < best_distance) {
471                    second_best = best;
472                    best = Some((train_index, distance));
473                } else if second_best.is_none_or(|(_, second_distance)| distance < second_distance)
474                {
475                    second_best = Some((train_index, distance));
476                }
477            }
478
479            let Some((train_index, distance)) = best else {
480                continue;
481            };
482
483            if let Some(ratio) = self.ratio {
484                if let Some((_, second_distance)) = second_best {
485                    if distance >= ratio * second_distance {
486                        continue;
487                    }
488                }
489            }
490
491            matches.push(DescriptorMatch {
492                query_index,
493                train_index,
494                distance,
495                second_best_distance: second_best.map(|(_, second_distance)| second_distance),
496                ratio: second_best.map(|(_, second_distance)| distance / second_distance),
497                confidence: None,
498            });
499        }
500
501        matches
502    }
503}
504
505#[derive(Debug, Clone, PartialEq)]
506pub struct CrossCheckMatcher<M = BruteForceMatcher> {
507    pub inner: M,
508}
509
510impl<M> CrossCheckMatcher<M> {
511    pub const fn new(inner: M) -> Self {
512        Self { inner }
513    }
514}
515
516impl<M> Default for CrossCheckMatcher<M>
517where
518    M: Default,
519{
520    fn default() -> Self {
521        Self {
522            inner: M::default(),
523        }
524    }
525}
526
527impl<M> Matcher for CrossCheckMatcher<M>
528where
529    M: Matcher,
530{
531    fn match_descriptors(&self, query: &[Vec<f32>], train: &[Vec<f32>]) -> Vec<DescriptorMatch> {
532        let forward = self.inner.match_descriptors(query, train);
533        if forward.is_empty() {
534            return forward;
535        }
536
537        let reverse = self.inner.match_descriptors(train, query);
538        let mut reverse_best_query_by_train = vec![None; train.len()];
539        for descriptor_match in reverse {
540            if descriptor_match.query_index < reverse_best_query_by_train.len() {
541                reverse_best_query_by_train[descriptor_match.query_index] =
542                    Some(descriptor_match.train_index);
543            }
544        }
545
546        forward
547            .into_iter()
548            .filter(|descriptor_match| {
549                reverse_best_query_by_train
550                    .get(descriptor_match.train_index)
551                    .copied()
552                    .flatten()
553                    == Some(descriptor_match.query_index)
554            })
555            .collect()
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use super::{BruteForceMatcher, CrossCheckMatcher, Matcher};
562
563    #[test]
564    fn single_gemm_cross_check_matches_two_pass_reference() {
565        for (query_count, train_count, dim) in [(3, 5, 4), (17, 11, 32), (9, 13, 128)] {
566            let descriptors = |count: usize, salt: usize| {
567                (0..count)
568                    .map(|row| {
569                        (0..dim)
570                            .map(|column| {
571                                let value = (row * 131 + column * 17 + salt * 29) % 251;
572                                (value as f32 - 125.0) / 127.0
573                            })
574                            .collect::<Vec<_>>()
575                    })
576                    .collect::<Vec<_>>()
577            };
578            let query = descriptors(query_count, 3);
579            let train = descriptors(train_count, 7);
580            for ratio in [None, Some(0.8), Some(0.95)] {
581                let matcher = BruteForceMatcher { ratio };
582                let reference = CrossCheckMatcher::new(matcher).match_descriptors(&query, &train);
583                assert_eq!(
584                    matcher.match_descriptors_cross_checked(&query, &train),
585                    reference
586                );
587            }
588        }
589    }
590
591    #[test]
592    fn single_gemm_cross_check_preserves_mixed_dimension_fallback() {
593        let query = vec![vec![0.0, 1.0], vec![1.0]];
594        let train = vec![vec![0.0, 1.0], vec![2.0]];
595        let matcher = BruteForceMatcher { ratio: Some(0.8) };
596        let reference = CrossCheckMatcher::new(matcher).match_descriptors(&query, &train);
597        assert_eq!(
598            matcher.match_descriptors_cross_checked(&query, &train),
599            reference
600        );
601    }
602
603    #[test]
604    fn matches_nearest_descriptor_with_ratio_test() {
605        let matcher = BruteForceMatcher { ratio: Some(0.9) };
606        let query = vec![vec![1.0, 0.0]];
607        let train = vec![vec![1.01, 0.0], vec![3.0, 0.0]];
608        let matches = matcher.match_descriptors(&query, &train);
609        assert_eq!(matches.len(), 1);
610        assert_eq!(matches[0].train_index, 0);
611        assert!(matches[0].second_best_distance.is_some());
612        assert!(matches[0].ratio.unwrap() < 0.9);
613    }
614
615    #[test]
616    fn cross_check_matcher_keeps_only_mutual_matches() {
617        let matcher = CrossCheckMatcher::new(BruteForceMatcher { ratio: None });
618        let query = vec![vec![0.0], vec![0.2]];
619        let train = vec![vec![0.1], vec![5.0]];
620
621        let matches = matcher.match_descriptors(&query, &train);
622
623        assert_eq!(matches.len(), 1);
624        assert_eq!(matches[0].query_index, 0);
625        assert_eq!(matches[0].train_index, 0);
626    }
627}