1use super::{DescriptorMatch, Matcher};
18
19#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct MutualSoftmaxConfig {
22 pub temperature: f32,
25 pub min_confidence: f32,
27 pub emit_ratio_metadata: bool,
31}
32
33impl Default for MutualSoftmaxConfig {
34 fn default() -> Self {
35 Self {
36 temperature: 20.0,
37 min_confidence: 0.2,
38 emit_ratio_metadata: false,
39 }
40 }
41}
42
43#[derive(Debug, Clone, Copy, Default, PartialEq)]
45pub struct MutualSoftmaxMatcher {
46 pub config: MutualSoftmaxConfig,
47}
48
49impl MutualSoftmaxMatcher {
50 pub const fn new(config: MutualSoftmaxConfig) -> Self {
51 Self { config }
52 }
53
54 fn similarity(query: &[Vec<f32>], train: &[Vec<f32>]) -> Option<Vec<f32>> {
55 let descriptor_dim = query.first().map_or(0, |q| q.len());
56 if descriptor_dim == 0 {
57 return None;
58 }
59 for descriptor in query.iter().chain(train.iter()) {
60 if descriptor.len() != descriptor_dim {
61 return None;
62 }
63 }
64 let mut similarity = vec![0.0_f32; query.len() * train.len()];
65 for (qi, q) in query.iter().enumerate() {
66 for (tj, t) in train.iter().enumerate() {
67 let mut dot = 0.0_f32;
68 for (a, b) in q.iter().zip(t.iter()) {
69 dot += a * b;
70 }
71 similarity[qi * train.len() + tj] = dot;
72 }
73 }
74 Some(similarity)
75 }
76
77 fn softmax_row(similarity: &[f32], rows: usize, cols: usize, temperature: f32) -> Vec<f32> {
78 let mut out = vec![0.0_f32; rows * cols];
79 for r in 0..rows {
80 let row = &similarity[r * cols..(r + 1) * cols];
81 let max = row.iter().copied().fold(f32::NEG_INFINITY, f32::max);
82 if !max.is_finite() {
83 continue;
84 }
85 let mut sum = 0.0_f32;
86 for (c, &value) in row.iter().enumerate() {
87 let exp = ((value - max) * temperature).exp();
88 out[r * cols + c] = exp;
89 sum += exp;
90 }
91 if sum > 0.0 {
92 for c in 0..cols {
93 out[r * cols + c] /= sum;
94 }
95 }
96 }
97 out
98 }
99
100 fn softmax_col(similarity: &[f32], rows: usize, cols: usize, temperature: f32) -> Vec<f32> {
101 let mut out = vec![0.0_f32; rows * cols];
102 for c in 0..cols {
103 let mut max = f32::NEG_INFINITY;
104 for r in 0..rows {
105 let value = similarity[r * cols + c];
106 if value > max {
107 max = value;
108 }
109 }
110 if !max.is_finite() {
111 continue;
112 }
113 let mut sum = 0.0_f32;
114 for r in 0..rows {
115 let exp = ((similarity[r * cols + c] - max) * temperature).exp();
116 out[r * cols + c] = exp;
117 sum += exp;
118 }
119 if sum > 0.0 {
120 for r in 0..rows {
121 out[r * cols + c] /= sum;
122 }
123 }
124 }
125 out
126 }
127}
128
129impl Matcher for MutualSoftmaxMatcher {
130 fn match_descriptors(&self, query: &[Vec<f32>], train: &[Vec<f32>]) -> Vec<DescriptorMatch> {
131 if query.is_empty() || train.is_empty() {
132 return Vec::new();
133 }
134 let Some(similarity) = Self::similarity(query, train) else {
135 return Vec::new();
136 };
137 let rows = query.len();
138 let cols = train.len();
139 let temperature = self.config.temperature;
140 let row_soft = Self::softmax_row(&similarity, rows, cols, temperature);
141 let col_soft = Self::softmax_col(&similarity, rows, cols, temperature);
142
143 let mut confidence = vec![0.0_f32; rows * cols];
144 for index in 0..rows * cols {
145 confidence[index] = (row_soft[index] * col_soft[index]).sqrt();
146 }
147
148 let mut row_best = vec![(0usize, f32::NEG_INFINITY); rows];
150 let mut row_second = vec![f32::NEG_INFINITY; rows];
151 for r in 0..rows {
152 for c in 0..cols {
153 let v = confidence[r * cols + c];
154 if v > row_best[r].1 {
155 row_second[r] = row_best[r].1;
156 row_best[r] = (c, v);
157 } else if v > row_second[r] {
158 row_second[r] = v;
159 }
160 }
161 }
162
163 let mut col_best = vec![(0usize, f32::NEG_INFINITY); cols];
165 for c in 0..cols {
166 for r in 0..rows {
167 let v = confidence[r * cols + c];
168 if v > col_best[c].1 {
169 col_best[c] = (r, v);
170 }
171 }
172 }
173
174 let mut matches = Vec::new();
175 for (qi, &(best_train, best_conf)) in row_best.iter().enumerate() {
176 if best_conf < self.config.min_confidence {
177 continue;
178 }
179 let (mutual_query, _) = col_best[best_train];
180 if mutual_query != qi {
181 continue;
182 }
183 let similarity_value = similarity[qi * cols + best_train];
184 let descriptor_distance = ((1.0 - similarity_value).max(0.0) * 2.0).sqrt();
185 let second_value = row_second[qi];
186 let ratio = if self.config.emit_ratio_metadata && second_value > 0.0 {
187 Some(second_value / best_conf)
188 } else {
189 None
190 };
191 matches.push(DescriptorMatch {
192 query_index: qi,
193 train_index: best_train,
194 distance: descriptor_distance,
195 second_best_distance: if self.config.emit_ratio_metadata {
196 Some(((1.0 - second_value).max(0.0) * 2.0).sqrt())
197 } else {
198 None
199 },
200 ratio,
201 confidence: Some(best_conf),
202 });
203 }
204 matches
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 fn unit(values: &[f32]) -> Vec<f32> {
213 let norm = values.iter().map(|v| v * v).sum::<f32>().sqrt();
214 values.iter().map(|v| v / norm.max(1e-12)).collect()
215 }
216
217 #[test]
218 fn matches_identical_descriptors_one_to_one() {
219 let descriptors = vec![
220 unit(&[1.0, 0.0, 0.0, 0.0]),
221 unit(&[0.0, 1.0, 0.0, 0.0]),
222 unit(&[0.0, 0.0, 1.0, 0.0]),
223 ];
224 let matcher = MutualSoftmaxMatcher::default();
225 let matches = matcher.match_descriptors(&descriptors, &descriptors);
226 assert_eq!(matches.len(), 3);
227 for m in &matches {
228 assert_eq!(m.query_index, m.train_index);
229 assert!(m.distance < 1e-3, "self-match distance should be near zero");
230 let conf = m.confidence.expect("MutualSoftmax populates confidence");
233 assert!(
234 conf > 0.99,
235 "self-match confidence should be near 1.0, got {conf}"
236 );
237 }
238 }
239
240 #[test]
241 fn confidence_is_strictly_higher_for_a_better_match_than_an_ambiguous_one() {
242 let query = vec![
247 unit(&[1.0, 0.0, 0.0, 0.0]),
248 unit(&[0.7, 0.7, 0.0, 0.0]), ];
250 let train = vec![
251 unit(&[1.0, 0.0, 0.0, 0.0]),
252 unit(&[1.0, 1.0, 0.0, 0.0]),
253 unit(&[1.0, 0.9, 0.0, 0.0]),
254 ];
255 let matcher = MutualSoftmaxMatcher::new(MutualSoftmaxConfig {
256 temperature: 25.0,
257 min_confidence: 0.0,
258 emit_ratio_metadata: false,
259 });
260 let matches = matcher.match_descriptors(&query, &train);
261 let conf_distinct = matches
262 .iter()
263 .find(|m| m.query_index == 0)
264 .and_then(|m| m.confidence)
265 .expect("query 0 matches the distinctive train descriptor");
266 let conf_ambig = matches
267 .iter()
268 .find(|m| m.query_index == 1)
269 .and_then(|m| m.confidence)
270 .expect("query 1 still produces a match below the threshold");
271 assert!(
272 conf_distinct > conf_ambig,
273 "distinctive match should have higher confidence: distinct={conf_distinct} ambiguous={conf_ambig}"
274 );
275 }
276
277 #[test]
278 fn rejects_low_confidence_when_train_is_ambiguous() {
279 let query = vec![unit(&[1.0, 0.5, 0.0, 0.0])];
283 let train = vec![unit(&[1.0, 0.5, 0.0, 0.0]); 2];
284 let matcher = MutualSoftmaxMatcher::new(MutualSoftmaxConfig {
285 temperature: 20.0,
286 min_confidence: 0.8,
287 emit_ratio_metadata: false,
288 });
289 let matches = matcher.match_descriptors(&query, &train);
290 assert!(
291 matches.is_empty(),
292 "ambiguous row-softmax matches should be filtered by confidence threshold"
293 );
294 }
295
296 #[test]
297 fn rejects_low_confidence_when_both_directions_are_ambiguous() {
298 let query = vec![unit(&[1.0, 0.5, 0.0, 0.0]); 2];
301 let train = vec![unit(&[1.0, 0.5, 0.0, 0.0]); 2];
302 let matcher = MutualSoftmaxMatcher::new(MutualSoftmaxConfig {
303 temperature: 20.0,
304 min_confidence: 0.6,
305 emit_ratio_metadata: false,
306 });
307 let matches = matcher.match_descriptors(&query, &train);
308 assert!(matches.is_empty());
309 }
310
311 #[test]
312 fn enforces_mutual_nearest_neighbour() {
313 let query = vec![unit(&[1.0, 0.0]), unit(&[0.95, 0.05])];
315 let train = vec![unit(&[1.0, 0.0])];
316 let matcher = MutualSoftmaxMatcher::new(MutualSoftmaxConfig {
317 temperature: 30.0,
318 min_confidence: 0.05,
319 emit_ratio_metadata: false,
320 });
321 let matches = matcher.match_descriptors(&query, &train);
322 assert_eq!(matches.len(), 1);
324 assert_eq!(matches[0].query_index, 0);
325 assert_eq!(matches[0].train_index, 0);
326 }
327
328 #[test]
329 fn handles_empty_inputs() {
330 let matcher = MutualSoftmaxMatcher::default();
331 assert!(matcher.match_descriptors(&[], &[]).is_empty());
332 assert!(matcher
333 .match_descriptors(&[unit(&[1.0, 0.0])], &[])
334 .is_empty());
335 assert!(matcher
336 .match_descriptors(&[], &[unit(&[1.0, 0.0])])
337 .is_empty());
338 }
339
340 #[test]
341 fn temperature_zero_falls_back_to_uniform_filtering() {
342 let query = vec![unit(&[1.0, 0.0]), unit(&[0.0, 1.0])];
345 let train = vec![unit(&[1.0, 0.0]), unit(&[0.0, 1.0])];
346 let matcher = MutualSoftmaxMatcher::new(MutualSoftmaxConfig {
347 temperature: 0.0,
348 min_confidence: 0.9,
349 emit_ratio_metadata: false,
350 });
351 let matches = matcher.match_descriptors(&query, &train);
352 assert!(matches.is_empty());
353 }
354
355 #[test]
356 fn shape_mismatched_descriptors_yield_no_matches() {
357 let query = vec![vec![1.0, 0.0]];
358 let train = vec![vec![1.0, 0.0, 0.0]];
359 let matcher = MutualSoftmaxMatcher::default();
360 assert!(matcher.match_descriptors(&query, &train).is_empty());
361 }
362}