Skip to content

armgit / ente

Public Imported from GitHub
0

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

Fix pet recognition: Mutex to RwLock, cat face classification, and misc bugs

Amrithesh Kakkoth Ente38f6f4ef2018
diff --git a/mobile/apps/photos/lib/db/ml/base.dart b/mobile/apps/photos/lib/db/ml/base.dart
index 37ad3a9df8..6e11af11dc 100644
--- a/mobile/apps/photos/lib/db/ml/base.dart
+++ b/mobile/apps/photos/lib/db/ml/base.dart
@@ -129,4 +129,5 @@ abstract class IMLDataDB<T> {
Future<Map<int, int>> petIndexedFileIds({int minimumMlVersion});
Future<int> getPetIndexedFileCount({int minimumMlVersion});
Future<void> markPetIndexed(int fileID, int mlVersion);
+ Future<void> deletePetDataForFiles(List<int> fileIDs);
}
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dart
index e5a1dacc2b..6ccb1aed7b 100644
--- a/mobile/apps/photos/lib/db/ml/db.dart
+++ b/mobile/apps/photos/lib/db/ml/db.dart
@@ -231,15 +231,15 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
const String sql = '''
INSERT INTO $detectedObjectsTable (
- $fileIDColumn, $objectIDColumn, $detectionColumn, $bodyVectorIdColumn, $speciesColumn, $faceScore, $imageHeight, $imageWidth, $mlVersionColumn, $petBodyEmbeddingColumn
+ $fileIDColumn, $detectedObjectIDColumn, $detectionColumn, $bodyVectorIdColumn, $speciesColumn, $faceScore, $imageHeight, $imageWidth, $mlVersionColumn, $petBodyEmbeddingColumn
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT($fileIDColumn, $objectIDColumn) DO UPDATE SET $detectionColumn = excluded.$detectionColumn, $bodyVectorIdColumn = excluded.$bodyVectorIdColumn, $speciesColumn = excluded.$speciesColumn, $faceScore = excluded.$faceScore, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn, $petBodyEmbeddingColumn = excluded.$petBodyEmbeddingColumn
+ ON CONFLICT($fileIDColumn, $detectedObjectIDColumn) DO UPDATE SET $detectionColumn = excluded.$detectionColumn, $bodyVectorIdColumn = excluded.$bodyVectorIdColumn, $speciesColumn = excluded.$speciesColumn, $faceScore = excluded.$faceScore, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn, $petBodyEmbeddingColumn = excluded.$petBodyEmbeddingColumn
''';
final parameterSets = batch.map((obj) {
final map = obj.toMap();
return [
map[fileIDColumn],
- map[objectIDColumn],
+ map[detectedObjectIDColumn],
map[detectionColumn],
map[bodyVectorIdColumn],
map[speciesColumn],
@@ -296,7 +296,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
const String sql = '''
UPDATE $detectedObjectsTable
SET $bodyVectorIdColumn = ?
- WHERE $objectIDColumn = ?
+ WHERE $detectedObjectIDColumn = ?
''';
final parameterSets = batch.map((e) => [e.value, e.key]).toList();
await db.executeBatch(sql, parameterSets);
@@ -368,10 +368,10 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
List<DetectedObjectResult> objects,
) async {
try {
- // Group by species (COCO class 15 = cat β†’ species 1, 16 = dog β†’ species 0)
+ // Group by species (0 = dog, 1 = cat)
final bySpecies = <int, List<(DBDetectedObject, DetectedObjectResult)>>{};
for (int i = 0; i < dbObjects.length; i++) {
- final species = dbObjects[i].species == 15 ? 1 : 0;
+ final species = dbObjects[i].species;
bySpecies.putIfAbsent(species, () => []);
bySpecies[species]!.add((dbObjects[i], objects[i]));
}
@@ -2383,6 +2383,22 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
);
}
+ @override
+ Future<void> deletePetDataForFiles(List<int> fileIDs) async {
+ if (fileIDs.isEmpty) return;
+ final db = await asyncDB;
+ final ids = fileIDs.join(", ");
+ await db.execute(
+ 'DELETE FROM $petFacesTable WHERE $fileIDColumn IN ($ids)',
+ );
+ await db.execute(
+ 'DELETE FROM $detectedObjectsTable WHERE $fileIDColumn IN ($ids)',
+ );
+ await db.execute(
+ 'DELETE FROM $petIndexedFilesTable WHERE $fileIDColumn IN ($ids)',
+ );
+ }
+
@override
Future<void> putClip(List<ClipEmbedding> embeddings) async {
if (embeddings.isEmpty) return;
diff --git a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
index ede8243c65..dedff0ff99 100644
--- a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
+++ b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
@@ -93,7 +93,7 @@ class DBDetectedObject {
Map<String, dynamic> toMap() {
return {
fileIDColumn: fileId,
- objectIDColumn: objectId,
+ detectedObjectIDColumn: objectId,
detectionColumn: detection,
bodyVectorIdColumn: bodyVectorId,
speciesColumn: species,
@@ -108,7 +108,7 @@ class DBDetectedObject {
factory DBDetectedObject.fromMap(Map<String, dynamic> map) {
return DBDetectedObject(
fileId: map[fileIDColumn] as int,
- objectId: map[objectIDColumn] as String,
+ objectId: map[detectedObjectIDColumn] as String,
detection: map[detectionColumn] as String,
bodyVectorId: map[bodyVectorIdColumn] as int,
species: map[speciesColumn] as int,
diff --git a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
index 717c9899c2..b18611259c 100644
--- a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
+++ b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
@@ -176,7 +176,7 @@ class PetVectorDB {
if (createIfMissing) {
const insertSql = '''
- INSERT OR IGNORE INTO $objectVectorIdMappingTable ($objectIDColumn)
+ INSERT OR IGNORE INTO $objectVectorIdMappingTable ($detectedObjectIDColumn)
VALUES (?)
''';
final insertParams = <List<Object?>>[];
@@ -192,14 +192,14 @@ class PetVectorDB {
final chunk = uniqueIds.sublist(i, min(i + chunkSize, uniqueIds.length));
final rows = await db.getAll(
'''
- SELECT $objectIDColumn, $objectVectorIdColumn
+ SELECT $detectedObjectIDColumn, $objectVectorIdColumn
FROM $objectVectorIdMappingTable
- WHERE $objectIDColumn IN (${List.filled(chunk.length, '?').join(',')})
+ WHERE $detectedObjectIDColumn IN (${List.filled(chunk.length, '?').join(',')})
''',
chunk,
);
for (final row in rows) {
- result[row[objectIDColumn] as String] =
+ result[row[detectedObjectIDColumn] as String] =
row[objectVectorIdColumn] as int;
}
}
diff --git a/mobile/apps/photos/lib/db/ml/schema.dart b/mobile/apps/photos/lib/db/ml/schema.dart
index bed7b3a7e0..6d56d5d6bb 100644
--- a/mobile/apps/photos/lib/db/ml/schema.dart
+++ b/mobile/apps/photos/lib/db/ml/schema.dart
@@ -187,7 +187,7 @@ CREATE TABLE IF NOT EXISTS $offlineFileKeyMapTable (
// Shared column names
const petFaceIDColumn = 'pet_face_id';
-const objectIDColumn = 'object_id';
+const detectedObjectIDColumn = 'object_id';
const speciesColumn = 'species';
const detectionColumn = 'detection';
const faceVectorIdColumn = 'face_vector_id';
@@ -221,7 +221,7 @@ const detectedObjectsTable = 'detected_objects';
const createDetectedObjectsTable =
'''CREATE TABLE IF NOT EXISTS $detectedObjectsTable (
$fileIDColumn INTEGER NOT NULL,
- $objectIDColumn TEXT NOT NULL UNIQUE,
+ $detectedObjectIDColumn TEXT NOT NULL UNIQUE,
$detectionColumn TEXT NOT NULL,
$bodyVectorIdColumn INTEGER NOT NULL,
$speciesColumn INTEGER NOT NULL,
@@ -230,7 +230,7 @@ const createDetectedObjectsTable =
$imageWidth INTEGER NOT NULL DEFAULT 0,
$mlVersionColumn INTEGER NOT NULL DEFAULT -1,
$petBodyEmbeddingColumn BLOB,
- PRIMARY KEY($fileIDColumn, $objectIDColumn)
+ PRIMARY KEY($fileIDColumn, $detectedObjectIDColumn)
);
''';
@@ -295,7 +295,7 @@ const objectVectorIdColumn = 'object_vector_id';
const createObjectVectorIdMappingTable = '''
CREATE TABLE IF NOT EXISTS $objectVectorIdMappingTable (
$objectVectorIdColumn INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- $objectIDColumn TEXT NOT NULL UNIQUE
+ $detectedObjectIDColumn TEXT NOT NULL UNIQUE
);
''';
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index 6ef0f89156..873d5e766b 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -686,7 +686,7 @@ class MLService {
objectId: obj.objectId,
detection: jsonEncode(detectionObj.toJson()),
bodyVectorId: -1,
- species: obj.cocoClass,
+ species: obj.cocoClass == 15 ? 1 : 0,
score: obj.score,
imageHeight: result.decodedImageSize.height,
imageWidth: result.decodedImageSize.width,
@@ -701,7 +701,7 @@ class MLService {
);
}
}
- if (instruction.shouldRunPets) {
+ if (instruction.shouldRunPets && rustPets) {
await mlDataDB.markPetIndexed(result.fileId, petMlVersion);
}
_logger.info("ML result for fileID ${result.fileId} stored remote+local");
diff --git a/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart b/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart
index 4557cf662d..ceaae61822 100644
--- a/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart
@@ -1,8 +1,8 @@
import 'package:logging/logging.dart';
import "package:photos/services/machine_learning/ml_model.dart";
-/// Pet face detection model (YOLOv5-face with 3 keypoints).
-/// Model: yolov5n_petface_v2.onnx β€” detects pet faces with left_eye, right_eye, nose landmarks.
+/// Pet face detection model (YOLOv5s-face with 3 keypoints, FP16).
+/// Model: yolov5s_pet_face_fp16.onnx β€” detects pet faces with left_eye, right_eye, nose landmarks.
class PetFaceDetectionService extends MlModel {
static const kRemoteBucketModelPath = "yolov5s_pet_face_fp16.onnx";
static const _modelName = "YOLOv5PetFace";
diff --git a/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart b/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart
index 9a02cd6733..caa23b83a7 100644
--- a/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart
+++ b/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart
@@ -279,6 +279,7 @@ class _MLUserDeveloperOptionsState extends State<MLUserDeveloperOptions> {
final Set<int> emptyFileIDs = await mlDataDB.getErroredFileIDs();
await mlDataDB.deleteFaceIndexForFiles(emptyFileIDs.toList());
await mlDataDB.deleteClipEmbeddings(emptyFileIDs.toList());
+ await mlDataDB.deletePetDataForFiles(emptyFileIDs.toList());
showShortToast(context, "Deleted ${emptyFileIDs.length} entries");
} catch (e) {
// ignore: unawaited_futures
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
index 00366f2f58..7530dddfc7 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
@@ -10,6 +10,7 @@ import "package:photos/models/ml/face/box.dart";
import "package:photos/models/ml/face/detection.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/theme/ente_theme.dart";
+import "package:photos/theme/text_style.dart";
import "package:photos/ui/common/loading_widget.dart";
import "package:photos/ui/components/buttons/icon_button_widget.dart";
import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";
@@ -170,7 +171,10 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {
runSpacing: 8,
spacing: 12,
children: _petFaces
- .map((info) => _buildPetThumbnail(info, thumbnailWidth))
+ .map(
+ (info) =>
+ _buildPetThumbnail(info, thumbnailWidth, textTheme),
+ )
.toList(),
),
),
@@ -179,7 +183,11 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {
);
}
- Widget _buildPetThumbnail(_PetFaceInfo info, double thumbnailWidth) {
+ Widget _buildPetThumbnail(
+ _PetFaceInfo info,
+ double thumbnailWidth,
+ EnteTextTheme textTheme,
+ ) {
final l10n = AppLocalizations.of(context);
final speciesLabel = info.species == 0 ? l10n.dog : l10n.cat;
@@ -200,7 +208,7 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {
const SizedBox(height: 4),
Text(
speciesLabel,
- style: getEnteTextTheme(context).mini,
+ style: textTheme.mini,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index b2511227a5..a7cd7572bd 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -398,6 +398,12 @@ String _runtimeConfigCacheKey(
modelPaths.faceEmbedding,
modelPaths.clipImage,
modelPaths.clipText,
+ modelPaths.petFaceDetection,
+ modelPaths.petFaceEmbeddingDog,
+ modelPaths.petFaceEmbeddingCat,
+ modelPaths.petBodyDetection,
+ modelPaths.petBodyEmbeddingDog,
+ modelPaths.petBodyEmbeddingCat,
providerPolicy.preferCoreml,
providerPolicy.preferNnapi,
providerPolicy.preferXnnpack,
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 7a3603183a..2c6038f543 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -828,7 +828,8 @@ Future<MLResult> analyzeImageRust(Map args) async {
.toList(growable: false),
);
final alignment = AlignmentResult(
- affineMatrix: [],
+ // Pet alignment is done in Rust; no Dart-side affine matrix needed.
+ affineMatrix: const [],
center: face.alignment.center.toList(growable: false),
size: face.alignment.cropSize,
rotation: face.alignment.angle,
diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
index 8bc36afca3..993779ecd6 100644
--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
@@ -182,9 +182,7 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRe
provider_policy: to_provider_policy(&req.provider_policy),
};
- runtime::with_runtime_mut(&runtime_config, |runtime| {
- // Decode inside the lock so only one image is in memory at a time.
- // Without this, all queued images decode simultaneously, wasting memory.
+ runtime::with_runtime(&runtime_config, |runtime| {
let decoded = decode_image_from_path(&req.image_path)?;
let dims = RustDimensions {
width: decoded.dimensions.width as i32,
@@ -293,7 +291,7 @@ fn run_clip_text_rust_inner(req: RunClipTextRequest) -> MlResult<RunClipTextResu
provider_policy: to_provider_policy(&provider_policy),
};
- runtime::with_runtime_mut(&runtime_config, move |runtime| {
+ runtime::with_runtime(&runtime_config, |runtime| {
let clip = run_clip_text_query(runtime, &text, &vocab_path)?;
Ok(RunClipTextResult {
embedding: clip
diff --git a/mobile/apps/photos/rust/src/ml/clip/image.rs b/mobile/apps/photos/rust/src/ml/clip/image.rs
index c712b1d275..91b656eb27 100644
--- a/mobile/apps/photos/rust/src/ml/clip/image.rs
+++ b/mobile/apps/photos/rust/src/ml/clip/image.rs
@@ -5,9 +5,9 @@ use crate::ml::{
types::{ClipResult, DecodedImage},
};
-pub fn run_clip_image(runtime: &mut MlRuntime, decoded: &DecodedImage) -> MlResult<ClipResult> {
+pub fn run_clip_image(runtime: &MlRuntime, decoded: &DecodedImage) -> MlResult<ClipResult> {
let input = preprocess::preprocess_clip(decoded)?;
- let clip_image = runtime.clip_image_session_mut()?;
+ let clip_image = runtime.clip_image_session()?;
let (shape, output) = onnx::run_f32(clip_image, input, [1, 3, 256, 256])?;
let mut embedding = if shape.len() == 2 {
diff --git a/mobile/apps/photos/rust/src/ml/clip/text.rs b/mobile/apps/photos/rust/src/ml/clip/text.rs
index 18e5725482..a6e4426b26 100644
--- a/mobile/apps/photos/rust/src/ml/clip/text.rs
+++ b/mobile/apps/photos/rust/src/ml/clip/text.rs
@@ -8,7 +8,7 @@ use crate::ml::{
const CLIP_TEXT_TOKEN_COUNT: usize = 77;
-pub fn run_clip_text(runtime: &mut MlRuntime, token_ids: &[i32]) -> MlResult<ClipResult> {
+pub fn run_clip_text(runtime: &MlRuntime, token_ids: &[i32]) -> MlResult<ClipResult> {
if token_ids.len() != CLIP_TEXT_TOKEN_COUNT {
return Err(MlError::InvalidRequest(format!(
"clip text expects exactly {CLIP_TEXT_TOKEN_COUNT} tokens, got {}",
@@ -16,7 +16,7 @@ pub fn run_clip_text(runtime: &mut MlRuntime, token_ids: &[i32]) -> MlResult<Cli
)));
}
- let clip_text = runtime.clip_text_session_mut()?;
+ let clip_text = runtime.clip_text_session()?;
let (shape, output) = onnx::run_i32_f32(
clip_text,
token_ids.to_vec(),
@@ -45,7 +45,7 @@ pub fn run_clip_text(runtime: &mut MlRuntime, token_ids: &[i32]) -> MlResult<Cli
}
pub fn run_clip_text_query(
- runtime: &mut MlRuntime,
+ runtime: &MlRuntime,
query: &str,
vocab_path: &str,
) -> MlResult<ClipResult> {
diff --git a/mobile/apps/photos/rust/src/ml/face/detect.rs b/mobile/apps/photos/rust/src/ml/face/detect.rs
index a71991eaa1..860d7dc126 100644
--- a/mobile/apps/photos/rust/src/ml/face/detect.rs
+++ b/mobile/apps/photos/rust/src/ml/face/detect.rs
@@ -11,12 +11,12 @@ const IOU_THRESHOLD: f32 = 0.4;
const MIN_SCORE_THRESHOLD: f32 = 0.5;
pub fn run_face_detection(
- runtime: &mut MlRuntime,
+ runtime: &MlRuntime,
decoded: &DecodedImage,
) -> MlResult<Vec<FaceDetection>> {
let (input, scaled_width, scaled_height, pad_left, pad_top) =
preprocess::preprocess_yolo(decoded)?;
- let face_detection = runtime.face_detection_session_mut()?;
+ let face_detection = runtime.face_detection_session()?;
let output_data = onnx::run_f32_data(
face_detection,
input,
diff --git a/mobile/apps/photos/rust/src/ml/face/embed.rs b/mobile/apps/photos/rust/src/ml/face/embed.rs
index 309dead3a2..c1372ed244 100644
--- a/mobile/apps/photos/rust/src/ml/face/embed.rs
+++ b/mobile/apps/photos/rust/src/ml/face/embed.rs
@@ -10,7 +10,7 @@ const FACE_INPUT_HEIGHT: i64 = 112;
const FACE_INPUT_CHANNELS: i64 = 3;
pub fn run_face_embedding(
- runtime: &mut MlRuntime,
+ runtime: &MlRuntime,
aligned_faces: &[Vec<f32>],
face_results: &mut [FaceResult],
) -> MlResult<()> {
@@ -38,7 +38,7 @@ pub fn run_face_embedding(
input.extend_from_slice(aligned);
}
- let face_embedding = runtime.face_embedding_session_mut()?;
+ let face_embedding = runtime.face_embedding_session()?;
let (shape, output) = onnx::run_f32(
face_embedding,
input,
diff --git a/mobile/apps/photos/rust/src/ml/onnx.rs b/mobile/apps/photos/rust/src/ml/onnx.rs
index d61fc453e4..4c9f60b817 100644
--- a/mobile/apps/photos/rust/src/ml/onnx.rs
+++ b/mobile/apps/photos/rust/src/ml/onnx.rs
@@ -119,7 +119,7 @@ fn session_expects_f16(session: &Session) -> bool {
/// Run inference accepting f32 data and returning f32 results.
/// Automatically converts inputs/outputs for FP16 models.
pub fn run_f32<const N: usize>(
- session: &mut Session,
+ session: &Session,
input: Vec<f32>,
input_shape: [i64; N],
) -> MlResult<(Vec<i64>, Vec<f32>)> {
@@ -155,7 +155,7 @@ pub fn run_f32<const N: usize>(
}
pub fn run_f32_data<const N: usize>(
- session: &mut Session,
+ session: &Session,
input: Vec<f32>,
input_shape: [i64; N],
) -> MlResult<Vec<f32>> {
@@ -170,7 +170,7 @@ pub fn run_f32_data<const N: usize>(
}
pub fn run_i32_f32<const N: usize>(
- session: &mut Session,
+ session: &Session,
input: Vec<i32>,
input_shape: [i64; N],
) -> MlResult<(Vec<i64>, Vec<f32>)> {
diff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rs
index d337e6b987..cd57dd98c5 100644
--- a/mobile/apps/photos/rust/src/ml/pet/detect.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs
@@ -27,21 +27,21 @@ const COCO_DOG: u8 = 16;
///
/// This mirrors `pet_pipeline/detection.py` `FaceDetector.detect()`.
pub fn run_pet_face_detection(
- runtime: &mut MlRuntime,
+ runtime: &MlRuntime,
decoded: &DecodedImage,
) -> MlResult<Vec<PetFaceDetection>> {
let (input, scaled_width, scaled_height, pad_left, pad_top) =
preprocess::preprocess_yolo(decoded)?;
- let pet_face_detection = runtime.pet_face_detection_session_mut()?;
+ let pet_face_detection = runtime.pet_face_detection_session()?;
let (output_shape, output_data) = onnx::run_f32(
pet_face_detection,
input,
[1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
)?;
- // 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
+ // Row format: [x, y, w, h, conf, lm_x1, lm_y1, lm_x2, lm_y2, lm_x3, lm_y3, cls0, cls1]
+ // row_len = 4 + 1 + 6 + 2 = 13 for 2-class model
// 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
@@ -109,9 +109,12 @@ 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
+ // For a 2-class model (row_len >= 13): row[11] = dog score,
+ // row[12] = cat score. Pick argmax.
+ // For a 1-class model (row_len == 12): row[11] is the single class
+ // score; class is always 0 (dog).
+ let class_id: u8 = if row_len >= 13 {
+ if row[12] > row[11] { 1 } else { 0 }
} else {
0
};
@@ -134,13 +137,13 @@ pub fn run_pet_face_detection(
///
/// This mirrors `pet_pipeline/detection.py` `BodyDetector.detect()`.
pub fn run_pet_body_detection(
- runtime: &mut MlRuntime,
+ runtime: &MlRuntime,
decoded: &DecodedImage,
) -> MlResult<Vec<PetBodyDetection>> {
let (input, scaled_width, scaled_height, pad_left, pad_top) =
preprocess::preprocess_yolo(decoded)?;
- let body_detection = runtime.pet_body_detection_session_mut()?;
+ let body_detection = runtime.pet_body_detection_session()?;
let (_output_shape, output_data) = onnx::run_f32(
body_detection,
input,
diff --git a/mobile/apps/photos/rust/src/ml/pet/embed.rs b/mobile/apps/photos/rust/src/ml/pet/embed.rs
index 7fd7f04338..3cdd94ec34 100644
--- a/mobile/apps/photos/rust/src/ml/pet/embed.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/embed.rs
@@ -25,7 +25,7 @@ const BODY_EMBED_CHANNELS: i64 = 3;
/// 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,
+ runtime: &MlRuntime,
aligned_faces: &[Vec<f32>],
face_results: &mut [PetFaceResult],
) -> MlResult<()> {
@@ -73,9 +73,9 @@ pub fn run_pet_face_embedding(
}
let session = if species == 0 {
- runtime.pet_face_embedding_dog_session_mut()?
+ runtime.pet_face_embedding_dog_session()?
} else {
- runtime.pet_face_embedding_cat_session_mut()?
+ runtime.pet_face_embedding_cat_session()?
};
let (shape, output) = onnx::run_f32(
@@ -119,38 +119,86 @@ pub fn run_pet_face_embedding(
///
/// Each body's own `coco_class` (16=dog, 15=cat) selects the embedding model,
/// so mixed-species images get the correct model per detection.
+/// Bodies are grouped by species and batched per model.
///
/// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_body()`.
pub fn run_pet_body_embedding(
- runtime: &mut MlRuntime,
+ runtime: &MlRuntime,
decoded: &DecodedImage,
body_results: &mut [PetBodyResult],
) -> 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)?;
+ if body_results.is_empty() {
+ return Ok(());
+ }
+ let per_body_len =
+ (BODY_EMBED_INPUT_SIZE * BODY_EMBED_INPUT_SIZE * BODY_EMBED_CHANNELS) as usize;
+
+ // Preprocess all crops and group by species.
+ let mut dog_indices = Vec::new();
+ let mut cat_indices = Vec::new();
+ let mut preprocessed: Vec<Vec<f32>> = Vec::with_capacity(body_results.len());
+ for (i, body_result) in body_results.iter().enumerate() {
+ 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)?;
+ preprocessed.push(input);
// COCO class 15 = cat, 16 = dog
- let session = if body_result.detection.coco_class == 15 {
- runtime.pet_body_embedding_cat_session_mut()?
+ if body_result.detection.coco_class == 15 {
+ cat_indices.push(i);
+ } else {
+ dog_indices.push(i);
+ }
+ }
+
+ // Process each species batch.
+ for (is_cat, indices) in [(false, &dog_indices), (true, &cat_indices)] {
+ if indices.is_empty() {
+ continue;
+ }
+
+ let mut input = Vec::with_capacity(per_body_len * indices.len());
+ for &idx in indices {
+ input.extend_from_slice(&preprocessed[idx]);
+ }
+
+ let session = if is_cat {
+ runtime.pet_body_embedding_cat_session()?
} else {
- runtime.pet_body_embedding_dog_session_mut()?
+ runtime.pet_body_embedding_dog_session()?
};
- let (_shape, output) = onnx::run_f32(
+ let (shape, output) = onnx::run_f32(
session,
input,
[
- 1,
+ indices.len() as i64,
BODY_EMBED_CHANNELS,
BODY_EMBED_INPUT_SIZE,
BODY_EMBED_INPUT_SIZE,
],
)?;
- let mut embedding = output;
- normalize_embedding(&mut embedding);
- body_result.body_embedding = embedding;
+ if shape.is_empty() {
+ return Err(MlError::Postprocess(
+ "pet body embedding output shape is empty".to_string(),
+ ));
+ }
+ let batch = shape[0] as usize;
+ if batch != indices.len() {
+ return Err(MlError::Postprocess(format!(
+ "pet body 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);
+ body_results[orig_idx].body_embedding = embedding;
+ }
}
Ok(())
diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rs
index e41b592351..31d9ebab4c 100644
--- a/mobile/apps/photos/rust/src/ml/runtime.rs
+++ b/mobile/apps/photos/rust/src/ml/runtime.rs
@@ -1,6 +1,6 @@
-use std::sync::Mutex;
+use std::sync::RwLock;
-use once_cell::sync::Lazy;
+use once_cell::sync::{Lazy, OnceCell};
use ort::Session;
use crate::ml::{
@@ -69,11 +69,16 @@ pub struct MlRuntimeConfig {
pub provider_policy: ExecutionProviderPolicy,
}
+/// A lazily-initialized ONNX session that is thread-safe for concurrent reads.
+///
+/// `OnceLock` ensures the session is loaded exactly once (on first use) and
+/// then shared via `&Session` for concurrent inference β€” `ort::Session::run()`
+/// takes `&self` and is `Send + Sync`.
#[derive(Debug)]
struct LazySession {
path: String,
policy: ExecutionProviderPolicy,
- session: Option<Session>,
+ session: OnceCell<Session>,
}
impl LazySession {
@@ -81,22 +86,23 @@ impl LazySession {
Self {
path,
policy,
- session: None,
+ session: OnceCell::new(),
}
}
- fn get_mut(&mut self, error_msg: &str) -> MlResult<&mut Session> {
+ fn get(&self, error_msg: &str) -> MlResult<&Session> {
if self.path.trim().is_empty() {
return Err(MlError::InvalidRequest(error_msg.to_string()));
}
- if self.session.is_none() {
- let model_name = self.path.rsplit('/').next().unwrap_or(&self.path);
- rt_log(&format!("loading {model_name}"));
- let t = std::time::Instant::now();
- self.session = Some(onnx::build_session(&self.path, &self.policy)?);
- rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));
- }
- Ok(self.session.as_mut().unwrap())
+ self.session
+ .get_or_try_init(|| {
+ let model_name = self.path.rsplit('/').next().unwrap_or(&self.path);
+ rt_log(&format!("loading {model_name}"));
+ let t = std::time::Instant::now();
+ let s = onnx::build_session(&self.path, &self.policy)?;
+ rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));
+ Ok(s)
+ })
}
}
@@ -120,7 +126,7 @@ struct RuntimeState {
runtime: MlRuntime,
}
-static GLOBAL_RUNTIME: Lazy<Mutex<Option<RuntimeState>>> = Lazy::new(|| Mutex::new(None));
+static GLOBAL_RUNTIME: Lazy<RwLock<Option<RuntimeState>>> = Lazy::new(|| RwLock::new(None));
fn create_runtime(config: &MlRuntimeConfig) -> MlRuntime {
let p = &config.provider_policy;
@@ -147,68 +153,74 @@ fn create_runtime(config: &MlRuntimeConfig) -> MlRuntime {
}
impl MlRuntime {
- pub fn face_detection_session_mut(&mut self) -> MlResult<&mut Session> {
- self.face_detection.get_mut(
+ pub fn face_detection_session(&self) -> MlResult<&Session> {
+ self.face_detection.get(
"missing model path: faceDetectionModelPath is required when runFaces is true",
)
}
- pub fn face_embedding_session_mut(&mut self) -> MlResult<&mut Session> {
- self.face_embedding.get_mut(
+ pub fn face_embedding_session(&self) -> MlResult<&Session> {
+ self.face_embedding.get(
"missing model path: faceEmbeddingModelPath is required when runFaces is true",
)
}
- pub fn clip_image_session_mut(&mut self) -> MlResult<&mut Session> {
- self.clip_image.get_mut(
+ pub fn clip_image_session(&self) -> MlResult<&Session> {
+ self.clip_image.get(
"missing model path: clipImageModelPath is required when runClip is true",
)
}
- pub fn clip_text_session_mut(&mut self) -> MlResult<&mut Session> {
- self.clip_text.get_mut(
+ pub fn clip_text_session(&self) -> MlResult<&Session> {
+ self.clip_text.get(
"missing model path: clipTextModelPath is required when running clip text",
)
}
- pub fn pet_face_detection_session_mut(&mut self) -> MlResult<&mut Session> {
- self.pet_face_detection.get_mut(
+ pub fn pet_face_detection_session(&self) -> MlResult<&Session> {
+ self.pet_face_detection.get(
"missing model path: petFaceDetectionModelPath is required when runPets is true",
)
}
- pub fn pet_face_embedding_dog_session_mut(&mut self) -> MlResult<&mut Session> {
+ pub fn pet_face_embedding_dog_session(&self) -> MlResult<&Session> {
self.pet_face_embedding_dog
- .get_mut("missing model path: petFaceEmbeddingDogModelPath is required")
+ .get("missing model path: petFaceEmbeddingDogModelPath is required")
}
- pub fn pet_face_embedding_cat_session_mut(&mut self) -> MlResult<&mut Session> {
+ pub fn pet_face_embedding_cat_session(&self) -> MlResult<&Session> {
self.pet_face_embedding_cat
- .get_mut("missing model path: petFaceEmbeddingCatModelPath is required")
+ .get("missing model path: petFaceEmbeddingCatModelPath is required")
}
- pub fn pet_body_detection_session_mut(&mut self) -> MlResult<&mut Session> {
- self.pet_body_detection.get_mut(
+ pub fn pet_body_detection_session(&self) -> MlResult<&Session> {
+ self.pet_body_detection.get(
"missing model path: petBodyDetectionModelPath is required when runPets is true",
)
}
- pub fn pet_body_embedding_dog_session_mut(&mut self) -> MlResult<&mut Session> {
+ pub fn pet_body_embedding_dog_session(&self) -> MlResult<&Session> {
self.pet_body_embedding_dog
- .get_mut("missing model path: petBodyEmbeddingDogModelPath is required")
+ .get("missing model path: petBodyEmbeddingDogModelPath is required")
}
- pub fn pet_body_embedding_cat_session_mut(&mut self) -> MlResult<&mut Session> {
+ pub fn pet_body_embedding_cat_session(&self) -> MlResult<&Session> {
self.pet_body_embedding_cat
- .get_mut("missing model path: petBodyEmbeddingCatModelPath is required")
+ .get("missing model path: petBodyEmbeddingCatModelPath is required")
+ }
+}
+
+fn read_runtime() -> std::sync::RwLockReadGuard<'static, Option<RuntimeState>> {
+ match GLOBAL_RUNTIME.read() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
}
}
-fn lock_runtime() -> std::sync::MutexGuard<'static, Option<RuntimeState>> {
- match GLOBAL_RUNTIME.lock() {
+fn write_runtime() -> std::sync::RwLockWriteGuard<'static, Option<RuntimeState>> {
+ match GLOBAL_RUNTIME.write() {
Ok(guard) => guard,
Err(poisoned) => {
- // Recover from a previous panic by clearing runtime state.
let mut guard = poisoned.into_inner();
*guard = None;
guard
@@ -218,7 +230,7 @@ fn lock_runtime() -> std::sync::MutexGuard<'static, Option<RuntimeState>> {
pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
let should_rebuild = {
- let guard = lock_runtime();
+ let guard = read_runtime();
match guard.as_ref() {
Some(existing) => existing.config != *config,
None => true,
@@ -227,7 +239,7 @@ pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
if should_rebuild {
let runtime = create_runtime(config);
- let mut guard = lock_runtime();
+ let mut guard = write_runtime();
*guard = Some(RuntimeState {
config: config.clone(),
runtime,
@@ -236,18 +248,23 @@ pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
Ok(())
}
-pub fn with_runtime_mut<F, R>(config: &MlRuntimeConfig, mut func: F) -> MlResult<R>
+/// Run a function with a shared (read) reference to the runtime.
+///
+/// Multiple callers can hold the read lock concurrently, so CLIP text
+/// queries no longer block on image indexing and vice versa. The write
+/// lock is only acquired during `ensure_runtime` to swap the config.
+pub fn with_runtime<F, R>(config: &MlRuntimeConfig, func: F) -> MlResult<R>
where
- F: FnMut(&mut MlRuntime) -> MlResult<R>,
+ F: Fn(&MlRuntime) -> MlResult<R>,
{
ensure_runtime(config)?;
let first_result = {
- let mut guard = lock_runtime();
+ let guard = read_runtime();
let state = guard
- .as_mut()
+ .as_ref()
.ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;
- func(&mut state.runtime)
+ func(&state.runtime)
};
match first_result {
@@ -261,18 +278,16 @@ where
rt_log(&format!("execution provider failed, retrying with CPU-only runtime: {first_error}"));
ensure_runtime(&fallback_config)?;
let retry_result = {
- let mut guard = lock_runtime();
+ let guard = read_runtime();
let state = guard
- .as_mut()
+ .as_ref()
.ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;
- func(&mut state.runtime)
+ func(&state.runtime)
};
if retry_result.is_ok() {
- let mut guard = lock_runtime();
+ let mut guard = write_runtime();
if let Some(state) = guard.as_mut() {
- // Keep the recovered runtime hot for this requested config to avoid
- // repeatedly attempting the failing EP combination on every image.
state.config = config.clone();
}
}
@@ -314,7 +329,7 @@ fn is_execution_provider_failure(error: &MlError) -> bool {
}
pub fn release_runtime() -> MlResult<()> {
- let mut guard = lock_runtime();
+ let mut guard = write_runtime();
*guard = None;
Ok(())
}