Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use custom WebGPU ONNX Runtime build on Android

laurenspriemc95898ba529b
diff --git a/mobile/apps/photos/android/app/build.gradle b/mobile/apps/photos/android/app/build.gradle
index df389b8ff4..97f2870075 100644
--- a/mobile/apps/photos/android/app/build.gradle
+++ b/mobile/apps/photos/android/app/build.gradle
@@ -29,6 +29,27 @@ if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
+def onnxRuntimeAar = new File(
+ gradle.gradleUserHomeDir,
+ 'caches/io.ente/onnxruntime/ort-1.27.0-webgpu-pilot.5/' +
+ 'onnxruntime-webgpu-android-1.27.0-pilot.5.aar',
+)
+def prepareOnnxRuntimeAndroid = tasks.register('prepareOnnxRuntimeAndroid', Exec) {
+ def prepareScript = file('../../../../native/onnxruntime/prepare-android.sh')
+ inputs.file(prepareScript)
+ outputs.file(onnxRuntimeAar)
+ outputs.upToDateWhen { false }
+ commandLine 'sh', prepareScript, onnxRuntimeAar
+}
+def onnxRuntimeFiles = files(onnxRuntimeAar)
+onnxRuntimeFiles.builtBy(prepareOnnxRuntimeAndroid)
+
+configurations.configureEach {
+ // mobile_ocr also declares Microsoft's stock AAR. The custom AAR exposes
+ // the same Java API and must be the sole source of libonnxruntime.so.
+ exclude group: 'com.microsoft.onnxruntime', module: 'onnxruntime-android'
+}
+
android {
namespace = "io.ente.photos"
compileSdk = 36
@@ -173,8 +194,9 @@ dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
- // Required by Rust ML, which dynamically loads libonnxruntime.so.
- implementation 'com.microsoft.onnxruntime:onnxruntime-android:1.27.0'
+ // Custom WebGPU/XNNPACK build required by Rust ML, which dynamically
+ // loads libonnxruntime.so.
+ implementation(onnxRuntimeFiles)
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
diff --git a/mobile/native/android/apps/ensu/rust/build.gradle.kts b/mobile/native/android/apps/ensu/rust/build.gradle.kts
index 64171d8dca..5dedcd44a6 100644
--- a/mobile/native/android/apps/ensu/rust/build.gradle.kts
+++ b/mobile/native/android/apps/ensu/rust/build.gradle.kts
@@ -9,6 +9,18 @@ val knownAbis = listOf("arm64-v8a", "armeabi-v7a", "x86_64")
val debugJniLibsDir = layout.buildDirectory.dir("generated/jniLibs/debug")
val releaseJniLibsDir = layout.buildDirectory.dir("generated/jniLibs/release")
+val onnxRuntimeAar = gradle.gradleUserHomeDir.resolve(
+ "caches/io.ente/onnxruntime/ort-1.27.0-webgpu-pilot.5/" +
+ "onnxruntime-webgpu-android-1.27.0-pilot.5.aar",
+)
+val prepareOnnxRuntimeAndroid = tasks.register<Exec>("prepareOnnxRuntimeAndroid") {
+ val prepareScript = file("../../../../onnxruntime/prepare-android.sh")
+ inputs.file(prepareScript)
+ outputs.file(onnxRuntimeAar)
+ outputs.upToDateWhen { false }
+ commandLine("sh", prepareScript, onnxRuntimeAar)
+}
+val onnxRuntimeFiles = files(onnxRuntimeAar).builtBy(prepareOnnxRuntimeAndroid)
fun capture(vararg cmd: String): String? = runCatching {
val out = ByteArrayOutputStream()
@@ -131,5 +143,7 @@ tasks.matching { it.name == "preReleaseBuild" }.configureEach {
dependencies {
api("net.java.dev.jna:jna:5.18.1@aar")
api("androidx.annotation:annotation:1.7.1")
- api("com.microsoft.onnxruntime:onnxruntime-android:1.27.0")
+ // Custom WebGPU/XNNPACK build; the Rust runtime dynamically loads its
+ // libonnxruntime.so.
+ api(onnxRuntimeFiles)
}
diff --git a/mobile/native/onnxruntime/prepare-android.sh b/mobile/native/onnxruntime/prepare-android.sh
new file mode 100755
index 0000000000..da60c77962
--- /dev/null
+++ b/mobile/native/onnxruntime/prepare-android.sh
@@ -0,0 +1,40 @@
+#!/bin/sh
+set -eu
+
+asset_name="onnxruntime-webgpu-android-1.27.0-pilot.5.aar"
+asset_url="https://github.com/laurens-pilot/ort-packaging/releases/download/ort-1.27.0-webgpu-pilot.5/$asset_name"
+expected_sha256="f40ef31bb6ff8399c556872bcad272bddb650b0845f3026c56a065de9b1ec579"
+
+destination=${1:?"usage: prepare-android.sh <destination.aar>"}
+
+sha256_file() {
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "$1" | awk '{print $1}'
+ elif command -v shasum >/dev/null 2>&1; then
+ shasum -a 256 "$1" | awk '{print $1}'
+ else
+ echo "A SHA-256 utility (sha256sum or shasum) is required" >&2
+ exit 1
+ fi
+}
+
+if [ -f "$destination" ] && [ "$(sha256_file "$destination")" = "$expected_sha256" ]; then
+ exit 0
+fi
+
+mkdir -p "$(dirname "$destination")"
+temporary_file="$destination.download.$$"
+trap 'rm -f "$temporary_file"' EXIT HUP INT TERM
+
+curl --fail --location --retry 3 --silent --show-error \
+ --output "$temporary_file" \
+ "$asset_url"
+
+actual_sha256=$(sha256_file "$temporary_file")
+if [ "$actual_sha256" != "$expected_sha256" ]; then
+ echo "SHA-256 mismatch for $asset_name: got $actual_sha256, expected $expected_sha256" >&2
+ exit 1
+fi
+
+mv "$temporary_file" "$destination"
+trap - EXIT HUP INT TERM
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 43e5a11a1e..946d350a53 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -6113,6 +6113,7 @@ name = "ort-sys"
version = "2.0.0-rc.12"
source = "git+https://github.com/pykeio/ort.git?rev=31c8f1443bb579bfddb82705288347697e468fb3#31c8f1443bb579bfddb82705288347697e468fb3"
dependencies = [
+ "glob",
"hmac-sha256",
"lzma-rust2",
"ureq",
diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.toml
index 7a24353e6c..a432a71103 100644
--- a/rust/crates/photos/Cargo.toml
+++ b/rust/crates/photos/Cargo.toml
@@ -46,6 +46,7 @@ ort = { workspace = true, features = [
"api-27",
"load-dynamic",
"copy-dylibs",
+ "webgpu",
"xnnpack",
] }
diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rs
index 22fdfec918..873a36b41c 100644
--- a/rust/crates/photos/src/ml/onnx.rs
+++ b/rust/crates/photos/src/ml/onnx.rs
@@ -10,14 +10,17 @@ use std::{
use half::prelude::{HalfFloatSliceExt, HalfFloatVecExt};
-#[cfg(target_os = "android")]
-use ort::ep::XNNPACK;
#[cfg(target_os = "ios")]
use ort::ep::{
CoreML,
coreml::{ComputeUnits, ModelFormat, SpecializationStrategy},
};
#[cfg(target_os = "android")]
+use ort::ep::{
+ WebGPU, XNNPACK,
+ webgpu::{DawnBackendType, PreferredLayout},
+};
+#[cfg(target_os = "android")]
use std::num::NonZeroUsize;
use crate::ml::error::{MlError, MlResult};
@@ -85,20 +88,31 @@ impl PreparedF32Input {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExecutionMode {
PlatformDefault,
+ #[cfg(target_os = "android")]
+ Xnnpack,
CpuOnly,
}
+impl ExecutionMode {
+ pub(crate) fn fallback(self) -> Option<Self> {
+ match self {
+ #[cfg(target_os = "android")]
+ Self::PlatformDefault => Some(Self::Xnnpack),
+ #[cfg(not(target_os = "android"))]
+ Self::PlatformDefault => Some(Self::CpuOnly),
+ #[cfg(target_os = "android")]
+ Self::Xnnpack => Some(Self::CpuOnly),
+ Self::CpuOnly => None,
+ }
+ }
+}
+
pub(crate) fn build_session(
model_path: &str,
mode: ExecutionMode,
coreml_cache_namespace: &str,
) -> MlResult<Session> {
- let primary = provider_attempt(mode, model_path, coreml_cache_namespace);
- let retry_with_cpu_only = primary.retry_with_cpu_only;
- let mut attempts = vec![primary];
- if retry_with_cpu_only {
- attempts.push(ProviderAttempt::cpu_only());
- }
+ let attempts = provider_attempts(mode, model_path, coreml_cache_namespace);
let mut errors = Vec::new();
for attempt in attempts {
@@ -149,7 +163,6 @@ fn has_protobuf_parse_failure(errors: &[String]) -> bool {
struct ProviderAttempt {
providers: Vec<ExecutionProviderDispatch>,
- retry_with_cpu_only: bool,
disable_intra_op_spinning: bool,
coreml_cache_dir: Option<PathBuf>,
}
@@ -158,38 +171,44 @@ impl ProviderAttempt {
fn cpu_only() -> Self {
Self {
providers: vec![CPU::default().with_arena_allocator(true).build()],
- retry_with_cpu_only: false,
disable_intra_op_spinning: false,
coreml_cache_dir: None,
}
}
}
-fn provider_attempt(
+fn provider_attempts(
mode: ExecutionMode,
model_path: &str,
coreml_cache_namespace: &str,
-) -> ProviderAttempt {
+) -> Vec<ProviderAttempt> {
match mode {
ExecutionMode::PlatformDefault => {
- platform_default_attempt(model_path, coreml_cache_namespace)
+ platform_default_attempts(model_path, coreml_cache_namespace)
}
- ExecutionMode::CpuOnly => ProviderAttempt::cpu_only(),
+ #[cfg(target_os = "android")]
+ ExecutionMode::Xnnpack => vec![xnnpack_attempt(), ProviderAttempt::cpu_only()],
+ ExecutionMode::CpuOnly => vec![ProviderAttempt::cpu_only()],
}
}
#[cfg(target_os = "ios")]
-fn platform_default_attempt(model_path: &str, coreml_cache_namespace: &str) -> ProviderAttempt {
+fn platform_default_attempts(
+ model_path: &str,
+ coreml_cache_namespace: &str,
+) -> Vec<ProviderAttempt> {
let (coreml_provider, coreml_cache_dir) = coreml_provider(model_path, coreml_cache_namespace);
- ProviderAttempt {
- providers: vec![
- coreml_provider,
- CPU::default().with_arena_allocator(true).build(),
- ],
- retry_with_cpu_only: true,
- disable_intra_op_spinning: false,
- coreml_cache_dir,
- }
+ vec![
+ ProviderAttempt {
+ providers: vec![
+ coreml_provider,
+ CPU::default().with_arena_allocator(true).build(),
+ ],
+ disable_intra_op_spinning: false,
+ coreml_cache_dir,
+ },
+ ProviderAttempt::cpu_only(),
+ ]
}
#[cfg(target_os = "ios")]
@@ -219,21 +238,44 @@ fn coreml_provider(
}
#[cfg(target_os = "android")]
-fn platform_default_attempt(_model_path: &str, _coreml_cache_namespace: &str) -> ProviderAttempt {
- ProviderAttempt {
- providers: vec![
- xnnpack_provider(),
- CPU::default().with_arena_allocator(true).build(),
- ],
- retry_with_cpu_only: true,
- disable_intra_op_spinning: true,
- coreml_cache_dir: None,
- }
+fn platform_default_attempts(
+ _model_path: &str,
+ _coreml_cache_namespace: &str,
+) -> Vec<ProviderAttempt> {
+ vec![
+ ProviderAttempt {
+ // EP priority follows registration order. Unsupported WebGPU nodes
+ // fall through to XNNPACK and then CPU in the same session.
+ providers: vec![
+ webgpu_provider(),
+ xnnpack_provider().fail_silently(),
+ CPU::default().with_arena_allocator(true).build(),
+ ],
+ 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(),
+ ]
+}
+
+#[cfg(target_os = "android")]
+fn webgpu_provider() -> ExecutionProviderDispatch {
+ WebGPU::default()
+ .with_dawn_backend_type(DawnBackendType::Vulkan)
+ .with_preferred_layout(PreferredLayout::NCHW)
+ .build()
+ .error_on_failure()
}
#[cfg(not(any(target_os = "ios", target_os = "android")))]
-fn platform_default_attempt(_model_path: &str, _coreml_cache_namespace: &str) -> ProviderAttempt {
- ProviderAttempt::cpu_only()
+fn platform_default_attempts(
+ _model_path: &str,
+ _coreml_cache_namespace: &str,
+) -> Vec<ProviderAttempt> {
+ vec![ProviderAttempt::cpu_only()]
}
#[cfg(target_os = "ios")]
@@ -364,6 +406,18 @@ fn xnnpack_provider() -> ExecutionProviderDispatch {
.error_on_failure()
}
+#[cfg(target_os = "android")]
+fn xnnpack_attempt() -> ProviderAttempt {
+ ProviderAttempt {
+ providers: vec![
+ xnnpack_provider(),
+ CPU::default().with_arena_allocator(true).build(),
+ ],
+ disable_intra_op_spinning: true,
+ coreml_cache_dir: None,
+ }
+}
+
fn build_session_with_providers(model_path: &str, attempt: ProviderAttempt) -> MlResult<Session> {
let mut builder = Session::builder()?
.with_optimization_level(GraphOptimizationLevel::All)?
diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rs
index c5e954e126..54194271e7 100644
--- a/rust/crates/photos/src/ml/runtime.rs
+++ b/rust/crates/photos/src/ml/runtime.rs
@@ -52,7 +52,7 @@ pub struct ModelPaths {
#[derive(Debug)]
struct ModelSlotState {
path: String,
- fell_back_to_cpu: bool,
+ fallback_execution_mode: Option<onnx::ExecutionMode>,
pin_count: usize,
session: Option<Session>,
}
@@ -103,7 +103,7 @@ impl ModelSlot {
coreml_cache_namespace,
state: Mutex::new(ModelSlotState {
path: String::new(),
- fell_back_to_cpu: false,
+ fallback_execution_mode: None,
pin_count: 0,
session: None,
}),
@@ -146,21 +146,25 @@ impl ModelSlot {
}
}
- fn force_cpu_fallback_if_configured(&self, path: &str) {
- if self.default_execution_mode == onnx::ExecutionMode::CpuOnly || path.trim().is_empty() {
- return;
+ fn advance_provider_fallback_if_configured(&self, path: &str) -> bool {
+ if path.trim().is_empty() {
+ return false;
}
let mut state = self.lock_state();
if state.path != path {
- return;
- }
- if state.fell_back_to_cpu {
- return;
+ return false;
}
+ let current_mode = state
+ .fallback_execution_mode
+ .unwrap_or(self.default_execution_mode);
+ let Some(fallback_mode) = current_mode.fallback() else {
+ return false;
+ };
- state.fell_back_to_cpu = true;
+ state.fallback_execution_mode = Some(fallback_mode);
state.session = None;
+ true
}
fn session_guard_for(&self, path: &str, error_msg: &str) -> MlResult<ModelSessionGuard<'_>> {
@@ -179,12 +183,12 @@ impl ModelSlot {
return;
}
state.path = path.to_string();
- state.fell_back_to_cpu = false;
+ state.fallback_execution_mode = None;
state.session = None;
}
fn clear_transient_runtime_state_locked(state: &mut ModelSlotState) {
- state.fell_back_to_cpu = false;
+ state.fallback_execution_mode = None;
state.session = None;
}
@@ -194,6 +198,12 @@ impl ModelSlot {
Self::clear_transient_runtime_state_locked(state);
}
+ fn effective_execution_mode(&self, state: &ModelSlotState) -> onnx::ExecutionMode {
+ state
+ .fallback_execution_mode
+ .unwrap_or(self.default_execution_mode)
+ }
+
fn ensure_loaded_locked(&self, state: &mut ModelSlotState, error_msg: &str) -> MlResult<()> {
if state.path.trim().is_empty() {
return Err(MlError::InvalidRequest(error_msg.to_string()));
@@ -202,14 +212,12 @@ impl ModelSlot {
return Ok(());
}
+ let execution_mode = self.effective_execution_mode(state);
let model_name = state.path.rsplit('/').next().unwrap_or(&state.path);
- rt_log(&format!("loading {model_name}"));
+ rt_log(&format!(
+ "loading {model_name} with {execution_mode:?} execution"
+ ));
let t = std::time::Instant::now();
- let execution_mode = if state.fell_back_to_cpu {
- onnx::ExecutionMode::CpuOnly
- } else {
- self.default_execution_mode
- };
let session =
onnx::build_session(&state.path, execution_mode, self.coreml_cache_namespace)?;
rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));
@@ -237,23 +245,24 @@ static GLOBAL_RUNTIME: Lazy<MlRuntime> = Lazy::new(MlRuntime::new);
impl MlRuntime {
fn new() -> Self {
let platform_default = onnx::ExecutionMode::PlatformDefault;
- let cpu_only = onnx::ExecutionMode::CpuOnly;
+ #[cfg(target_os = "android")]
+ let pet_default = platform_default;
+ #[cfg(not(target_os = "android"))]
+ let pet_default = 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"),
- // Pet models previously had device-specific FP16 driver failures.
- // TODO: Benchmark every pet model with the platform-default providers
- // on supported iOS and Android devices before release, then remove
- // this CPU-only exception if parity and stability are preserved.
- 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"),
+ // 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"),
}
}
@@ -313,27 +322,39 @@ impl MlRuntime {
self.pet_body_embedding_cat.release_residency();
}
- fn force_cpu_only_for_requested_models(&self, model_paths: &ModelPaths) {
- self.face_detection
- .force_cpu_fallback_if_configured(&model_paths.face_detection);
- self.face_embedding
- .force_cpu_fallback_if_configured(&model_paths.face_embedding);
- self.clip_image
- .force_cpu_fallback_if_configured(&model_paths.clip_image);
- self.clip_text
- .force_cpu_fallback_if_configured(&model_paths.clip_text);
- self.pet_face_detection
- .force_cpu_fallback_if_configured(&model_paths.pet_face_detection);
- self.pet_face_embedding_dog
- .force_cpu_fallback_if_configured(&model_paths.pet_face_embedding_dog);
- self.pet_face_embedding_cat
- .force_cpu_fallback_if_configured(&model_paths.pet_face_embedding_cat);
- self.pet_body_detection
- .force_cpu_fallback_if_configured(&model_paths.pet_body_detection);
- self.pet_body_embedding_dog
- .force_cpu_fallback_if_configured(&model_paths.pet_body_embedding_dog);
- self.pet_body_embedding_cat
- .force_cpu_fallback_if_configured(&model_paths.pet_body_embedding_cat);
+ fn advance_provider_fallbacks_for_requested_models(&self, model_paths: &ModelPaths) -> bool {
+ let mut advanced = false;
+ advanced |= self
+ .face_detection
+ .advance_provider_fallback_if_configured(&model_paths.face_detection);
+ advanced |= self
+ .face_embedding
+ .advance_provider_fallback_if_configured(&model_paths.face_embedding);
+ advanced |= self
+ .clip_image
+ .advance_provider_fallback_if_configured(&model_paths.clip_image);
+ advanced |= self
+ .clip_text
+ .advance_provider_fallback_if_configured(&model_paths.clip_text);
+ advanced |= self
+ .pet_face_detection
+ .advance_provider_fallback_if_configured(&model_paths.pet_face_detection);
+ advanced |= self
+ .pet_face_embedding_dog
+ .advance_provider_fallback_if_configured(&model_paths.pet_face_embedding_dog);
+ advanced |= self
+ .pet_face_embedding_cat
+ .advance_provider_fallback_if_configured(&model_paths.pet_face_embedding_cat);
+ advanced |= self
+ .pet_body_detection
+ .advance_provider_fallback_if_configured(&model_paths.pet_body_detection);
+ advanced |= self
+ .pet_body_embedding_dog
+ .advance_provider_fallback_if_configured(&model_paths.pet_body_embedding_dog);
+ advanced |= self
+ .pet_body_embedding_cat
+ .advance_provider_fallback_if_configured(&model_paths.pet_body_embedding_cat);
+ advanced
}
fn view<'a>(&'a self, model_paths: &'a ModelPaths) -> MlRuntimeView<'a> {
@@ -431,20 +452,22 @@ where
ensure_runtime(model_paths);
let runtime_view = GLOBAL_RUNTIME.view(model_paths);
- let first_result = func(&runtime_view);
- match first_result {
- Ok(result) => Ok(result),
- Err(first_error) => {
- if !should_retry_with_cpu_only_runtime(&first_error) {
- return Err(first_error);
+ let mut result = func(&runtime_view);
+ loop {
+ match result {
+ Ok(value) => return Ok(value),
+ Err(error) => {
+ if !should_retry_execution_provider_runtime(&error)
+ || !GLOBAL_RUNTIME.advance_provider_fallbacks_for_requested_models(model_paths)
+ {
+ return Err(error);
+ }
+
+ rt_log(&format!(
+ "execution provider failed, retrying with the next provider fallback: {error}"
+ ));
+ result = func(&runtime_view);
}
-
- rt_log(&format!(
- "execution provider failed, retrying with CPU-only runtime: {first_error}"
- ));
- GLOBAL_RUNTIME.force_cpu_only_for_requested_models(model_paths);
- let runtime_view = GLOBAL_RUNTIME.view(model_paths);
- func(&runtime_view)
}
}
}
@@ -453,7 +476,7 @@ pub(crate) fn release_runtime() {
GLOBAL_RUNTIME.release_indexing_models();
}
-fn should_retry_with_cpu_only_runtime(error: &MlError) -> bool {
+fn should_retry_execution_provider_runtime(error: &MlError) -> bool {
cfg!(any(target_os = "ios", target_os = "android")) && is_execution_provider_failure(error)
}
@@ -466,6 +489,11 @@ fn is_execution_provider_failure(error: &MlError) -> bool {
|| normalized.contains("unknown allocation device")
|| normalized.contains("xnnpackexecutionprovider")
|| normalized.contains("coremlexecutionprovider")
+ || normalized.contains("webgpu")
+ || normalized.contains("wgpu")
+ || normalized.contains("dawn")
+ || normalized.contains("vulkan")
+ || normalized.contains("vk_error")
|| normalized.contains("ep error")
}
@@ -514,13 +542,13 @@ mod tests {
let mut clip_text = runtime.clip_text.lock_state();
clip_text.path = "clip_text.onnx".to_string();
clip_text.pin_count = 0;
- clip_text.fell_back_to_cpu = true;
+ clip_text.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
}
{
let mut face_detection = runtime.face_detection.lock_state();
face_detection.path = "face.onnx".to_string();
face_detection.pin_count = 1;
- face_detection.fell_back_to_cpu = true;
+ face_detection.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
}
runtime.release_indexing_models();
@@ -528,11 +556,14 @@ mod tests {
let clip_text = runtime.clip_text.lock_state();
assert_eq!(clip_text.path, "clip_text.onnx");
assert_eq!(clip_text.pin_count, 0);
- assert!(clip_text.fell_back_to_cpu);
+ assert_eq!(
+ clip_text.fallback_execution_mode,
+ Some(onnx::ExecutionMode::CpuOnly)
+ );
let face_detection = runtime.face_detection.lock_state();
assert_eq!(face_detection.pin_count, 0);
- assert!(!face_detection.fell_back_to_cpu);
+ assert_eq!(face_detection.fallback_execution_mode, None);
}
#[test]
@@ -567,7 +598,7 @@ mod tests {
let mut state = slot.lock_state();
state.path = "pet.onnx".to_string();
state.pin_count = 1;
- state.fell_back_to_cpu = true;
+ state.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
}
slot.sync_indexing_residency("");
@@ -575,7 +606,7 @@ mod tests {
let state = slot.lock_state();
assert!(state.path.is_empty());
assert_eq!(state.pin_count, 0);
- assert!(!state.fell_back_to_cpu);
+ assert_eq!(state.fallback_execution_mode, None);
assert!(state.session.is_none());
}
@@ -587,20 +618,45 @@ mod tests {
let mut state = slot.lock_state();
state.path = "clip_text.onnx".to_string();
state.pin_count = 1;
- state.fell_back_to_cpu = true;
+ state.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
}
slot.release_residency();
let state = slot.lock_state();
assert_eq!(state.pin_count, 0);
- assert!(!state.fell_back_to_cpu);
+ assert_eq!(state.fallback_execution_mode, None);
assert!(state.session.is_none());
}
#[test]
- fn only_pet_models_default_to_cpu_only() {
+ fn execution_provider_fallback_order_matches_platform_policy() {
+ #[cfg(target_os = "android")]
+ {
+ assert_eq!(
+ onnx::ExecutionMode::PlatformDefault.fallback(),
+ Some(onnx::ExecutionMode::Xnnpack)
+ );
+ assert_eq!(
+ onnx::ExecutionMode::Xnnpack.fallback(),
+ Some(onnx::ExecutionMode::CpuOnly)
+ );
+ }
+ #[cfg(not(target_os = "android"))]
+ assert_eq!(
+ onnx::ExecutionMode::PlatformDefault.fallback(),
+ Some(onnx::ExecutionMode::CpuOnly)
+ );
+ assert_eq!(onnx::ExecutionMode::CpuOnly.fallback(), None);
+ }
+
+ #[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"))]
+ let expected_pet_mode = onnx::ExecutionMode::CpuOnly;
assert_eq!(
runtime.face_detection.default_execution_mode,
@@ -620,27 +676,27 @@ mod tests {
);
assert_eq!(
runtime.pet_face_detection.default_execution_mode,
- onnx::ExecutionMode::CpuOnly
+ expected_pet_mode
);
assert_eq!(
runtime.pet_face_embedding_dog.default_execution_mode,
- onnx::ExecutionMode::CpuOnly
+ expected_pet_mode
);
assert_eq!(
runtime.pet_face_embedding_cat.default_execution_mode,
- onnx::ExecutionMode::CpuOnly
+ expected_pet_mode
);
assert_eq!(
runtime.pet_body_detection.default_execution_mode,
- onnx::ExecutionMode::CpuOnly
+ expected_pet_mode
);
assert_eq!(
runtime.pet_body_embedding_dog.default_execution_mode,
- onnx::ExecutionMode::CpuOnly
+ expected_pet_mode
);
assert_eq!(
runtime.pet_body_embedding_cat.default_execution_mode,
- onnx::ExecutionMode::CpuOnly
+ expected_pet_mode
);
}
}