//! Face grouping: which faces on this phone are one person (coordinator, 27 Nov, NEXT-GROUPING.md; GROUPING 1).//! The same rule on both phones, so it lives here; the phones hand faces in and draw the groups.//!//! Single linkage is never used: on real photos it chained 741 faces of many people into one group at cosine 0.5,//! because one look-alike pair is enough to join two people. Instead://!//! ```text//! cannot-link two faces in one photo are never one person; nor two named people; nor a face he said is "not//! this person"; nor two groups he answered "No" to "Same person?". A hard constraint on every step.//! seed a face that is nearest to another loose face, and that face's nearest too (mutual nearest//! neighbours), at cosine SEED or more, starts a group of two. Doubtful faces stay loose.//! join a face joins the group whose centroid it is nearest, at JOIN or more, unless a cannot-link stands.//! This is also the incremental step: one comparison per group for each new face.//! merge groups merge, best first, while their AVERAGE pairwise cosine is MERGE or more and no cannot-link//! stands. Average, not nearest pair, so one look-alike face cannot bridge two people.//! show a group is on the People screen at SHOWN_PHOTOS photos or more, or once named. Two shown groups//! whose average cosine is in [ASK, MERGE) are offered as "Same person?", never merged by themselves.//! his choices Name and Merge are must-links (those faces start in one group); Not this person, and No to Same//! person?, are cannot-links. They are inputs to every regrouping, so they survive it.//! ```//!//! Work is bounded: faces are taken in slices of [`SLICE`]; each face is compared with the groups' centroids and//! the loose faces, and only groups that changed in a slice are compared for merging. Nothing here stores anything://! vectors, keys and choices come in, groups go out.//!//! The constants were tuned on the synthetic libraries (1,210 faces of 103 made-up people, HyperFace-50k vectors//! from the phone's whole chain; scripts/albums-grouping.py is the reference and the grid): purity 0.996,//! completeness 0.994, no cannot-link broken, 44 of the 45 people with 5 or more photos found as one group, none//! split or mixed. The set chosen sits in the middle of the plateau, away from its edges.use std::cmp::Ordering;use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap};/// Mutual nearest neighbours at this cosine or more start a group.pubconst SEED: f32 = 0.55;/// A face joins the group whose centroid it is nearest at this cosine or more.pubconst JOIN: f32 = 0.45;/// Two groups merge at this average pairwise cosine or more.pubconst MERGE: f32 = 0.40;/// Two shown groups at this average cosine or more, short of MERGE, are offered as "Same person?".pubconst ASK: f32 = 0.30;/// A group is shown at this many photos or more (or once named).pubconst SHOWN_PHOTOS: usize = 5;/// Faces taken per slice.pubconst SLICE: usize = 500;/// One face: a key that stays the same across passes, its photo, its vector (any length; made unit here), the/// person he named it as, and the people he said it is not.#[derive(Debug, Clone, Default)]pubstructFace {pub key: String,pub photo: String,pub vector: Vec<f32>,pub person: Option<String>,pub not: Vec<String>,}/// His choices between faces, by face key: `same` from Merge, `different` from "No" to "Same person?".#[derive(Debug, Clone, Default)]pubstructChoices {pub same: Vec<(String, String)>,pub different: Vec<(String, String)>,}#[derive(Debug, Clone, PartialEq)]pubstructGroup {/// Face indices, in the order given.pub faces: Vec<usize>,pub photos: usize,pub person: Option<String>,pub shown: bool,}/// "Same person?" between two shown groups (indices into `groups`), most alike first.#[derive(Debug, Clone, PartialEq)]pubstructSuggestion {pub a: usize,pub b: usize,pub similarity: f32,}#[derive(Debug, Clone, PartialEq)]pubstructGrouping {/// One label per face: its index in `groups`. A loose face is a group of one.pub labels: Vec<usize>,/// Biggest first (named people first among equals).pub groups: Vec<Group>,pub suggestions: Vec<Suggestion>,}/// Groups `faces` under his `choices`.pubfn group(faces: Vec<Face>, choices: &Choices) -> Grouping {letmut g = Grouper::new(choices.clone()); g.add(faces); g.result()}struct G { members: Vec<usize>, sum: Vec<f32>, photos: BTreeSet<u32>, person: Option<String>, nots: BTreeSet<String>, alive: bool, version: u32,}/// The grouping as it stands; `add` takes more faces (the incremental pass), `result` reads it.pubstructGrouper { choices: Choices, faces: Vec<Face>, photo_of: Vec<u32>, photo_ids: HashMap<String, u32>, key_ix: HashMap<String, usize>, group_of: Vec<Option<usize>>, groups: Vec<G>, loose: Vec<usize>,/// The best cosine each loose face has seen with another loose face. best: Vec<f32>,/// Face-level cannot-links from his "No" answers, by face index. cannot: HashMap<usize, Vec<usize>>, persons: HashMap<String, usize>,}fn dot(a: &[f32], b: &[f32]) -> f32 { a.iter().zip(b).map(|(x, y)| x * y).sum()}fn norm(a: &[f32]) -> f32 { dot(a, a).sqrt()}#[derive(PartialEq)]structCandidate(f32, usize, usize, u32, u32);implEqforCandidate {}implOrdforCandidate {fn cmp(&self, o: &Self) -> Ordering {self.0.total_cmp(&o.0).then_with(|| o.1.cmp(&self.1)).then_with(|| o.2.cmp(&self.2)) }}implPartialOrdforCandidate {fn partial_cmp(&self, o: &Self) -> Option<Ordering> {Some(self.cmp(o)) }}implGrouper {pubfn new(choices: Choices) -> Self {Grouper { choices, faces: vec![], photo_of: vec![], photo_ids: HashMap::new(), key_ix: HashMap::new(), group_of: vec![], groups: vec![], loose: vec![], best: vec![], cannot: HashMap::new(), persons: HashMap::new(), } }fn new_group(&mutself, f: usize) -> usize {let face = &self.faces[f];let g = G { members: vec![f], sum: face.vector.clone(), photos: BTreeSet::from([self.photo_of[f]]), person: face.person.clone(), nots: face.not.iter().cloned().collect(), alive: true, version: 0, };self.groups.push(g);let ix = self.groups.len() - 1;self.group_of[f] = Some(ix);ifletSome(p) = &self.faces[f].person {self.persons.insert(p.clone(), ix); } ix }/// Whether face `f` may join group `g`.fn face_fits(&self, f: usize, g: usize) -> bool {let (face, grp) = (&self.faces[f], &self.groups[g]);if grp.photos.contains(&self.photo_of[f]) {returnfalse; }match (&face.person, &grp.person) { (Some(a), Some(b)) if a != b => returnfalse, _ => {} }if grp.person.as_ref().is_some_and(|p| face.not.contains(p)) || face.person.as_ref().is_some_and(|p| grp.nots.contains(p)) {returnfalse; } !self.cannot.get(&f).is_some_and(|cs| cs.iter().any(|&c| self.group_of[c] == Some(g))) }/// Whether groups `a` and `b` may be one person.fn groups_fit(&self, a: usize, b: usize) -> bool {let (ga, gb) = (&self.groups[a], &self.groups[b]);if !ga.photos.is_disjoint(&gb.photos) {returnfalse; }match (&ga.person, &gb.person) { (Some(x), Some(y)) if x != y => returnfalse, _ => {} }if ga.person.as_ref().is_some_and(|p| gb.nots.contains(p)) || gb.person.as_ref().is_some_and(|p| ga.nots.contains(p)) {returnfalse; }let (small, other) = if ga.members.len() <= gb.members.len() { (ga, b) } else { (gb, a) }; !small.members.iter().any(|f| self.cannot.get(f).is_some_and(|cs| cs.iter().any(|&c| self.group_of[c] == Some(other)))) }fn join(&mutself, f: usize, g: usize) {let v = self.faces[f].vector.clone();let p = self.photo_of[f];let nots = self.faces[f].not.clone();let person = self.faces[f].person.clone();let grp = &mutself.groups[g]; grp.members.push(f); grp.sum.iter_mut().zip(&v).for_each(|(s, x)| *s += x); grp.photos.insert(p); grp.nots.extend(nots);if grp.person.is_none() { grp.person = person.clone(); } grp.version += 1;self.group_of[f] = Some(g);ifletSome(p) = person {self.persons.insert(p, g); } }fn merge(&mutself, a: usize, b: usize) -> usize {let (keep, gone) = ifself.groups[a].members.len() >= self.groups[b].members.len() { (a, b) } else { (b, a) };let moved = std::mem::take(&mutself.groups[gone].members);let sum = std::mem::take(&mutself.groups[gone].sum);let photos = std::mem::take(&mutself.groups[gone].photos);let nots = std::mem::take(&mutself.groups[gone].nots);let person = self.groups[gone].person.take();self.groups[gone].alive = false;for &f in &moved {self.group_of[f] = Some(keep); }let k = &mutself.groups[keep]; k.members.extend(moved); k.sum.iter_mut().zip(&sum).for_each(|(s, x)| *s += x); k.photos.extend(photos); k.nots.extend(nots);if k.person.is_none() { k.person = person; } k.version += 1;ifletSome(p) = k.person.clone() {self.persons.insert(p, keep); } keep }fn average(&self, a: usize, b: usize) -> f32 {let (ga, gb) = (&self.groups[a], &self.groups[b]); dot(&ga.sum, &gb.sum) / (ga.members.len() * gb.members.len()) as f32 }fn centroid_cosine(&self, f: usize, g: usize) -> f32 {let s = &self.groups[g].sum; dot(&self.faces[f].vector, s) / norm(s).max(1e-6) }/// The best group face `f` may join at JOIN or more, among `among`.fn best_group(&self, f: usize, among: implIterator<Item = usize>) -> Option<usize> {letmut scored: Vec<(f32, usize)> = among.filter(|&g| self.groups[g].alive).map(|g| (self.centroid_cosine(f, g), g)).filter(|&(s, _)| s >= JOIN).collect(); scored.sort_by(|x, y| y.0.total_cmp(&x.0).then(x.1.cmp(&y.1))); scored.into_iter().map(|(_, g)| g).find(|&g| self.face_fits(f, g)) }/// Takes more faces: his named and merged faces first, then the rest in slices.pubfn add(&mutself, faces: Vec<Face>) {let start = self.faces.len();formut face in faces {let n = norm(&face.vector);if n > 0.0 && n.is_finite() { face.vector.iter_mut().for_each(|x| *x /= n); } else { face.vector.iter_mut().for_each(|x| *x = 0.0); }let next = self.photo_ids.len() as u32;let pid = *self.photo_ids.entry(face.photo.clone()).or_insert(next);self.photo_of.push(pid);self.key_ix.insert(face.key.clone(), self.faces.len());self.faces.push(face);self.group_of.push(None);self.best.push(f32::NEG_INFINITY); }let end = self.faces.len();for (a, b) inself.choices.different.clone() {iflet (Some(&x), Some(&y)) = (self.key_ix.get(&a), self.key_ix.get(&b)) {if (start..end).contains(&x) || (start..end).contains(&y) {self.cannot.entry(x).or_default().push(y);self.cannot.entry(y).or_default().push(x); } } }letmut touched: BTreeSet<usize> = BTreeSet::new();// His must-links: a named face goes to its person's group; faces he merged go together.for f in start..end {ifletSome(p) = self.faces[f].person.clone() {let g = matchself.persons.get(&p) {Some(&g) ifself.face_fits(f, g) => {self.join(f, g); g }Some(_) => continue,None => self.new_group(f), }; touched.insert(g); } }for (a, b) inself.choices.same.clone() {let (Some(&x), Some(&y)) = (self.key_ix.get(&a), self.key_ix.get(&b)) else { continue };if !((start..end).contains(&x) || (start..end).contains(&y)) {continue; }let gx = self.group_of[x].unwrap_or_else(|| self.new_group(x));matchself.group_of[y] {Noneifself.face_fits(y, gx) => self.join(y, gx),Some(gy) if gy != gx && self.groups_fit(gx, gy) => {let k = self.merge(gx, gy); touched.insert(k); } _ => {} } touched.insert(self.group_of[x].unwrap()); }let rest: Vec<usize> = (start..end).filter(|&f| self.group_of[f].is_none()).collect();for slice in rest.chunks(SLICE) {self.take_slice(slice, std::mem::take(&mut touched)); }if !touched.is_empty() {self.take_slice(&[], touched); } }fn take_slice(&mutself, slice: &[usize], mut touched: BTreeSet<usize>) {for &f in slice {if norm(&self.faces[f].vector) == 0.0 {continue; // no vector: never grouped, a group of one }// join: the nearest group's centroidifletSome(g) = self.best_group(f, 0..self.groups.len()) {self.join(f, g); touched.insert(g);continue; }// seed: mutual nearest neighbours among the loose faceslet v = self.faces[f].vector.clone();letmut top: Option<(f32, usize)> = None;letmut own = f32::NEG_INFINITY;for k in0..self.loose.len() {let j = self.loose[k];ifself.photo_of[j] == self.photo_of[f] {continue; }let s = dot(&v, &self.faces[j].vector);if s > self.best[j] {self.best[j] = s; } own = own.max(s);let forbidden = self.cannot.get(&f).is_some_and(|cs| cs.contains(&j)) || self.faces[j].person.as_ref().is_some_and(|p| self.faces[f].not.contains(p));if !forbidden && top.is_none_or(|(t, _)| s > t) { top = Some((s, j)); } }match top {Some((s, j)) if s >= SEED && s >= self.best[j] => {self.loose.retain(|&x| x != j);let g = self.new_group(j);self.join(f, g); touched.insert(g); } _ => {self.best[f] = own;self.loose.push(f); } } }// merge: groups that changed, against every group, average linkage, best firstletmut heap = BinaryHeap::new();for &a in &touched {self.push_candidates(a, &mut heap); }whileletSome(Candidate(_, a, b, va, vb)) = heap.pop() {if !self.groups[a].alive || !self.groups[b].alive || self.groups[a].version != va || self.groups[b].version != vb {continue; }if !self.groups_fit(a, b) {continue; }let k = self.merge(a, b); touched.insert(k);self.push_candidates(k, &mut heap); }// loose faces again, against the groups that changedlet touched: Vec<usize> = touched.into_iter().filter(|&g| self.groups[g].alive).collect();let loose = std::mem::take(&mutself.loose);for f in loose {matchself.best_group(f, touched.iter().copied()) {Some(g) => self.join(f, g),None => self.loose.push(f), } } }fn push_candidates(&self, a: usize, heap: &mutBinaryHeap<Candidate>) {for b in0..self.groups.len() {if b == a || !self.groups[b].alive {continue; }let s = self.average(a, b);if s >= MERGE {let (x, y) = (a.min(b), a.max(b)); heap.push(Candidate(s, x, y, self.groups[x].version, self.groups[y].version)); } } }pubfn result(&self) -> Grouping {letmut out: Vec<(Group, Option<usize>)> = vec![];for (ix, g) inself.groups.iter().enumerate().filter(|(_, g)| g.alive) {letmut faces = g.members.clone(); faces.sort_unstable(); out.push((Group { faces, photos: g.photos.len(), person: g.person.clone(), shown: g.person.is_some() || g.photos.len() >= SHOWN_PHOTOS }, Some(ix))); }for f in0..self.faces.len() {ifself.group_of[f].is_none() {let person = self.faces[f].person.clone(); out.push((Group { faces: vec![f], photos: 1, shown: person.is_some(), person }, None)); } } out.sort_by(|(x, _), (y, _)| y.photos.cmp(&x.photos).then(y.person.is_some().cmp(&x.person.is_some())).then(x.faces[0].cmp(&y.faces[0])));letmut labels = vec![0; self.faces.len()];letmut index_of: BTreeMap<usize, usize> = BTreeMap::new();for (n, (g, inner)) in out.iter().enumerate() {for &f in &g.faces { labels[f] = n; }ifletSome(i) = inner { index_of.insert(*i, n); } }let shown: Vec<(usize, usize)> = index_of.iter().filter(|(_, &n)| out[n].0.shown).map(|(&i, &n)| (i, n)).collect();letmut suggestions = vec![];for x in0..shown.len() {for y in x + 1..shown.len() {let (a, b) = (shown[x].0, shown[y].0);let s = self.average(a, b);if (ASK..MERGE).contains(&s) && self.groups_fit(a, b) {let (na, nb) = (shown[x].1.min(shown[y].1), shown[x].1.max(shown[y].1)); suggestions.push(Suggestion { a: na, b: nb, similarity: s }); } } } suggestions.sort_by(|p, q| q.similarity.total_cmp(&p.similarity).then(p.a.cmp(&q.a)).then(p.b.cmp(&q.b)));Grouping { labels, groups: out.into_iter().map(|(g, _)| g).collect(), suggestions } }}#[cfg(test)]mod tests {usesuper::*;/// A unit vector near axis `axis` of 16, nudged by `jitter` along axis 15 - axis.fn v(axis: usize, jitter: f32) -> Vec<f32> {letmut x = vec![0.0; 16]; x[axis] = 1.0; x[15 - axis] += jitter; x }fn face(key: &str, photo: &str, vector: Vec<f32>) -> Face {Face { key: key.into(), photo: photo.into(), vector, ..Default::default() } }fn same(g: &Grouping, a: usize, b: usize) -> bool { g.labels[a] == g.labels[b] }/// Five photos of person X (axis 0) and five of Y (axis 1).fn two_people() -> Vec<Face> {letmut faces = vec![];for k in0..5 { faces.push(face(&format!("x{k}"), &format!("px{k}"), v(0, 0.05 * k as f32))); faces.push(face(&format!("y{k}"), &format!("py{k}"), v(1, 0.05 * k as f32))); } faces } #[test]fn two_faces_in_one_photo_are_never_one_person_even_when_identical() {letmut faces = two_people(); faces.push(face("twin-a", "group-photo", v(0, 0.0))); faces.push(face("twin-b", "group-photo", v(0, 0.0)));let photos: Vec<String> = faces.iter().map(|f| f.photo.clone()).collect();let g = group(faces, &Choices::default()); assert!(!same(&g, 10, 11), "two faces of one photo landed in one group");for grp in &g.groups {let distinct: BTreeSet<_> = grp.faces.iter().map(|&f| &photos[f]).collect(); assert_eq!(distinct.len(), grp.faces.len(), "a group holds two faces of one photo"); } } #[test]fn a_look_alike_face_does_not_chain_two_people_into_one() {letmut faces = two_people();// halfway between X and Y: cosine 0.71 with both, enough for single linkage at 0.5 to join everyoneletmut bridge = v(0, 0.0); bridge[1] = 1.0; faces.push(face("bridge", "pb", bridge));let g = group(faces, &Choices::default()); assert!(!same(&g, 0, 1), "X and Y were chained through one look-alike face"); assert!((0..5).all(|k| same(&g, 0, 2 * k)) && (0..5).all(|k| same(&g, 1, 2 * k + 1)), "each person is one group"); assert_eq!(g.groups.iter().filter(|x| x.shown).count(), 2); } #[test]fn a_group_is_shown_only_at_five_photos() {let faces: Vec<Face> = (0..4).map(|k| face(&format!("z{k}"), &format!("pz{k}"), v(2, 0.05 * k as f32))).collect();let g = group(faces.clone(), &Choices::default()); assert!(same(&g, 0, 3)); assert!(!g.groups[g.labels[0]].shown, "four photos are not shown");letmut five = faces; five.push(face("z4", "pz4", v(2, 0.2)));let g = group(five, &Choices::default()); assert!(g.groups[g.labels[0]].shown); } #[test]fn his_choices_survive_regrouping() {letmut faces = two_people();// he named x0 and y0, said x4 is not Asha, and merged a far-off face into Ravi faces[0].person = Some("Asha".into()); faces[1].person = Some("Ravi".into()); faces[8].not = vec!["Asha".into()]; faces.push(face("odd", "podd", v(3, 0.0)));let choices = Choices { same: vec![("y0".into(), "odd".into())], different: vec![] };for _ in0..2 {let g = group(faces.clone(), &choices); assert_eq!(g.groups[g.labels[0]].person.as_deref(), Some("Asha")); assert_eq!(g.groups[g.labels[1]].person.as_deref(), Some("Ravi")); assert!(!same(&g, 0, 8), "x4 joined Asha after he said it is not her"); assert!(same(&g, 1, 10), "his merge did not survive"); assert!(same(&g, 0, 2), "other faces of Asha still join her"); } } #[test]fn two_named_people_never_merge_however_alike() {let faces = vec![Face { person: Some("Asha".into()), ..face("a", "p1", v(0, 0.0)) },Face { person: Some("Meera".into()), ..face("m", "p2", v(0, 0.01)) }, ];let g = group(faces, &Choices::default()); assert!(!same(&g, 0, 1)); } #[test]fn no_to_same_person_keeps_two_groups_apart() {// two groups at average cosine about 0.42 (2t / (1 + t^2), t = 0.22): over MERGE, so merged by themselves,// but no face is near enough the other's centroid to join it (JOIN 0.45)letmut faces = vec![];for k in0..5 {letmut a = v(4, 0.0); a[5] = 0.22; a[6] = 0.02 * k as f32;letmut b = v(5, 0.0); b[4] = 0.22; b[7] = 0.02 * k as f32; faces.push(face(&format!("a{k}"), &format!("pa{k}"), a)); faces.push(face(&format!("b{k}"), &format!("pb{k}"), b)); }let g = group(faces.clone(), &Choices::default()); assert!(same(&g, 0, 1), "alike enough to be one person by themselves");let no = Choices { same: vec![], different: vec![("a0".into(), "b0".into())] };let g = group(faces, &no); assert!(!same(&g, 0, 1), "his No was not kept"); assert!((0..5).all(|k| same(&g, 0, 2 * k)) && (0..5).all(|k| same(&g, 1, 2 * k + 1))); } #[test]fn an_unsure_pair_of_groups_is_a_suggestion_not_a_merge() {// average cosine about 0.35 (2t / (1 + t^2), t = 0.18): in [ASK, MERGE)let faces = two_unsure_groups();let g = group(faces, &Choices::default()); assert!(!same(&g, 0, 1)); assert_eq!(g.suggestions.len(), 1, "{:?}", g.suggestions);let s = &g.suggestions[0]; assert!((ASK..MERGE).contains(&s.similarity)); assert_eq!(BTreeSet::from([s.a, s.b]), BTreeSet::from([g.labels[0], g.labels[1]]));// his No ends the question, and the groups stay apartlet no = Choices { same: vec![], different: vec![("a3".into(), "b1".into())] };let g = group(two_unsure_groups(), &no); assert!(g.suggestions.is_empty() && !same(&g, 0, 1)); }fn two_unsure_groups() -> Vec<Face> {letmut faces = vec![];for k in0..5 {letmut a = v(8, 0.0); a[9] = 0.18; a[10] = 0.03 * k as f32;letmut b = v(9, 0.0); b[8] = 0.18; b[11] = 0.03 * k as f32; faces.push(face(&format!("a{k}"), &format!("pa{k}"), a)); faces.push(face(&format!("b{k}"), &format!("pb{k}"), b)); } faces } #[test]fn faces_taken_later_join_the_groups_already_there() {letmut g = Grouper::new(Choices::default()); g.add(two_people()); g.add(vec![face("x-late", "pl1", v(0, 0.1)), face("y-late", "pl2", v(1, 0.1))]);let r = g.result(); assert!(same(&r, 0, 10) && same(&r, 1, 11) && !same(&r, 10, 11)); } #[test]fn a_face_without_a_vector_stays_alone() {letmut faces = two_people(); faces.push(face("blank", "pblank", vec![0.0; 16]));let g = group(faces, &Choices::default()); assert_eq!(g.groups[g.labels[10]].faces, vec![10]); }}