Skip to content

armgit / ente

Public Imported from GitHub
0

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

Unify ONNX provider fallback state

laurenspriem32558d394d27
diff --git a/rust/crates/photos/src/ml/golden_tooling.rs b/rust/crates/photos/src/ml/golden_tooling.rs
index 1e0adc95d1..a83537ae80 100644
--- a/rust/crates/photos/src/ml/golden_tooling.rs
+++ b/rust/crates/photos/src/ml/golden_tooling.rs
@@ -198,8 +198,8 @@ fn model_file_name(model_path: &str) -> Result<&str, String> {
}
fn build_cpu_session(model_path: &str) -> Result<ort::session::Session, String> {
- onnx::build_session(model_path, onnx::ExecutionMode::CpuOnly, "golden-tooling")
- .map(|(session, _)| session)
+ let mut plan = onnx::ProviderPlan::new(onnx::ExecutionMode::CpuOnly, model_path);
+ onnx::build_session(model_path, &mut plan, "golden-tooling")
.map_err(|error| format!("building CPU session for '{model_path}': {error}"))
}
diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rs
index e494839557..fe676a7e7c 100644
--- a/rust/crates/photos/src/ml/onnx.rs
+++ b/rust/crates/photos/src/ml/onnx.rs
@@ -2,7 +2,10 @@ use ort::{
ep::{CPU, ExecutionProviderDispatch},
session::{Session, builder::GraphOptimizationLevel},
};
-use std::path::{Path, PathBuf};
+use std::{
+ fmt,
+ path::{Path, PathBuf},
+};
#[cfg(target_os = "android")]
use ort::ep::XNNPACK;
@@ -38,8 +41,6 @@ const ENABLE_PERSISTENT_COREML_CACHE: bool = true;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExecutionMode {
PlatformDefault,
- #[cfg(target_os = "android")]
- Xnnpack,
CpuOnly,
}
@@ -54,35 +55,123 @@ pub(crate) enum ExecutionProvider {
Cpu,
}
-impl ExecutionMode {
- pub(crate) fn fallback(self) -> Option<Self> {
+#[derive(Debug)]
+pub(crate) struct ProviderPlan {
+ providers: Vec<ExecutionProvider>,
+ next: usize,
+ selected: Option<ExecutionProvider>,
+}
+
+impl ProviderPlan {
+ pub(crate) fn new(mode: ExecutionMode, model_path: &str) -> Self {
+ let providers = match mode {
+ ExecutionMode::PlatformDefault => platform_default_providers(model_path),
+ ExecutionMode::CpuOnly => vec![ExecutionProvider::Cpu],
+ };
+ Self {
+ providers,
+ next: 0,
+ selected: None,
+ }
+ }
+
+ fn next_provider(&mut self) -> Option<ExecutionProvider> {
+ let provider = self.providers.get(self.next).copied()?;
+ self.next += 1;
+ Some(provider)
+ }
+
+ fn select(&mut self, provider: ExecutionProvider) {
+ self.selected = Some(provider);
+ }
+
+ pub(crate) fn selected_provider(&self) -> Option<ExecutionProvider> {
+ self.selected
+ }
+
+ pub(crate) fn has_fallback(&self) -> bool {
+ self.next < self.providers.len()
+ }
+
+ fn retain_last_provider_for_retry(&mut self) {
+ self.selected = None;
+ self.next = self.providers.len().saturating_sub(1);
+ }
+}
+
+#[derive(Debug)]
+pub(crate) enum SessionRunError {
+ Retryable(MlError),
+ Terminal(MlError),
+}
+
+pub(crate) type SessionRunResult<T> = Result<T, SessionRunError>;
+
+impl SessionRunError {
+ pub(crate) fn retryable(error: MlError) -> Self {
+ Self::Retryable(error)
+ }
+
+ pub(crate) fn is_retryable(&self) -> bool {
+ matches!(self, Self::Retryable(_))
+ }
+
+ pub(crate) fn into_ml_error(self) -> MlError {
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,
+ Self::Retryable(error) | Self::Terminal(error) => error,
+ }
+ }
+}
+
+impl fmt::Display for SessionRunError {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Retryable(error) | Self::Terminal(error) => error.fmt(formatter),
+ }
+ }
+}
+
+impl From<MlError> for SessionRunError {
+ fn from(error: MlError) -> Self {
+ Self::Terminal(error)
+ }
+}
+
+impl From<SessionRunError> for MlError {
+ fn from(error: SessionRunError) -> Self {
+ error.into_ml_error()
+ }
+}
+
+impl<R> From<ort::Error<R>> for SessionRunError {
+ fn from(error: ort::Error<R>) -> Self {
+ let error = MlError::Ort(error.to_string());
+ if is_execution_provider_run_failure(&error) {
+ Self::Retryable(error)
+ } else {
+ Self::Terminal(error)
}
}
}
pub(crate) fn build_session(
model_path: &str,
- mode: ExecutionMode,
+ plan: &mut ProviderPlan,
model_namespace: &str,
-) -> MlResult<(Session, ExecutionProvider)> {
- let attempts = provider_attempts(mode, model_path, model_namespace);
+) -> MlResult<Session> {
+ plan.selected = None;
let mut errors = Vec::new();
- for attempt in attempts {
- let execution_provider = attempt.execution_provider;
+ while let Some(execution_provider) = plan.next_provider() {
+ let attempt = provider_attempt(execution_provider, model_path, model_namespace);
if attempt.uses_webgpu {
#[cfg(any(target_os = "android", target_os = "linux", target_os = "windows"))]
{
match build_webgpu_session_with_canary(model_path, model_namespace, attempt) {
- Ok(session) => return Ok((session, execution_provider)),
+ Ok(session) => {
+ plan.select(execution_provider);
+ return Ok(session);
+ }
Err(error) => errors.push(format!("{error}")),
}
continue;
@@ -97,7 +186,8 @@ pub(crate) fn build_session(
if let Some(cache_dir) = coreml_cache_dir {
coreml_cache::finalize(&cache_dir, model_path);
}
- return Ok((session, execution_provider));
+ plan.select(execution_provider);
+ return Ok(session);
}
Err(error) => {
if let Some(cache_dir) = coreml_cache_dir
@@ -113,6 +203,8 @@ pub(crate) fn build_session(
}
}
+ plan.retain_last_provider_for_retry();
+
if has_protobuf_parse_failure(&errors) {
return Err(MlError::CorruptModel(model_path.to_string()));
}
@@ -123,6 +215,23 @@ pub(crate) fn build_session(
)))
}
+fn is_execution_provider_run_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("coremlexecutionprovider")
+ || normalized.contains("webgpu")
+ || normalized.contains("wgpu")
+ || normalized.contains("dawn")
+ || normalized.contains("vulkan")
+ || normalized.contains("vk_error")
+ || normalized.contains("ep error")
+}
+
// A CoreML self-test failure is treated as construction failure so the caller
// invalidates the possibly corrupt persistent cache. WebGPU validation stays
// inside its crash-canary window instead.
@@ -306,7 +415,7 @@ fn run_session_self_test(
"{provider_label} zero-input warm-up inference failed for '{model_file}': \
{error}; falling back to the next execution provider"
);
- return Err(error);
+ return Err(error.into());
}
};
if let Err(reason) = golden::validate_output(entry, &zero_output) {
@@ -330,7 +439,7 @@ fn run_session_self_test(
"{provider_label} golden self-test inference failed for '{model_file}': \
{error}; falling back to the next execution provider"
);
- return Err(error);
+ return Err(error.into());
}
};
match golden::compare_output(entry, &golden_output) {
@@ -389,37 +498,51 @@ impl ProviderAttempt {
}
}
-fn provider_attempts(
- mode: ExecutionMode,
- model_path: &str,
- model_namespace: &str,
-) -> Vec<ProviderAttempt> {
- match mode {
- ExecutionMode::PlatformDefault => platform_default_attempts(model_path, model_namespace),
+fn provider_attempt(
+ provider: ExecutionProvider,
+ _model_path: &str,
+ _model_namespace: &str,
+) -> ProviderAttempt {
+ match provider {
+ ExecutionProvider::Cpu => ProviderAttempt::cpu_only(),
+ #[cfg(any(target_os = "ios", target_os = "macos"))]
+ ExecutionProvider::CoreMl => {
+ let (coreml_provider, coreml_cache_dir) =
+ coreml_provider(_model_path, _model_namespace);
+ ProviderAttempt {
+ providers: vec![
+ coreml_provider,
+ CPU::default().with_arena_allocator(true).build(),
+ ],
+ disable_intra_op_spinning: false,
+ coreml_cache_dir,
+ uses_webgpu: false,
+ execution_provider: ExecutionProvider::CoreMl,
+ }
+ }
+ #[cfg(any(target_os = "android", target_os = "linux", target_os = "windows"))]
+ ExecutionProvider::WebGpu => ProviderAttempt {
+ providers: webgpu_attempt_providers(),
+ disable_intra_op_spinning: true,
+ coreml_cache_dir: None,
+ uses_webgpu: true,
+ execution_provider: ExecutionProvider::WebGpu,
+ },
#[cfg(target_os = "android")]
- ExecutionMode::Xnnpack => vec![xnnpack_attempt(), ProviderAttempt::cpu_only()],
- ExecutionMode::CpuOnly => vec![ProviderAttempt::cpu_only()],
+ ExecutionProvider::Xnnpack => xnnpack_attempt(),
+ #[allow(unreachable_patterns)]
+ _ => unreachable!("provider is not available on this platform"),
}
}
#[cfg(any(target_os = "ios", target_os = "macos"))]
-fn platform_default_attempts(model_path: &str, model_namespace: &str) -> Vec<ProviderAttempt> {
- let mut attempts = Vec::new();
+fn platform_default_providers(model_path: &str) -> Vec<ExecutionProvider> {
+ let mut providers = Vec::new();
if golden_entry_required(model_path, "CoreML") {
- let (coreml_provider, coreml_cache_dir) = coreml_provider(model_path, model_namespace);
- attempts.push(ProviderAttempt {
- providers: vec![
- coreml_provider,
- CPU::default().with_arena_allocator(true).build(),
- ],
- disable_intra_op_spinning: false,
- coreml_cache_dir,
- uses_webgpu: false,
- execution_provider: ExecutionProvider::CoreMl,
- });
+ providers.push(ExecutionProvider::CoreMl);
}
- attempts.push(ProviderAttempt::cpu_only());
- attempts
+ providers.push(ExecutionProvider::Cpu);
+ providers
}
#[cfg(any(target_os = "ios", target_os = "macos"))]
@@ -454,45 +577,24 @@ fn coreml_provider(
}
#[cfg(target_os = "android")]
-fn platform_default_attempts(model_path: &str, _model_namespace: &str) -> Vec<ProviderAttempt> {
- let mut attempts = Vec::new();
+fn platform_default_providers(model_path: &str) -> Vec<ExecutionProvider> {
+ let mut providers = Vec::new();
if webgpu::attempt_permitted(model_path) && golden_entry_required(model_path, "WebGPU") {
- attempts.push(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,
- uses_webgpu: true,
- execution_provider: ExecutionProvider::WebGpu,
- });
+ providers.push(ExecutionProvider::WebGpu);
}
- attempts.push(xnnpack_attempt());
- attempts.push(ProviderAttempt::cpu_only());
- attempts
+ providers.push(ExecutionProvider::Xnnpack);
+ providers.push(ExecutionProvider::Cpu);
+ providers
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
-fn platform_default_attempts(model_path: &str, _model_namespace: &str) -> Vec<ProviderAttempt> {
- let mut attempts = Vec::new();
+fn platform_default_providers(model_path: &str) -> Vec<ExecutionProvider> {
+ let mut providers = Vec::new();
if webgpu::attempt_permitted(model_path) && golden_entry_required(model_path, "WebGPU") {
- attempts.push(ProviderAttempt {
- providers: vec![
- webgpu_provider(),
- CPU::default().with_arena_allocator(true).build(),
- ],
- disable_intra_op_spinning: true,
- coreml_cache_dir: None,
- uses_webgpu: true,
- execution_provider: ExecutionProvider::WebGpu,
- });
+ providers.push(ExecutionProvider::WebGpu);
}
- attempts.push(ProviderAttempt::cpu_only());
- attempts
+ providers.push(ExecutionProvider::Cpu);
+ providers
}
// Missing goldens fail closed, usually indicating they were not regenerated
@@ -525,6 +627,23 @@ fn webgpu_provider() -> ExecutionProviderDispatch {
provider.build().error_on_failure()
}
+#[cfg(target_os = "android")]
+fn webgpu_attempt_providers() -> Vec<ExecutionProviderDispatch> {
+ vec![
+ webgpu_provider(),
+ xnnpack_provider().fail_silently(),
+ CPU::default().with_arena_allocator(true).build(),
+ ]
+}
+
+#[cfg(any(target_os = "linux", target_os = "windows"))]
+fn webgpu_attempt_providers() -> Vec<ExecutionProviderDispatch> {
+ vec![
+ webgpu_provider(),
+ CPU::default().with_arena_allocator(true).build(),
+ ]
+}
+
#[cfg(not(any(
target_os = "ios",
target_os = "android",
@@ -532,8 +651,8 @@ fn webgpu_provider() -> ExecutionProviderDispatch {
target_os = "macos",
target_os = "windows"
)))]
-fn platform_default_attempts(_model_path: &str, _model_namespace: &str) -> Vec<ProviderAttempt> {
- vec![ProviderAttempt::cpu_only()]
+fn platform_default_providers(_model_path: &str) -> Vec<ExecutionProvider> {
+ vec![ExecutionProvider::Cpu]
}
#[cfg(target_os = "android")]
@@ -575,7 +694,78 @@ fn build_session_with_providers(model_path: &str, attempt: ProviderAttempt) -> M
#[cfg(test)]
mod tests {
- use super::{ExecutionProvider, has_protobuf_parse_failure, provider_attempt_failure_message};
+ use super::{
+ ExecutionMode, ExecutionProvider, ProviderPlan, has_protobuf_parse_failure,
+ is_execution_provider_run_failure, provider_attempt_failure_message,
+ };
+
+ #[test]
+ fn provider_plan_resumes_after_the_concrete_selected_provider() {
+ let mut plan = ProviderPlan {
+ providers: vec![
+ ExecutionProvider::WebGpu,
+ ExecutionProvider::Xnnpack,
+ ExecutionProvider::Cpu,
+ ],
+ next: 0,
+ selected: None,
+ };
+
+ assert_eq!(plan.next_provider(), Some(ExecutionProvider::WebGpu));
+ assert_eq!(plan.next_provider(), Some(ExecutionProvider::Xnnpack));
+ plan.select(ExecutionProvider::Xnnpack);
+
+ assert_eq!(plan.selected_provider(), Some(ExecutionProvider::Xnnpack));
+ assert!(plan.has_fallback());
+ assert_eq!(plan.next_provider(), Some(ExecutionProvider::Cpu));
+ assert!(!plan.has_fallback());
+ }
+
+ #[test]
+ fn cpu_only_provider_plan_is_bounded() {
+ let mut plan = ProviderPlan::new(ExecutionMode::CpuOnly, "model.onnx");
+
+ assert_eq!(plan.next_provider(), Some(ExecutionProvider::Cpu));
+ assert_eq!(plan.next_provider(), None);
+ assert!(!plan.has_fallback());
+ }
+
+ #[test]
+ fn exhausted_provider_plan_retries_only_the_final_provider() {
+ let mut plan = ProviderPlan {
+ providers: vec![
+ ExecutionProvider::WebGpu,
+ ExecutionProvider::Xnnpack,
+ ExecutionProvider::Cpu,
+ ],
+ next: 0,
+ selected: None,
+ };
+
+ while plan.next_provider().is_some() {}
+ plan.retain_last_provider_for_retry();
+
+ assert_eq!(plan.next_provider(), Some(ExecutionProvider::Cpu));
+ assert_eq!(plan.next_provider(), None);
+ }
+
+ #[test]
+ fn classifies_only_provider_related_ort_run_failures_as_retryable() {
+ assert!(is_execution_provider_run_failure(&super::MlError::Ort(
+ "WebGPU EP error: VK_ERROR_DEVICE_LOST".to_string()
+ )));
+ assert!(!is_execution_provider_run_failure(&super::MlError::Ort(
+ "invalid tensor shape".to_string()
+ )));
+ assert!(!is_execution_provider_run_failure(
+ &super::MlError::Postprocess("WebGPU".to_string())
+ ));
+
+ let terminal = super::SessionRunError::from(super::MlError::Ort(
+ "WebGPU text from a typed terminal error".to_string(),
+ ));
+ assert!(!terminal.is_retryable());
+ }
#[test]
fn detects_protobuf_parse_failure() {
diff --git a/rust/crates/photos/src/ml/onnx/tensor.rs b/rust/crates/photos/src/ml/onnx/tensor.rs
index 54ea445059..0d9d1893eb 100644
--- a/rust/crates/photos/src/ml/onnx/tensor.rs
+++ b/rust/crates/photos/src/ml/onnx/tensor.rs
@@ -11,6 +11,8 @@ use crate::ml::{
golden,
};
+use super::{SessionRunError, SessionRunResult};
+
pub(crate) struct PreparedF32Input {
f32_data: Vec<f32>,
f16_data: OnceCell<Vec<half::f16>>,
@@ -67,7 +69,7 @@ pub(crate) fn run_golden_tensor(
session: &mut Session,
input_shape: &[i64],
input: &golden::PreparedGoldenInput,
-) -> MlResult<Vec<f32>> {
+) -> SessionRunResult<Vec<f32>> {
let outputs = match input {
golden::PreparedGoldenInput::F32(data) => {
if session_expects_f16(session) {
@@ -89,7 +91,7 @@ pub(crate) fn run_golden_tensor(
};
if outputs.len() == 0 {
- return Err(MlError::Ort("missing first output tensor".to_string()));
+ return Err(MlError::Ort("missing first output tensor".to_string()).into());
}
let output = &outputs[0];
if let Ok((_, tensor_data)) = output.try_extract_tensor::<f32>() {
@@ -102,23 +104,22 @@ pub(crate) fn run_golden_tensor(
}
}
-fn ensure_finite_f32(data: &[f32]) -> MlResult<()> {
+fn ensure_finite_f32(data: &[f32]) -> SessionRunResult<()> {
if data.iter().copied().all(f32::is_finite) {
return Ok(());
}
- // Runtime classifies this message as a retryable provider failure.
- Err(MlError::Ort(
+ Err(SessionRunError::retryable(MlError::Ort(
"model produced non-finite output values".to_string(),
- ))
+ )))
}
-fn ensure_finite_f16(data: &[half::f16]) -> MlResult<()> {
+fn ensure_finite_f16(data: &[half::f16]) -> SessionRunResult<()> {
if data.iter().all(|value| value.is_finite()) {
return Ok(());
}
- Err(MlError::Ort(
+ Err(SessionRunError::retryable(MlError::Ort(
"model produced non-finite output values".to_string(),
- ))
+ )))
}
fn session_expects_f16(session: &Session) -> bool {
@@ -136,7 +137,7 @@ pub(crate) fn run_f32<const N: usize>(
session: &mut Session,
input: &PreparedF32Input,
input_shape: [i64; N],
-) -> MlResult<(Vec<i64>, Vec<f32>)> {
+) -> SessionRunResult<(Vec<i64>, Vec<f32>)> {
let outputs = if session_expects_f16(session) {
let input_tensor =
TensorRef::<half::f16>::from_array_view((input_shape, input.f16_data()))?;
@@ -148,7 +149,7 @@ pub(crate) fn run_f32<const N: usize>(
};
if outputs.len() == 0 {
- return Err(MlError::Ort("missing first output tensor".to_string()));
+ return Err(MlError::Ort("missing first output tensor".to_string()).into());
}
let output = &outputs[0];
@@ -172,7 +173,7 @@ pub(crate) fn with_prepared_float_output<const N: usize, T>(
input: &PreparedF32Input,
input_shape: [i64; N],
consume: impl FnOnce(&[i64], BorrowedFloatTensor<'_>) -> MlResult<T>,
-) -> MlResult<T> {
+) -> SessionRunResult<T> {
let outputs = if session_expects_f16(session) {
let input_tensor =
TensorRef::<half::f16>::from_array_view((input_shape, input.f16_data()))?;
@@ -184,16 +185,16 @@ pub(crate) fn with_prepared_float_output<const N: usize, T>(
};
if outputs.len() == 0 {
- return Err(MlError::Ort("missing first output tensor".to_string()));
+ return Err(MlError::Ort("missing first output tensor".to_string()).into());
}
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))
+ consume(tensor_shape, BorrowedFloatTensor::F32(tensor_data)).map_err(Into::into)
} else {
let (tensor_shape, tensor_data) = output.try_extract_tensor::<half::f16>()?;
ensure_finite_f16(tensor_data)?;
- consume(tensor_shape, BorrowedFloatTensor::F16(tensor_data))
+ consume(tensor_shape, BorrowedFloatTensor::F16(tensor_data)).map_err(Into::into)
}
}
@@ -201,11 +202,11 @@ pub(crate) fn run_i32_f32<const N: usize>(
session: &mut Session,
input: &[i32],
input_shape: [i64; N],
-) -> MlResult<(Vec<i64>, Vec<f32>)> {
+) -> SessionRunResult<(Vec<i64>, Vec<f32>)> {
let input_tensor = TensorRef::<i32>::from_array_view((input_shape, input))?;
let outputs = session.run(ort::inputs![input_tensor])?;
if outputs.len() == 0 {
- return Err(MlError::Ort("missing first output tensor".to_string()));
+ return Err(MlError::Ort("missing first output tensor".to_string()).into());
}
let output = &outputs[0];
let (tensor_shape, tensor_data) = output.try_extract_tensor::<f32>()?;
@@ -230,8 +231,10 @@ mod tests {
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"));
+ assert!(error.is_retryable());
}
let error = ensure_finite_f16(&[half::f16::NAN]).unwrap_err();
assert!(error.to_string().contains("non-finite"));
+ assert!(error.is_retryable());
}
}
diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rs
index 599ee46939..6ac9ecfdf9 100644
--- a/rust/crates/photos/src/ml/runtime.rs
+++ b/rust/crates/photos/src/ml/runtime.rs
@@ -26,17 +26,11 @@ pub struct ModelPaths {
pub pet_body_embedding_cat: String,
}
-#[derive(Debug)]
-struct LoadedSession {
- session: Session,
- execution_provider: onnx::ExecutionProvider,
-}
-
#[derive(Debug)]
struct ModelSlotState {
path: String,
- fallback_execution_mode: Option<onnx::ExecutionMode>,
- loaded: Option<LoadedSession>,
+ provider_plan: Option<onnx::ProviderPlan>,
+ session: Option<Session>,
}
#[derive(Debug)]
@@ -75,8 +69,8 @@ impl ModelSlot {
model_namespace,
state: Mutex::new(ModelSlotState {
path: String::new(),
- fallback_execution_mode: None,
- loaded: None,
+ provider_plan: None,
+ session: None,
}),
}
}
@@ -111,24 +105,11 @@ impl ModelSlot {
Self::clear_transient_runtime_state_locked(&mut state);
}
- fn advance_provider_fallback_locked(&self, state: &mut ModelSlotState) -> bool {
- let current_mode = state
- .fallback_execution_mode
- .unwrap_or(self.default_execution_mode);
- let Some(fallback_mode) = current_mode.fallback() else {
- return false;
- };
-
- state.fallback_execution_mode = Some(fallback_mode);
- state.loaded = None;
- true
- }
-
fn run<T>(
&self,
path: &str,
error_msg: &str,
- mut operation: impl FnMut(&mut Session) -> MlResult<T>,
+ mut operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<(T, onnx::ExecutionProvider)> {
if path.trim().is_empty() {
return Err(MlError::InvalidRequest(error_msg.to_string()));
@@ -137,26 +118,25 @@ impl ModelSlot {
loop {
let mut state = self.lock_state();
Self::set_config_locked(&mut state, path);
- if let Err(error) = self.ensure_loaded_locked(&mut state, error_msg) {
- if self.retry_after_provider_failure_locked(&mut state, &error) {
- continue;
- }
- return Err(error);
- }
-
- let loaded = state
- .loaded
+ self.ensure_loaded_locked(&mut state, error_msg)?;
+
+ let execution_provider = state
+ .provider_plan
+ .as_ref()
+ .and_then(onnx::ProviderPlan::selected_provider)
+ .expect("loaded session must have a selected execution provider");
+ let session = state
+ .session
.as_mut()
.expect("session must be loaded before model execution");
- let execution_provider = loaded.execution_provider;
- let result = operation(&mut loaded.session);
+ let result = operation(session);
match result {
Ok(value) => return Ok((value, execution_provider)),
Err(error) => {
if self.retry_after_provider_failure_locked(&mut state, &error) {
continue;
}
- return Err(error);
+ return Err(error.into_ml_error());
}
}
}
@@ -165,14 +145,18 @@ impl ModelSlot {
fn retry_after_provider_failure_locked(
&self,
state: &mut ModelSlotState,
- error: &MlError,
+ error: &onnx::SessionRunError,
) -> bool {
- if !should_retry_execution_provider_runtime(error)
- || !self.advance_provider_fallback_locked(state)
+ if !error.is_retryable()
+ || !state
+ .provider_plan
+ .as_ref()
+ .is_some_and(onnx::ProviderPlan::has_fallback)
{
return false;
}
+ state.session = None;
log::warn!(
"execution provider failed, retrying model with the next provider fallback: {error}"
);
@@ -184,13 +168,13 @@ impl ModelSlot {
return;
}
state.path = path.to_string();
- state.fallback_execution_mode = None;
- state.loaded = None;
+ state.provider_plan = None;
+ state.session = None;
}
fn clear_transient_runtime_state_locked(state: &mut ModelSlotState) {
- state.fallback_execution_mode = None;
- state.loaded = None;
+ state.provider_plan = None;
+ state.session = None;
}
fn reset_slot_locked(state: &mut ModelSlotState) {
@@ -198,34 +182,35 @@ 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()));
}
- if state.loaded.is_some() {
+ if state.session.is_some() {
return Ok(());
}
- let execution_mode = self.effective_execution_mode(state);
+ let provider_plan = state.provider_plan.get_or_insert_with(|| {
+ onnx::ProviderPlan::new(self.default_execution_mode, &state.path)
+ });
let model_name = Path::new(&state.path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(&state.path);
- log::info!("loading {model_name} with {execution_mode:?} execution");
+ log::info!(
+ "loading {model_name} with {:?} execution",
+ self.default_execution_mode
+ );
let t = std::time::Instant::now();
- let (session, execution_provider) =
- onnx::build_session(&state.path, execution_mode, self.model_namespace)?;
- log::info!("loaded {model_name} in {:?}", t.elapsed());
- state.loaded = Some(LoadedSession {
- session,
- execution_provider,
- });
+ let session = onnx::build_session(&state.path, provider_plan, self.model_namespace)?;
+ let execution_provider = provider_plan
+ .selected_provider()
+ .expect("successful session build must select an execution provider");
+ log::info!(
+ "loaded {model_name} with {execution_provider:?} in {:?}",
+ t.elapsed()
+ );
+ state.session = Some(session);
Ok(())
}
}
@@ -344,7 +329,7 @@ impl<'a> MlRuntimeView<'a> {
slot: &ModelSlot,
path: &str,
error_msg: &str,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
let (value, execution_provider) = slot.run(path, error_msg, operation)?;
let mut used = self.used_providers.get();
@@ -355,7 +340,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_face_detection_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.face_detection,
@@ -367,7 +352,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_face_embedding_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.face_embedding,
@@ -379,7 +364,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_clip_image_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.clip_image,
@@ -391,7 +376,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_clip_text_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.clip_text,
@@ -403,7 +388,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_pet_face_detection_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.pet_face_detection,
@@ -415,7 +400,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_pet_face_embedding_dog_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.pet_face_embedding_dog,
@@ -427,7 +412,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_pet_face_embedding_cat_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.pet_face_embedding_cat,
@@ -439,7 +424,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_pet_body_detection_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.pet_body_detection,
@@ -451,7 +436,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_pet_body_embedding_dog_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.pet_body_embedding_dog,
@@ -463,7 +448,7 @@ impl<'a> MlRuntimeView<'a> {
pub(crate) fn with_pet_body_embedding_cat_session<T>(
&self,
- operation: impl FnMut(&mut Session) -> MlResult<T>,
+ operation: impl FnMut(&mut Session) -> onnx::SessionRunResult<T>,
) -> MlResult<T> {
self.run_tracked(
&self.runtime.pet_body_embedding_cat,
@@ -496,34 +481,6 @@ pub(crate) fn release_runtime() {
GLOBAL_RUNTIME.release_indexing_models();
}
-fn should_retry_execution_provider_runtime(error: &MlError) -> bool {
- cfg!(any(
- target_os = "ios",
- target_os = "android",
- target_os = "linux",
- target_os = "macos",
- target_os = "windows"
- )) && is_execution_provider_failure(error)
-}
-
-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("coremlexecutionprovider")
- || normalized.contains("webgpu")
- || normalized.contains("wgpu")
- || normalized.contains("dawn")
- || normalized.contains("vulkan")
- || normalized.contains("vk_error")
- || normalized.contains("non-finite")
- || normalized.contains("ep error")
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -546,34 +503,6 @@ mod tests {
assert_eq!(clip_text.path, "clip_text.onnx");
}
- #[test]
- fn provider_fallback_advances_only_the_selected_model_slot() {
- let runtime = MlRuntime::new();
- let model_paths = ModelPaths {
- face_detection: "face.onnx".to_string(),
- clip_image: "clip.onnx".to_string(),
- ..ModelPaths::default()
- };
- runtime.configure_requested_models(&model_paths);
-
- {
- let mut face_detection = runtime.face_detection.lock_state();
- assert!(
- runtime
- .face_detection
- .advance_provider_fallback_locked(&mut face_detection)
- );
- }
-
- let face_detection = runtime.face_detection.lock_state();
- assert_eq!(
- face_detection.fallback_execution_mode,
- onnx::ExecutionMode::PlatformDefault.fallback()
- );
- let clip_image = runtime.clip_image.lock_state();
- assert_eq!(clip_image.fallback_execution_mode, None);
- }
-
#[test]
fn runtime_accepts_single_use_operation() {
let value = String::from("once");
@@ -590,25 +519,28 @@ mod tests {
{
let mut clip_text = runtime.clip_text.lock_state();
clip_text.path = "clip_text.onnx".to_string();
- clip_text.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
+ clip_text.provider_plan = Some(onnx::ProviderPlan::new(
+ onnx::ExecutionMode::CpuOnly,
+ "clip_text.onnx",
+ ));
}
{
let mut face_detection = runtime.face_detection.lock_state();
face_detection.path = "face.onnx".to_string();
- face_detection.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
+ face_detection.provider_plan = Some(onnx::ProviderPlan::new(
+ onnx::ExecutionMode::CpuOnly,
+ "face.onnx",
+ ));
}
runtime.release_indexing_models();
let clip_text = runtime.clip_text.lock_state();
assert_eq!(clip_text.path, "clip_text.onnx");
- assert_eq!(
- clip_text.fallback_execution_mode,
- Some(onnx::ExecutionMode::CpuOnly)
- );
+ assert!(clip_text.provider_plan.is_some());
let face_detection = runtime.face_detection.lock_state();
- assert_eq!(face_detection.fallback_execution_mode, None);
+ assert!(face_detection.provider_plan.is_none());
}
#[test]
@@ -624,15 +556,15 @@ mod tests {
let face_detection = runtime.face_detection.lock_state();
assert_eq!(face_detection.path, "face.onnx");
- assert!(face_detection.loaded.is_none());
+ assert!(face_detection.session.is_none());
let face_embedding = runtime.face_embedding.lock_state();
assert_eq!(face_embedding.path, "embed.onnx");
- assert!(face_embedding.loaded.is_none());
+ assert!(face_embedding.session.is_none());
let clip_image = runtime.clip_image.lock_state();
assert_eq!(clip_image.path, "clip.onnx");
- assert!(clip_image.loaded.is_none());
+ assert!(clip_image.session.is_none());
}
#[test]
@@ -642,15 +574,18 @@ mod tests {
{
let mut state = slot.lock_state();
state.path = "pet.onnx".to_string();
- state.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
+ state.provider_plan = Some(onnx::ProviderPlan::new(
+ onnx::ExecutionMode::CpuOnly,
+ "pet.onnx",
+ ));
}
slot.sync_indexing_residency("");
let state = slot.lock_state();
assert!(state.path.is_empty());
- assert_eq!(state.fallback_execution_mode, None);
- assert!(state.loaded.is_none());
+ assert!(state.provider_plan.is_none());
+ assert!(state.session.is_none());
}
#[test]
@@ -660,52 +595,17 @@ mod tests {
{
let mut state = slot.lock_state();
state.path = "clip_text.onnx".to_string();
- state.fallback_execution_mode = Some(onnx::ExecutionMode::CpuOnly);
+ state.provider_plan = Some(onnx::ProviderPlan::new(
+ onnx::ExecutionMode::CpuOnly,
+ "clip_text.onnx",
+ ));
}
slot.release_residency();
let state = slot.lock_state();
- assert_eq!(state.fallback_execution_mode, None);
- assert!(state.loaded.is_none());
- }
-
- #[test]
- 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_slot_provider_fallback_is_bounded() {
- let slot = ModelSlot::new(onnx::ExecutionMode::PlatformDefault, "test-model");
- let mut state = slot.lock_state();
- let mut advances = 0;
-
- while slot.advance_provider_fallback_locked(&mut state) {
- advances += 1;
- assert!(advances <= 2);
- }
-
- #[cfg(target_os = "android")]
- assert_eq!(advances, 2);
- #[cfg(not(target_os = "android"))]
- assert_eq!(advances, 1);
+ assert!(state.provider_plan.is_none());
+ assert!(state.session.is_none());
}
#[test]