π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Gate Android WebGPU rollout and detect non-finite model outputs
laurenspriemb5735675bf94
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dartindex c0c59ae53e..7c3fa858ed 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart@@ -6,6 +6,7 @@ import "package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart"import "package:logging/logging.dart";import "package:photos/core/errors.dart";import "package:photos/models/ml/vector.dart";+import "package:photos/service_locator.dart" show flagService;import "package:photos/services/machine_learning/ml_constants.dart";import "package:photos/services/machine_learning/ml_model_assets.dart";import "package:photos/services/machine_learning/ml_model_download_service.dart";@@ -86,6 +87,10 @@ class MLComputer extends SuperIsolate {"text": query,"clipTextModelPath": modelPath,"clipTextVocabPath": vocabPath,+ // Keep in sync with MLIndexingIsolate: WebGPU is only enabled for+ // internal users while the custom Android ONNX Runtime build is+ // being validated. Ignored on other platforms.+ "enableWebGpu": flagService.webGPUEnabled,});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 6ac3913f46..b136cfd852 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@@ -176,6 +176,9 @@ class MLIndexingIsolate extends SuperIsolate {}return {+ // WebGPU is only enabled for internal users while the custom Android+ // ONNX Runtime build is being validated. Ignored on other platforms.+ "enableWebGpu": flagService.webGPUEnabled,"faceDetectionModelPath": faceDetectionPath,"faceEmbeddingModelPath": faceEmbeddingPath,"clipImageModelPath": clipImagePath,diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dartindex 0b34b52a9f..886ae42a8c 100644--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart@@ -182,6 +182,13 @@ Future<dynamic> isolateFunction();}+ // Configure execution behavior before the CLIP text session is+ // created; the session is process-global and cannot be reconfigured+ // once built.+ await rust_ml.setMlExecutionConfig(+ enableWebgpu: (args["enableWebGpu"] as bool?) ?? false,+ );+final rust_ml.RunClipTextResult result;try {result = await rust_ml.runClipTextRust(@@ -379,6 +386,10 @@ Future<void> _ensureRustDisposed() async {}Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {+ // Configure execution behavior before any ONNX session is created.+ await rust_ml.setMlExecutionConfig(+ enableWebgpu: (args["enableWebGpu"] as bool?) ?? false,+ );final modelPaths = rust_ml.RustModelPaths(faceDetection: (args["faceDetectionModelPath"] as String?) ?? "",faceEmbedding: (args["faceEmbeddingModelPath"] as String?) ?? "",diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dartindex 6ee53341f3..fa546b988d 100644--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@ -821,6 +821,13 @@ Future<MLResult> analyzeImageRust(Map args) async {);}+ // The Rust runtime creates sessions lazily, so configure execution+ // behavior here as well in case the runtime was not prepared explicitly+ // in this isolate.+ await rust_ml.setMlExecutionConfig(+ enableWebgpu: (args["enableWebGpu"] as bool?) ?? false,+ );+final modelPaths = rust_ml.RustModelPaths(faceDetection: faceDetectionModelPath ?? "",faceEmbedding: faceEmbeddingModelPath ?? "",diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dartindex 485976f32e..5f440de2b5 100644--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart@@ -53,6 +53,8 @@ class FlagService {return (flags.internalUser || kDebugMode) && !isDisabled;}+ bool get webGPUEnabled => internalUser;+bool get cloudflareUploadWorker =>internalUser || _isInUserRollout(_cfUploadWorkerRolloutPercent);diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 946d350a53..4302e48110 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2424,6 +2424,7 @@ dependencies = [name = "ente-photos"version = "0.0.0"dependencies = [+ "android_system_properties","anyhow","ente-image","fast_image_resize",diff --git a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs b/rust/bindings/frb/photos/src/api/ml_indexing_api.rsindex 9322095b29..fd638d81cf 100644--- a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs+++ b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs@@ -130,6 +130,14 @@ pub struct RunClipTextResult {pub embedding: Vec<f64>,}+/// Configures process-wide ML execution behavior. `enable_webgpu` opts+/// Android into the WebGPU execution provider (off by default, and only+/// honored on Android 12+); it has no effect on other platforms. Call this+/// before the runtime creates its first session.+pub fn set_ml_execution_config(enable_webgpu: bool) {+ shared_indexing::set_ml_execution_config(enable_webgpu);+}+pub fn init_ml_runtime(model_paths: RustModelPaths) {shared_indexing::init_ml_runtime(to_model_paths(&model_paths));}diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.tomlindex 74814e4736..6ca0c8c434 100644--- a/rust/crates/photos/Cargo.toml+++ b/rust/crates/photos/Cargo.toml@@ -25,7 +25,9 @@ thiserror.workspace = true# ORT source and revision are pinned once in the workspace manifest; only the# per-target feature sets are declared here.-# The iOS Cargokit build sets ORT_LIB_PATH to the verified custom static archive.+# The iOS Cargokit build sets ORT_LIB_PATH to the directory containing the+# verified custom static archive; see mobile/native/onnxruntime/README.md for+# building outside Xcode.[target.'cfg(target_os = "ios")'.dependencies]ort = { workspace = true, features = ["std",@@ -37,6 +39,8 @@ ort = { workspace = true, features = [] }[target.'cfg(target_os = "android")'.dependencies]+# Used to gate the WebGPU execution provider to Android 12+ (SDK 31).+android_system_properties = "0.1.5"ort = { workspace = true, features = ["ndarray","half",diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rsindex 7108350977..b092da6a0a 100644--- a/rust/crates/photos/src/ml/indexing.rs+++ b/rust/crates/photos/src/ml/indexing.rs@@ -44,6 +44,16 @@ pub struct RunClipTextResult {pub embedding: Vec<f32>,}+/// Configures process-wide ML execution behavior. Must be called before the+/// first session is created to take effect for that session.+///+/// `enable_webgpu` opts Android into the WebGPU execution provider; it is off+/// by default and additionally requires Android 12+ (SDK 31). It has no+/// effect on other platforms.+pub fn set_ml_execution_config(enable_webgpu: bool) {+ crate::ml::onnx::set_webgpu_enabled(enable_webgpu);+}+pub fn init_ml_runtime(model_paths: ModelPaths) {runtime::prepare_runtime(&model_paths);}diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rsindex 873a36b41c..ddf1482f21 100644--- a/rust/crates/photos/src/ml/onnx.rs+++ b/rust/crates/photos/src/ml/onnx.rs@@ -22,9 +22,44 @@ use ort::ep::{};#[cfg(target_os = "android")]use std::num::NonZeroUsize;+#[cfg(target_os = "android")]+use std::sync::{+ OnceLock,+ atomic::{AtomicBool, Ordering},+};use crate::ml::error::{MlError, MlResult};+/// WebGPU is opt-in while the custom Android ONNX Runtime build is being+/// validated: the app currently enables it for internal users only.+#[cfg(target_os = "android")]+static WEBGPU_ENABLED: AtomicBool = AtomicBool::new(false);++pub(crate) fn set_webgpu_enabled(enabled: bool) {+ #[cfg(target_os = "android")]+ WEBGPU_ENABLED.store(enabled, Ordering::Relaxed);+ #[cfg(not(target_os = "android"))]+ let _ = enabled;+}++#[cfg(target_os = "android")]+fn webgpu_allowed() -> bool {+ WEBGPU_ENABLED.load(Ordering::Relaxed) && android_supports_webgpu()+}++/// Dawn's Vulkan backend is only trusted on Android 12+ (SDK 31). This fails+/// closed: if the SDK level cannot be read, WebGPU stays disabled.+#[cfg(target_os = "android")]+fn android_supports_webgpu() -> bool {+ static SDK_AT_LEAST_31: OnceLock<bool> = OnceLock::new();+ *SDK_AT_LEAST_31.get_or_init(|| {+ android_system_properties::AndroidSystemProperties::new()+ .get("ro.build.version.sdk")+ .and_then(|value| value.trim().parse::<u32>().ok())+ .is_some_and(|sdk| sdk >= 31)+ })+}+#[cfg(any(target_os = "ios", test))]const COREML_CACHE_SCHEMA: &str = "ort-1_27-mlprogram-all-default-v1";const COREML_CACHE_COMPLETE_MARKER: &str = ".ente-cache-complete";@@ -242,8 +277,9 @@ fn platform_default_attempts(_model_path: &str,_coreml_cache_namespace: &str,) -> Vec<ProviderAttempt> {- vec![- ProviderAttempt {+ let mut attempts = Vec::new();+ if webgpu_allowed() {+ attempts.push(ProviderAttempt {// EP priority follows registration order. Unsupported WebGPU nodes// fall through to XNNPACK and then CPU in the same session.providers: vec![@@ -253,12 +289,13 @@ fn platform_default_attempts(],disable_intra_op_spinning: true,coreml_cache_dir: None,- },- // Retain clean-session fallbacks for provider or driver failures that- // prevent the primary session from being constructed at all.- xnnpack_attempt(),- ProviderAttempt::cpu_only(),- ]+ });+ }+ // Clean-session fallbacks for provider or driver failures that prevent+ // the primary session from being constructed at all.+ attempts.push(xnnpack_attempt());+ attempts.push(ProviderAttempt::cpu_only());+ attempts}#[cfg(target_os = "android")]@@ -433,6 +470,27 @@ fn build_session_with_providers(model_path: &str, attempt: ProviderAttempt) -> MOk(session)}+/// Guard against execution providers that return NaN or infinity instead of+/// failing. The error message matches `is_execution_provider_failure` so the+/// runtime advances to the next execution provider fallback.+fn ensure_finite_f32(data: &[f32]) -> MlResult<()> {+ if data.iter().copied().all(f32::is_finite) {+ return Ok(());+ }+ Err(MlError::Ort(+ "model produced non-finite output values".to_string(),+ ))+}++fn ensure_finite_f16(data: &[half::f16]) -> MlResult<()> {+ if data.iter().all(|value| value.is_finite()) {+ return Ok(());+ }+ Err(MlError::Ort(+ "model produced non-finite output values".to_string(),+ ))+}+/// Returns true if the session's first input expects FP16 tensors.fn session_expects_f16(session: &Session) -> bool {session@@ -470,12 +528,14 @@ pub(crate) fn run_f32<const N: usize>(if let Ok((tensor_shape, tensor_data)) = output.try_extract_tensor::<f32>() {let shape = tensor_shape.iter().copied().collect::<Vec<_>>();let data = tensor_data.to_vec();+ ensure_finite_f32(&data)?;Ok((shape, data))} else {let (tensor_shape, tensor_data) = output.try_extract_tensor::<half::f16>()?;let shape = tensor_shape.iter().copied().collect::<Vec<_>>();let mut data = vec![0.0; tensor_data.len()];tensor_data.convert_to_f32_slice(&mut data);+ ensure_finite_f32(&data)?;Ok((shape, data))}}@@ -504,9 +564,11 @@ pub(crate) fn with_prepared_float_output<const N: usize, T>(}let output = &outputs[0];if let Ok((tensor_shape, tensor_data)) = output.try_extract_tensor::<f32>() {+ ensure_finite_f32(tensor_data)?;consume(tensor_shape, BorrowedFloatTensor::F32(tensor_data))} else {let (tensor_shape, tensor_data) = output.try_extract_tensor::<half::f16>()?;+ ensure_finite_f16(tensor_data)?;consume(tensor_shape, BorrowedFloatTensor::F16(tensor_data))}}@@ -525,6 +587,7 @@ pub(crate) fn run_i32_f32<const N: usize>(let (tensor_shape, tensor_data) = output.try_extract_tensor::<f32>()?;let shape = tensor_shape.iter().copied().collect::<Vec<_>>();let data = tensor_data.to_vec();+ ensure_finite_f32(&data)?;Ok((shape, data))}@@ -533,11 +596,28 @@ mod tests {use std::{io::Write, path::Path};use super::{- coreml_cache_root, coreml_model_cache_key, has_protobuf_parse_failure,- invalidate_coreml_cache, mark_coreml_cache_complete, prepare_coreml_cache_entry,- prune_superseded_coreml_cache_directories, sanitize_cache_component,+ coreml_cache_root, coreml_model_cache_key, ensure_finite_f16, ensure_finite_f32,+ has_protobuf_parse_failure, invalidate_coreml_cache, mark_coreml_cache_complete,+ prepare_coreml_cache_entry, prune_superseded_coreml_cache_directories,+ sanitize_cache_component,};+ #[test]+ fn accepts_finite_model_outputs() {+ assert!(ensure_finite_f32(&[0.0, -1.5, f32::MAX]).is_ok());+ assert!(ensure_finite_f16(&[half::f16::from_f32(0.25)]).is_ok());+ }++ #[test]+ fn rejects_non_finite_model_outputs() {+ for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ let error = ensure_finite_f32(&[1.0, bad]).unwrap_err();+ assert!(error.to_string().contains("non-finite"));+ }+ let error = ensure_finite_f16(&[half::f16::NAN]).unwrap_err();+ assert!(error.to_string().contains("non-finite"));+ }+#[test]fn detects_protobuf_parse_failure() {assert!(has_protobuf_parse_failure(&[String::from(diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rsindex 54194271e7..63e7d49757 100644--- a/rust/crates/photos/src/ml/runtime.rs+++ b/rust/crates/photos/src/ml/runtime.rs@@ -245,24 +245,22 @@ static GLOBAL_RUNTIME: Lazy<MlRuntime> = Lazy::new(MlRuntime::new);impl MlRuntime {fn new() -> Self {let platform_default = onnx::ExecutionMode::PlatformDefault;- #[cfg(target_os = "android")]- let pet_default = platform_default;- #[cfg(not(target_os = "android"))]- let pet_default = onnx::ExecutionMode::CpuOnly;+ let cpu_only = onnx::ExecutionMode::CpuOnly;Self {face_detection: ModelSlot::new(platform_default, "face-detection"),face_embedding: ModelSlot::new(platform_default, "face-embedding"),clip_image: ModelSlot::new(platform_default, "clip-image"),clip_text: ModelSlot::new(platform_default, "clip-text"),- // Android uses the same WebGPU-first chain for every model. Keep- // the existing CPU-only pet policy on other platforms.- pet_face_detection: ModelSlot::new(pet_default, "pet-face-detection"),- pet_face_embedding_dog: ModelSlot::new(pet_default, "pet-face-embedding-dog"),- pet_face_embedding_cat: ModelSlot::new(pet_default, "pet-face-embedding-cat"),- pet_body_detection: ModelSlot::new(pet_default, "pet-body-detection"),- pet_body_embedding_dog: ModelSlot::new(pet_default, "pet-body-embedding-dog"),- pet_body_embedding_cat: ModelSlot::new(pet_default, "pet-body-embedding-cat"),+ // Pet models previously had device-specific FP16 driver failures.+ // Keep them CPU-only until they have been validated on the GPU+ // execution providers of supported iOS and Android devices.+ pet_face_detection: ModelSlot::new(cpu_only, "pet-face-detection"),+ pet_face_embedding_dog: ModelSlot::new(cpu_only, "pet-face-embedding-dog"),+ pet_face_embedding_cat: ModelSlot::new(cpu_only, "pet-face-embedding-cat"),+ pet_body_detection: ModelSlot::new(cpu_only, "pet-body-detection"),+ pet_body_embedding_dog: ModelSlot::new(cpu_only, "pet-body-embedding-dog"),+ pet_body_embedding_cat: ModelSlot::new(cpu_only, "pet-body-embedding-cat"),}}@@ -494,6 +492,7 @@ fn is_execution_provider_failure(error: &MlError) -> bool {|| normalized.contains("dawn")|| normalized.contains("vulkan")|| normalized.contains("vk_error")+ || normalized.contains("non-finite")|| normalized.contains("ep error")}@@ -653,9 +652,8 @@ mod tests {#[test]fn model_execution_modes_match_platform_policy() {let runtime = MlRuntime::new();- #[cfg(target_os = "android")]- let expected_pet_mode = onnx::ExecutionMode::PlatformDefault;- #[cfg(not(target_os = "android"))]+ // Pet models stay CPU-only on every platform until they are+ // validated on the GPU execution providers.let expected_pet_mode = onnx::ExecutionMode::CpuOnly;assert_eq!(