Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Port photos face clustering to Rust

laurenspriem4c02a9ad0778
diff --git a/rust/crates/photos/src/face_clustering/complete.rs b/rust/crates/photos/src/face_clustering/complete.rs
new file mode 100644
index 0000000000..4e227e540a
--- /dev/null
+++ b/rust/crates/photos/src/face_clustering/complete.rs
@@ -0,0 +1,240 @@
+use std::collections::HashMap;
+
+use super::{
+ Clustering, Face, add_scaled, distance, new_cluster_id, newest_first, normalized, scaled,
+ summarize,
+};
+
+struct Group {
+ cluster_id: String,
+ mean: Vec<f32>,
+ count: usize,
+}
+
+pub(super) fn cluster(
+ mut faces: Vec<Face>,
+ distance_threshold: f64,
+ merge_threshold: f64,
+) -> Clustering {
+ faces.sort_by_key(|face| newest_first(face.creation_time));
+ let clusters = assign_nearest(&faces, distance_threshold);
+ let merged_into = merge_groups(group_means(&faces, &clusters), merge_threshold);
+ let clusters: Vec<String> = clusters
+ .iter()
+ .map(|cluster_id| final_cluster(&merged_into, cluster_id).to_owned())
+ .collect();
+ Clustering {
+ assignments: faces
+ .iter()
+ .zip(&clusters)
+ .map(|(face, cluster_id)| (face.face_id.clone(), cluster_id.clone()))
+ .collect(),
+ means: summarize(
+ faces
+ .iter()
+ .zip(&clusters)
+ .map(|(face, cluster_id)| (cluster_id, face.embedding.as_slice())),
+ &HashMap::new(),
+ ),
+ }
+}
+
+fn assign_nearest(faces: &[Face], distance_threshold: f64) -> Vec<String> {
+ let mut clusters: Vec<Option<String>> = vec![None; faces.len()];
+ for (index, face) in faces.iter().enumerate() {
+ if clusters[index].is_some() {
+ continue;
+ }
+ let cluster_id = match closest_other(faces, index, face) {
+ Some((other, other_distance)) if other_distance < distance_threshold => {
+ clusters[other].get_or_insert_with(new_cluster_id).clone()
+ }
+ _ => new_cluster_id(),
+ };
+ clusters[index] = Some(cluster_id);
+ }
+ clusters.into_iter().flatten().collect()
+}
+
+fn closest_other(faces: &[Face], index: usize, face: &Face) -> Option<(usize, f64)> {
+ let mut closest: Option<(usize, f64)> = None;
+ for (other, candidate) in faces.iter().enumerate() {
+ if other == index {
+ continue;
+ }
+ let candidate_distance = distance(&face.embedding, &candidate.embedding);
+ if candidate_distance < closest.map_or(f64::INFINITY, |(_, closest)| closest) {
+ closest = Some((other, candidate_distance));
+ }
+ }
+ closest
+}
+
+fn group_means(faces: &[Face], clusters: &[String]) -> Vec<Group> {
+ let mut groups: Vec<Group> = Vec::new();
+ let mut positions: HashMap<&String, usize> = HashMap::new();
+ for (face, cluster_id) in faces.iter().zip(clusters) {
+ let position = *positions.entry(cluster_id).or_insert_with(|| {
+ groups.push(Group {
+ cluster_id: cluster_id.clone(),
+ mean: vec![0.0; face.embedding.len()],
+ count: 0,
+ });
+ groups.len() - 1
+ });
+ add_scaled(&mut groups[position].mean, &face.embedding, 1.0);
+ groups[position].count += 1;
+ }
+ for group in &mut groups {
+ let sum = std::mem::take(&mut group.mean);
+ group.mean = normalized(scaled(sum, 1.0 / group.count as f64));
+ }
+ groups
+}
+
+fn merge_groups(mut groups: Vec<Group>, merge_threshold: f64) -> HashMap<String, String> {
+ let mut merged_into = HashMap::new();
+ while let Some((keep, absorb)) = closest_pair(&groups, merge_threshold) {
+ let absorbed = groups.remove(absorb);
+ let kept = &mut groups[keep];
+ let total = (kept.count + absorbed.count) as f64;
+ let mut mean = vec![0.0; kept.mean.len()];
+ add_scaled(&mut mean, &kept.mean, kept.count as f64 / total);
+ add_scaled(&mut mean, &absorbed.mean, absorbed.count as f64 / total);
+ kept.mean = normalized(mean);
+ kept.count += absorbed.count;
+ merged_into.insert(absorbed.cluster_id, kept.cluster_id.clone());
+ }
+ merged_into
+}
+
+fn closest_pair(groups: &[Group], merge_threshold: f64) -> Option<(usize, usize)> {
+ let mut closest: Option<(usize, usize, f64)> = None;
+ for (first, first_group) in groups.iter().enumerate() {
+ for (second, second_group) in groups.iter().enumerate().skip(first + 1) {
+ let pair_distance = distance(&first_group.mean, &second_group.mean);
+ if pair_distance < closest.map_or(f64::INFINITY, |(_, _, closest)| closest) {
+ closest = Some((first, second, pair_distance));
+ }
+ }
+ }
+ closest
+ .filter(|(_, _, pair_distance)| *pair_distance < merge_threshold)
+ .map(|(first, second, _)| (first, second))
+}
+
+fn final_cluster<'a>(merged_into: &'a HashMap<String, String>, cluster_id: &'a str) -> &'a str {
+ let mut cluster_id = cluster_id;
+ while let Some(next) = merged_into.get(cluster_id) {
+ cluster_id = next;
+ }
+ cluster_id
+}
+
+#[cfg(test)]
+mod tests {
+ use super::cluster;
+ use crate::face_clustering::tests::{assert_close, direction, face, groups, names};
+
+ #[test]
+ fn close_faces_cluster_and_distant_faces_stay_apart() {
+ let clustering = cluster(
+ vec![
+ face("a0", 0.0, 4),
+ face("a1", 1.0, 3),
+ face("b0", 90.0, 2),
+ face("b1", 91.0, 1),
+ ],
+ 0.16,
+ 0.24,
+ );
+ assert_eq!(groups(&clustering), names(&[&["a0", "a1"], &["b0", "b1"]]));
+ }
+
+ #[test]
+ fn clusters_merge_when_their_means_are_within_the_merge_threshold() {
+ for (degrees, expected_groups) in [(34.0, 1), (45.6, 2)] {
+ let clustering = cluster(
+ vec![
+ face("a0", 0.0, 4),
+ face("a1", 0.0, 3),
+ face("b0", degrees, 2),
+ face("b1", degrees, 1),
+ ],
+ 0.16,
+ 0.24,
+ );
+ assert_eq!(groups(&clustering).len(), expected_groups);
+ }
+ }
+
+ #[test]
+ fn equally_close_faces_resolve_to_the_first_one() {
+ let clustering = cluster(
+ vec![
+ face("a0", 40.0, 5),
+ face("a1", 40.0, 4),
+ face("b0", -40.0, 3),
+ face("b1", -40.0, 2),
+ face("m", 0.0, 1),
+ ],
+ 0.24,
+ 0.24,
+ );
+ assert_eq!(
+ groups(&clustering),
+ names(&[&["a0", "a1", "m"], &["b0", "b1"]])
+ );
+ }
+
+ #[test]
+ fn equally_close_clusters_merge_in_index_order() {
+ let clustering = cluster(
+ vec![
+ face("g0", 0.0, 3),
+ face("g1", 30.0, 2),
+ face("g2", -30.0, 1),
+ ],
+ 0.0,
+ 0.2,
+ );
+ assert_eq!(groups(&clustering), names(&[&["g0", "g1"], &["g2"]]));
+ }
+
+ #[test]
+ fn chained_merges_relabel_every_face() {
+ let clustering = cluster(
+ vec![
+ face("a0", 0.0, 6),
+ face("a1", 0.0, 5),
+ face("b0", 28.0, 4),
+ face("b1", 28.0, 3),
+ face("c0", 50.0, 2),
+ face("c1", 50.0, 1),
+ ],
+ 0.05,
+ 0.24,
+ );
+ assert_eq!(
+ groups(&clustering),
+ names(&[&["a0", "a1", "b0", "b1", "c0", "c1"]])
+ );
+ assert_eq!(clustering.means.len(), 1);
+ assert_eq!(clustering.means[&clustering.assignments["a0"]].count, 6);
+ }
+
+ #[test]
+ fn means_cover_every_face_of_each_final_cluster() {
+ let clustering = cluster(
+ vec![face("a0", 0.0, 3), face("a1", 2.0, 2), face("b0", 90.0, 1)],
+ 0.16,
+ 0.24,
+ );
+ let a = &clustering.means[&clustering.assignments["a0"]];
+ assert_eq!(a.count, 2);
+ assert_close(&a.mean, &direction(1.0));
+ let b = &clustering.means[&clustering.assignments["b0"]];
+ assert_eq!(b.count, 1);
+ assert_close(&b.mean, &direction(90.0));
+ }
+}
diff --git a/rust/crates/photos/src/face_clustering/linear.rs b/rust/crates/photos/src/face_clustering/linear.rs
new file mode 100644
index 0000000000..8b67600e46
--- /dev/null
+++ b/rust/crates/photos/src/face_clustering/linear.rs
@@ -0,0 +1,265 @@
+use std::collections::HashMap;
+
+use super::{
+ ClusterMean, Clustering, IncrementalFace, conservative_threshold, distance, new_cluster_id,
+ newest_first, summarize,
+};
+
+#[derive(Clone, Copy, Debug)]
+pub(super) struct Thresholds {
+ distance: f64,
+ conservative: f64,
+ dynamic: bool,
+}
+
+impl Thresholds {
+ pub(super) fn new(distance: f64, dynamic: bool) -> Self {
+ Self {
+ distance,
+ conservative: conservative_threshold(distance),
+ dynamic,
+ }
+ }
+
+ fn for_face(self, face: &IncrementalFace) -> f64 {
+ if self.dynamic && face.bad {
+ self.conservative
+ } else {
+ self.distance
+ }
+ }
+}
+
+pub(super) fn cluster(
+ mut faces: Vec<IncrementalFace>,
+ thresholds: Thresholds,
+ previous_means: &HashMap<String, ClusterMean>,
+) -> Clustering {
+ faces.sort_by_key(|face| {
+ (
+ face.cluster_id.is_none(),
+ newest_first(face.face.creation_time),
+ )
+ });
+ let mut clusters: Vec<String> = Vec::with_capacity(faces.len());
+ for (index, face) in faces.iter().enumerate() {
+ let cluster_id = match &face.cluster_id {
+ Some(cluster_id) => cluster_id.clone(),
+ None => nearest_cluster(face, &faces[..index], &clusters, thresholds)
+ .unwrap_or_else(new_cluster_id),
+ };
+ clusters.push(cluster_id);
+ }
+
+ let first_new = faces.partition_point(|face| face.cluster_id.is_some());
+ let new_faces = || faces[first_new..].iter().zip(&clusters[first_new..]);
+ Clustering {
+ assignments: new_faces()
+ .map(|(face, cluster_id)| (face.face.face_id.clone(), cluster_id.clone()))
+ .collect(),
+ means: summarize(
+ new_faces().map(|(face, cluster_id)| (cluster_id, face.face.embedding.as_slice())),
+ previous_means,
+ ),
+ }
+}
+
+fn nearest_cluster(
+ face: &IncrementalFace,
+ earlier: &[IncrementalFace],
+ clusters: &[String],
+ thresholds: Thresholds,
+) -> Option<String> {
+ let mut closest_distance = f64::INFINITY;
+ let mut closest_index = None;
+ for (index, candidate) in earlier.iter().enumerate().rev() {
+ let candidate_distance = distance(&face.face.embedding, &candidate.face.embedding);
+ if candidate_distance < closest_distance
+ && !is_excluded(
+ face,
+ candidate,
+ &clusters[index],
+ candidate_distance,
+ thresholds,
+ )
+ {
+ closest_distance = candidate_distance;
+ closest_index = Some(index);
+ }
+ }
+ closest_index
+ .filter(|_| closest_distance < thresholds.for_face(face))
+ .map(|index| clusters[index].clone())
+}
+
+fn is_excluded(
+ face: &IncrementalFace,
+ candidate: &IncrementalFace,
+ candidate_cluster: &str,
+ candidate_distance: f64,
+ thresholds: Thresholds,
+) -> bool {
+ (candidate.bad && candidate_distance > thresholds.conservative)
+ || (!face.rejected_cluster_ids.is_empty()
+ && face.rejected_cluster_ids.contains(candidate_cluster))
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+
+ use super::{Thresholds, cluster};
+ use crate::face_clustering::tests::{
+ assert_close, clustered_face, direction, groups, names, new_face,
+ };
+ use crate::face_clustering::{
+ ClusterMean, Clustering, IncrementalFace, RECOMMENDED_DISTANCE_THRESHOLD,
+ cluster_incrementally,
+ };
+
+ fn cluster_dynamic(faces: Vec<IncrementalFace>) -> Clustering {
+ cluster_incrementally(faces, RECOMMENDED_DISTANCE_THRESHOLD, &HashMap::new())
+ }
+
+ #[test]
+ fn faces_join_an_earlier_cluster_only_within_the_threshold() {
+ let clustering = cluster_dynamic(vec![
+ new_face("x", 0.0, 3),
+ new_face("y", 10.0, 2),
+ new_face("z", 60.0, 1),
+ ]);
+ assert_eq!(groups(&clustering), names(&[&["x", "y"], &["z"]]));
+ }
+
+ #[test]
+ fn faces_join_the_nearest_cluster_not_the_most_recent_one() {
+ for (degrees, expected) in [(30.0, "q"), (12.0, "p")] {
+ let clustering = cluster_dynamic(vec![
+ clustered_face("p0", 0.0, 2, "p"),
+ clustered_face("q0", 40.0, 1, "q"),
+ new_face("f", degrees, 3),
+ ]);
+ assert_eq!(clustering.assignments["f"], expected);
+ }
+ }
+
+ #[test]
+ fn only_new_faces_are_assigned() {
+ let clustering = cluster_dynamic(vec![
+ clustered_face("p0", 0.0, 1, "p"),
+ new_face("f", 5.0, 2),
+ ]);
+ assert_eq!(clustering.assignments.len(), 1);
+ assert_eq!(clustering.assignments["f"], "p");
+ }
+
+ #[test]
+ fn bad_faces_join_only_within_the_conservative_threshold() {
+ for (bad, joins) in [(true, false), (false, true)] {
+ let mut joining = new_face("f", 34.0, 2);
+ joining.bad = bad;
+ let clustering = cluster_dynamic(vec![clustered_face("p0", 0.0, 1, "p"), joining]);
+ assert_eq!(clustering.assignments["f"] == "p", joins);
+ }
+ }
+
+ #[test]
+ fn bad_faces_use_the_full_threshold_without_dynamic_thresholds() {
+ let mut joining = new_face("f", 34.0, 2);
+ joining.bad = true;
+ let clustering = cluster(
+ vec![clustered_face("p0", 0.0, 1, "p"), joining],
+ Thresholds::new(RECOMMENDED_DISTANCE_THRESHOLD, false),
+ &HashMap::new(),
+ );
+ assert_eq!(clustering.assignments["f"], "p");
+ }
+
+ #[test]
+ fn bad_candidates_attract_only_within_the_conservative_threshold() {
+ for (degrees, joins) in [(34.0, false), (20.0, true)] {
+ let mut candidate = clustered_face("p0", 0.0, 1, "p");
+ candidate.bad = true;
+ let clustering = cluster_dynamic(vec![candidate, new_face("f", degrees, 2)]);
+ assert_eq!(clustering.assignments["f"] == "p", joins);
+ }
+ }
+
+ #[test]
+ fn equally_close_faces_resolve_to_the_one_processed_last() {
+ let clustering = cluster_dynamic(vec![
+ clustered_face("p0", 0.0, 2, "p"),
+ clustered_face("q0", 0.0, 1, "q"),
+ new_face("f", 5.0, 3),
+ ]);
+ assert_eq!(clustering.assignments["f"], "q");
+ }
+
+ #[test]
+ fn distances_are_compared_in_double_precision_like_dart() {
+ let mut a = new_face("a", 0.0, 2);
+ a.face.embedding = vec![0.6, 0.8];
+ let mut b = new_face("b", 0.0, 1);
+ b.face.embedding = vec![-0.063938476, 0.99795383];
+ let clustering = cluster_dynamic(vec![a, b]);
+ assert_eq!(clustering.assignments["a"], clustering.assignments["b"]);
+ }
+
+ #[test]
+ fn rejected_clusters_are_skipped() {
+ let mut rejecting = new_face("f", 5.0, 3);
+ rejecting.rejected_cluster_ids.insert("p".to_owned());
+ let clustering = cluster_dynamic(vec![
+ clustered_face("p0", 0.0, 2, "p"),
+ clustered_face("q0", 25.0, 1, "q"),
+ rejecting,
+ ]);
+ assert_eq!(clustering.assignments["f"], "q");
+ }
+
+ #[test]
+ fn faces_are_clustered_newest_first() {
+ let clustering = cluster_dynamic(vec![
+ new_face("x", 0.0, 3),
+ new_face("z", 74.0, 1),
+ new_face("y", 37.0, 2),
+ ]);
+ assert_eq!(groups(&clustering), names(&[&["x", "y", "z"]]));
+ }
+
+ #[test]
+ fn means_fold_new_faces_into_the_previous_cluster_mean() {
+ let previous = HashMap::from([(
+ "p".to_owned(),
+ ClusterMean {
+ mean: direction(0.0),
+ count: 3,
+ },
+ )]);
+ let clustering = cluster_incrementally(
+ vec![
+ clustered_face("p0", 0.0, 1, "p"),
+ new_face("f", 20.0, 2),
+ new_face("g", 90.0, 3),
+ ],
+ RECOMMENDED_DISTANCE_THRESHOLD,
+ &previous,
+ );
+
+ let joined = &clustering.means["p"];
+ let new_member = direction(20.0);
+ let sum = [3.0 + new_member[0], new_member[1]];
+ let norm = (sum[0] * sum[0] + sum[1] * sum[1]).sqrt();
+ assert_eq!(joined.count, 4);
+ assert_close(&joined.mean, &[sum[0] / norm, sum[1] / norm]);
+
+ let created = &clustering.means[&clustering.assignments["g"]];
+ assert_eq!(created.count, 1);
+ assert_close(&created.mean, &direction(90.0));
+ }
+
+ #[test]
+ fn empty_input_has_no_clusters() {
+ assert_eq!(cluster_dynamic(Vec::new()), Clustering::default());
+ }
+}
diff --git a/rust/crates/photos/src/face_clustering/mod.rs b/rust/crates/photos/src/face_clustering/mod.rs
new file mode 100644
index 0000000000..9bb4c3bd1a
--- /dev/null
+++ b/rust/crates/photos/src/face_clustering/mod.rs
@@ -0,0 +1,342 @@
+mod complete;
+mod linear;
+
+use std::cmp::Reverse;
+use std::collections::{HashMap, HashSet};
+use std::iter;
+
+use ente_core::crypto::random_bytes;
+
+const RECOMMENDED_DISTANCE_THRESHOLD: f64 = 0.24;
+const CONSERVATIVE_DISTANCE_THRESHOLD: f64 = 0.16;
+
+const CONSERVATIVE_DISTANCE_DELTA: f64 =
+ RECOMMENDED_DISTANCE_THRESHOLD - CONSERVATIVE_DISTANCE_THRESHOLD;
+const COMPLETE_CLUSTERING_FACE_LIMIT: usize = 500;
+
+const CLUSTER_ID_PREFIX: &str = "cluster_";
+const CLUSTER_ID_ALPHABET: &[u8] =
+ b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+const CLUSTER_ID_LENGTH: usize = 22;
+const CLUSTER_ID_MASK: u8 = 63;
+const SIMD_LANES: usize = 4;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Face {
+ pub face_id: String,
+ pub embedding: Vec<f32>,
+ pub creation_time: Option<i64>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct IncrementalFace {
+ pub face: Face,
+ pub cluster_id: Option<String>,
+ pub bad: bool,
+ pub rejected_cluster_ids: HashSet<String>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct ClusterMean {
+ pub mean: Vec<f32>,
+ pub count: usize,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Clustering {
+ pub assignments: HashMap<String, String>,
+ pub means: HashMap<String, ClusterMean>,
+}
+
+pub fn cluster_incrementally(
+ faces: Vec<IncrementalFace>,
+ distance_threshold: f64,
+ previous_means: &HashMap<String, ClusterMean>,
+) -> Clustering {
+ linear::cluster(
+ faces,
+ linear::Thresholds::new(distance_threshold, true),
+ previous_means,
+ )
+}
+
+pub fn recluster(faces: Vec<Face>, distance_threshold: f64) -> Clustering {
+ if faces.len() < COMPLETE_CLUSTERING_FACE_LIMIT {
+ return complete::cluster(
+ faces,
+ conservative_threshold(distance_threshold),
+ distance_threshold,
+ );
+ }
+ let faces = faces
+ .into_iter()
+ .map(|face| IncrementalFace {
+ face,
+ cluster_id: None,
+ bad: false,
+ rejected_cluster_ids: HashSet::new(),
+ })
+ .collect();
+ linear::cluster(
+ faces,
+ linear::Thresholds::new(distance_threshold, false),
+ &HashMap::new(),
+ )
+}
+
+fn conservative_threshold(distance_threshold: f64) -> f64 {
+ (distance_threshold - CONSERVATIVE_DISTANCE_DELTA)
+ .max(0.0)
+ .min(distance_threshold)
+}
+
+fn newest_first(creation_time: Option<i64>) -> (bool, Reverse<Option<i64>>) {
+ (creation_time.is_some(), Reverse(creation_time))
+}
+
+fn new_cluster_id() -> String {
+ let suffix: String = iter::repeat_with(|| random_bytes(CLUSTER_ID_LENGTH * 2))
+ .flatten()
+ .filter_map(|byte| CLUSTER_ID_ALPHABET.get(usize::from(byte & CLUSTER_ID_MASK)))
+ .take(CLUSTER_ID_LENGTH)
+ .map(|&byte| char::from(byte))
+ .collect();
+ format!("{CLUSTER_ID_PREFIX}{suffix}")
+}
+
+fn distance(a: &[f32], b: &[f32]) -> f64 {
+ 1.0 - dot(a, b)
+}
+
+fn dot(a: &[f32], b: &[f32]) -> f64 {
+ debug_assert_eq!(a.len(), b.len());
+ let (a_chunks, a_rest) = a.as_chunks::<SIMD_LANES>();
+ let (b_chunks, b_rest) = b.as_chunks::<SIMD_LANES>();
+ let mut lanes = [0.0_f32; SIMD_LANES];
+ for (a_chunk, b_chunk) in a_chunks.iter().zip(b_chunks) {
+ for ((lane, x), y) in lanes.iter_mut().zip(a_chunk).zip(b_chunk) {
+ *lane += x * y;
+ }
+ }
+ for ((lane, x), y) in lanes.iter_mut().zip(a_rest).zip(b_rest) {
+ *lane += x * y;
+ }
+ lanes.into_iter().map(f64::from).sum()
+}
+
+fn add_scaled(sum: &mut [f32], vector: &[f32], scale: f64) {
+ let scale = scale as f32;
+ for (total, value) in sum.iter_mut().zip(vector) {
+ *total += value * scale;
+ }
+}
+
+fn scaled(mut vector: Vec<f32>, scale: f64) -> Vec<f32> {
+ let scale = scale as f32;
+ for value in &mut vector {
+ *value *= scale;
+ }
+ vector
+}
+
+fn normalized(vector: Vec<f32>) -> Vec<f32> {
+ let norm = dot(&vector, &vector).sqrt();
+ scaled(vector, 1.0 / norm)
+}
+
+fn summarize<'a>(
+ members: impl IntoIterator<Item = (&'a String, &'a [f32])>,
+ previous_means: &HashMap<String, ClusterMean>,
+) -> HashMap<String, ClusterMean> {
+ let mut sums: HashMap<&String, (Vec<f32>, usize)> = HashMap::new();
+ for (cluster_id, embedding) in members {
+ let (sum, count) = sums
+ .entry(cluster_id)
+ .or_insert_with(|| (vec![0.0; embedding.len()], 0));
+ add_scaled(sum, embedding, 1.0);
+ *count += 1;
+ }
+ sums.into_iter()
+ .map(|(cluster_id, (mut sum, mut count))| {
+ if let Some(previous) = previous_means.get(cluster_id) {
+ add_scaled(&mut sum, &previous.mean, previous.count as f64);
+ count += previous.count;
+ sum = scaled(sum, 1.0 / count as f64);
+ }
+ (
+ cluster_id.clone(),
+ ClusterMean {
+ mean: normalized(sum),
+ count,
+ },
+ )
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::{HashMap, HashSet};
+
+ use super::{
+ CLUSTER_ID_LENGTH, CLUSTER_ID_PREFIX, Clustering, Face, IncrementalFace, dot,
+ new_cluster_id, newest_first, recluster,
+ };
+
+ pub(super) fn direction(degrees: f32) -> Vec<f32> {
+ let radians = degrees.to_radians();
+ vec![radians.cos(), radians.sin()]
+ }
+
+ pub(super) fn face(face_id: &str, degrees: f32, creation_time: i64) -> Face {
+ Face {
+ face_id: face_id.to_owned(),
+ embedding: direction(degrees),
+ creation_time: Some(creation_time),
+ }
+ }
+
+ pub(super) fn new_face(face_id: &str, degrees: f32, creation_time: i64) -> IncrementalFace {
+ IncrementalFace {
+ face: face(face_id, degrees, creation_time),
+ cluster_id: None,
+ bad: false,
+ rejected_cluster_ids: HashSet::new(),
+ }
+ }
+
+ pub(super) fn clustered_face(
+ face_id: &str,
+ degrees: f32,
+ creation_time: i64,
+ cluster_id: &str,
+ ) -> IncrementalFace {
+ IncrementalFace {
+ cluster_id: Some(cluster_id.to_owned()),
+ ..new_face(face_id, degrees, creation_time)
+ }
+ }
+
+ pub(super) fn groups(clustering: &Clustering) -> Vec<Vec<String>> {
+ let mut by_cluster: HashMap<&String, Vec<String>> = HashMap::new();
+ for (face_id, cluster_id) in &clustering.assignments {
+ by_cluster
+ .entry(cluster_id)
+ .or_default()
+ .push(face_id.clone());
+ }
+ let mut groups: Vec<Vec<String>> = by_cluster
+ .into_values()
+ .map(|mut faces| {
+ faces.sort();
+ faces
+ })
+ .collect();
+ groups.sort();
+ groups
+ }
+
+ pub(super) fn names(groups: &[&[&str]]) -> Vec<Vec<String>> {
+ let mut groups: Vec<Vec<String>> = groups
+ .iter()
+ .map(|group| {
+ let mut group: Vec<String> = group.iter().map(|name| (*name).to_owned()).collect();
+ group.sort();
+ group
+ })
+ .collect();
+ groups.sort();
+ groups
+ }
+
+ pub(super) fn assert_close(actual: &[f32], expected: &[f32]) {
+ assert_eq!(actual.len(), expected.len());
+ for (actual, expected) in actual.iter().zip(expected) {
+ assert!((actual - expected).abs() < 1e-5, "{actual} != {expected}");
+ }
+ }
+
+ fn chained_faces(count_before_bridge: usize, count_after_bridge: usize) -> Vec<Face> {
+ let far_side = 45.57;
+ let mut faces = Vec::new();
+ let mut creation_time = 10_000;
+ for index in 0..count_before_bridge {
+ faces.push(face(&format!("a{index}"), 0.0, creation_time));
+ creation_time -= 1;
+ }
+ faces.push(face("bridge", far_side / 2.0, creation_time));
+ creation_time -= 1;
+ for index in 0..count_after_bridge {
+ faces.push(face(&format!("b{index}"), far_side, creation_time));
+ creation_time -= 1;
+ }
+ faces
+ }
+
+ #[test]
+ fn cluster_ids_match_the_dart_and_web_format() {
+ let first = new_cluster_id();
+ let second = new_cluster_id();
+ assert_ne!(first, second);
+ for id in [first, second] {
+ let suffix = id.strip_prefix(CLUSTER_ID_PREFIX).unwrap();
+ assert_eq!(suffix.len(), CLUSTER_ID_LENGTH);
+ assert!(suffix.chars().all(|c| c.is_ascii_alphanumeric()));
+ }
+ }
+
+ #[test]
+ fn dot_covers_full_lanes_and_the_remainder() {
+ let a: Vec<f32> = (0..19).map(|value| value as f32).collect();
+ let b = vec![2.0; 19];
+ assert_eq!(dot(&a, &b), 342.0);
+ }
+
+ #[test]
+ fn dot_rounds_like_dart_float32x4_lanes_summed_as_doubles() {
+ let tiny = f32::EPSILON / 4.0;
+ let a = [1.0, tiny, 0.0, 0.0, tiny, 0.0, 0.0, 0.0];
+ assert_eq!(dot(&a, &[1.0; 8]), 1.0 + f64::from(tiny));
+ }
+
+ #[test]
+ fn unknown_creation_times_sort_first_then_newest() {
+ let mut times = vec![Some(1), None, Some(3), Some(2)];
+ times.sort_by_key(|time| newest_first(*time));
+ assert_eq!(times, vec![None, Some(3), Some(2), Some(1)]);
+ }
+
+ #[test]
+ fn reclustering_below_500_faces_merges_by_cluster_mean() {
+ let clustering = recluster(chained_faces(249, 249), 0.24);
+ assert_eq!(groups(&clustering).len(), 2);
+ assert_eq!(clustering.assignments.len(), 499);
+ }
+
+ #[test]
+ fn reclustering_below_500_faces_assigns_conservatively_and_merges_at_the_threshold() {
+ let clustering = recluster(
+ vec![face("a", 0.0, 3), face("b", 34.0, 2), face("c", 68.0, 1)],
+ 0.24,
+ );
+ assert_eq!(groups(&clustering).len(), 2);
+ }
+
+ #[test]
+ fn reclustering_from_500_faces_joins_within_the_full_threshold() {
+ let faces = (0..500_i64)
+ .map(|index| {
+ let degrees = if index < 250 { 0.0 } else { 34.0 };
+ face(&format!("f{index}"), degrees, 1000 - index)
+ })
+ .collect();
+ assert_eq!(groups(&recluster(faces, 0.24)).len(), 1);
+ }
+
+ #[test]
+ fn reclustering_from_500_faces_chains_through_nearest_faces() {
+ let clustering = recluster(chained_faces(250, 249), 0.24);
+ assert_eq!(groups(&clustering).len(), 1);
+ assert_eq!(clustering.assignments.len(), 500);
+ }
+}
diff --git a/rust/crates/photos/src/lib.rs b/rust/crates/photos/src/lib.rs
index c472bde578..8779e2c117 100644
--- a/rust/crates/photos/src/lib.rs
+++ b/rust/crates/photos/src/lib.rs
@@ -1,5 +1,6 @@
pub mod collections;
pub mod db;
+pub mod face_clustering;
pub mod files;
pub mod location;
pub mod metadata;