π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Enable CoreML + XNNPack
laurenspriemf78bc778c44f
diff --git a/infra/ml/test/ml_indexing/assets.json b/infra/ml/test/ml_indexing/assets.jsonindex 191b2b1318..276c14f876 100644--- a/infra/ml/test/ml_indexing/assets.json+++ b/infra/ml/test/ml_indexing/assets.json@@ -37,14 +37,14 @@},"models": {"face_detection": {- "file_name": "yolov5s_face_640_640_dynamic.onnx",- "url": "https://models.ente.io/yolov5s_face_640_640_dynamic.onnx",- "sha256": "71a008707283b03db4881449a24f4da197f9dbd9ddaca5c91fcdb363fbf7e06f"+ "file_name": "yolov5s_face_640_640_static_b1.onnx",+ "url": "https://entedevassets.priem.dev/yolov5s_face_640_640_static_b1.onnx",+ "sha256": "e047647409403d52696035ecd445792173e50d7fbdcccac97b958a585db9aa3d"},"face_embedding": {- "file_name": "mobilefacenet_opset15.onnx",- "url": "https://models.ente.io/mobilefacenet_opset15.onnx",- "sha256": "472a0f7e24d0b070cbbdc031b085bc2a06c70655b3bdefb87dbd69bc98662f45"+ "file_name": "mobilefacenet_prelu_static_b1.onnx",+ "url": "https://entedevassets.priem.dev/mobilefacenet_prelu_static_b1.onnx",+ "sha256": "f525daf3089ec41c938a66c47cd8278c2a443f31ee2bd2dac987db531c58ccfd"},"clip_image": {"file_name": "mobileclip_s2_image.onnx",diff --git a/infra/ml/test/run_ml_parity_tests.sh b/infra/ml/test/run_ml_parity_tests.shindex 258f1f9309..aded93c274 100755--- a/infra/ml/test/run_ml_parity_tests.sh+++ b/infra/ml/test/run_ml_parity_tests.sh@@ -184,15 +184,16 @@ prepare_local_model_mirror_cache() {local downloaded=0local reused=0local failed=0- local -a model_files=(- "yolov5s_face_640_640_dynamic.onnx"- "mobilefacenet_opset15.onnx"- "mobileclip_s2_image.onnx"+ local -a model_urls=(+ "https://entedevassets.priem.dev/yolov5s_face_640_640_static_b1.onnx"+ "https://entedevassets.priem.dev/mobilefacenet_prelu_static_b1.onnx"+ "https://models.ente.com/mobileclip_s2_image.onnx")mkdir -p "$model_dir"- for model_file in "${model_files[@]}"; do+ for model_url in "${model_urls[@]}"; do+ local model_file="${model_url##*/}"local target_path="$model_dir/$model_file"if [[ -f "$target_path" ]]; thenreused=$((reused + 1))@@ -200,7 +201,7 @@ prepare_local_model_mirror_cache() {filocal tmp_path="$target_path.tmp"- if curl -fsSL --retry 3 --retry-delay 1 "https://models.ente.io/$model_file" -o "$tmp_path"; then+ if curl -fsSL --retry 3 --retry-delay 1 "$model_url" -o "$tmp_path"; thenmv "$tmp_path" "$target_path"downloaded=$((downloaded + 1))elsediff --git a/mobile/apps/photos/integration_test/ml_parity_shared.dart b/mobile/apps/photos/integration_test/ml_parity_shared.dartindex 768b6d4dcc..cc490b0e9f 100644--- a/mobile/apps/photos/integration_test/ml_parity_shared.dart+++ b/mobile/apps/photos/integration_test/ml_parity_shared.dart@@ -27,12 +27,6 @@ const _localMirrorBaseUrl = String.fromEnvironment(const _localModelMirrorRelativeDir = ".cache/local_model_mirror";const _parityReportDataKey = "ml_parity_results_json";-const _modelBaseUrl = "https://models.ente.com/";-const _modelFiles = <String>[- "yolov5s_face_640_640_dynamic.onnx",- "mobilefacenet_opset15.onnx",- "mobileclip_s2_image.onnx",-];class _ManifestItem {final String fileID;@@ -78,9 +72,8 @@ void runMLParityIntegrationTest({required String expectedPlatform}) {manifestItems: manifestItems,fixtureRoot: fixtureRoot,);- await _stageModelsFromLocalMirror(appSupportDir);-final modelSpecs = _modelSpecs();+ await _stageModelsFromLocalMirror(appSupportDir, modelSpecs);final loadedModels = await _downloadModels(modelSpecs);const runtime = "rust-ml";@@ -271,7 +264,10 @@ Future<void> _stageFixturesFromLocalMirror({}}-Future<void> _stageModelsFromLocalMirror(Directory appSupportDir) async {+Future<void> _stageModelsFromLocalMirror(+ Directory appSupportDir,+ List<_ModelSpec> modelSpecs,+) async {if (_localMirrorBaseUrl.isEmpty) {return;}@@ -279,8 +275,9 @@ Future<void> _stageModelsFromLocalMirror(Directory appSupportDir) async {final assetsDir = Directory("${appSupportDir.path}/assets");await assetsDir.create(recursive: true);- for (final modelFile in _modelFiles) {- final canonicalURL = "$_modelBaseUrl$modelFile";+ for (final modelSpec in modelSpecs) {+ final canonicalURL = modelSpec.model.modelRemotePath;+ final modelFile = Uri.parse(canonicalURL).pathSegments.last;final targetPath ="${assetsDir.path}/${_remoteAssetPathToLocalFileName(canonicalURL)}";final targetFile = File(targetPath);@@ -445,10 +442,6 @@ Future<MLResult> _analyzeImage({"faceDetectionModelPath": faceDetectionModelPath,"faceEmbeddingModelPath": faceEmbeddingModelPath,"clipImageModelPath": clipImageModelPath,- "preferCoreml": Platform.isIOS,- "preferNnapi": Platform.isAndroid,- "preferXnnpack": Platform.isAndroid,- "allowCpuFallback": true,});final resultJSONString =diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dartindex 267f15726f..c0c59ae53e 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart@@ -1,5 +1,4 @@import 'dart:async';-import "dart:io" show Platform;import "dart:typed_data" show Float32List;import "package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart"@@ -87,10 +86,6 @@ class MLComputer extends SuperIsolate {"text": query,"clipTextModelPath": modelPath,"clipTextVocabPath": vocabPath,- "preferCoreml": Platform.isIOS,- "preferNnapi": Platform.isAndroid,- "preferXnnpack": Platform.isAndroid,- "allowCpuFallback": true,});if (isolateResult is RustCorruptModelCacheDeletedException) {_clipTextModelPath = null;diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dartindex 3bc9e695ef..6ac3913f46 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart@@ -1,5 +1,3 @@-import "dart:io" show Platform;-import "package:flutter/foundation.dart" show debugPrint, kDebugMode;import "package:logging/logging.dart";import "package:photos/service_locator.dart" show flagService, localSettings;@@ -187,10 +185,6 @@ class MLIndexingIsolate extends SuperIsolate {"petBodyDetectionModelPath": petBodyDetectionPath,"petBodyEmbeddingDogModelPath": petBodyEmbeddingDogPath,"petBodyEmbeddingCatModelPath": petBodyEmbeddingCatPath,- "preferCoreml": Platform.isIOS,- "preferNnapi": Platform.isAndroid,- "preferXnnpack": Platform.isAndroid,- "allowCpuFallback": true,};}diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart b/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dartindex a520178c46..36bbb44e4b 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart@@ -1,30 +1,32 @@import "package:photos/services/machine_learning/ml_model.dart";+const _optimizedModelBucketEndpoint = "https://entedevassets.priem.dev/";+class FaceDetectionModel extends MlModelAsset {- static const remoteFileName = "yolov5s_face_640_640_dynamic.onnx";+ static const remoteFileName = "yolov5s_face_640_640_static_b1.onnx";static const _sha256 =- "71a008707283b03db4881449a24f4da197f9dbd9ddaca5c91fcdb363fbf7e06f";+ "e047647409403d52696035ecd445792173e50d7fbdcccac97b958a585db9aa3d";FaceDetectionModel._();static final instance = FaceDetectionModel._();@override- String get modelRemotePath => kModelBucketEndpoint + remoteFileName;+ String get modelRemotePath => _optimizedModelBucketEndpoint + remoteFileName;@overrideString get modelSha256 => _sha256;}class FaceEmbeddingModel extends MlModelAsset {- static const remoteFileName = "mobilefacenet_opset15.onnx";+ static const remoteFileName = "mobilefacenet_prelu_static_b1.onnx";static const _sha256 =- "472a0f7e24d0b070cbbdc031b085bc2a06c70655b3bdefb87dbd69bc98662f45";+ "f525daf3089ec41c938a66c47cd8278c2a443f31ee2bd2dac987db531c58ccfd";FaceEmbeddingModel._();static final instance = FaceEmbeddingModel._();@override- String get modelRemotePath => kModelBucketEndpoint + remoteFileName;+ String get modelRemotePath => _optimizedModelBucketEndpoint + remoteFileName;@overrideString get modelSha256 => _sha256;diff --git a/mobile/apps/photos/lib/services/remote_assets_service.dart b/mobile/apps/photos/lib/services/remote_assets_service.dartindex e4feb37793..1775d04674 100644--- a/mobile/apps/photos/lib/services/remote_assets_service.dart+++ b/mobile/apps/photos/lib/services/remote_assets_service.dart@@ -193,6 +193,10 @@ class RemoteAssetsService {"https://models.ente.io/mobileclip_s2_text_int32.onnx","https://models.ente.io/yolov5s_face_opset18_rgba_opt.onnx","https://models.ente.io/yolov5s_face_opset18_rgba_opt_nosplits.onnx",+ "https://models.ente.io/yolov5s_face_640_640_dynamic.onnx",+ "https://models.ente.io/mobilefacenet_opset15.onnx",+ "https://models.ente.com/yolov5s_face_640_640_dynamic.onnx",+ "https://models.ente.com/mobilefacenet_opset15.onnx",];await cleanupSelectedModels(oldModelNames);diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dartindex 123b17d56e..09c9733c6e 100644--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart@@ -189,12 +189,6 @@ Future<dynamic> isolateFunction(text: text,modelPath: clipTextModelPath,vocabPath: clipTextVocabPath,- providerPolicy: rust_ml.RustExecutionProviderPolicy(- preferCoreml: args["preferCoreml"] as bool? ?? true,- preferNnapi: args["preferNnapi"] as bool? ?? true,- preferXnnpack: args["preferXnnpack"] as bool? ?? false,- allowCpuFallback: args["allowCpuFallback"] as bool? ?? true,- ),),);} on rust_ml.RustMlError_CorruptModel catch (e) {@@ -401,13 +395,7 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {petBodyEmbeddingCat:(args["petBodyEmbeddingCatModelPath"] as String?) ?? "",);- final providerPolicy = rust_ml.RustExecutionProviderPolicy(- preferCoreml: args["preferCoreml"] as bool? ?? true,- preferNnapi: args["preferNnapi"] as bool? ?? true,- preferXnnpack: args["preferXnnpack"] as bool? ?? false,- allowCpuFallback: args["allowCpuFallback"] as bool? ?? true,- );- final runtimeConfigKey = _runtimeConfigCacheKey(modelPaths, providerPolicy);+ final runtimeConfigKey = _runtimeConfigCacheKey(modelPaths);final currentConfigKey =_isolateCache[_rustMlRuntimeConfigCacheKey] as String?;if (currentConfigKey == runtimeConfigKey) {@@ -431,10 +419,7 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {}await rust_ml.initMlRuntime(- config: rust_ml.RustMlRuntimeConfig(- modelPaths: modelPaths,- providerPolicy: providerPolicy,- ),+ config: rust_ml.RustMlRuntimeConfig(modelPaths: modelPaths),);_isolateCache[_rustMlRuntimeConfigCacheKey] = runtimeConfigKey;}@@ -452,10 +437,7 @@ Future<void> _releaseRustRuntime() async {_isolateCache.remove(_rustMlRuntimeConfigCacheKey);}-String _runtimeConfigCacheKey(- rust_ml.RustModelPaths modelPaths,- rust_ml.RustExecutionProviderPolicy providerPolicy,-) {+String _runtimeConfigCacheKey(rust_ml.RustModelPaths modelPaths) {return [modelPaths.faceDetection,modelPaths.faceEmbedding,@@ -467,9 +449,5 @@ String _runtimeConfigCacheKey(modelPaths.petBodyDetection,modelPaths.petBodyEmbeddingDog,modelPaths.petBodyEmbeddingCat,- providerPolicy.preferCoreml,- providerPolicy.preferNnapi,- providerPolicy.preferXnnpack,- providerPolicy.allowCpuFallback,].join("|");}diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dartindex 179eb2d0de..6ee53341f3 100644--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@ -781,11 +781,6 @@ Future<MLResult> analyzeImageRust(Map args) async {args["petBodyEmbeddingDogModelPath"] as String?;final String? petBodyEmbeddingCatModelPath =args["petBodyEmbeddingCatModelPath"] as String?;- final bool preferCoreml = args["preferCoreml"] as bool? ?? true;- final bool preferNnapi = args["preferNnapi"] as bool? ?? true;- final bool preferXnnpack = args["preferXnnpack"] as bool? ?? false;- final bool allowCpuFallback = args["allowCpuFallback"] as bool? ?? true;-bool isMissingModelPath(String? path) =>path == null || path.trim().isEmpty;final missingModelPaths = <String>[];@@ -838,13 +833,6 @@ Future<MLResult> analyzeImageRust(Map args) async {petBodyEmbeddingDog: petBodyEmbeddingDogModelPath ?? "",petBodyEmbeddingCat: petBodyEmbeddingCatModelPath ?? "",);- final providerPolicy = rust_ml.RustExecutionProviderPolicy(- preferCoreml: preferCoreml,- preferNnapi: preferNnapi,- preferXnnpack: preferXnnpack,- allowCpuFallback: allowCpuFallback,- );-Future<rust_ml.AnalyzeImageResult> runRustAnalyzeForPath(String analyzePath,) {@@ -856,7 +844,6 @@ Future<MLResult> analyzeImageRust(Map args) async {runClip: runClip,runPets: runPets,modelPaths: modelPaths,- providerPolicy: providerPolicy,),);}diff --git a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs b/rust/bindings/frb/photos/src/api/ml_indexing_api.rsindex f44f9d9fcc..5cf76a4592 100644--- a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs+++ b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs@@ -1,29 +1,10 @@use ente_photos::ml::{error::MlError as SharedMlError,indexing as shared_indexing,- runtime::{ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},+ runtime::{MlRuntimeConfig, ModelPaths},types as shared_types,};-#[derive(Clone, Debug)]-pub struct RustExecutionProviderPolicy {- pub prefer_coreml: bool,- pub prefer_nnapi: bool,- pub prefer_xnnpack: bool,- pub allow_cpu_fallback: bool,-}--impl Default for RustExecutionProviderPolicy {- fn default() -> Self {- Self {- prefer_coreml: true,- prefer_nnapi: true,- prefer_xnnpack: false,- allow_cpu_fallback: true,- }- }-}-#[derive(Clone, Debug)]pub struct RustModelPaths {pub face_detection: String,@@ -41,7 +22,6 @@ pub struct RustModelPaths {#[derive(Clone, Debug)]pub struct RustMlRuntimeConfig {pub model_paths: RustModelPaths,- pub provider_policy: RustExecutionProviderPolicy,}#[derive(Clone, Debug)]@@ -52,7 +32,6 @@ pub struct AnalyzeImageRequest {pub run_clip: bool,pub run_pets: bool,pub model_paths: RustModelPaths,- pub provider_policy: RustExecutionProviderPolicy,}#[derive(Clone, Debug)]@@ -151,7 +130,6 @@ pub struct RunClipTextRequest {pub text: String,pub model_path: String,pub vocab_path: String,- pub provider_policy: RustExecutionProviderPolicy,}#[derive(Clone, Debug)]@@ -176,7 +154,6 @@ pub fn analyze_image_rust(req: AnalyzeImageRequest) -> Result<AnalyzeImageResultrun_pets: req.run_pets,runtime_config: MlRuntimeConfig {model_paths: to_model_paths(&req.model_paths),- provider_policy: to_provider_policy(&req.provider_policy),},};@@ -190,7 +167,6 @@ pub fn run_clip_text_rust(req: RunClipTextRequest) -> Result<RunClipTextResult,text: req.text,model_path: req.model_path,vocab_path: req.vocab_path,- provider_policy: to_provider_policy(&req.provider_policy),};shared_indexing::run_clip_text(shared_req)@@ -211,7 +187,6 @@ pub fn tokenize_clip_text_rust(text: String, vocab_path: String) -> Result<Vec<ifn to_runtime_config(config: &RustMlRuntimeConfig) -> MlRuntimeConfig {MlRuntimeConfig {model_paths: to_model_paths(&config.model_paths),- provider_policy: to_provider_policy(&config.provider_policy),}}@@ -230,15 +205,6 @@ fn to_model_paths(paths: &RustModelPaths) -> ModelPaths {}}-fn to_provider_policy(policy: &RustExecutionProviderPolicy) -> ExecutionProviderPolicy {- ExecutionProviderPolicy {- prefer_coreml: policy.prefer_coreml,- prefer_nnapi: policy.prefer_nnapi,- prefer_xnnpack: policy.prefer_xnnpack,- allow_cpu_fallback: policy.allow_cpu_fallback,- }-}-impl From<SharedMlError> for RustMlError {fn from(value: SharedMlError) -> Self {match value {diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.tomlindex 2245a483ea..7a24353e6c 100644--- a/rust/crates/photos/Cargo.toml+++ b/rust/crates/photos/Cargo.toml@@ -30,30 +30,34 @@ ort = { workspace = true, features = ["std","ndarray","half",- # Temporarily disabled to avoid iOS duplicate ObjC class collisions- # when both Dart ONNXRuntime and Rust ONNXRuntime are linked.- # Re-enable once we move to a single shared ORT runtime.- # "coreml",+ # CoreML is the preferred iOS execution provider for Rust ML sessions.+ "coreml","api-27",# Link the revision-pinned crate's verified 1.27 archive directly into the# Rust ML library."download-binaries","tls-native",- "xnnpack",] }-[target.'cfg(not(target_os = "ios"))'.dependencies]+[target.'cfg(target_os = "android")'.dependencies]ort = { workspace = true, features = ["ndarray","half","api-27","load-dynamic","copy-dylibs",- "coreml",- "nnapi","xnnpack",] }+[target.'cfg(not(any(target_os = "ios", target_os = "android")))'.dependencies]+ort = { workspace = true, features = [+ "ndarray",+ "half",+ "api-27",+ "load-dynamic",+ "copy-dylibs",+] }+[dev-dependencies]anyhow = "1"flate2 = "1.1"diff --git a/rust/crates/photos/src/ml/face/embed.rs b/rust/crates/photos/src/ml/face/embed.rsindex 0785c45423..6c4da66f72 100644--- a/rust/crates/photos/src/ml/face/embed.rs+++ b/rust/crates/photos/src/ml/face/embed.rs@@ -25,54 +25,29 @@ pub fn run_face_embedding()));}- let per_face_len = (FACE_INPUT_WIDTH * FACE_INPUT_HEIGHT * FACE_INPUT_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 {+ let expected_input_len = (FACE_INPUT_WIDTH * FACE_INPUT_HEIGHT * FACE_INPUT_CHANNELS) as usize;+ let mut face_embedding = runtime.face_embedding_session()?;+ for (aligned, face_result) in aligned_faces.iter().zip(face_results.iter_mut()) {+ if aligned.len() != expected_input_len {return Err(MlError::Preprocess(format!("aligned face tensor length {} does not match expected {}",aligned.len(),- per_face_len+ expected_input_len)));}- input.extend_from_slice(aligned);- }-- let mut face_embedding = runtime.face_embedding_session()?;- let (shape, output) = onnx::run_f32(- &mut face_embedding,- input,- [- aligned_faces.len() as i64,- FACE_INPUT_HEIGHT,- FACE_INPUT_WIDTH,- FACE_INPUT_CHANNELS,- ],- )?;- if shape.is_empty() {- return Err(MlError::Postprocess(- "face embedding output shape is empty".to_string(),- ));- }- let batch = shape[0] as usize;- if batch != face_results.len() {- return Err(MlError::Postprocess(format!(- "face embedding batch mismatch: output={batch}, expected={}",- face_results.len()- )));- }- let embedding_size = output.len() / batch;- if embedding_size == 0 || output.len() != batch * embedding_size {- return Err(MlError::Postprocess(format!(- "invalid face embedding tensor shape {:?} for data length {}",- shape,- output.len()- )));- }- for (face_index, face_result) in face_results.iter_mut().enumerate() {- let start = face_index * embedding_size;- let mut embedding = output[start..(start + embedding_size)].to_vec();+ let (shape, mut embedding) = onnx::run_f32(+ &mut face_embedding,+ aligned.clone(),+ [1, FACE_INPUT_HEIGHT, FACE_INPUT_WIDTH, FACE_INPUT_CHANNELS],+ )?;+ if shape.first() != Some(&1) || embedding.is_empty() {+ return Err(MlError::Postprocess(format!(+ "invalid single-face embedding tensor shape {:?} for data length {}",+ shape,+ embedding.len()+ )));+ }normalize_embedding(&mut embedding);face_result.embedding = embedding;}diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rsindex 7659a55060..082fb74665 100644--- a/rust/crates/photos/src/ml/indexing.rs+++ b/rust/crates/photos/src/ml/indexing.rs@@ -10,7 +10,7 @@ use crate::ml::{detect::{run_pet_body_detection, run_pet_face_detection},embed::{run_pet_body_embedding, run_pet_face_embedding},},- runtime::{self, ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},+ runtime::{self, MlRuntimeConfig, ModelPaths},types::{self, ClipResult, Dimensions, FaceResult, PetBodyResult, PetFaceResult},};use ente_image::decode::decode_image_from_path;@@ -40,7 +40,6 @@ pub struct RunClipTextRequest {pub text: String,pub model_path: String,pub vocab_path: String,- pub provider_policy: ExecutionProviderPolicy,}#[derive(Clone, Debug)]@@ -143,7 +142,6 @@ pub fn run_clip_text(req: RunClipTextRequest) -> MlResult<RunClipTextResult> {text,model_path,vocab_path,- provider_policy,} = req;if model_path.trim().is_empty() {@@ -170,7 +168,6 @@ pub fn run_clip_text(req: RunClipTextRequest) -> MlResult<RunClipTextResult> {pet_body_embedding_dog: String::new(),pet_body_embedding_cat: String::new(),},- provider_policy,};runtime::with_runtime(&runtime_config, |runtime| {diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rsindex 848bc1c625..2855778009 100644--- a/rust/crates/photos/src/ml/onnx.rs+++ b/rust/crates/photos/src/ml/onnx.rs@@ -1,61 +1,43 @@use ort::{- ep::{CPU, ExecutionProviderDispatch, XNNPACK},+ ep::{CPU, ExecutionProviderDispatch},session::{Session, builder::GraphOptimizationLevel},value::{Tensor, TensorElementType, ValueType},};-// Temporarily disabled on Rust side to avoid iOS duplicate ObjC class collisions-// (`CoreMLExecution`) while Dart ONNXRuntime is still linked in production.-// Re-enable once iOS uses a single shared ORT runtime.-// #[cfg(target_vendor = "apple")]-// use ort::ep::CoreML;#[cfg(target_os = "android")]-use ort::ep::NNAPI;--use crate::ml::{- error::{MlError, MlResult},- runtime::ExecutionProviderPolicy,+use ort::ep::XNNPACK;+#[cfg(target_os = "ios")]+use ort::ep::{+ CoreML,+ coreml::{ComputeUnits, ModelFormat, SpecializationStrategy},};+#[cfg(target_os = "android")]+use std::num::NonZeroUsize;-pub fn build_session(model_path: &str, policy: &ExecutionProviderPolicy) -> MlResult<Session> {- let primary_providers = providers_for_policy(policy, true);- let mut attempts = vec![primary_providers];+use crate::ml::error::{MlError, MlResult};- if policy.allow_cpu_fallback && policy.prefer_xnnpack {- let providers_without_xnnpack = providers_for_policy(policy, false);- attempts.push(providers_without_xnnpack);- }+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum ExecutionMode {+ PlatformDefault,+ CpuOnly,+}- if policy.allow_cpu_fallback {- let cpu_only_policy = ExecutionProviderPolicy {- prefer_coreml: false,- prefer_nnapi: false,- prefer_xnnpack: false,- allow_cpu_fallback: true,- };- let cpu_only_providers = providers_for_policy(&cpu_only_policy, false);- attempts.push(cpu_only_providers);+pub(crate) fn build_session(model_path: &str, mode: ExecutionMode) -> MlResult<Session> {+ let primary = providers_for_mode(mode);+ let has_preferred_provider = primary.has_preferred_provider;+ let mut attempts = vec![primary];+ if has_preferred_provider {+ attempts.push(ProviderAttempt::cpu_only());}let mut errors = Vec::new();- for providers in attempts {- if providers.is_empty() {- continue;- }-- match build_session_with_providers(model_path, providers) {+ for attempt in attempts {+ match build_session_with_providers(model_path, attempt) {Ok(session) => return Ok(session),Err(error) => errors.push(format!("{error}")),}}- if errors.is_empty() {- return Err(MlError::InvalidRequest(- "no supported execution provider selected for this platform while CPU fallback is disabled"- .to_string(),- ));- }-if has_protobuf_parse_failure(&errors) {return Err(MlError::CorruptModel(model_path.to_string()));}@@ -74,44 +56,80 @@ fn has_protobuf_parse_failure(errors: &[String]) -> bool {})}-fn providers_for_policy(- policy: &ExecutionProviderPolicy,- include_xnnpack: bool,-) -> Vec<ExecutionProviderDispatch> {- let mut providers: Vec<ExecutionProviderDispatch> = Vec::new();+struct ProviderAttempt {+ providers: Vec<ExecutionProviderDispatch>,+ has_preferred_provider: bool,+ uses_xnnpack: bool,+}++impl ProviderAttempt {+ fn cpu_only() -> Self {+ Self {+ providers: vec![CPU::default().with_arena_allocator(true).build()],+ has_preferred_provider: false,+ uses_xnnpack: false,+ }+ }+}- // Temporarily disabled on Rust side. Keep this block for easy re-enable.- // #[cfg(target_vendor = "apple")]- // if policy.prefer_coreml {- // providers.push(CoreML::default().build());- // }+fn providers_for_mode(_mode: ExecutionMode) -> ProviderAttempt {+ let mut providers: Vec<ExecutionProviderDispatch> = Vec::new();+ #[cfg(any(target_os = "ios", target_os = "android"))]+ let mut has_preferred_provider = false;+ #[cfg(not(any(target_os = "ios", target_os = "android")))]+ let has_preferred_provider = false;+ #[cfg(not(target_os = "android"))]+ let uses_xnnpack = false;+ #[cfg(target_os = "android")]+ let mut uses_xnnpack = false;++ #[cfg(target_os = "ios")]+ if _mode == ExecutionMode::PlatformDefault {+ providers.push(+ CoreML::default()+ .with_model_format(ModelFormat::MLProgram)+ .with_compute_units(ComputeUnits::All)+ .with_specialization_strategy(SpecializationStrategy::Default)+ .build()+ .error_on_failure(),+ );+ has_preferred_provider = true;+ }#[cfg(target_os = "android")]- if policy.prefer_nnapi {- // Prefer NNAPI accelerators and let ORT handle CPU fallback via the added CPU EP.- providers.push(NNAPI::default().with_disable_cpu(true).build());+ if _mode == ExecutionMode::PlatformDefault {+ providers.push(xnnpack_provider());+ has_preferred_provider = true;+ uses_xnnpack = true;}- if policy.allow_cpu_fallback {- if include_xnnpack && policy.prefer_xnnpack {- providers.push(XNNPACK::default().build());- }- providers.push(CPU::default().with_arena_allocator(true).build());+ providers.push(CPU::default().with_arena_allocator(true).build());++ ProviderAttempt {+ providers,+ has_preferred_provider,+ uses_xnnpack,}+}- providers+#[cfg(target_os = "android")]+fn xnnpack_provider() -> ExecutionProviderDispatch {+ XNNPACK::default()+ .with_intra_op_num_threads(NonZeroUsize::new(4).expect("four is non-zero"))+ .build()+ .error_on_failure()}-fn build_session_with_providers(- model_path: &str,- providers: Vec<ExecutionProviderDispatch>,-) -> MlResult<Session> {+fn build_session_with_providers(model_path: &str, attempt: ProviderAttempt) -> MlResult<Session> {let mut builder = Session::builder()?.with_optimization_level(GraphOptimizationLevel::All)?.with_intra_threads(1)?.with_inter_threads(1)?;- builder = builder.with_execution_providers(providers)?;+ if attempt.uses_xnnpack {+ builder = builder.with_intra_op_spinning(false)?;+ }+ builder = builder.with_execution_providers(attempt.providers)?;let session = builder.commit_from_file(model_path)?;Ok(session)diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rsindex 9db603eea2..e70ef31acb 100644--- a/rust/crates/photos/src/ml/runtime.rs+++ b/rust/crates/photos/src/ml/runtime.rs@@ -35,25 +35,6 @@ fn rt_log(msg: &str) {}}-#[derive(Clone, Debug, PartialEq, Eq)]-pub struct ExecutionProviderPolicy {- pub prefer_coreml: bool,- pub prefer_nnapi: bool,- pub prefer_xnnpack: bool,- pub allow_cpu_fallback: bool,-}--impl Default for ExecutionProviderPolicy {- fn default() -> Self {- Self {- prefer_coreml: true,- prefer_nnapi: true,- prefer_xnnpack: false,- allow_cpu_fallback: true,- }- }-}-#[derive(Clone, Debug, PartialEq, Eq)]pub struct ModelPaths {pub face_detection: String,@@ -71,13 +52,11 @@ pub struct ModelPaths {#[derive(Clone, Debug, PartialEq, Eq)]pub struct MlRuntimeConfig {pub model_paths: ModelPaths,- pub provider_policy: ExecutionProviderPolicy,}#[derive(Debug)]struct ModelSlotState {path: String,- requested_policy: ExecutionProviderPolicy,fell_back_to_cpu: bool,pin_count: usize,session: Option<Session>,@@ -122,7 +101,6 @@ impl ModelSlot {Self {state: Mutex::new(ModelSlotState {path: String::new(),- requested_policy: ExecutionProviderPolicy::default(),fell_back_to_cpu: false,pin_count: 0,session: None,@@ -137,22 +115,22 @@ impl ModelSlot {}}- fn configure_if_requested(&self, path: &str, policy: &ExecutionProviderPolicy) {+ fn configure_if_requested(&self, path: &str) {if path.trim().is_empty() {return;}let mut state = self.lock_state();- Self::set_config_locked(&mut state, path, policy);+ Self::set_config_locked(&mut state, path);}- fn sync_indexing_residency(&self, path: &str, policy: &ExecutionProviderPolicy) {+ fn sync_indexing_residency(&self, path: &str) {let mut state = self.lock_state();if path.trim().is_empty() {Self::reset_slot_locked(&mut state);return;}- Self::set_config_locked(&mut state, path, policy);+ Self::set_config_locked(&mut state, path);state.pin_count = 1;}@@ -175,12 +153,7 @@ impl ModelSlot {if state.path != path {return;}- if !state.requested_policy.allow_cpu_fallback {- return;- }- if cpu_only_policy(&state.requested_policy) == state.requested_policy- || state.fell_back_to_cpu- {+ if state.fell_back_to_cpu {return;}@@ -188,28 +161,22 @@ impl ModelSlot {state.session = None;}- fn session_guard_for(- &self,- path: &str,- policy: &ExecutionProviderPolicy,- error_msg: &str,- ) -> MlResult<ModelSessionGuard<'_>> {+ fn session_guard_for(&self, path: &str, error_msg: &str) -> MlResult<ModelSessionGuard<'_>> {if path.trim().is_empty() {return Err(MlError::InvalidRequest(error_msg.to_string()));}let mut state = self.lock_state();- Self::set_config_locked(&mut state, path, policy);+ Self::set_config_locked(&mut state, path);Self::ensure_loaded_locked(&mut state, error_msg)?;Ok(ModelSessionGuard { state })}- fn set_config_locked(state: &mut ModelSlotState, path: &str, policy: &ExecutionProviderPolicy) {- if state.path == path && state.requested_policy == *policy {+ fn set_config_locked(state: &mut ModelSlotState, path: &str) {+ if state.path == path {return;}state.path = path.to_string();- state.requested_policy = policy.clone();state.fell_back_to_cpu = false;state.session = None;}@@ -236,30 +203,18 @@ impl ModelSlot {let model_name = state.path.rsplit('/').next().unwrap_or(&state.path);rt_log(&format!("loading {model_name}"));let t = std::time::Instant::now();- let session = onnx::build_session(&state.path, &effective_policy(state))?;+ let execution_mode = if state.fell_back_to_cpu {+ onnx::ExecutionMode::CpuOnly+ } else {+ onnx::ExecutionMode::PlatformDefault+ };+ let session = onnx::build_session(&state.path, execution_mode)?;rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));state.session = Some(session);Ok(())}}-fn effective_policy(state: &ModelSlotState) -> ExecutionProviderPolicy {- if state.fell_back_to_cpu && state.requested_policy.allow_cpu_fallback {- cpu_only_policy(&state.requested_policy)- } else {- state.requested_policy.clone()- }-}--fn cpu_only_policy(policy: &ExecutionProviderPolicy) -> ExecutionProviderPolicy {- ExecutionProviderPolicy {- prefer_coreml: false,- prefer_nnapi: false,- prefer_xnnpack: false,- allow_cpu_fallback: policy.allow_cpu_fallback,- }-}-#[derive(Debug)]pub struct MlRuntime {face_detection: ModelSlot,@@ -276,19 +231,6 @@ pub struct MlRuntime {static GLOBAL_RUNTIME: Lazy<MlRuntime> = Lazy::new(MlRuntime::new);-fn pet_policy() -> ExecutionProviderPolicy {- // Pet models use CPU-only to avoid NNAPI/CoreML driver issues with- // FP16 models on some devices.- // TODO: Make pet EP policy configurable so hardware acceleration can be- // re-enabled once driver issues are resolved.- ExecutionProviderPolicy {- prefer_coreml: false,- prefer_nnapi: false,- prefer_xnnpack: false,- allow_cpu_fallback: true,- }-}-impl MlRuntime {fn new() -> Self {Self {@@ -306,53 +248,47 @@ impl MlRuntime {}fn configure_requested_models(&self, config: &MlRuntimeConfig) {- let shared_policy = &config.provider_policy;- let pet_policy = pet_policy();-self.face_detection- .configure_if_requested(&config.model_paths.face_detection, shared_policy);+ .configure_if_requested(&config.model_paths.face_detection);self.face_embedding- .configure_if_requested(&config.model_paths.face_embedding, shared_policy);+ .configure_if_requested(&config.model_paths.face_embedding);self.clip_image- .configure_if_requested(&config.model_paths.clip_image, shared_policy);+ .configure_if_requested(&config.model_paths.clip_image);self.clip_text- .configure_if_requested(&config.model_paths.clip_text, shared_policy);+ .configure_if_requested(&config.model_paths.clip_text);self.pet_face_detection- .configure_if_requested(&config.model_paths.pet_face_detection, &pet_policy);+ .configure_if_requested(&config.model_paths.pet_face_detection);self.pet_face_embedding_dog- .configure_if_requested(&config.model_paths.pet_face_embedding_dog, &pet_policy);+ .configure_if_requested(&config.model_paths.pet_face_embedding_dog);self.pet_face_embedding_cat- .configure_if_requested(&config.model_paths.pet_face_embedding_cat, &pet_policy);+ .configure_if_requested(&config.model_paths.pet_face_embedding_cat);self.pet_body_detection- .configure_if_requested(&config.model_paths.pet_body_detection, &pet_policy);+ .configure_if_requested(&config.model_paths.pet_body_detection);self.pet_body_embedding_dog- .configure_if_requested(&config.model_paths.pet_body_embedding_dog, &pet_policy);+ .configure_if_requested(&config.model_paths.pet_body_embedding_dog);self.pet_body_embedding_cat- .configure_if_requested(&config.model_paths.pet_body_embedding_cat, &pet_policy);+ .configure_if_requested(&config.model_paths.pet_body_embedding_cat);}fn prepare_indexing_models(&self, config: &MlRuntimeConfig) -> MlResult<()> {- let shared_policy = &config.provider_policy;- let pet_policy = pet_policy();-self.face_detection- .sync_indexing_residency(&config.model_paths.face_detection, shared_policy);+ .sync_indexing_residency(&config.model_paths.face_detection);self.face_embedding- .sync_indexing_residency(&config.model_paths.face_embedding, shared_policy);+ .sync_indexing_residency(&config.model_paths.face_embedding);self.clip_image- .sync_indexing_residency(&config.model_paths.clip_image, shared_policy);+ .sync_indexing_residency(&config.model_paths.clip_image);self.pet_face_detection- .sync_indexing_residency(&config.model_paths.pet_face_detection, &pet_policy);+ .sync_indexing_residency(&config.model_paths.pet_face_detection);self.pet_face_embedding_dog- .sync_indexing_residency(&config.model_paths.pet_face_embedding_dog, &pet_policy);+ .sync_indexing_residency(&config.model_paths.pet_face_embedding_dog);self.pet_face_embedding_cat- .sync_indexing_residency(&config.model_paths.pet_face_embedding_cat, &pet_policy);+ .sync_indexing_residency(&config.model_paths.pet_face_embedding_cat);self.pet_body_detection- .sync_indexing_residency(&config.model_paths.pet_body_detection, &pet_policy);+ .sync_indexing_residency(&config.model_paths.pet_body_detection);self.pet_body_embedding_dog- .sync_indexing_residency(&config.model_paths.pet_body_embedding_dog, &pet_policy);+ .sync_indexing_residency(&config.model_paths.pet_body_embedding_dog);self.pet_body_embedding_cat- .sync_indexing_residency(&config.model_paths.pet_body_embedding_cat, &pet_policy);+ .sync_indexing_residency(&config.model_paths.pet_body_embedding_cat);Ok(())}@@ -404,7 +340,6 @@ impl MlRuntimeView<'_> {pub fn face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.face_detection.session_guard_for(&self.config.model_paths.face_detection,- &self.config.provider_policy,"missing model path: faceDetectionModelPath is required when runFaces is true",)}@@ -412,7 +347,6 @@ impl MlRuntimeView<'_> {pub fn face_embedding_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.face_embedding.session_guard_for(&self.config.model_paths.face_embedding,- &self.config.provider_policy,"missing model path: faceEmbeddingModelPath is required when runFaces is true",)}@@ -420,7 +354,6 @@ impl MlRuntimeView<'_> {pub fn clip_image_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.clip_image.session_guard_for(&self.config.model_paths.clip_image,- &self.config.provider_policy,"missing model path: clipImageModelPath is required when runClip is true",)}@@ -428,7 +361,6 @@ impl MlRuntimeView<'_> {pub fn clip_text_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.clip_text.session_guard_for(&self.config.model_paths.clip_text,- &self.config.provider_policy,"missing model path: clipTextModelPath is required when running clip text",)}@@ -436,7 +368,6 @@ impl MlRuntimeView<'_> {pub fn pet_face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_face_detection.session_guard_for(&self.config.model_paths.pet_face_detection,- &pet_policy(),"missing model path: petFaceDetectionModelPath is required when runPets is true",)}@@ -444,7 +375,6 @@ impl MlRuntimeView<'_> {pub fn pet_face_embedding_dog_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_face_embedding_dog.session_guard_for(&self.config.model_paths.pet_face_embedding_dog,- &pet_policy(),"missing model path: petFaceEmbeddingDogModelPath is required",)}@@ -452,7 +382,6 @@ impl MlRuntimeView<'_> {pub fn pet_face_embedding_cat_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_face_embedding_cat.session_guard_for(&self.config.model_paths.pet_face_embedding_cat,- &pet_policy(),"missing model path: petFaceEmbeddingCatModelPath is required",)}@@ -460,7 +389,6 @@ impl MlRuntimeView<'_> {pub fn pet_body_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_body_detection.session_guard_for(&self.config.model_paths.pet_body_detection,- &pet_policy(),"missing model path: petBodyDetectionModelPath is required when runPets is true",)}@@ -468,7 +396,6 @@ impl MlRuntimeView<'_> {pub fn pet_body_embedding_dog_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_body_embedding_dog.session_guard_for(&self.config.model_paths.pet_body_embedding_dog,- &pet_policy(),"missing model path: petBodyEmbeddingDogModelPath is required",)}@@ -476,7 +403,6 @@ impl MlRuntimeView<'_> {pub fn pet_body_embedding_cat_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_body_embedding_cat.session_guard_for(&self.config.model_paths.pet_body_embedding_cat,- &pet_policy(),"missing model path: petBodyEmbeddingCatModelPath is required",)}@@ -502,7 +428,7 @@ wherematch first_result {Ok(result) => Ok(result),Err(first_error) => {- if !should_retry_with_cpu_only_runtime(config, &first_error) {+ if !should_retry_with_cpu_only_runtime(&first_error) {return Err(first_error);}@@ -521,14 +447,8 @@ pub fn release_runtime() -> MlResult<()> {Ok(())}-fn should_retry_with_cpu_only_runtime(config: &MlRuntimeConfig, error: &MlError) -> bool {- if !config.provider_policy.allow_cpu_fallback {- return false;- }- if !is_execution_provider_failure(error) {- return false;- }- cpu_only_policy(&config.provider_policy) != config.provider_policy+fn should_retry_with_cpu_only_runtime(error: &MlError) -> bool {+ cfg!(any(target_os = "ios", target_os = "android")) && is_execution_provider_failure(error)}fn is_execution_provider_failure(error: &MlError) -> bool {@@ -539,7 +459,6 @@ fn is_execution_provider_failure(error: &MlError) -> bool {normalized.contains("executionprovider")|| normalized.contains("unknown allocation device")|| normalized.contains("xnnpackexecutionprovider")- || normalized.contains("nnapiexecutionprovider")|| normalized.contains("coremlexecutionprovider")|| normalized.contains("ep error")}@@ -548,15 +467,6 @@ fn is_execution_provider_failure(error: &MlError) -> bool {mod tests {use super::*;- fn test_policy() -> ExecutionProviderPolicy {- ExecutionProviderPolicy {- prefer_coreml: false,- prefer_nnapi: false,- prefer_xnnpack: false,- allow_cpu_fallback: true,- }- }-fn empty_paths() -> ModelPaths {ModelPaths {face_detection: String::new(),@@ -575,14 +485,12 @@ mod tests {#[test]fn configure_requested_models_preserves_unrequested_slots() {let runtime = MlRuntime::new();- let policy = test_policy();runtime.configure_requested_models(&MlRuntimeConfig {model_paths: ModelPaths {clip_text: "clip_text.onnx".to_string(),..empty_paths()},- provider_policy: policy.clone(),});runtime.configure_requested_models(&MlRuntimeConfig {@@ -590,7 +498,6 @@ mod tests {face_detection: "face.onnx".to_string(),..empty_paths()},- provider_policy: policy,});let clip_text = runtime.clip_text.lock_state();@@ -638,7 +545,6 @@ mod tests {clip_image: "clip.onnx".to_string(),..empty_paths()},- provider_policy: test_policy(),}).unwrap();@@ -666,7 +572,7 @@ mod tests {state.fell_back_to_cpu = true;}- slot.sync_indexing_residency("", &test_policy());+ slot.sync_indexing_residency("");let state = slot.lock_state();assert!(state.path.is_empty());@@ -682,7 +588,6 @@ mod tests {{let mut state = slot.lock_state();state.path = "clip_text.onnx".to_string();- state.requested_policy = test_policy();state.pin_count = 1;state.fell_back_to_cpu = true;}diff --git a/rust/crates/photos/tests/support/ml_indexing.rs b/rust/crates/photos/tests/support/ml_indexing.rsindex 14b8d5bc88..5e0ac6964b 100644--- a/rust/crates/photos/tests/support/ml_indexing.rs+++ b/rust/crates/photos/tests/support/ml_indexing.rs@@ -12,7 +12,7 @@ use ente_photos::ml::{indexing::{AnalyzeImageRequest, AnalyzeImageResult, analyze_image, init_ml_runtime, release_ml_runtime,},- runtime::{ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},+ runtime::{MlRuntimeConfig, ModelPaths},types::FaceResult as RustFaceResult,};use flate2::read::GzDecoder;@@ -203,12 +203,6 @@ impl MlIndexingTestContext {let runtime_config = MlRuntimeConfig {model_paths: resolve_model_paths(&client, &cache_dir, &asset_lock.models)?,- provider_policy: ExecutionProviderPolicy {- prefer_coreml: false,- prefer_nnapi: false,- prefer_xnnpack: false,- allow_cpu_fallback: true,- },};Ok(Self {