π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Safety cpu fallback for EPs in onnx runtime
laurenspriemd6c9422e183a
diff --git a/mobile/apps/photos/integration_test/ml_parity_shared.dart b/mobile/apps/photos/integration_test/ml_parity_shared.dartindex af0b6634eb..be01c13e78 100644--- a/mobile/apps/photos/integration_test/ml_parity_shared.dart+++ b/mobile/apps/photos/integration_test/ml_parity_shared.dart@@ -504,6 +504,7 @@ Future<MLResult> _analyzeImage({"clipImageModelPath": clipImageModelPath,"preferCoreml": Platform.isIOS,"preferNnapi": Platform.isAndroid,+ "preferXnnpack": Platform.isAndroid,"allowCpuFallback": true,});} else {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 fc3edc978b..c767a881bd 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@@ -343,6 +343,7 @@ class MLIndexingIsolate extends SuperIsolate {"clipImageModelPath": clipImage.$2,"preferCoreml": Platform.isIOS,"preferNnapi": Platform.isAndroid,+ "preferXnnpack": Platform.isAndroid,"allowCpuFallback": true,};}diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dartindex 27cb315257..2724803833 100644--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart@@ -273,6 +273,7 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {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);@@ -330,6 +331,7 @@ String _runtimeConfigCacheKey(modelPaths.clipImage,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 8740c982d9..7ae705f744 100644--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@ -608,6 +608,7 @@ Future<MLResult> analyzeImageRust(Map args) async {final String? clipImageModelPath = args["clipImageModelPath"] 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) =>@@ -638,6 +639,7 @@ Future<MLResult> analyzeImageRust(Map args) async {final providerPolicy = rust_ml.RustExecutionProviderPolicy(preferCoreml: preferCoreml,preferNnapi: preferNnapi,+ preferXnnpack: preferXnnpack,allowCpuFallback: allowCpuFallback,);diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rsindex 6bdfb48497..a7a418a3c7 100644--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs@@ -10,6 +10,7 @@ use crate::ml::{pub struct RustExecutionProviderPolicy {pub prefer_coreml: bool,pub prefer_nnapi: bool,+ pub prefer_xnnpack: bool,pub allow_cpu_fallback: bool,}@@ -18,6 +19,7 @@ impl Default for RustExecutionProviderPolicy {Self {prefer_coreml: true,prefer_nnapi: true,+ prefer_xnnpack: false,allow_cpu_fallback: true,}}@@ -141,7 +143,7 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageReOk(AnalyzeImageResult {file_id: req.file_id,- decoded_image_size: dims,+ decoded_image_size: dims.clone(),faces,clip,})@@ -190,6 +192,7 @@ fn to_provider_policy(policy: &RustExecutionProviderPolicy) -> ExecutionProviderExecutionProviderPolicy {prefer_coreml: policy.prefer_coreml,prefer_nnapi: policy.prefer_nnapi,+ prefer_xnnpack: policy.prefer_xnnpack,allow_cpu_fallback: policy.allow_cpu_fallback,}}diff --git a/mobile/apps/photos/rust/src/ml/onnx.rs b/mobile/apps/photos/rust/src/ml/onnx.rsindex 8e12c5be61..444fcc280d 100644--- a/mobile/apps/photos/rust/src/ml/onnx.rs+++ b/mobile/apps/photos/rust/src/ml/onnx.rs@@ -14,11 +14,54 @@ use crate::ml::{};pub fn build_session(model_path: &str, policy: &ExecutionProviderPolicy) -> MlResult<Session> {- let mut builder = Session::builder()?- .with_optimization_level(GraphOptimizationLevel::Level3)?- .with_intra_threads(1)?- .with_inter_threads(1)?;+ let primary_providers = providers_for_policy(policy, true);+ let mut attempts = vec![primary_providers];++ if policy.allow_cpu_fallback && policy.prefer_xnnpack {+ let providers_without_xnnpack = providers_for_policy(policy, false);+ attempts.push(providers_without_xnnpack);+ }++ 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);+ }++ let mut errors = Vec::new();+ for providers in attempts {+ if providers.is_empty() {+ continue;+ }++ match build_session_with_providers(model_path, providers) {+ 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(),+ ));+ }++ Err(MlError::Ort(format!(+ "failed to create ONNX session for model '{model_path}' across EP fallbacks: {}",+ errors.join(" | ")+ )))+}++fn providers_for_policy(+ policy: &ExecutionProviderPolicy,+ include_xnnpack: bool,+) -> Vec<ExecutionProviderDispatch> {let mut providers: Vec<ExecutionProviderDispatch> = Vec::new();#[cfg(target_vendor = "apple")]@@ -28,22 +71,32 @@ pub fn build_session(model_path: &str, policy: &ExecutionProviderPolicy) -> MlRe#[cfg(target_os = "android")]if policy.prefer_nnapi {- // Prefer NNAPI accelerators and let ORT handle CPU fallback via XNNPACK/CPU EP.+ // Prefer NNAPI accelerators and let ORT handle CPU fallback via the added CPU EP.providers.push(NNAPIExecutionProvider::default().with_disable_cpu().build());}if policy.allow_cpu_fallback {- // XNNPACK is generally a faster CPU path on mobile; keep plain CPU EP as last fallback.- providers.push(XNNPACKExecutionProvider::default().build());- providers.push(CPUExecutionProvider::default().with_arena_allocator().build());+ if include_xnnpack && policy.prefer_xnnpack {+ providers.push(XNNPACKExecutionProvider::default().build());+ }+ providers.push(+ CPUExecutionProvider::default()+ .with_arena_allocator()+ .build(),+ );}- if providers.is_empty() {- return Err(MlError::InvalidRequest(- "no supported execution provider selected for this platform while CPU fallback is disabled"- .to_string(),- ));- }+ providers+}++fn build_session_with_providers(+ model_path: &str,+ providers: Vec<ExecutionProviderDispatch>,+) -> MlResult<Session> {+ let mut builder = Session::builder()?+ .with_optimization_level(GraphOptimizationLevel::Level3)?+ .with_intra_threads(1)?+ .with_inter_threads(1)?;builder = builder.with_execution_providers(providers)?;diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rsindex 83bb0ba4c7..a1ad457bfa 100644--- a/mobile/apps/photos/rust/src/ml/runtime.rs+++ b/mobile/apps/photos/rust/src/ml/runtime.rs@@ -12,6 +12,7 @@ use crate::ml::{pub struct ExecutionProviderPolicy {pub prefer_coreml: bool,pub prefer_nnapi: bool,+ pub prefer_xnnpack: bool,pub allow_cpu_fallback: bool,}@@ -20,6 +21,7 @@ impl Default for ExecutionProviderPolicy {Self {prefer_coreml: true,prefer_nnapi: true,+ prefer_xnnpack: false,allow_cpu_fallback: true,}}@@ -140,14 +142,88 @@ pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {pub fn with_runtime_mut<F, R>(config: &MlRuntimeConfig, func: F) -> MlResult<R>where- F: FnOnce(&mut MlRuntime) -> MlResult<R>,+ F: FnMut(&mut MlRuntime) -> MlResult<R>,+{+ with_runtime_mut_inner(config, func)+}++fn with_runtime_mut_inner<F, R>(config: &MlRuntimeConfig, mut func: F) -> MlResult<R>+where+ F: FnMut(&mut MlRuntime) -> MlResult<R>,{ensure_runtime(config)?;- let mut guard = lock_runtime();- let state = guard- .as_mut()- .ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;- func(&mut state.runtime)++ let first_result = {+ let mut guard = lock_runtime();+ let state = guard+ .as_mut()+ .ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;+ func(&mut state.runtime)+ };++ match first_result {+ Ok(result) => Ok(result),+ Err(first_error) => {+ if !should_retry_with_cpu_only_runtime(config, &first_error) {+ return Err(first_error);+ }++ let fallback_config = cpu_only_runtime_config(config);+ eprintln!(+ "[ml][runtime] execution provider failed, retrying with CPU-only runtime: {first_error}"+ );+ ensure_runtime(&fallback_config)?;+ let retry_result = {+ let mut guard = lock_runtime();+ let state = guard+ .as_mut()+ .ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;+ func(&mut state.runtime)+ };++ if retry_result.is_ok() {+ let mut guard = lock_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();+ }+ }++ retry_result+ }+ }+}++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_runtime_config(config) != *config+}++fn cpu_only_runtime_config(config: &MlRuntimeConfig) -> MlRuntimeConfig {+ let mut fallback = config.clone();+ fallback.provider_policy.prefer_coreml = false;+ fallback.provider_policy.prefer_nnapi = false;+ fallback.provider_policy.prefer_xnnpack = false;+ fallback+}++fn is_execution_provider_failure(error: &MlError) -> bool {+ let MlError::Ort(message) = error else {+ return false;+ };+ let normalized = message.to_ascii_lowercase();+ normalized.contains("executionprovider")+ || normalized.contains("unknown allocation device")+ || normalized.contains("xnnpackexecutionprovider")+ || normalized.contains("nnapiexecutionprovider")+ || normalized.contains("coremlexecutionprovider")+ || normalized.contains("ep error")}pub fn release_runtime() -> MlResult<()> {