Skip to main content

smriti/ml/
face_embedder.rs

1//! ArcFace Face Embedding
2//!
3//! Generates 512-dimensional embeddings for face recognition.
4//! Uses the ArcFace-R100 model via ONNX Runtime, with optional
5//! offloading to a remote GPU bridge.
6
7use std::path::PathBuf;
8
9use image::RgbImage;
10use ndarray::Array1;
11use ort::session::Session;
12use ort::value::TensorRef;
13
14use super::remote_embedder::RemoteEmbedder;
15use super::OnnxRuntime;
16
17/// 512-dimensional face embedding
18#[derive(Debug, Clone)]
19pub struct FaceEmbedding {
20    /// The embedding vector
21    pub vector: Array1<f32>,
22}
23
24impl FaceEmbedding {
25    /// Create from a vector
26    pub fn new(vector: Array1<f32>) -> Self {
27        Self { vector }
28    }
29
30    /// Calculate cosine similarity with another embedding
31    pub fn cosine_similarity(&self, other: &FaceEmbedding) -> f32 {
32        let dot: f32 = self
33            .vector
34            .iter()
35            .zip(other.vector.iter())
36            .map(|(a, b)| a * b)
37            .sum();
38
39        let norm1: f32 = self.vector.iter().map(|x| x * x).sum::<f32>().sqrt();
40        let norm2: f32 = other.vector.iter().map(|x| x * x).sum::<f32>().sqrt();
41
42        if norm1 > 0.0 && norm2 > 0.0 {
43            dot / (norm1 * norm2)
44        } else {
45            0.0
46        }
47    }
48
49    /// Convert to bytes for database storage (little-endian f32 values)
50    pub fn to_bytes(&self) -> Vec<u8> {
51        self.vector.iter().flat_map(|f| f.to_le_bytes()).collect()
52    }
53
54    /// Create from bytes (expects 512 * 4 = 2048 bytes, little-endian f32)
55    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
56        if bytes.len() != 512 * 4 {
57            return None;
58        }
59
60        let vector: Array1<f32> = Array1::from_iter(
61            bytes
62                .as_chunks::<4>()
63                .0
64                .iter()
65                .map(|chunk| f32::from_le_bytes(*chunk)),
66        );
67
68        Some(Self { vector })
69    }
70}
71
72/// Configuration for creating a FaceEmbedder.
73#[derive(Debug, Clone)]
74pub struct EmbedderConfig {
75    pub model_path: PathBuf,
76    pub gpu_bridge_url: Option<String>,
77    /// Name of the model the desktop is configured to use (e.g.
78    /// `adaface_ir101_webface12m.onnx`). Passed to the bridge so it
79    /// can refuse if its loaded model is different — mismatched models
80    /// produce embeddings in different metric spaces and would corrupt
81    /// clustering.
82    pub expected_model: String,
83    pub intra_threads: usize,
84}
85
86/// Dispatch enum — either local ONNX or remote GPU bridge.
87///
88/// The `Remote` variant always carries a `LocalEmbedder` alongside it.
89/// When the remote bridge fails for a batch, we fall back to local for
90/// just that batch instead of dropping the faces silently. The remote's
91/// own 3-strikes / unhealthy check still applies; this is the per-batch
92/// safety net while it's nominally healthy.
93pub enum FaceEmbedder {
94    Local(LocalEmbedder),
95    Remote {
96        remote: RemoteEmbedder,
97        local_fallback: Option<LocalEmbedder>,
98    },
99}
100
101impl FaceEmbedder {
102    /// Build the configured embedder. Always constructs a local
103    /// instance — it's required as a fallback even when the bridge is
104    /// healthy. If a remote bridge URL is configured AND the bridge
105    /// passes its initial health check (including model match), the
106    /// returned embedder routes batches through the remote first.
107    pub fn from_config(rt: &OnnxRuntime, cfg: &EmbedderConfig) -> Result<Self, ort::Error> {
108        if let Some(ref url) = cfg.gpu_bridge_url {
109            let remote = RemoteEmbedder::new(url.clone(), cfg.expected_model.clone());
110            if remote.is_healthy() {
111                let local_fallback = if cfg.model_path.exists() {
112                    Some(LocalEmbedder::new_with_threads(
113                        rt,
114                        &cfg.model_path,
115                        cfg.intra_threads,
116                    )?)
117                } else {
118                    tracing::warn!(
119                        "Local face embedder model {} missing; using remote bridge without local fallback",
120                        cfg.model_path.display()
121                    );
122                    None
123                };
124                tracing::info!("Face embedding routed to remote GPU bridge at {}", url);
125                return Ok(FaceEmbedder::Remote {
126                    remote,
127                    local_fallback,
128                });
129            }
130            tracing::info!("Remote GPU bridge unavailable; using local embedder");
131        }
132        let local = LocalEmbedder::new_with_threads(rt, &cfg.model_path, cfg.intra_threads)?;
133        Ok(FaceEmbedder::Local(local))
134    }
135
136    /// Generate embedding for an aligned face image (112x112).
137    pub fn embed(&mut self, aligned_face: &RgbImage) -> Option<FaceEmbedding> {
138        self.embed_batch(std::slice::from_ref(aligned_face))
139            .into_iter()
140            .next()
141            .flatten()
142    }
143
144    /// Generate embeddings for a batch of aligned face images.
145    /// Returns one Option per input; None only if both remote and
146    /// local-fallback produced no embedding for that input.
147    pub fn embed_batch(&mut self, faces: &[RgbImage]) -> Vec<Option<FaceEmbedding>> {
148        match self {
149            FaceEmbedder::Local(e) => e.embed_batch(faces),
150            FaceEmbedder::Remote {
151                remote,
152                local_fallback,
153            } => {
154                let mut out = remote.embed_batch(faces);
155                if out.len() != faces.len() {
156                    // Defensive: should never happen, but if it does,
157                    // recompute fully on local when available.
158                    return local_fallback
159                        .as_mut()
160                        .map_or_else(|| vec![None; faces.len()], |local| local.embed_batch(faces));
161                }
162                let missing: Vec<usize> = out
163                    .iter()
164                    .enumerate()
165                    .filter_map(|(i, r)| if r.is_none() { Some(i) } else { None })
166                    .collect();
167                if missing.is_empty() {
168                    return out;
169                }
170                if let Some(local) = local_fallback.as_mut() {
171                    let crops: Vec<RgbImage> = missing.iter().map(|&i| faces[i].clone()).collect();
172                    let fb = local.embed_batch(&crops);
173                    for (k, &orig_i) in missing.iter().enumerate() {
174                        if let Some(emb) = fb.get(k).cloned().flatten() {
175                            out[orig_i] = Some(emb);
176                        }
177                    }
178                }
179                out
180            }
181        }
182    }
183}
184
185/// Local ArcFace Face Embedder using ONNX Runtime.
186pub struct LocalEmbedder {
187    session: Option<Session>,
188    model_path: PathBuf,
189    cpu_fallback_attempted: bool,
190}
191
192impl LocalEmbedder {
193    /// Load the ArcFace model with a specific thread count per session.
194    pub fn new_with_threads<P: AsRef<std::path::Path>>(
195        runtime: &OnnxRuntime,
196        model_path: P,
197        intra_threads: usize,
198    ) -> ort::Result<Self> {
199        let model_path = model_path.as_ref().to_path_buf();
200        let _ = runtime;
201        let session = OnnxRuntime::load_cpu_model_with_threads(&model_path, intra_threads)?;
202
203        Ok(Self {
204            session: Some(session),
205            model_path,
206            cpu_fallback_attempted: false,
207        })
208    }
209
210    /// Generate embedding for an aligned face image (112x112)
211    pub fn embed(&mut self, aligned_face: &RgbImage) -> Option<FaceEmbedding> {
212        self.embed_batch(std::slice::from_ref(aligned_face))
213            .into_iter()
214            .next()
215            .flatten()
216    }
217
218    /// Generate embeddings for a batch of aligned face images.
219    /// Returns one Option per input; None if that input was invalid.
220    pub fn embed_batch(&mut self, faces: &[RgbImage]) -> Vec<Option<FaceEmbedding>> {
221        let n = faces.len();
222        if n == 0 {
223            return Vec::new();
224        }
225
226        // Validate dimensions and preprocess each face into a flat [3*112*112] row.
227        let mut valid_indices: Vec<usize> = Vec::with_capacity(n);
228        let mut batch_data: Vec<f32> = Vec::with_capacity(n * 3 * 112 * 112);
229        for (i, face) in faces.iter().enumerate() {
230            if face.width() != 112 || face.height() != 112 {
231                continue;
232            }
233            valid_indices.push(i);
234            let row = self.preprocess(face);
235            batch_data.extend_from_slice(&row);
236        }
237
238        if valid_indices.is_empty() {
239            return vec![None; n];
240        }
241
242        let batch_n = valid_indices.len();
243        let raw_outputs = match self.run_inference_batch(&batch_data, batch_n as i64) {
244            Ok(v) => v,
245            Err(e) => {
246                tracing::warn!("Batch embedding inference failed: {}", e);
247                return vec![None; n];
248            }
249        };
250
251        // Each output row is 512 floats. L2-normalize each.
252        let mut embeddings: Vec<Option<FaceEmbedding>> = vec![None; n];
253        for (out_i, orig_i) in valid_indices.iter().enumerate() {
254            let start = out_i * 512;
255            let end = start + 512;
256            if end > raw_outputs.len() {
257                break;
258            }
259            let row = Array1::from_vec(raw_outputs[start..end].to_vec());
260            let normalized = self.normalize(&row);
261            embeddings[*orig_i] = Some(FaceEmbedding::new(normalized));
262        }
263        embeddings
264    }
265
266    /// Preprocess face image for ArcFace: normalize to [-1, 1], produce NCHW vec
267    fn preprocess(&self, face: &RgbImage) -> Vec<f32> {
268        let mut input = vec![0.0f32; 3 * 112 * 112];
269        let hw = 112 * 112;
270
271        for y in 0..112u32 {
272            for x in 0..112u32 {
273                let pixel = face.get_pixel(x, y);
274                let idx = (y * 112 + x) as usize;
275                input[idx] = (pixel[0] as f32 - 127.5) / 127.5;
276                input[hw + idx] = (pixel[1] as f32 - 127.5) / 127.5;
277                input[2 * hw + idx] = (pixel[2] as f32 - 127.5) / 127.5;
278            }
279        }
280
281        input
282    }
283
284    /// Run ONNX inference with a batch of faces [N, 3, 112, 112].
285    /// Returns a flat `Vec<f32>` of N * 512 floats.
286    fn run_inference_batch(
287        &mut self,
288        input_data: &[f32],
289        batch_size: i64,
290    ) -> ort::Result<Vec<f32>> {
291        match self.run_inference_once(input_data, batch_size) {
292            Ok(output) => Ok(output),
293            Err(error) if !self.cpu_fallback_attempted => {
294                tracing::warn!(%error, "Embedding inference failed; retrying once on CPU");
295                self.cpu_fallback_attempted = true;
296                self.session = None;
297                self.session = Some(OnnxRuntime::load_cpu_model(&self.model_path)?);
298                self.run_inference_once(input_data, batch_size)
299            }
300            Err(error) => Err(error),
301        }
302    }
303
304    fn run_inference_once(&mut self, input_data: &[f32], batch_size: i64) -> ort::Result<Vec<f32>> {
305        let input_tensor =
306            TensorRef::<f32>::from_array_view((vec![batch_size, 3, 112, 112], input_data))?;
307
308        let outputs = self
309            .session
310            .as_mut()
311            .ok_or_else(|| ort::Error::new("Embedder session unavailable"))?
312            .run(ort::inputs![input_tensor])?;
313
314        let (_name, output) = outputs
315            .iter()
316            .next()
317            .ok_or_else(|| ort::Error::new("No output tensor from ArcFace model".to_string()))?;
318
319        let (_shape, data) = output.try_extract_tensor::<f32>()?;
320        Ok(data.to_vec())
321    }
322
323    /// L2 normalize the embedding vector
324    fn normalize(&self, embedding: &Array1<f32>) -> Array1<f32> {
325        let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
326
327        if norm > 0.0 {
328            embedding / norm
329        } else {
330            embedding.clone()
331        }
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338
339    #[test]
340    fn test_cosine_similarity_identical() {
341        let emb1 = FaceEmbedding::new(Array1::from_vec(vec![1.0, 0.0, 0.0]));
342        let emb2 = FaceEmbedding::new(Array1::from_vec(vec![1.0, 0.0, 0.0]));
343
344        assert!((emb1.cosine_similarity(&emb2) - 1.0).abs() < 0.001);
345    }
346
347    #[test]
348    fn test_cosine_similarity_orthogonal() {
349        let emb1 = FaceEmbedding::new(Array1::from_vec(vec![1.0, 0.0, 0.0]));
350        let emb2 = FaceEmbedding::new(Array1::from_vec(vec![0.0, 1.0, 0.0]));
351
352        assert!((emb1.cosine_similarity(&emb2) - 0.0).abs() < 0.001);
353    }
354
355    #[test]
356    fn test_embedding_serialization() {
357        let original = FaceEmbedding::new(Array1::from_vec(vec![1.0; 512]));
358        let bytes = original.to_bytes();
359        assert_eq!(bytes.len(), 512 * 4);
360
361        let restored = FaceEmbedding::from_bytes(&bytes).unwrap();
362        assert!((original.cosine_similarity(&restored) - 1.0).abs() < 0.001);
363    }
364
365    #[test]
366    fn test_embedding_from_bytes_wrong_size() {
367        let bytes = vec![0u8; 100];
368        assert!(FaceEmbedding::from_bytes(&bytes).is_none());
369    }
370}