Skip to main content

smriti/ml/
clustering.rs

1//! Face clustering using agglomerative complete-linkage.
2//!
3//! This avoids DBSCAN chaining by only merging clusters where *all*
4//! pairwise distances remain under a strict threshold.
5
6use std::collections::HashMap;
7
8use super::FaceEmbedding;
9
10// HNSW deliberately randomizes graph levels. Exact complete-link clustering
11// is affordable for small batches and makes repeated runs stable; large
12// libraries retain the O(n log n) path.
13#[cfg(feature = "hnsw_clustering")]
14const EXACT_CLUSTER_LIMIT: usize = 256;
15
16#[derive(Debug, Clone)]
17pub struct ClusterInput {
18    pub face_id: i64,
19    pub photo_id: i64,
20    /// Current cluster assignment (if any) — used with face_negatives to
21    /// avoid clustering a face back into a cluster it was rejected from.
22    pub current_cluster_id: Option<i64>,
23    pub embedding: FaceEmbedding,
24}
25
26/// Agglomerative clusterer with complete linkage.
27pub struct FaceClusterer {
28    /// Maximum cosine distance (1 - cosine similarity) allowed within cluster.
29    max_distance: f32,
30}
31
32impl FaceClusterer {
33    /// Strict default to reduce false merges.
34    pub fn new() -> Self {
35        Self { max_distance: 0.28 }
36    }
37
38    pub fn with_max_distance(mut self, max_distance: f32) -> Self {
39        self.max_distance = max_distance.clamp(0.05, 1.0);
40        self
41    }
42
43    /// Cluster faces and return map of face_id -> cluster_label (-1 = singleton/noise).
44    ///
45    /// `negatives` is an optional set of (face_id, not_cluster_id) pairs from
46    /// the `face_negatives` table. When present, two faces whose current clusters
47    /// are blocked by a negative constraint will not be merged.
48    pub fn cluster(
49        &self,
50        faces: &[ClusterInput],
51        negatives: Option<&std::collections::HashSet<(i64, i64)>>,
52    ) -> HashMap<i64, i32> {
53        #[cfg(feature = "hnsw_clustering")]
54        {
55            if faces.len() <= EXACT_CLUSTER_LIMIT {
56                self.cluster_complete_link(faces, negatives)
57            } else {
58                cluster_hnsw(faces, self.max_distance, negatives)
59            }
60        }
61        #[cfg(not(feature = "hnsw_clustering"))]
62        {
63            self.cluster_complete_link(faces, negatives)
64        }
65    }
66
67    /// Legacy O(n²) complete-link path. Kept compiled when
68    /// `hnsw_clustering` is off so we can A/B against the new
69    /// implementation on a real library by toggling features.
70    fn cluster_complete_link(
71        &self,
72        faces: &[ClusterInput],
73        negatives: Option<&std::collections::HashSet<(i64, i64)>>,
74    ) -> HashMap<i64, i32> {
75        if faces.is_empty() {
76            return HashMap::new();
77        }
78
79        // Start with each face in its own cluster.
80        let mut clusters: Vec<Vec<usize>> = (0..faces.len()).map(|i| vec![i]).collect();
81
82        loop {
83            let mut best_pair: Option<(usize, usize, f32)> = None;
84
85            for i in 0..clusters.len() {
86                for j in (i + 1)..clusters.len() {
87                    let d = self.complete_link_distance(&clusters[i], &clusters[j], faces);
88                    if d > self.max_distance {
89                        continue;
90                    }
91
92                    let mut merged = clusters[i].clone();
93                    merged.extend_from_slice(&clusters[j]);
94                    if Self::has_same_photo_conflict(&merged, faces) {
95                        continue;
96                    }
97                    if Self::has_negative_conflict(&clusters[i], &clusters[j], faces, negatives) {
98                        continue;
99                    }
100
101                    match best_pair {
102                        Some((_, _, best_d)) if d >= best_d => {}
103                        _ => best_pair = Some((i, j, d)),
104                    }
105                }
106            }
107
108            let Some((a, b, _)) = best_pair else {
109                break;
110            };
111
112            let mut merged = clusters[a].clone();
113            merged.extend_from_slice(&clusters[b]);
114
115            // Merge b into a
116            clusters[a] = merged;
117            clusters.remove(b);
118        }
119
120        let mut out = HashMap::new();
121        let mut label = 0i32;
122        for members in clusters {
123            if members.len() < 2 {
124                out.insert(faces[members[0]].face_id, -1);
125            } else {
126                for idx in members {
127                    out.insert(faces[idx].face_id, label);
128                }
129                label += 1;
130            }
131        }
132        out
133    }
134
135    fn complete_link_distance(&self, a: &[usize], b: &[usize], faces: &[ClusterInput]) -> f32 {
136        let mut max_d = 0.0f32;
137        for &i in a {
138            for &j in b {
139                let sim = faces[i].embedding.cosine_similarity(&faces[j].embedding);
140                let d = 1.0 - sim;
141                if d > max_d {
142                    max_d = d;
143                }
144            }
145        }
146        max_d
147    }
148
149    fn has_same_photo_conflict(cluster: &[usize], faces: &[ClusterInput]) -> bool {
150        let mut seen = std::collections::HashSet::new();
151        for &idx in cluster {
152            let pid = faces[idx].photo_id;
153            if !seen.insert(pid) {
154                return true;
155            }
156        }
157        false
158    }
159
160    /// If any face in cluster A has a (face_id, current_cluster_id-of-some-face-in-B)
161    /// pair in `negatives` — or vice versa — the merge is forbidden.
162    fn has_negative_conflict(
163        a: &[usize],
164        b: &[usize],
165        faces: &[ClusterInput],
166        negatives: Option<&std::collections::HashSet<(i64, i64)>>,
167    ) -> bool {
168        let neg = match negatives {
169            Some(n) if !n.is_empty() => n,
170            _ => return false,
171        };
172        for &ai in a {
173            for &bi in b {
174                if let Some(bc) = faces[bi].current_cluster_id {
175                    if neg.contains(&(faces[ai].face_id, bc)) {
176                        return true;
177                    }
178                }
179                if let Some(ac) = faces[ai].current_cluster_id {
180                    if neg.contains(&(faces[bi].face_id, ac)) {
181                        return true;
182                    }
183                }
184            }
185        }
186        false
187    }
188}
189
190/// HNSW-based clustering — replaces complete-link's O(n²) with
191/// O(n log n) index build + O(n · k) k-NN queries + O(n · α) union-find.
192/// Wall time on 10k faces: <30 s vs hours for the legacy path.
193///
194/// 1. Build an HNSW index over all embeddings using cosine distance.
195/// 2. For each face, query top-K nearest neighbours (K=15).
196/// 3. Edges with similarity ≥ (1 − max_distance) and no same-photo
197///    conflict get unioned via union-find.
198/// 4. Each connected component with ≥ 2 members becomes a cluster.
199#[cfg(feature = "hnsw_clustering")]
200fn cluster_hnsw(
201    faces: &[ClusterInput],
202    max_distance: f32,
203    negatives: Option<&std::collections::HashSet<(i64, i64)>>,
204) -> HashMap<i64, i32> {
205    use hnsw_rs::prelude::*;
206    use std::collections::HashSet;
207    if faces.is_empty() {
208        return HashMap::new();
209    }
210    if faces.len() == 1 {
211        let mut out = HashMap::new();
212        out.insert(faces[0].face_id, -1);
213        return out;
214    }
215
216    let n = faces.len();
217    // M=16 / ef_c=200 are the de-facto-good defaults for cosine
218    // recall on ~512-dim vectors.
219    let max_nb_connection = 16;
220    let ef_c = 200;
221    let nb_layer = 16.min(((n as f32).ln().trunc() as usize).max(1));
222    let hns: Hnsw<f32, DistCosine> = Hnsw::new(max_nb_connection, n, nb_layer, ef_c, DistCosine {});
223
224    // Insert with HNSW's per-row index as the data id; we map back
225    // to face_id via the input slice.
226    let data: Vec<(&[f32], usize)> = faces
227        .iter()
228        .enumerate()
229        .map(|(i, f)| (f.embedding.vector.as_slice().unwrap_or(&[]), i))
230        .collect();
231    hns.parallel_insert_slice(&data);
232
233    // Union-find over face indices.
234    let mut parent: Vec<usize> = (0..n).collect();
235    fn find(parent: &mut [usize], mut x: usize) -> usize {
236        while parent[x] != x {
237            parent[x] = parent[parent[x]];
238            x = parent[x];
239        }
240        x
241    }
242    fn union(parent: &mut [usize], a: usize, b: usize) {
243        let ra = find(parent, a);
244        let rb = find(parent, b);
245        if ra != rb {
246            parent[ra] = rb;
247        }
248    }
249
250    // Per-component state, kept on the union-find root and merged
251    // smaller-into-larger, so each candidate edge is checked in time
252    // proportional to the (small) component sets instead of rescanning
253    // every face:
254    // - photos: same-photo conflict (two faces of one photo never share
255    //   a person);
256    // - clusters / negated: face_negatives — no face may join a cluster
257    //   the user said it is not.
258    struct Component {
259        photos: HashSet<i64>,
260        clusters: HashSet<i64>,
261        negated: HashSet<i64>,
262    }
263    let mut negated_by_face: HashMap<i64, Vec<i64>> = HashMap::new();
264    if let Some(neg) = negatives {
265        for &(face_id, cluster_id) in neg {
266            negated_by_face.entry(face_id).or_default().push(cluster_id);
267        }
268    }
269    let mut components: HashMap<usize, Component> = faces
270        .iter()
271        .enumerate()
272        .map(|(i, f)| {
273            let component = Component {
274                photos: HashSet::from([f.photo_id]),
275                clusters: f.current_cluster_id.into_iter().collect(),
276                negated: negated_by_face
277                    .get(&f.face_id)
278                    .map(|cids| cids.iter().copied().collect())
279                    .unwrap_or_default(),
280            };
281            (i, component)
282        })
283        .collect();
284
285    let knbn = 15;
286    let ef_search = ef_c;
287    for (i, face_i) in faces.iter().enumerate() {
288        let query = match face_i.embedding.vector.as_slice() {
289            Some(s) => s,
290            None => continue,
291        };
292        let neighbours = hns.search(query, knbn, ef_search);
293        for nb in neighbours {
294            let j = nb.d_id;
295            if j == i {
296                continue;
297            }
298            // DistCosine returns 1 - cos_sim, which is exactly our
299            // existing "max_distance" threshold semantics.
300            if nb.distance > max_distance {
301                continue;
302            }
303            let ra = find(&mut parent, i);
304            let rb = find(&mut parent, j);
305            if ra == rb {
306                continue;
307            }
308            let (Some(a), Some(b)) = (components.get(&ra), components.get(&rb)) else {
309                continue;
310            };
311            if !a.photos.is_disjoint(&b.photos)
312                || !a.negated.is_disjoint(&b.clusters)
313                || !b.negated.is_disjoint(&a.clusters)
314            {
315                continue;
316            }
317
318            union(&mut parent, ra, rb);
319            let new_root = find(&mut parent, ra);
320            let (Some(mut a), Some(mut b)) = (components.remove(&ra), components.remove(&rb))
321            else {
322                continue;
323            };
324            if a.photos.len() < b.photos.len() {
325                std::mem::swap(&mut a, &mut b);
326            }
327            a.photos.extend(b.photos);
328            a.clusters.extend(b.clusters);
329            a.negated.extend(b.negated);
330            components.insert(new_root, a);
331        }
332    }
333
334    // Group by root → emit cluster labels.
335    let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
336    for i in 0..n {
337        let r = find(&mut parent, i);
338        groups.entry(r).or_default().push(i);
339    }
340
341    let mut out = HashMap::new();
342    let mut label = 0i32;
343    for (_root, members) in groups {
344        if members.len() < 2 {
345            out.insert(faces[members[0]].face_id, -1);
346        } else {
347            for idx in members {
348                out.insert(faces[idx].face_id, label);
349            }
350            label += 1;
351        }
352    }
353    out
354}
355
356impl Default for FaceClusterer {
357    fn default() -> Self {
358        Self::new()
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    fn emb(v: &[f32]) -> FaceEmbedding {
367        FaceEmbedding::new(ndarray::Array1::from_vec(v.to_vec()))
368    }
369
370    #[test]
371    fn complete_link_rejects_chain() {
372        // A-B close, B-C close, A-C far => should not all merge.
373        let mk = |id: i64, p: i64, vec: Vec<f32>| ClusterInput {
374            face_id: id,
375            photo_id: p,
376            current_cluster_id: None,
377            embedding: emb(&vec),
378        };
379        let a = mk(1, 11, vec![1.0, 0.0, 0.0]);
380        let b = mk(2, 12, vec![0.8, 0.2, 0.0]);
381        let c = mk(3, 13, vec![0.0, 1.0, 0.0]);
382
383        let clusterer = FaceClusterer::new().with_max_distance(0.35);
384        let labels = clusterer.cluster(&[a, b, c], None);
385        // Should not place all three in one non-negative cluster.
386        let vals: Vec<i32> = labels.values().copied().filter(|v| *v >= 0).collect();
387        assert!(vals.len() < 3);
388    }
389
390    #[test]
391    fn prevents_same_photo_merge() {
392        let mk = |id: i64, p: i64| ClusterInput {
393            face_id: id,
394            photo_id: p,
395            current_cluster_id: None,
396            embedding: emb(&[1.0, 0.0, 0.0]),
397        };
398
399        let clusterer = FaceClusterer::new();
400        let labels = clusterer.cluster(&[mk(1, 42), mk(2, 42)], None);
401        assert_eq!(labels[&1], -1);
402        assert_eq!(labels[&2], -1);
403    }
404
405    #[cfg(feature = "hnsw_clustering")]
406    #[test]
407    fn hnsw_merges_identical_faces_from_different_photos() {
408        let mk = |id: i64, p: i64| ClusterInput {
409            face_id: id,
410            photo_id: p,
411            current_cluster_id: None,
412            embedding: emb(&[1.0, 0.0, 0.0]),
413        };
414        let labels = cluster_hnsw(&[mk(1, 10), mk(2, 20), mk(3, 30)], 0.35, None);
415        assert!(labels[&1] >= 0);
416        assert_eq!(labels[&1], labels[&2]);
417        assert_eq!(labels[&2], labels[&3]);
418    }
419
420    #[cfg(feature = "hnsw_clustering")]
421    #[test]
422    fn hnsw_honours_face_negatives_and_same_photo() {
423        // Face 1 was rejected from cluster 7; face 2 belongs to cluster 7.
424        // They look identical but must not be grouped.
425        let a = ClusterInput {
426            face_id: 1,
427            photo_id: 10,
428            current_cluster_id: None,
429            embedding: emb(&[1.0, 0.0, 0.0]),
430        };
431        let b = ClusterInput {
432            face_id: 2,
433            photo_id: 20,
434            current_cluster_id: Some(7),
435            embedding: emb(&[1.0, 0.0, 0.0]),
436        };
437        // Face 3 shares a photo with face 2: never the same person.
438        let c = ClusterInput {
439            face_id: 3,
440            photo_id: 20,
441            current_cluster_id: None,
442            embedding: emb(&[1.0, 0.0, 0.0]),
443        };
444        let negatives = std::collections::HashSet::from([(1_i64, 7_i64)]);
445        let labels = cluster_hnsw(&[a, b, c], 0.35, Some(&negatives));
446        assert!(labels[&1] < 0 || labels[&1] != labels[&2]);
447        assert!(labels[&2] < 0 || labels[&2] != labels[&3]);
448    }
449}