Skip to main content

smriti/ml/
retrieval.rs

1//! Gallery-based face retrieval.
2//!
3//! Given a query embedding and a set of per-cluster galleries (N diverse
4//! exemplars per cluster), find the best-matching clusters via k-NN.
5//! Each cluster's score is the mean of the top-k cosine similarities among its
6//! gallery members. This is strictly stronger than centroid matching: a
7//! cluster is "close" if *multiple* of its real members are close, not just
8//! its mean.
9//!
10//! The result drives confidence-banded assignment: HIGH -> auto-assign,
11//! LOW -> leave unassigned, AMBIGUOUS -> queue for user review.
12
13use super::FaceEmbedding;
14
15/// A cluster candidate ranked against the query face.
16#[derive(Debug, Clone)]
17pub struct RetrievalHit {
18    pub cluster_id: i64,
19    /// Mean of the top-k cosine similarities against this cluster's gallery.
20    /// Higher = better. Range [-1, 1], but in practice [0, 1].
21    pub score: f32,
22    /// Face id within the gallery that had the single highest similarity.
23    pub best_match_face_id: i64,
24    /// How many gallery members exceeded `min_similarity`.
25    pub num_matches: usize,
26}
27
28/// Assignment recommendation for a query face.
29#[derive(Debug, Clone)]
30pub enum ConfidenceBand {
31    /// Top candidate exceeds `high_threshold` and leads the runner-up by
32    /// at least `margin`. Safe to auto-assign.
33    High { hit: RetrievalHit },
34    /// Between thresholds, or top-2 candidates too close. Queue for review.
35    Ambiguous {
36        top: RetrievalHit,
37        runner_up: Option<RetrievalHit>,
38    },
39    /// Top score below `low_threshold`. Face does not match any existing
40    /// cluster; leave for agglomerative pass or mark as a new singleton.
41    Low,
42}
43
44/// Thresholds for banding. Tuned for ArcFace / GLinTR L2-normalized embeddings.
45#[derive(Debug, Clone, Copy)]
46pub struct BandingConfig {
47    /// Minimum score to consider any match at all.
48    pub low_threshold: f32,
49    /// Minimum top score to auto-assign without review.
50    pub high_threshold: f32,
51    /// Minimum score gap between top and runner-up to auto-assign.
52    pub margin: f32,
53}
54
55impl Default for BandingConfig {
56    fn default() -> Self {
57        // Tuned to err toward caution. A face gets auto-assigned only when
58        // its mean top-K cosine to a cluster's gallery is ≥ 0.65 AND beats
59        // the runner-up cluster by ≥ 0.12. Anything weaker is AMBIGUOUS and
60        // left for the clustering pass. Better to leave a face unassigned
61        // than to silently misclassify.
62        Self {
63            low_threshold: 0.40,
64            high_threshold: 0.65,
65            margin: 0.12,
66        }
67    }
68}
69
70/// Retrieve ranked cluster candidates for a query embedding.
71///
72/// `galleries` is a slice of (cluster_id, Vec<(face_id, embedding)>). All
73/// embeddings are assumed L2-normalized (as produced by the embedder and
74/// stored in `person_gallery_embeddings`).
75///
76/// `top_k` is the number of best matches per cluster to average into that
77/// cluster's score. 5 is a good default.
78///
79/// `min_similarity` filters individual gallery members below this cosine
80/// similarity before they contribute to the score.
81///
82/// Clusters in `exclude` are skipped entirely -- used to honor
83/// cannot-merge constraints and same-photo conflict prevention.
84///
85/// Returns clusters sorted by descending score. Empty if no cluster scored
86/// above `min_similarity`.
87pub fn retrieve_candidates(
88    query: &FaceEmbedding,
89    galleries: &[(i64, Vec<(i64, FaceEmbedding)>)],
90    top_k: usize,
91    min_similarity: f32,
92    exclude: &std::collections::HashSet<i64>,
93) -> Vec<RetrievalHit> {
94    if top_k == 0 {
95        return Vec::new();
96    }
97
98    let mut hits: Vec<RetrievalHit> = Vec::with_capacity(galleries.len());
99
100    for (cluster_id, members) in galleries {
101        if exclude.contains(cluster_id) || members.is_empty() {
102            continue;
103        }
104
105        // Score each member, keep those above min_similarity.
106        let mut scored: Vec<(i64, f32)> = members
107            .iter()
108            .map(|(face_id, emb)| (*face_id, query.cosine_similarity(emb)))
109            .filter(|(_, s)| *s >= min_similarity)
110            .collect();
111
112        if scored.is_empty() {
113            continue;
114        }
115
116        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
117        let k = top_k.min(scored.len());
118        let mean_top_k: f32 = scored.iter().take(k).map(|(_, s)| s).sum::<f32>() / k as f32;
119
120        hits.push(RetrievalHit {
121            cluster_id: *cluster_id,
122            score: mean_top_k,
123            best_match_face_id: scored[0].0,
124            num_matches: scored.len(),
125        });
126    }
127
128    hits.sort_by(|a, b| {
129        b.score
130            .partial_cmp(&a.score)
131            .unwrap_or(std::cmp::Ordering::Equal)
132    });
133    hits
134}
135
136/// Classify the retrieval result into a confidence band.
137pub fn classify(hits: &[RetrievalHit], cfg: &BandingConfig) -> ConfidenceBand {
138    match hits.len() {
139        0 => ConfidenceBand::Low,
140        1 => {
141            let top = hits[0].clone();
142            if top.score >= cfg.high_threshold {
143                ConfidenceBand::High { hit: top }
144            } else if top.score >= cfg.low_threshold {
145                ConfidenceBand::Ambiguous {
146                    top,
147                    runner_up: None,
148                }
149            } else {
150                ConfidenceBand::Low
151            }
152        }
153        _ => {
154            let top = hits[0].clone();
155            let runner_up = hits[1].clone();
156            if top.score < cfg.low_threshold {
157                ConfidenceBand::Low
158            } else if top.score >= cfg.high_threshold && (top.score - runner_up.score) >= cfg.margin
159            {
160                ConfidenceBand::High { hit: top }
161            } else {
162                ConfidenceBand::Ambiguous {
163                    top,
164                    runner_up: Some(runner_up),
165                }
166            }
167        }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use ndarray::Array1;
175    use std::collections::HashSet;
176
177    fn emb(v: Vec<f32>) -> FaceEmbedding {
178        let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
179        let normed: Vec<f32> = v.iter().map(|x| x / norm).collect();
180        FaceEmbedding::new(Array1::from_vec(normed))
181    }
182
183    #[test]
184    fn empty_galleries_yield_no_hits() {
185        let q = emb(vec![1.0, 0.0, 0.0]);
186        let hits = retrieve_candidates(&q, &[], 3, 0.3, &HashSet::new());
187        assert!(hits.is_empty());
188    }
189
190    #[test]
191    fn zero_top_k_yields_no_hits() {
192        let q = emb(vec![1.0, 0.0, 0.0]);
193        let galleries = vec![(1, vec![(10, emb(vec![1.0, 0.0, 0.0]))])];
194
195        let hits = retrieve_candidates(&q, &galleries, 0, 0.3, &HashSet::new());
196
197        assert!(hits.is_empty());
198    }
199
200    #[test]
201    fn near_identical_gallery_scores_highest() {
202        let q = emb(vec![1.0, 0.0, 0.0]);
203        let galleries: Vec<(i64, Vec<(i64, FaceEmbedding)>)> = vec![
204            (
205                1,
206                vec![
207                    (10, emb(vec![0.99, 0.01, 0.0])),
208                    (11, emb(vec![0.98, 0.0, 0.1])),
209                ],
210            ),
211            (2, vec![(20, emb(vec![0.0, 1.0, 0.0]))]),
212        ];
213
214        let hits = retrieve_candidates(&q, &galleries, 3, 0.3, &HashSet::new());
215        assert_eq!(hits.len(), 1); // cluster 2 is below threshold
216        assert_eq!(hits[0].cluster_id, 1);
217        assert!(hits[0].score > 0.98);
218    }
219
220    #[test]
221    fn exclusion_is_respected() {
222        let q = emb(vec![1.0, 0.0, 0.0]);
223        let galleries: Vec<(i64, Vec<(i64, FaceEmbedding)>)> = vec![
224            (1, vec![(10, emb(vec![0.99, 0.01, 0.0]))]),
225            (2, vec![(20, emb(vec![0.95, 0.05, 0.0]))]),
226        ];
227
228        let mut exclude = HashSet::new();
229        exclude.insert(1);
230        let hits = retrieve_candidates(&q, &galleries, 3, 0.3, &exclude);
231        assert_eq!(hits.len(), 1);
232        assert_eq!(hits[0].cluster_id, 2);
233    }
234
235    #[test]
236    fn classify_bands() {
237        let cfg = BandingConfig::default();
238
239        let low = vec![RetrievalHit {
240            cluster_id: 1,
241            score: 0.2,
242            best_match_face_id: 1,
243            num_matches: 1,
244        }];
245        assert!(matches!(classify(&low, &cfg), ConfidenceBand::Low));
246
247        let high = vec![RetrievalHit {
248            cluster_id: 1,
249            score: 0.7,
250            best_match_face_id: 1,
251            num_matches: 3,
252        }];
253        assert!(matches!(classify(&high, &cfg), ConfidenceBand::High { .. }));
254
255        let ambiguous_pair = vec![
256            RetrievalHit {
257                cluster_id: 1,
258                score: 0.60,
259                best_match_face_id: 1,
260                num_matches: 2,
261            },
262            RetrievalHit {
263                cluster_id: 2,
264                score: 0.57,
265                best_match_face_id: 2,
266                num_matches: 2,
267            },
268        ];
269        assert!(matches!(
270            classify(&ambiguous_pair, &cfg),
271            ConfidenceBand::Ambiguous { .. }
272        ));
273    }
274}