π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
feat: Use species class ID from pet detection results to dynamically select appropriate embedding models.
Amrithesh Kakkoth Entec0f524a302ee
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dartindex c678348b8b..3314810b7b 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart@@ -782,6 +782,7 @@ class MLService {);final vectorIds = <int>[];final embeddings = <Float32List>[];+ final insertedPetFaceIds = <String>[];for (final (dbFace, pfResult) in entry.value) {final vid = idMap[dbFace.petFaceId];if (vid == null) continue;@@ -794,6 +795,7 @@ class MLService {}vectorIds.add(vid);embeddings.add(emb);+ insertedPetFaceIds.add(dbFace.petFaceId);}if (vectorIds.isNotEmpty) {await vdb.bulkInsertEmbeddings(@@ -801,7 +803,7 @@ class MLService {embeddings: embeddings,);final updateMap = Map.fromIterables(- entry.value.map((e) => e.$1.petFaceId),+ insertedPetFaceIds,vectorIds,);await mlDataDB.updatePetFaceVectorIds(updateMap);@@ -839,6 +841,7 @@ class MLService {);final vectorIds = <int>[];final embeddings = <Float32List>[];+ final insertedPetBodyIds = <String>[];for (final (dbBody, pbResult) in entry.value) {final vid = idMap[dbBody.petBodyId];if (vid == null) continue;@@ -851,6 +854,7 @@ class MLService {}vectorIds.add(vid);embeddings.add(emb);+ insertedPetBodyIds.add(dbBody.petBodyId);}if (vectorIds.isNotEmpty) {await vdb.bulkInsertEmbeddings(@@ -858,7 +862,7 @@ class MLService {embeddings: embeddings,);final updateMap = Map.fromIterables(- entry.value.map((e) => e.$1.petBodyId),+ insertedPetBodyIds,vectorIds,);await mlDataDB.updatePetBodyVectorIds(updateMap);diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rsindex c21438625c..38901a1888 100644--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs@@ -5,7 +5,7 @@ use crate::ml::{face::{align::run_face_alignment, detect::run_face_detection, embed::run_face_embedding},pet::{align::run_pet_face_alignment,- detect::{detect_species, run_pet_body_detection, run_pet_face_detection},+ detect::{run_pet_body_detection, run_pet_face_detection},embed::{run_pet_body_embedding, run_pet_face_embedding},},runtime::{self, ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},@@ -268,8 +268,6 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRelet body_detections = run_pet_body_detection(runtime, &decoded)?;ml_log(&format!("file={} pet body detection: {} bodies in {:?} rss={}MB", req.file_id, body_detections.len(), t.elapsed(), vm_rss_kb() / 1024));- let species = detect_species(&body_detections);-runtime.unload_pet_detection_sessions();ml_log(&format!("file={} pet detection sessions unloaded rss={}MB", req.file_id, vm_rss_kb() / 1024));@@ -278,7 +276,7 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRelet (aligned, mut pet_results) =run_pet_face_alignment(req.file_id, &decoded, &pet_face_detections)?;ml_log(&format!("file={} pet face aligned rss={}MB", req.file_id, vm_rss_kb() / 1024));- run_pet_face_embedding(runtime, &aligned, &mut pet_results, species)?;+ run_pet_face_embedding(runtime, &aligned, &mut pet_results)?;ml_log(&format!("file={} pet face embedding: {} faces in {:?} rss={}MB", req.file_id, pet_results.len(), t.elapsed(), vm_rss_kb() / 1024));pet_results} else {@@ -298,7 +296,7 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRe.collect();if !body_results.is_empty() {let t = std::time::Instant::now();- run_pet_body_embedding(runtime, &decoded, &mut body_results, species)?;+ run_pet_body_embedding(runtime, &decoded, &mut body_results)?;ml_log(&format!("file={} pet body embedding: {} bodies in {:?} rss={}MB", req.file_id, body_results.len(), t.elapsed(), vm_rss_kb() / 1024));}diff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rsindex 254d1178ce..a07248ebc7 100644--- a/mobile/apps/photos/rust/src/ml/pet/detect.rs+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs@@ -40,9 +40,8 @@ pub fn run_pet_face_detection([1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],)?;- // Row format: [x, y, w, h, obj_conf, lx, ly, rx, ry, nx, ny, cls_conf...]- // For 2-class model (cat/dog): row_len = 4 + 1 + 6 + 2 = 13- // For 1-class model: row_len = 4 + 1 + 6 + 1 = 12+ // Row format: [x, y, w, h, conf, lm_x1, lm_y1, lm_x2, lm_y2, lm_x3, lm_y3, class_id]+ // row_len = 4 + 1 + 6 + 1 = 12// Use the output shape's last dimension to determine row length reliably.let row_len = if output_shape.len() >= 2 {*output_shape.last().unwrap() as usize@@ -110,10 +109,18 @@ pub fn run_pet_face_detection(pad_top,);+ // class_id at index 11: 0=dog, 1=cat+ let class_id = if row_len >= 12 {+ row[11] as u8+ } else {+ 0+ };+detections.push(PetFaceDetection {score,box_xyxy,keypoints,+ class_id,});}diff --git a/mobile/apps/photos/rust/src/ml/pet/embed.rs b/mobile/apps/photos/rust/src/ml/pet/embed.rsindex 850343654e..7fd7f04338 100644--- a/mobile/apps/photos/rust/src/ml/pet/embed.rs+++ b/mobile/apps/photos/rust/src/ml/pet/embed.rs@@ -20,11 +20,14 @@ const BODY_EMBED_CHANNELS: i64 = 3;/// Output: L2-normalized embedding vector (128-d for BYOL).////// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_face()`.+/// Run pet face embedding using each face's own `class_id` to select the model.+///+/// Faces are grouped by species and batched per model to avoid running the+/// wrong embedding model on any detection.pub fn run_pet_face_embedding(runtime: &mut MlRuntime,aligned_faces: &[Vec<f32>],face_results: &mut [PetFaceResult],- species: u8,) -> MlResult<()> {if aligned_faces.is_empty() {return Ok(());@@ -38,55 +41,75 @@ pub fn run_pet_face_embedding(}let per_face_len = (FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;- let mut input = Vec::with_capacity(per_face_len * aligned_faces.len());- for aligned in aligned_faces {- if aligned.len() != per_face_len {- return Err(MlError::Preprocess(format!(- "aligned pet face tensor length {} does not match expected {}",- aligned.len(),- per_face_len- )));++ // Group indices by species (class_id from detection).+ let mut dog_indices = Vec::new();+ let mut cat_indices = Vec::new();+ for (i, fr) in face_results.iter().enumerate() {+ if fr.detection.class_id == 1 {+ cat_indices.push(i);+ } else {+ dog_indices.push(i);}- input.extend_from_slice(aligned);}- let session = if species == 0 {- runtime.pet_face_embedding_dog_session_mut()?- } else {- runtime.pet_face_embedding_cat_session_mut()?- };-- let (shape, output) = onnx::run_f32(- session,- input,- [- aligned_faces.len() as i64,- FACE_EMBED_CHANNELS,- FACE_EMBED_INPUT_SIZE,- FACE_EMBED_INPUT_SIZE,- ],- )?;-- if shape.is_empty() {- return Err(MlError::Postprocess(- "pet face embedding output shape is empty".to_string(),- ));- }- let batch = shape[0] as usize;- if batch != face_results.len() {- return Err(MlError::Postprocess(format!(- "pet face embedding batch mismatch: output={batch}, expected={}",- face_results.len()- )));- }- let embedding_size = output.len() / batch;+ // Process each species batch.+ for (species, indices) in [(0u8, &dog_indices), (1u8, &cat_indices)] {+ if indices.is_empty() {+ continue;+ }- for (idx, face_result) in face_results.iter_mut().enumerate() {- let start = idx * embedding_size;- let mut embedding = output[start..(start + embedding_size)].to_vec();- normalize_embedding(&mut embedding);- face_result.face_embedding = embedding;- face_result.species = species;+ let mut input = Vec::with_capacity(per_face_len * indices.len());+ for &idx in indices {+ let aligned = &aligned_faces[idx];+ if aligned.len() != per_face_len {+ return Err(MlError::Preprocess(format!(+ "aligned pet face tensor length {} does not match expected {}",+ aligned.len(),+ per_face_len+ )));+ }+ input.extend_from_slice(aligned);+ }++ let session = if species == 0 {+ runtime.pet_face_embedding_dog_session_mut()?+ } else {+ runtime.pet_face_embedding_cat_session_mut()?+ };++ let (shape, output) = onnx::run_f32(+ session,+ input,+ [+ indices.len() as i64,+ FACE_EMBED_CHANNELS,+ FACE_EMBED_INPUT_SIZE,+ FACE_EMBED_INPUT_SIZE,+ ],+ )?;++ if shape.is_empty() {+ return Err(MlError::Postprocess(+ "pet face embedding output shape is empty".to_string(),+ ));+ }+ let batch = shape[0] as usize;+ if batch != indices.len() {+ return Err(MlError::Postprocess(format!(+ "pet face embedding batch mismatch: output={batch}, expected={}",+ indices.len()+ )));+ }+ let embedding_size = output.len() / batch;++ for (batch_idx, &orig_idx) in indices.iter().enumerate() {+ let start = batch_idx * embedding_size;+ let mut embedding = output[start..(start + embedding_size)].to_vec();+ normalize_embedding(&mut embedding);+ face_results[orig_idx].face_embedding = embedding;+ face_results[orig_idx].species = species;+ }}Ok(())@@ -94,24 +117,24 @@ pub fn run_pet_face_embedding(/// Run pet body embedding on cropped body regions.///-/// For each body detection, extracts a crop, preprocesses with ImageNet-/// normalization, and runs through the species-specific body embedding model.+/// Each body's own `coco_class` (16=dog, 15=cat) selects the embedding model,+/// so mixed-species images get the correct model per detection.////// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_body()`.pub fn run_pet_body_embedding(runtime: &mut MlRuntime,decoded: &DecodedImage,body_results: &mut [PetBodyResult],- species: u8,) -> MlResult<()> {for body_result in body_results.iter_mut() {let (crop_data, crop_w, crop_h) = extract_crop(decoded, &body_result.detection.box_xyxy)?;let input = preprocess_pet_embedding(&crop_data, crop_w, crop_h)?;- let session = if species == 0 {- runtime.pet_body_embedding_dog_session_mut()?- } else {+ // COCO class 15 = cat, 16 = dog+ let session = if body_result.detection.coco_class == 15 {runtime.pet_body_embedding_cat_session_mut()?+ } else {+ runtime.pet_body_embedding_dog_session_mut()?};let (_shape, output) = onnx::run_f32(diff --git a/mobile/apps/photos/rust/src/ml/types.rs b/mobile/apps/photos/rust/src/ml/types.rsindex 25a245d5c4..2a64859d6a 100644--- a/mobile/apps/photos/rust/src/ml/types.rs+++ b/mobile/apps/photos/rust/src/ml/types.rs@@ -64,6 +64,8 @@ pub struct PetFaceDetection {pub box_xyxy: [f32; 4],/// 3 keypoints: [left_eye, right_eye, nose]pub keypoints: [[f32; 2]; 3],+ /// 0 = dog, 1 = cat (from class scores in detector output)+ pub class_id: u8,}#[derive(Clone, Debug)]