Skip to content

armgit / ente

Public Imported from GitHub
0

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

Cleanup

laurenspriem25f08a4f65ff
diff --git a/infra/ml/playground/optimizations/README.md b/infra/ml/playground/optimizations/README.md
index 1dbab84e27..30d8d1b93b 100644
--- a/infra/ml/playground/optimizations/README.md
+++ b/infra/ml/playground/optimizations/README.md
@@ -1,7 +1,9 @@
# Mobile ML model optimizations
This directory records the production transformations applied to Ente's mobile
-face models and contains the resulting CDN artifacts under `models/`.
+face models. The generated CDN artifacts are written under `models/`; ONNX
+files are intentionally gitignored, while `model_manifest.json` records the
+reproducible output metadata.
## Rebuilding the models
diff --git a/infra/ml/playground/optimizations/optimize_face_models.py b/infra/ml/playground/optimizations/optimize_face_models.py
index 6070047078..de2084dc50 100644
--- a/infra/ml/playground/optimizations/optimize_face_models.py
+++ b/infra/ml/playground/optimizations/optimize_face_models.py
@@ -2,8 +2,8 @@
"""Build Ente's optimized static face models for the mobile ML pipeline.
The generated models remain standard ONNX. The transformations make their
-graphs easier for CoreML and NNAPI to compile while preserving the outputs used
-by the application.
+graphs easier for CoreML and mobile CPU runtimes to optimize while preserving
+the outputs used by the application.
"""
from __future__ import annotations
diff --git a/infra/ml/test/run_ml_parity_tests.sh b/infra/ml/test/run_ml_parity_tests.sh
index aded93c274..22b3b3ff03 100755
--- a/infra/ml/test/run_ml_parity_tests.sh
+++ b/infra/ml/test/run_ml_parity_tests.sh
@@ -8,6 +8,7 @@ ROOT_DIR="$(
ML_DIR="$ROOT_DIR/infra/ml/test"
UV_PROJECT_DIR="$ROOT_DIR/infra/ml"
MANIFEST_PATH="$ROOT_DIR/infra/ml/test/ground_truth/manifest.json"
+ASSET_LOCK_PATH="$ML_DIR/ml_indexing/assets.json"
TEST_DATA_DIR="$ML_DIR/test_data/ml-indexing/v1"
PARITY_HELPERS="$ML_DIR/tools/parity_shell_helpers.py"
@@ -184,32 +185,46 @@ prepare_local_model_mirror_cache() {
local downloaded=0
local reused=0
local failed=0
- 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"
- )
+ local model_file model_url model_sha target_path tmp_path actual_sha
mkdir -p "$model_dir"
- for model_url in "${model_urls[@]}"; do
- local model_file="${model_url##*/}"
- local target_path="$model_dir/$model_file"
- if [[ -f "$target_path" ]]; then
- reused=$((reused + 1))
+ while IFS=$'\t' read -r model_file model_url model_sha; do
+ if [[ -z "$model_file" || -z "$model_url" || -z "$model_sha" ]]; then
+ echo "Local model mirror: invalid model entry in $ASSET_LOCK_PATH" >&2
+ failed=$((failed + 1))
continue
fi
- local tmp_path="$target_path.tmp"
+ target_path="$model_dir/$model_file"
+ if [[ -f "$target_path" ]]; then
+ actual_sha="$(sha256_file "$target_path")"
+ if [[ "$actual_sha" == "$model_sha" ]]; then
+ reused=$((reused + 1))
+ continue
+ fi
+ rm -f "$target_path"
+ fi
+
+ tmp_path="$target_path.tmp"
if curl -fsSL --retry 3 --retry-delay 1 "$model_url" -o "$tmp_path"; then
- mv "$tmp_path" "$target_path"
- downloaded=$((downloaded + 1))
+ actual_sha="$(sha256_file "$tmp_path")"
+ if [[ "$actual_sha" == "$model_sha" ]]; then
+ mv "$tmp_path" "$target_path"
+ downloaded=$((downloaded + 1))
+ else
+ rm -f "$tmp_path"
+ failed=$((failed + 1))
+ echo "Local model mirror: SHA-256 mismatch for $model_file"
+ fi
else
rm -f "$tmp_path"
failed=$((failed + 1))
echo "Local model mirror: failed to download $model_file (runner will fall back to direct model download)."
fi
- done
+ done < <(
+ python3 "$PARITY_HELPERS" model-assets "$ASSET_LOCK_PATH"
+ )
echo "Local model mirror cache: downloaded=$downloaded reused=$reused failed=$failed dir=$model_dir"
}
diff --git a/infra/ml/test/tools/parity_shell_helpers.py b/infra/ml/test/tools/parity_shell_helpers.py
index 9cd353e302..de100e0b9e 100644
--- a/infra/ml/test/tools/parity_shell_helpers.py
+++ b/infra/ml/test/tools/parity_shell_helpers.py
@@ -48,6 +48,15 @@ def cmd_manifest_fixtures(args: list[str]) -> None:
print(f"{source}\t{source_url}\t{source_sha}")
+def cmd_model_assets(args: list[str]) -> None:
+ asset_lock = json.loads(Path(args[0]).read_text())
+ for model in asset_lock.get("models", {}).values():
+ file_name = str(model.get("file_name", "")).strip()
+ url = str(model.get("url", "")).strip()
+ sha256 = str(model.get("sha256", "")).strip()
+ print(f"{file_name}\t{url}\t{sha256}")
+
+
def cmd_file_url(args: list[str]) -> None:
posix_path = Path(args[0]).resolve().as_posix()
if not posix_path.startswith("/"):
@@ -642,6 +651,7 @@ COMMANDS = {
"sha256-file": cmd_sha256_file,
"reserve-port": cmd_reserve_port,
"manifest-fixtures": cmd_manifest_fixtures,
+ "model-assets": cmd_model_assets,
"file-url": cmd_file_url,
"pick-device": cmd_pick_device,
"pick-ios-simulator": cmd_pick_ios_simulator,
diff --git a/mobile/apps/photos/integration_test/ml_parity_shared.dart b/mobile/apps/photos/integration_test/ml_parity_shared.dart
index cc490b0e9f..80c1eb1020 100644
--- a/mobile/apps/photos/integration_test/ml_parity_shared.dart
+++ b/mobile/apps/photos/integration_test/ml_parity_shared.dart
@@ -209,6 +209,13 @@ Future<_LoadedModels> _downloadModels(List<_ModelSpec> modelSpecs) async {
modelPathsBySchema[modelSpec.schemaName] = modelFile.path;
final modelSHA256 = await _sha256HexOfFile(modelFile);
+ if (modelSHA256.toLowerCase() !=
+ modelSpec.model.modelSha256.toLowerCase()) {
+ throw StateError(
+ "Model SHA mismatch for ${modelSpec.schemaName}: "
+ "expected ${modelSpec.model.modelSha256}, got $modelSHA256",
+ );
+ }
modelMetadata[modelSpec.schemaName] =
"${modelFile.uri.pathSegments.last}:$modelSHA256";
}
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index 09c9733c6e..0b34b52a9f 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -21,7 +21,7 @@ import "package:photos/utils/ml_util.dart";
final Map<String, dynamic> _isolateCache = {};
const _rustLibLoadedCacheKey = "rustLibLoaded";
-const _rustMlRuntimeConfigCacheKey = "rustMlRuntimeConfig";
+const _rustMlModelPathsCacheKey = "rustMlModelPaths";
class RustCorruptModelCacheDeletedException implements Exception {
const RustCorruptModelCacheDeletedException(this.modelPath);
@@ -395,10 +395,10 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {
petBodyEmbeddingCat:
(args["petBodyEmbeddingCatModelPath"] as String?) ?? "",
);
- final runtimeConfigKey = _runtimeConfigCacheKey(modelPaths);
- final currentConfigKey =
- _isolateCache[_rustMlRuntimeConfigCacheKey] as String?;
- if (currentConfigKey == runtimeConfigKey) {
+ final modelPathsKey = _modelPathsCacheKey(modelPaths);
+ final currentModelPathsKey =
+ _isolateCache[_rustMlModelPathsCacheKey] as String?;
+ if (currentModelPathsKey == modelPathsKey) {
return;
}
@@ -418,10 +418,8 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {
);
}
- await rust_ml.initMlRuntime(
- config: rust_ml.RustMlRuntimeConfig(modelPaths: modelPaths),
- );
- _isolateCache[_rustMlRuntimeConfigCacheKey] = runtimeConfigKey;
+ await rust_ml.initMlRuntime(modelPaths: modelPaths);
+ _isolateCache[_rustMlModelPathsCacheKey] = modelPathsKey;
}
Future<void> _releaseRustRuntime() async {
@@ -434,10 +432,10 @@ Future<void> _releaseRustRuntime() async {
} catch (_) {
// no-op: indexing-model release is best-effort.
}
- _isolateCache.remove(_rustMlRuntimeConfigCacheKey);
+ _isolateCache.remove(_rustMlModelPathsCacheKey);
}
-String _runtimeConfigCacheKey(rust_ml.RustModelPaths modelPaths) {
+String _modelPathsCacheKey(rust_ml.RustModelPaths modelPaths) {
return [
modelPaths.faceDetection,
modelPaths.faceEmbedding,
diff --git a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
index 5cf76a4592..9322095b29 100644
--- a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
+++ b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
@@ -1,7 +1,5 @@
use ente_photos::ml::{
- error::MlError as SharedMlError,
- indexing as shared_indexing,
- runtime::{MlRuntimeConfig, ModelPaths},
+ error::MlError as SharedMlError, indexing as shared_indexing, runtime::ModelPaths,
types as shared_types,
};
@@ -19,11 +17,6 @@ pub struct RustModelPaths {
pub pet_body_embedding_cat: String,
}
-#[derive(Clone, Debug)]
-pub struct RustMlRuntimeConfig {
- pub model_paths: RustModelPaths,
-}
-
#[derive(Clone, Debug)]
pub struct AnalyzeImageRequest {
pub file_id: i64,
@@ -137,12 +130,12 @@ pub struct RunClipTextResult {
pub embedding: Vec<f64>,
}
-pub fn init_ml_runtime(config: RustMlRuntimeConfig) -> Result<(), String> {
- shared_indexing::init_ml_runtime(to_runtime_config(&config)).map_err(|e| e.to_string())
+pub fn init_ml_runtime(model_paths: RustModelPaths) {
+ shared_indexing::init_ml_runtime(to_model_paths(&model_paths));
}
-pub fn release_ml_runtime() -> Result<(), String> {
- shared_indexing::release_ml_runtime().map_err(|e| e.to_string())
+pub fn release_ml_runtime() {
+ shared_indexing::release_ml_runtime();
}
pub fn analyze_image_rust(req: AnalyzeImageRequest) -> Result<AnalyzeImageResult, RustMlError> {
@@ -152,9 +145,7 @@ pub fn analyze_image_rust(req: AnalyzeImageRequest) -> Result<AnalyzeImageResult
run_faces: req.run_faces,
run_clip: req.run_clip,
run_pets: req.run_pets,
- runtime_config: MlRuntimeConfig {
- model_paths: to_model_paths(&req.model_paths),
- },
+ model_paths: to_model_paths(&req.model_paths),
};
shared_indexing::analyze_image(shared_req)
@@ -184,12 +175,6 @@ pub fn tokenize_clip_text_rust(text: String, vocab_path: String) -> Result<Vec<i
shared_indexing::tokenize_clip_text(&text, &vocab_path).map_err(|e| e.to_string())
}
-fn to_runtime_config(config: &RustMlRuntimeConfig) -> MlRuntimeConfig {
- MlRuntimeConfig {
- model_paths: to_model_paths(&config.model_paths),
- }
-}
-
fn to_model_paths(paths: &RustModelPaths) -> ModelPaths {
ModelPaths {
face_detection: paths.face_detection.clone(),
diff --git a/rust/crates/photos/src/ml/face/embed.rs b/rust/crates/photos/src/ml/face/embed.rs
index 6c4da66f72..37aa1938e3 100644
--- a/rust/crates/photos/src/ml/face/embed.rs
+++ b/rust/crates/photos/src/ml/face/embed.rs
@@ -11,7 +11,7 @@ const FACE_INPUT_CHANNELS: i64 = 3;
pub fn run_face_embedding(
runtime: &MlRuntimeView<'_>,
- aligned_faces: &[Vec<f32>],
+ aligned_faces: Vec<Vec<f32>>,
face_results: &mut [FaceResult],
) -> MlResult<()> {
if aligned_faces.is_empty() {
@@ -27,7 +27,7 @@ pub fn run_face_embedding(
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()) {
+ for (aligned, face_result) in aligned_faces.into_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 {}",
@@ -38,7 +38,7 @@ pub fn run_face_embedding(
let (shape, mut embedding) = onnx::run_f32(
&mut face_embedding,
- aligned.clone(),
+ aligned,
[1, FACE_INPUT_HEIGHT, FACE_INPUT_WIDTH, FACE_INPUT_CHANNELS],
)?;
if shape.first() != Some(&1) || embedding.is_empty() {
diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rs
index 082fb74665..9429aa21a8 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, MlRuntimeConfig, ModelPaths},
+ runtime::{self, ModelPaths},
types::{self, ClipResult, Dimensions, FaceResult, PetBodyResult, PetFaceResult},
};
use ente_image::decode::decode_image_from_path;
@@ -22,7 +22,7 @@ pub struct AnalyzeImageRequest {
pub run_faces: bool,
pub run_clip: bool,
pub run_pets: bool,
- pub runtime_config: MlRuntimeConfig,
+ pub model_paths: ModelPaths,
}
#[derive(Clone, Debug)]
@@ -47,12 +47,12 @@ pub struct RunClipTextResult {
pub embedding: Vec<f32>,
}
-pub fn init_ml_runtime(config: MlRuntimeConfig) -> MlResult<()> {
- runtime::prepare_runtime(&config)
+pub fn init_ml_runtime(model_paths: ModelPaths) {
+ runtime::prepare_runtime(&model_paths);
}
-pub fn release_ml_runtime() -> MlResult<()> {
- runtime::release_runtime()
+pub fn release_ml_runtime() {
+ runtime::release_runtime();
}
pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
@@ -64,10 +64,10 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
run_faces,
run_clip,
run_pets,
- runtime_config,
+ model_paths,
} = req;
- runtime::with_runtime(&runtime_config, |runtime| {
+ runtime::with_runtime(&model_paths, |runtime| {
let decoded = decode_image_from_path(&image_path)?;
let dims = decoded.dimensions.clone();
@@ -78,7 +78,7 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
} else {
let (aligned, mut face_results) =
run_face_alignment(file_id, &decoded, detections)?;
- run_face_embedding(runtime, &aligned, &mut face_results)?;
+ run_face_embedding(runtime, aligned, &mut face_results)?;
Some(face_results)
}
} else {
@@ -155,22 +155,20 @@ pub fn run_clip_text(req: RunClipTextRequest) -> MlResult<RunClipTextResult> {
));
}
- let runtime_config = MlRuntimeConfig {
- model_paths: ModelPaths {
- face_detection: String::new(),
- face_embedding: String::new(),
- clip_image: String::new(),
- clip_text: model_path,
- pet_face_detection: String::new(),
- pet_face_embedding_dog: String::new(),
- pet_face_embedding_cat: String::new(),
- pet_body_detection: String::new(),
- pet_body_embedding_dog: String::new(),
- pet_body_embedding_cat: String::new(),
- },
+ let model_paths = ModelPaths {
+ face_detection: String::new(),
+ face_embedding: String::new(),
+ clip_image: String::new(),
+ clip_text: model_path,
+ pet_face_detection: String::new(),
+ pet_face_embedding_dog: String::new(),
+ pet_face_embedding_cat: String::new(),
+ pet_body_detection: String::new(),
+ pet_body_embedding_dog: String::new(),
+ pet_body_embedding_cat: String::new(),
};
- runtime::with_runtime(&runtime_config, |runtime| {
+ runtime::with_runtime(&model_paths, |runtime| {
let clip = run_clip_text_query(runtime, &text, &vocab_path)?;
Ok(RunClipTextResult {
embedding: clip.embedding,
@@ -188,7 +186,7 @@ pub fn tokenize_clip_text(text: &str, vocab_path: &str) -> MlResult<Vec<i32>> {
}
fn validate_request_model_paths(req: &AnalyzeImageRequest) -> MlResult<()> {
- let model_paths = &req.runtime_config.model_paths;
+ let model_paths = &req.model_paths;
let mut missing = Vec::new();
if req.run_faces {
diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rs
index 2855778009..4feec00b80 100644
--- a/rust/crates/photos/src/ml/onnx.rs
+++ b/rust/crates/photos/src/ml/onnx.rs
@@ -23,10 +23,10 @@ pub(crate) enum ExecutionMode {
}
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 primary = provider_attempt(mode);
+ let retry_with_cpu_only = primary.retry_with_cpu_only;
let mut attempts = vec![primary];
- if has_preferred_provider {
+ if retry_with_cpu_only {
attempts.push(ProviderAttempt::cpu_only());
}
@@ -58,60 +58,61 @@ fn has_protobuf_parse_failure(errors: &[String]) -> bool {
struct ProviderAttempt {
providers: Vec<ExecutionProviderDispatch>,
- has_preferred_provider: bool,
- uses_xnnpack: bool,
+ retry_with_cpu_only: bool,
+ disable_intra_op_spinning: bool,
}
impl ProviderAttempt {
fn cpu_only() -> Self {
Self {
providers: vec![CPU::default().with_arena_allocator(true).build()],
- has_preferred_provider: false,
- uses_xnnpack: false,
+ retry_with_cpu_only: false,
+ disable_intra_op_spinning: false,
}
}
}
-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(
+fn provider_attempt(mode: ExecutionMode) -> ProviderAttempt {
+ match mode {
+ ExecutionMode::PlatformDefault => platform_default_attempt(),
+ ExecutionMode::CpuOnly => ProviderAttempt::cpu_only(),
+ }
+}
+
+#[cfg(target_os = "ios")]
+fn platform_default_attempt() -> ProviderAttempt {
+ ProviderAttempt {
+ providers: vec![
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 _mode == ExecutionMode::PlatformDefault {
- providers.push(xnnpack_provider());
- has_preferred_provider = true;
- uses_xnnpack = true;
+ CPU::default().with_arena_allocator(true).build(),
+ ],
+ retry_with_cpu_only: true,
+ disable_intra_op_spinning: false,
}
+}
- providers.push(CPU::default().with_arena_allocator(true).build());
-
+#[cfg(target_os = "android")]
+fn platform_default_attempt() -> ProviderAttempt {
ProviderAttempt {
- providers,
- has_preferred_provider,
- uses_xnnpack,
+ providers: vec![
+ xnnpack_provider(),
+ CPU::default().with_arena_allocator(true).build(),
+ ],
+ retry_with_cpu_only: true,
+ disable_intra_op_spinning: true,
}
}
+#[cfg(not(any(target_os = "ios", target_os = "android")))]
+fn platform_default_attempt() -> ProviderAttempt {
+ ProviderAttempt::cpu_only()
+}
+
#[cfg(target_os = "android")]
fn xnnpack_provider() -> ExecutionProviderDispatch {
XNNPACK::default()
@@ -126,7 +127,7 @@ fn build_session_with_providers(model_path: &str, attempt: ProviderAttempt) -> M
.with_intra_threads(1)?
.with_inter_threads(1)?;
- if attempt.uses_xnnpack {
+ if attempt.disable_intra_op_spinning {
builder = builder.with_intra_op_spinning(false)?;
}
builder = builder.with_execution_providers(attempt.providers)?;
diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rs
index e70ef31acb..33125dd908 100644
--- a/rust/crates/photos/src/ml/runtime.rs
+++ b/rust/crates/photos/src/ml/runtime.rs
@@ -49,11 +49,6 @@ pub struct ModelPaths {
pub pet_body_embedding_cat: String,
}
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct MlRuntimeConfig {
- pub model_paths: ModelPaths,
-}
-
#[derive(Debug)]
struct ModelSlotState {
path: String,
@@ -64,6 +59,7 @@ struct ModelSlotState {
#[derive(Debug)]
struct ModelSlot {
+ default_execution_mode: onnx::ExecutionMode,
state: Mutex<ModelSlotState>,
}
@@ -73,7 +69,7 @@ pub struct ModelSessionGuard<'a> {
pub struct MlRuntimeView<'a> {
runtime: &'a MlRuntime,
- config: &'a MlRuntimeConfig,
+ model_paths: &'a ModelPaths,
}
impl Deref for ModelSessionGuard<'_> {
@@ -97,8 +93,9 @@ impl DerefMut for ModelSessionGuard<'_> {
}
impl ModelSlot {
- fn new() -> Self {
+ fn new(default_execution_mode: onnx::ExecutionMode) -> Self {
Self {
+ default_execution_mode,
state: Mutex::new(ModelSlotState {
path: String::new(),
fell_back_to_cpu: false,
@@ -145,7 +142,7 @@ impl ModelSlot {
}
fn force_cpu_fallback_if_configured(&self, path: &str) {
- if path.trim().is_empty() {
+ if self.default_execution_mode == onnx::ExecutionMode::CpuOnly || path.trim().is_empty() {
return;
}
@@ -168,7 +165,7 @@ impl ModelSlot {
let mut state = self.lock_state();
Self::set_config_locked(&mut state, path);
- Self::ensure_loaded_locked(&mut state, error_msg)?;
+ self.ensure_loaded_locked(&mut state, error_msg)?;
Ok(ModelSessionGuard { state })
}
@@ -192,7 +189,7 @@ impl ModelSlot {
Self::clear_transient_runtime_state_locked(state);
}
- fn ensure_loaded_locked(state: &mut ModelSlotState, error_msg: &str) -> MlResult<()> {
+ 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()));
}
@@ -206,7 +203,7 @@ impl ModelSlot {
let execution_mode = if state.fell_back_to_cpu {
onnx::ExecutionMode::CpuOnly
} else {
- onnx::ExecutionMode::PlatformDefault
+ self.default_execution_mode
};
let session = onnx::build_session(&state.path, execution_mode)?;
rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));
@@ -233,64 +230,69 @@ 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;
+
Self {
- face_detection: ModelSlot::new(),
- face_embedding: ModelSlot::new(),
- clip_image: ModelSlot::new(),
- clip_text: ModelSlot::new(),
- pet_face_detection: ModelSlot::new(),
- pet_face_embedding_dog: ModelSlot::new(),
- pet_face_embedding_cat: ModelSlot::new(),
- pet_body_detection: ModelSlot::new(),
- pet_body_embedding_dog: ModelSlot::new(),
- pet_body_embedding_cat: ModelSlot::new(),
+ face_detection: ModelSlot::new(platform_default),
+ face_embedding: ModelSlot::new(platform_default),
+ clip_image: ModelSlot::new(platform_default),
+ clip_text: ModelSlot::new(platform_default),
+ // 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_embedding_dog: ModelSlot::new(cpu_only),
+ pet_face_embedding_cat: ModelSlot::new(cpu_only),
+ pet_body_detection: ModelSlot::new(cpu_only),
+ pet_body_embedding_dog: ModelSlot::new(cpu_only),
+ pet_body_embedding_cat: ModelSlot::new(cpu_only),
}
}
- fn configure_requested_models(&self, config: &MlRuntimeConfig) {
+ fn configure_requested_models(&self, model_paths: &ModelPaths) {
self.face_detection
- .configure_if_requested(&config.model_paths.face_detection);
+ .configure_if_requested(&model_paths.face_detection);
self.face_embedding
- .configure_if_requested(&config.model_paths.face_embedding);
+ .configure_if_requested(&model_paths.face_embedding);
self.clip_image
- .configure_if_requested(&config.model_paths.clip_image);
+ .configure_if_requested(&model_paths.clip_image);
self.clip_text
- .configure_if_requested(&config.model_paths.clip_text);
+ .configure_if_requested(&model_paths.clip_text);
self.pet_face_detection
- .configure_if_requested(&config.model_paths.pet_face_detection);
+ .configure_if_requested(&model_paths.pet_face_detection);
self.pet_face_embedding_dog
- .configure_if_requested(&config.model_paths.pet_face_embedding_dog);
+ .configure_if_requested(&model_paths.pet_face_embedding_dog);
self.pet_face_embedding_cat
- .configure_if_requested(&config.model_paths.pet_face_embedding_cat);
+ .configure_if_requested(&model_paths.pet_face_embedding_cat);
self.pet_body_detection
- .configure_if_requested(&config.model_paths.pet_body_detection);
+ .configure_if_requested(&model_paths.pet_body_detection);
self.pet_body_embedding_dog
- .configure_if_requested(&config.model_paths.pet_body_embedding_dog);
+ .configure_if_requested(&model_paths.pet_body_embedding_dog);
self.pet_body_embedding_cat
- .configure_if_requested(&config.model_paths.pet_body_embedding_cat);
+ .configure_if_requested(&model_paths.pet_body_embedding_cat);
}
- fn prepare_indexing_models(&self, config: &MlRuntimeConfig) -> MlResult<()> {
+ fn prepare_indexing_models(&self, model_paths: &ModelPaths) {
self.face_detection
- .sync_indexing_residency(&config.model_paths.face_detection);
+ .sync_indexing_residency(&model_paths.face_detection);
self.face_embedding
- .sync_indexing_residency(&config.model_paths.face_embedding);
+ .sync_indexing_residency(&model_paths.face_embedding);
self.clip_image
- .sync_indexing_residency(&config.model_paths.clip_image);
+ .sync_indexing_residency(&model_paths.clip_image);
self.pet_face_detection
- .sync_indexing_residency(&config.model_paths.pet_face_detection);
+ .sync_indexing_residency(&model_paths.pet_face_detection);
self.pet_face_embedding_dog
- .sync_indexing_residency(&config.model_paths.pet_face_embedding_dog);
+ .sync_indexing_residency(&model_paths.pet_face_embedding_dog);
self.pet_face_embedding_cat
- .sync_indexing_residency(&config.model_paths.pet_face_embedding_cat);
+ .sync_indexing_residency(&model_paths.pet_face_embedding_cat);
self.pet_body_detection
- .sync_indexing_residency(&config.model_paths.pet_body_detection);
+ .sync_indexing_residency(&model_paths.pet_body_detection);
self.pet_body_embedding_dog
- .sync_indexing_residency(&config.model_paths.pet_body_embedding_dog);
+ .sync_indexing_residency(&model_paths.pet_body_embedding_dog);
self.pet_body_embedding_cat
- .sync_indexing_residency(&config.model_paths.pet_body_embedding_cat);
-
- Ok(())
+ .sync_indexing_residency(&model_paths.pet_body_embedding_cat);
}
fn release_indexing_models(&self) {
@@ -305,33 +307,33 @@ impl MlRuntime {
self.pet_body_embedding_cat.release_residency();
}
- fn force_cpu_only_for_requested_models(&self, config: &MlRuntimeConfig) {
+ fn force_cpu_only_for_requested_models(&self, model_paths: &ModelPaths) {
self.face_detection
- .force_cpu_fallback_if_configured(&config.model_paths.face_detection);
+ .force_cpu_fallback_if_configured(&model_paths.face_detection);
self.face_embedding
- .force_cpu_fallback_if_configured(&config.model_paths.face_embedding);
+ .force_cpu_fallback_if_configured(&model_paths.face_embedding);
self.clip_image
- .force_cpu_fallback_if_configured(&config.model_paths.clip_image);
+ .force_cpu_fallback_if_configured(&model_paths.clip_image);
self.clip_text
- .force_cpu_fallback_if_configured(&config.model_paths.clip_text);
+ .force_cpu_fallback_if_configured(&model_paths.clip_text);
self.pet_face_detection
- .force_cpu_fallback_if_configured(&config.model_paths.pet_face_detection);
+ .force_cpu_fallback_if_configured(&model_paths.pet_face_detection);
self.pet_face_embedding_dog
- .force_cpu_fallback_if_configured(&config.model_paths.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(&config.model_paths.pet_face_embedding_cat);
+ .force_cpu_fallback_if_configured(&model_paths.pet_face_embedding_cat);
self.pet_body_detection
- .force_cpu_fallback_if_configured(&config.model_paths.pet_body_detection);
+ .force_cpu_fallback_if_configured(&model_paths.pet_body_detection);
self.pet_body_embedding_dog
- .force_cpu_fallback_if_configured(&config.model_paths.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(&config.model_paths.pet_body_embedding_cat);
+ .force_cpu_fallback_if_configured(&model_paths.pet_body_embedding_cat);
}
- fn view<'a>(&'a self, config: &'a MlRuntimeConfig) -> MlRuntimeView<'a> {
+ fn view<'a>(&'a self, model_paths: &'a ModelPaths) -> MlRuntimeView<'a> {
MlRuntimeView {
runtime: self,
- config,
+ model_paths,
}
}
}
@@ -339,91 +341,90 @@ impl MlRuntime {
impl MlRuntimeView<'_> {
pub fn face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {
self.runtime.face_detection.session_guard_for(
- &self.config.model_paths.face_detection,
+ &self.model_paths.face_detection,
"missing model path: faceDetectionModelPath is required when runFaces is true",
)
}
pub fn face_embedding_session(&self) -> MlResult<ModelSessionGuard<'_>> {
self.runtime.face_embedding.session_guard_for(
- &self.config.model_paths.face_embedding,
+ &self.model_paths.face_embedding,
"missing model path: faceEmbeddingModelPath is required when runFaces is true",
)
}
pub fn clip_image_session(&self) -> MlResult<ModelSessionGuard<'_>> {
self.runtime.clip_image.session_guard_for(
- &self.config.model_paths.clip_image,
+ &self.model_paths.clip_image,
"missing model path: clipImageModelPath is required when runClip is true",
)
}
pub fn clip_text_session(&self) -> MlResult<ModelSessionGuard<'_>> {
self.runtime.clip_text.session_guard_for(
- &self.config.model_paths.clip_text,
+ &self.model_paths.clip_text,
"missing model path: clipTextModelPath is required when running clip text",
)
}
pub fn pet_face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {
self.runtime.pet_face_detection.session_guard_for(
- &self.config.model_paths.pet_face_detection,
+ &self.model_paths.pet_face_detection,
"missing model path: petFaceDetectionModelPath is required when runPets is true",
)
}
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,
+ &self.model_paths.pet_face_embedding_dog,
"missing model path: petFaceEmbeddingDogModelPath is required",
)
}
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,
+ &self.model_paths.pet_face_embedding_cat,
"missing model path: petFaceEmbeddingCatModelPath is required",
)
}
pub fn pet_body_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {
self.runtime.pet_body_detection.session_guard_for(
- &self.config.model_paths.pet_body_detection,
+ &self.model_paths.pet_body_detection,
"missing model path: petBodyDetectionModelPath is required when runPets is true",
)
}
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,
+ &self.model_paths.pet_body_embedding_dog,
"missing model path: petBodyEmbeddingDogModelPath is required",
)
}
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,
+ &self.model_paths.pet_body_embedding_cat,
"missing model path: petBodyEmbeddingCatModelPath is required",
)
}
}
-pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
- GLOBAL_RUNTIME.configure_requested_models(config);
- Ok(())
+pub fn ensure_runtime(model_paths: &ModelPaths) {
+ GLOBAL_RUNTIME.configure_requested_models(model_paths);
}
-pub fn prepare_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
- GLOBAL_RUNTIME.prepare_indexing_models(config)
+pub fn prepare_runtime(model_paths: &ModelPaths) {
+ GLOBAL_RUNTIME.prepare_indexing_models(model_paths);
}
-pub fn with_runtime<F, R>(config: &MlRuntimeConfig, func: F) -> MlResult<R>
+pub fn with_runtime<F, R>(model_paths: &ModelPaths, func: F) -> MlResult<R>
where
F: for<'a> Fn(&MlRuntimeView<'a>) -> MlResult<R>,
{
- ensure_runtime(config)?;
+ ensure_runtime(model_paths);
- let runtime_view = GLOBAL_RUNTIME.view(config);
+ let runtime_view = GLOBAL_RUNTIME.view(model_paths);
let first_result = func(&runtime_view);
match first_result {
Ok(result) => Ok(result),
@@ -435,16 +436,15 @@ where
rt_log(&format!(
"execution provider failed, retrying with CPU-only runtime: {first_error}"
));
- GLOBAL_RUNTIME.force_cpu_only_for_requested_models(config);
- let runtime_view = GLOBAL_RUNTIME.view(config);
+ GLOBAL_RUNTIME.force_cpu_only_for_requested_models(model_paths);
+ let runtime_view = GLOBAL_RUNTIME.view(model_paths);
func(&runtime_view)
}
}
}
-pub fn release_runtime() -> MlResult<()> {
+pub fn release_runtime() {
GLOBAL_RUNTIME.release_indexing_models();
- Ok(())
}
fn should_retry_with_cpu_only_runtime(error: &MlError) -> bool {
@@ -486,18 +486,14 @@ mod tests {
fn configure_requested_models_preserves_unrequested_slots() {
let runtime = MlRuntime::new();
- runtime.configure_requested_models(&MlRuntimeConfig {
- model_paths: ModelPaths {
- clip_text: "clip_text.onnx".to_string(),
- ..empty_paths()
- },
+ runtime.configure_requested_models(&ModelPaths {
+ clip_text: "clip_text.onnx".to_string(),
+ ..empty_paths()
});
- runtime.configure_requested_models(&MlRuntimeConfig {
- model_paths: ModelPaths {
- face_detection: "face.onnx".to_string(),
- ..empty_paths()
- },
+ runtime.configure_requested_models(&ModelPaths {
+ face_detection: "face.onnx".to_string(),
+ ..empty_paths()
});
let clip_text = runtime.clip_text.lock_state();
@@ -537,16 +533,12 @@ mod tests {
fn prepare_indexing_models_pins_without_loading_sessions() {
let runtime = MlRuntime::new();
- runtime
- .prepare_indexing_models(&MlRuntimeConfig {
- model_paths: ModelPaths {
- face_detection: "face.onnx".to_string(),
- face_embedding: "embed.onnx".to_string(),
- clip_image: "clip.onnx".to_string(),
- ..empty_paths()
- },
- })
- .unwrap();
+ runtime.prepare_indexing_models(&ModelPaths {
+ face_detection: "face.onnx".to_string(),
+ face_embedding: "embed.onnx".to_string(),
+ clip_image: "clip.onnx".to_string(),
+ ..empty_paths()
+ });
let face_detection = runtime.face_detection.lock_state();
assert_eq!(face_detection.pin_count, 1);
@@ -563,7 +555,7 @@ mod tests {
#[test]
fn sync_indexing_residency_clears_disabled_slots() {
- let slot = ModelSlot::new();
+ let slot = ModelSlot::new(onnx::ExecutionMode::PlatformDefault);
{
let mut state = slot.lock_state();
@@ -583,7 +575,7 @@ mod tests {
#[test]
fn release_residency_resets_transient_cpu_fallback_for_any_slot() {
- let slot = ModelSlot::new();
+ let slot = ModelSlot::new(onnx::ExecutionMode::PlatformDefault);
{
let mut state = slot.lock_state();
@@ -599,4 +591,50 @@ mod tests {
assert!(!state.fell_back_to_cpu);
assert!(state.session.is_none());
}
+
+ #[test]
+ fn only_pet_models_default_to_cpu_only() {
+ let runtime = MlRuntime::new();
+
+ assert_eq!(
+ runtime.face_detection.default_execution_mode,
+ onnx::ExecutionMode::PlatformDefault
+ );
+ assert_eq!(
+ runtime.face_embedding.default_execution_mode,
+ onnx::ExecutionMode::PlatformDefault
+ );
+ assert_eq!(
+ runtime.clip_image.default_execution_mode,
+ onnx::ExecutionMode::PlatformDefault
+ );
+ assert_eq!(
+ runtime.clip_text.default_execution_mode,
+ onnx::ExecutionMode::PlatformDefault
+ );
+ assert_eq!(
+ runtime.pet_face_detection.default_execution_mode,
+ onnx::ExecutionMode::CpuOnly
+ );
+ assert_eq!(
+ runtime.pet_face_embedding_dog.default_execution_mode,
+ onnx::ExecutionMode::CpuOnly
+ );
+ assert_eq!(
+ runtime.pet_face_embedding_cat.default_execution_mode,
+ onnx::ExecutionMode::CpuOnly
+ );
+ assert_eq!(
+ runtime.pet_body_detection.default_execution_mode,
+ onnx::ExecutionMode::CpuOnly
+ );
+ assert_eq!(
+ runtime.pet_body_embedding_dog.default_execution_mode,
+ onnx::ExecutionMode::CpuOnly
+ );
+ assert_eq!(
+ runtime.pet_body_embedding_cat.default_execution_mode,
+ onnx::ExecutionMode::CpuOnly
+ );
+ }
}
diff --git a/rust/crates/photos/tests/ml_indexing.rs b/rust/crates/photos/tests/ml_indexing.rs
index 2b14985e9d..bec2fb685f 100644
--- a/rust/crates/photos/tests/ml_indexing.rs
+++ b/rust/crates/photos/tests/ml_indexing.rs
@@ -12,7 +12,7 @@ fn rust_ml_matches_python_goldens() {
fn run_ml_indexing_test() -> Result<()> {
let context = MlIndexingTestContext::load()?;
- let runtime = context.prepare_runtime()?;
+ let runtime = context.prepare_runtime();
let mut failures = context.validate_manifest_expectations()?;
let mut stats = ComparisonStats::default();
diff --git a/rust/crates/photos/tests/support/ml_indexing.rs b/rust/crates/photos/tests/support/ml_indexing.rs
index 5e0ac6964b..eef327b2c3 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::{MlRuntimeConfig, ModelPaths},
+ runtime::ModelPaths,
types::FaceResult as RustFaceResult,
};
use flate2::read::GzDecoder;
@@ -171,7 +171,7 @@ pub(crate) struct MlIndexingTestContext {
client: Client,
golden_results: HashMap<String, ComparableResult>,
manifest: FixtureManifest,
- runtime_config: MlRuntimeConfig,
+ model_paths: ModelPaths,
}
impl MlIndexingTestContext {
@@ -201,9 +201,7 @@ impl MlIndexingTestContext {
.context("load ONNX Runtime dynamic library")?
.commit();
- let runtime_config = MlRuntimeConfig {
- model_paths: resolve_model_paths(&client, &cache_dir, &asset_lock.models)?,
- };
+ let model_paths = resolve_model_paths(&client, &cache_dir, &asset_lock.models)?;
Ok(Self {
asset_lock,
@@ -211,15 +209,15 @@ impl MlIndexingTestContext {
client,
golden_results,
manifest,
- runtime_config,
+ model_paths,
})
}
- pub(crate) fn prepare_runtime(&self) -> Result<PreparedMlRuntime> {
- init_ml_runtime(self.runtime_config.clone()).context("prepare ML runtime")?;
- Ok(PreparedMlRuntime {
- config: self.runtime_config.clone(),
- })
+ pub(crate) fn prepare_runtime(&self) -> PreparedMlRuntime {
+ init_ml_runtime(self.model_paths.clone());
+ PreparedMlRuntime {
+ model_paths: self.model_paths.clone(),
+ }
}
pub(crate) fn validate_manifest_expectations(&self) -> Result<Vec<String>> {
@@ -258,7 +256,7 @@ impl MlIndexingTestContext {
run_faces: true,
run_clip: true,
run_pets: false,
- runtime_config: runtime.config().clone(),
+ model_paths: runtime.model_paths().clone(),
};
if expected_unsupported.contains(&file_id) {
@@ -365,18 +363,18 @@ impl MlIndexingTestContext {
}
pub(crate) struct PreparedMlRuntime {
- config: MlRuntimeConfig,
+ model_paths: ModelPaths,
}
impl PreparedMlRuntime {
- fn config(&self) -> &MlRuntimeConfig {
- &self.config
+ fn model_paths(&self) -> &ModelPaths {
+ &self.model_paths
}
}
impl Drop for PreparedMlRuntime {
fn drop(&mut self) {
- let _ = release_ml_runtime();
+ release_ml_runtime();
}
}