Skip to content

armgit / ente

Public Imported from GitHub
0

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

Refactor Rust ML runtime residency

laurenspriem32fe79dbff03
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
index be4665f924..1649410528 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
@@ -47,6 +47,7 @@ class MLIndexingIsolate extends SuperIsolate {
@override
Future<void> onDispose() async {
+ await releaseRustRuntime();
await _releaseModels();
}
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index a7cd7572bd..53e4c81d0b 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -313,12 +313,12 @@ Future<void> _ensureRustLoaded() async {
}
Future<void> _ensureRustDisposed() async {
- final bool loaded = _isolateCache[_rustLibLoadedCacheKey] as bool? ?? false;
- if (loaded) {
- await _releaseRustRuntime();
- EntePhotosRust.dispose();
- _isolateCache.remove(_rustLibLoadedCacheKey);
- }
+ // Intentionally a no-op.
+ //
+ // Rust ML residency is owned by the feature isolate using it, not by the
+ // generic cache-clear path. This avoids disposing the bridge before
+ // MLIndexingIsolate has a chance to release its selective indexing-model
+ // residency during onDispose().
}
Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {
@@ -384,7 +384,7 @@ Future<void> _releaseRustRuntime() async {
try {
await rust_ml.releaseMlRuntime();
} catch (_) {
- // no-op: runtime release is best-effort before process-wide bridge dispose.
+ // no-op: indexing-model release is best-effort.
}
_isolateCache.remove(_rustMlRuntimeConfigCacheKey);
}
diff --git a/mobile/apps/photos/lib/utils/isolate/super_isolate.dart b/mobile/apps/photos/lib/utils/isolate/super_isolate.dart
index 60ca4936e7..87460d295a 100644
--- a/mobile/apps/photos/lib/utils/isolate/super_isolate.dart
+++ b/mobile/apps/photos/lib/utils/isolate/super_isolate.dart
@@ -197,8 +197,8 @@ abstract class SuperIsolate {
void _disposeIsolate() async {
if (!_isIsolateSpawned) return;
logger.info('Disposing isolate');
- await clearAllCachedData();
await onDispose();
+ await clearAllCachedData();
_isIsolateSpawned = false;
_isolate.kill();
_receivePort.close();
diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
index f5eb5b1377..202e131a4a 100644
--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
@@ -155,7 +155,7 @@ pub struct RunClipTextResult {
}
pub fn init_ml_runtime(config: RustMlRuntimeConfig) -> Result<(), String> {
- runtime::ensure_runtime(&to_runtime_config(&config)).map_err(|e| e.to_string())
+ runtime::prepare_runtime(&to_runtime_config(&config)).map_err(|e| e.to_string())
}
pub fn release_ml_runtime() -> Result<(), String> {
@@ -242,8 +242,18 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRe
}
(
- Some(pet_face_results.into_iter().map(to_api_pet_face_result).collect()),
- Some(body_results.into_iter().map(to_api_pet_body_result).collect()),
+ Some(
+ pet_face_results
+ .into_iter()
+ .map(to_api_pet_face_result)
+ .collect(),
+ ),
+ Some(
+ body_results
+ .into_iter()
+ .map(to_api_pet_body_result)
+ .collect(),
+ ),
)
} else {
(None, None)
@@ -437,12 +447,21 @@ fn to_api_pet_face_result(result: crate::ml::types::PetFaceResult) -> RustPetFac
.collect(),
},
alignment: RustPetAlignmentResult {
- center: result.alignment.center.into_iter().map(|v| v as f64).collect(),
+ center: result
+ .alignment
+ .center
+ .into_iter()
+ .map(|v| v as f64)
+ .collect(),
angle: result.alignment.angle as f64,
crop_size: result.alignment.crop_size as f64,
},
species: result.species,
- face_embedding: result.face_embedding.into_iter().map(|v| v as f64).collect(),
+ face_embedding: result
+ .face_embedding
+ .into_iter()
+ .map(|v| v as f64)
+ .collect(),
pet_face_id: result.pet_face_id,
}
}
@@ -458,6 +477,10 @@ fn to_api_pet_body_result(result: crate::ml::types::PetBodyResult) -> RustPetBod
score: result.detection.score as f64,
coco_class: result.detection.coco_class,
pet_body_id: result.pet_body_id,
- body_embedding: result.body_embedding.into_iter().map(|v| v as f64).collect(),
+ body_embedding: result
+ .body_embedding
+ .into_iter()
+ .map(|v| v as f64)
+ .collect(),
}
}
diff --git a/mobile/apps/photos/rust/src/ml/clip/image.rs b/mobile/apps/photos/rust/src/ml/clip/image.rs
index 91b656eb27..0362ff2dc1 100644
--- a/mobile/apps/photos/rust/src/ml/clip/image.rs
+++ b/mobile/apps/photos/rust/src/ml/clip/image.rs
@@ -1,14 +1,14 @@
use crate::ml::{
error::{MlError, MlResult},
onnx, preprocess,
- runtime::MlRuntime,
+ runtime::MlRuntimeView,
types::{ClipResult, DecodedImage},
};
-pub fn run_clip_image(runtime: &MlRuntime, decoded: &DecodedImage) -> MlResult<ClipResult> {
+pub fn run_clip_image(runtime: &MlRuntimeView<'_>, decoded: &DecodedImage) -> MlResult<ClipResult> {
let input = preprocess::preprocess_clip(decoded)?;
let clip_image = runtime.clip_image_session()?;
- let (shape, output) = onnx::run_f32(clip_image, input, [1, 3, 256, 256])?;
+ let (shape, output) = onnx::run_f32(&clip_image, input, [1, 3, 256, 256])?;
let mut embedding = if shape.len() == 2 {
if shape[0] != 1 {
diff --git a/mobile/apps/photos/rust/src/ml/clip/text.rs b/mobile/apps/photos/rust/src/ml/clip/text.rs
index a6e4426b26..3dbee31a97 100644
--- a/mobile/apps/photos/rust/src/ml/clip/text.rs
+++ b/mobile/apps/photos/rust/src/ml/clip/text.rs
@@ -2,13 +2,13 @@ use crate::ml::{
clip::tokenizer,
error::{MlError, MlResult},
onnx,
- runtime::MlRuntime,
+ runtime::MlRuntimeView,
types::ClipResult,
};
const CLIP_TEXT_TOKEN_COUNT: usize = 77;
-pub fn run_clip_text(runtime: &MlRuntime, token_ids: &[i32]) -> MlResult<ClipResult> {
+pub fn run_clip_text(runtime: &MlRuntimeView<'_>, token_ids: &[i32]) -> MlResult<ClipResult> {
if token_ids.len() != CLIP_TEXT_TOKEN_COUNT {
return Err(MlError::InvalidRequest(format!(
"clip text expects exactly {CLIP_TEXT_TOKEN_COUNT} tokens, got {}",
@@ -18,7 +18,7 @@ pub fn run_clip_text(runtime: &MlRuntime, token_ids: &[i32]) -> MlResult<ClipRes
let clip_text = runtime.clip_text_session()?;
let (shape, output) = onnx::run_i32_f32(
- clip_text,
+ &clip_text,
token_ids.to_vec(),
[1, CLIP_TEXT_TOKEN_COUNT as i64],
)?;
@@ -45,7 +45,7 @@ pub fn run_clip_text(runtime: &MlRuntime, token_ids: &[i32]) -> MlResult<ClipRes
}
pub fn run_clip_text_query(
- runtime: &MlRuntime,
+ runtime: &MlRuntimeView<'_>,
query: &str,
vocab_path: &str,
) -> MlResult<ClipResult> {
diff --git a/mobile/apps/photos/rust/src/ml/face/detect.rs b/mobile/apps/photos/rust/src/ml/face/detect.rs
index 860d7dc126..e666bdb490 100644
--- a/mobile/apps/photos/rust/src/ml/face/detect.rs
+++ b/mobile/apps/photos/rust/src/ml/face/detect.rs
@@ -1,7 +1,7 @@
use crate::ml::{
error::{MlError, MlResult},
onnx, preprocess,
- runtime::MlRuntime,
+ runtime::MlRuntimeView,
types::{DecodedImage, FaceDetection},
};
@@ -11,14 +11,14 @@ const IOU_THRESHOLD: f32 = 0.4;
const MIN_SCORE_THRESHOLD: f32 = 0.5;
pub fn run_face_detection(
- runtime: &MlRuntime,
+ runtime: &MlRuntimeView<'_>,
decoded: &DecodedImage,
) -> MlResult<Vec<FaceDetection>> {
let (input, scaled_width, scaled_height, pad_left, pad_top) =
preprocess::preprocess_yolo(decoded)?;
let face_detection = runtime.face_detection_session()?;
let output_data = onnx::run_f32_data(
- face_detection,
+ &face_detection,
input,
[1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
)?;
diff --git a/mobile/apps/photos/rust/src/ml/face/embed.rs b/mobile/apps/photos/rust/src/ml/face/embed.rs
index c1372ed244..ccab739ead 100644
--- a/mobile/apps/photos/rust/src/ml/face/embed.rs
+++ b/mobile/apps/photos/rust/src/ml/face/embed.rs
@@ -1,7 +1,7 @@
use crate::ml::{
error::{MlError, MlResult},
onnx,
- runtime::MlRuntime,
+ runtime::MlRuntimeView,
types::FaceResult,
};
@@ -10,7 +10,7 @@ const FACE_INPUT_HEIGHT: i64 = 112;
const FACE_INPUT_CHANNELS: i64 = 3;
pub fn run_face_embedding(
- runtime: &MlRuntime,
+ runtime: &MlRuntimeView<'_>,
aligned_faces: &[Vec<f32>],
face_results: &mut [FaceResult],
) -> MlResult<()> {
@@ -40,7 +40,7 @@ pub fn run_face_embedding(
let face_embedding = runtime.face_embedding_session()?;
let (shape, output) = onnx::run_f32(
- face_embedding,
+ &face_embedding,
input,
[
aligned_faces.len() as i64,
diff --git a/mobile/apps/photos/rust/src/ml/onnx.rs b/mobile/apps/photos/rust/src/ml/onnx.rs
index 76ade597ef..d0d7e6f6f4 100644
--- a/mobile/apps/photos/rust/src/ml/onnx.rs
+++ b/mobile/apps/photos/rust/src/ml/onnx.rs
@@ -1,6 +1,6 @@
use ort::{
- CPUExecutionProvider, ExecutionProviderDispatch, GraphOptimizationLevel, Session,
- TensorElementType, Tensor, ValueType, XNNPACKExecutionProvider,
+ CPUExecutionProvider, ExecutionProviderDispatch, GraphOptimizationLevel, Session, Tensor,
+ TensorElementType, ValueType, XNNPACKExecutionProvider,
};
// Temporarily disabled on Rust side to avoid iOS duplicate ObjC class collisions
@@ -83,7 +83,11 @@ fn providers_for_policy(
if include_xnnpack && policy.prefer_xnnpack {
providers.push(XNNPACKExecutionProvider::default().build());
}
- providers.push(CPUExecutionProvider::default().with_arena_allocator().build());
+ providers.push(
+ CPUExecutionProvider::default()
+ .with_arena_allocator()
+ .build(),
+ );
}
providers
@@ -145,7 +149,10 @@ pub fn run_f32<const N: usize>(
} else {
let tensor = output.try_extract_tensor::<half::f16>()?;
let shape = tensor.shape().iter().map(|d| *d as i64).collect::<Vec<_>>();
- let data = tensor.iter().map(|v: &half::f16| v.to_f32()).collect::<Vec<_>>();
+ let data = tensor
+ .iter()
+ .map(|v: &half::f16| v.to_f32())
+ .collect::<Vec<_>>();
Ok((shape, data))
}
}
@@ -171,7 +178,10 @@ pub fn run_f32_data<const N: usize>(
Ok(tensor.iter().copied().collect::<Vec<_>>())
} else {
let tensor = output.try_extract_tensor::<half::f16>()?;
- Ok(tensor.iter().map(|v: &half::f16| v.to_f32()).collect::<Vec<_>>())
+ Ok(tensor
+ .iter()
+ .map(|v: &half::f16| v.to_f32())
+ .collect::<Vec<_>>())
}
}
diff --git a/mobile/apps/photos/rust/src/ml/pet/align.rs b/mobile/apps/photos/rust/src/ml/pet/align.rs
index 41685b3d0f..bd96dcc3b8 100644
--- a/mobile/apps/photos/rust/src/ml/pet/align.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/align.rs
@@ -8,7 +8,6 @@ use crate::ml::{
types::{DecodedImage, PetAlignmentResult, PetFaceDetection, PetFaceResult, to_face_id},
};
-
const PET_FACE_CROP_SIZE: u32 = 224;
/// Minimum eye distance in pixels below which alignment is skipped.
const MIN_EYE_DISTANCE: f32 = 5.0;
@@ -103,18 +102,15 @@ pub fn run_pet_face_alignment(
let local_cx = (box_x1 + box_x2) as f64 / 2.0 - region_x1 as f64;
let local_cy = (box_y1 + box_y2) as f64 / 2.0 - region_y1 as f64;
- let rotated = rotate_around_center(
- &region,
- angle_rad as f64,
- local_cx,
- local_cy,
- );
+ let rotated = rotate_around_center(&region, angle_rad as f64, local_cx, local_cy);
// Crop coordinates relative to the region
let nx1 = (box_x1 as f32 - bw * CROP_EXPAND - region_x1 as f32).max(0.0) as u32;
let ny1 = (box_y1 as f32 - bh * CROP_EXPAND - region_y1 as f32).max(0.0) as u32;
- let nx2 = (box_x2 as f32 + bw * CROP_EXPAND - region_x1 as f32).min(region_w as f32) as u32;
- let ny2 = (box_y2 as f32 + bh * CROP_EXPAND - region_y1 as f32).min(region_h as f32) as u32;
+ let nx2 =
+ (box_x2 as f32 + bw * CROP_EXPAND - region_x1 as f32).min(region_w as f32) as u32;
+ let ny2 =
+ (box_y2 as f32 + bh * CROP_EXPAND - region_y1 as f32).min(region_h as f32) as u32;
let crop_w = nx2.saturating_sub(nx1);
let crop_h = ny2.saturating_sub(ny1);
if crop_w == 0 || crop_h == 0 {
@@ -155,12 +151,7 @@ pub fn run_pet_face_alignment(
/// Rotate an image around a center point using bilinear interpolation
/// with BORDER_REPLICATE behaviour (clamp to nearest edge pixel).
-fn rotate_around_center(
- source: &RgbImage,
- angle_rad: f64,
- cx: f64,
- cy: f64,
-) -> RgbImage {
+fn rotate_around_center(source: &RgbImage, angle_rad: f64, cx: f64, cy: f64) -> RgbImage {
let w = source.width();
let h = source.height();
let cos_a = angle_rad.cos();
@@ -214,13 +205,7 @@ fn rotate_around_center(
}
/// Crop a region from an RGB image and resize to 224Γ—224 using bilinear interpolation.
-fn crop_and_resize_rgb(
- source: &RgbImage,
- x: u32,
- y: u32,
- w: u32,
- h: u32,
-) -> MlResult<RgbImage> {
+fn crop_and_resize_rgb(source: &RgbImage, x: u32, y: u32, w: u32, h: u32) -> MlResult<RgbImage> {
// Extract crop bytes
let src_w = source.width();
let src_h = source.height();
@@ -271,7 +256,8 @@ fn extract_rgb_region(
let end = start + (w as usize) * 3;
if end > decoded.rgb.len() {
return Err(MlError::Preprocess(format!(
- "region row {row} out of bounds (end={end}, len={})", decoded.rgb.len()
+ "region row {row} out of bounds (end={end}, len={})",
+ decoded.rgb.len()
)));
}
buf.extend_from_slice(&decoded.rgb[start..end]);
@@ -296,7 +282,8 @@ fn crop_and_resize_decoded(
let end = start + (w as usize) * 3;
if end > decoded.rgb.len() {
return Err(MlError::Preprocess(format!(
- "crop row {row} out of bounds (end={end}, len={})", decoded.rgb.len()
+ "crop row {row} out of bounds (end={end}, len={})",
+ decoded.rgb.len()
)));
}
crop_bytes.extend_from_slice(&decoded.rgb[start..end]);
diff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rs
index 99c0473431..817ecbd9c6 100644
--- a/mobile/apps/photos/rust/src/ml/pet/detect.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs
@@ -1,8 +1,8 @@
use crate::ml::{
error::{MlError, MlResult},
onnx, preprocess,
- runtime::MlRuntime,
- types::{DecodedImage, PetFaceDetection, PetBodyDetection},
+ runtime::MlRuntimeView,
+ types::{DecodedImage, PetBodyDetection, PetFaceDetection},
};
const INPUT_WIDTH: f32 = 640.0;
@@ -32,7 +32,7 @@ const COCO_DOG: u8 = 16;
///
/// This mirrors `pet_pipeline/detection.py` `FaceDetector.detect()`.
pub fn run_pet_face_detection(
- runtime: &MlRuntime,
+ runtime: &MlRuntimeView<'_>,
decoded: &DecodedImage,
) -> MlResult<Vec<PetFaceDetection>> {
let (input, scaled_width, scaled_height, pad_left, pad_top) =
@@ -40,7 +40,7 @@ pub fn run_pet_face_detection(
let pet_face_detection = runtime.pet_face_detection_session()?;
let (output_shape, output_data) = onnx::run_f32(
- pet_face_detection,
+ &pet_face_detection,
input,
[1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
)?;
@@ -54,10 +54,13 @@ pub fn run_pet_face_detection(
// Flat output: total_elements, must infer row_len.
// Prefer 13 (2-class model) as the expected format, then fall back.
let total = output_data.len();
- let inferred = if total % 13 == 0 { 13 }
- else if total % 12 == 0 { 12 }
- else if total % 11 == 0 { 11 }
- else {
+ let inferred = if total % 13 == 0 {
+ 13
+ } else if total % 12 == 0 {
+ 12
+ } else if total % 11 == 0 {
+ 11
+ } else {
return Err(MlError::Postprocess(format!(
"unexpected pet face detector output size: {} (shape: {:?})",
total, output_shape
@@ -81,7 +84,8 @@ pub fn run_pet_face_detection(
if row_len < 11 || output_data.len() < row_len {
return Err(MlError::Postprocess(format!(
"pet face detector row_len={} too small or output too short (len={})",
- row_len, output_data.len()
+ row_len,
+ output_data.len()
)));
}
@@ -152,7 +156,7 @@ pub fn run_pet_face_detection(
///
/// This mirrors `pet_pipeline/detection.py` `BodyDetector.detect()`.
pub fn run_pet_body_detection(
- runtime: &MlRuntime,
+ runtime: &MlRuntimeView<'_>,
decoded: &DecodedImage,
) -> MlResult<Vec<PetBodyDetection>> {
let (input, scaled_width, scaled_height, pad_left, pad_top) =
@@ -160,7 +164,7 @@ pub fn run_pet_body_detection(
let body_detection = runtime.pet_body_detection_session()?;
let (_output_shape, output_data) = onnx::run_f32(
- body_detection,
+ &body_detection,
input,
[1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
)?;
@@ -277,10 +281,12 @@ fn correct_for_maintained_aspect_ratio_3kp(
return;
}
- let transform_x =
- |x: f32| -> f32 { ((x * INPUT_WIDTH - pad_left as f32) / scaled_width as f32).clamp(0.0, 1.0) };
- let transform_y =
- |y: f32| -> f32 { ((y * INPUT_HEIGHT - pad_top as f32) / scaled_height as f32).clamp(0.0, 1.0) };
+ let transform_x = |x: f32| -> f32 {
+ ((x * INPUT_WIDTH - pad_left as f32) / scaled_width as f32).clamp(0.0, 1.0)
+ };
+ let transform_y = |y: f32| -> f32 {
+ ((y * INPUT_HEIGHT - pad_top as f32) / scaled_height as f32).clamp(0.0, 1.0)
+ };
for point in keypoints.iter_mut() {
point[0] = transform_x(point[0]);
@@ -358,7 +364,8 @@ fn naive_nms_pet_body(
// Only suppress within the same COCO class so a dog and cat
// occupying the same region are both retained.
if detections[i].coco_class == detections[j].coco_class
- && calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy) >= iou_threshold
+ && calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy)
+ >= iou_threshold
{
suppressed[j] = true;
}
diff --git a/mobile/apps/photos/rust/src/ml/pet/embed.rs b/mobile/apps/photos/rust/src/ml/pet/embed.rs
index 95f23a5b41..f640f56f5c 100644
--- a/mobile/apps/photos/rust/src/ml/pet/embed.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/embed.rs
@@ -1,7 +1,7 @@
use crate::ml::{
error::{MlError, MlResult},
onnx,
- runtime::MlRuntime,
+ runtime::MlRuntimeView,
types::{DecodedImage, PetBodyResult, PetFaceResult},
};
@@ -25,7 +25,7 @@ const BODY_EMBED_CHANNELS: i64 = 3;
/// Faces are grouped by species and batched per model to avoid running the
/// wrong embedding model on any detection.
pub fn run_pet_face_embedding(
- runtime: &MlRuntime,
+ runtime: &MlRuntimeView<'_>,
aligned_faces: &[Vec<f32>],
face_results: &mut [PetFaceResult],
) -> MlResult<()> {
@@ -40,7 +40,8 @@ pub fn run_pet_face_embedding(
)));
}
- let per_face_len = (FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;
+ let per_face_len =
+ (FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;
// Group indices by species (class_id from detection).
let mut dog_indices = Vec::new();
@@ -79,7 +80,7 @@ pub fn run_pet_face_embedding(
};
let (shape, output) = onnx::run_f32(
- session,
+ &session,
input,
[
indices.len() as i64,
@@ -129,7 +130,7 @@ pub fn run_pet_face_embedding(
///
/// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_body()`.
pub fn run_pet_body_embedding(
- runtime: &MlRuntime,
+ runtime: &MlRuntimeView<'_>,
decoded: &DecodedImage,
body_results: &mut [PetBodyResult],
) -> MlResult<()> {
@@ -147,8 +148,9 @@ pub fn run_pet_body_embedding(
let mut cat_indices = Vec::new();
let mut preprocessed: Vec<Option<Vec<f32>>> = Vec::with_capacity(body_results.len());
for (i, body_result) in body_results.iter().enumerate() {
- let crop = extract_crop(decoded, &body_result.detection.box_xyxy)
- .and_then(|(crop_data, crop_w, crop_h)| preprocess_pet_embedding(&crop_data, crop_w, crop_h));
+ let crop = extract_crop(decoded, &body_result.detection.box_xyxy).and_then(
+ |(crop_data, crop_w, crop_h)| preprocess_pet_embedding(&crop_data, crop_w, crop_h),
+ );
match crop {
Ok(input) => {
preprocessed.push(Some(input));
@@ -182,7 +184,7 @@ pub fn run_pet_body_embedding(
};
let (shape, output) = onnx::run_f32(
- session,
+ &session,
input,
[
indices.len() as i64,
diff --git a/mobile/apps/photos/rust/src/ml/pet/preprocess.rs b/mobile/apps/photos/rust/src/ml/pet/preprocess.rs
index c42e6abdd4..2f17b2f255 100644
--- a/mobile/apps/photos/rust/src/ml/pet/preprocess.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/preprocess.rs
@@ -41,8 +41,9 @@ pub fn preprocess_pet_embedding(
let target_w = PET_EMBED_INPUT_SIZE as u32;
let target_h = PET_EMBED_INPUT_SIZE as u32;
- let src_image = FirImage::from_vec_u8(crop_width, crop_height, rgb_crop.to_vec(), PixelType::U8x3)
- .map_err(|e| MlError::Preprocess(format!("failed to create FIR source image: {e}")))?;
+ let src_image =
+ FirImage::from_vec_u8(crop_width, crop_height, rgb_crop.to_vec(), PixelType::U8x3)
+ .map_err(|e| MlError::Preprocess(format!("failed to create FIR source image: {e}")))?;
let mut resized_image = FirImage::new(target_w, target_h, PixelType::U8x3);
let mut resizer = Resizer::new();
@@ -82,27 +83,30 @@ pub fn preprocess_pet_embedding(
///
/// The bounding box is in relative coordinates [0, 1].
/// Returns the crop as RGB bytes and its dimensions.
-pub fn extract_crop(
- decoded: &DecodedImage,
- box_xyxy: &[f32; 4],
-) -> MlResult<(Vec<u8>, u32, u32)> {
+pub fn extract_crop(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<(Vec<u8>, u32, u32)> {
let img_w = decoded.dimensions.width;
let img_h = decoded.dimensions.height;
let max_x = if img_w > 0 { img_w - 1 } else { 0 };
let max_y = if img_h > 0 { img_h - 1 } else { 0 };
- let x1 = (box_xyxy[0] * img_w as f32).round().clamp(0.0, max_x as f32) as u32;
- let y1 = (box_xyxy[1] * img_h as f32).round().clamp(0.0, max_y as f32) as u32;
- let x2 = (box_xyxy[2] * img_w as f32).round().clamp(0.0, img_w as f32) as u32;
- let y2 = (box_xyxy[3] * img_h as f32).round().clamp(0.0, img_h as f32) as u32;
+ let x1 = (box_xyxy[0] * img_w as f32)
+ .round()
+ .clamp(0.0, max_x as f32) as u32;
+ let y1 = (box_xyxy[1] * img_h as f32)
+ .round()
+ .clamp(0.0, max_y as f32) as u32;
+ let x2 = (box_xyxy[2] * img_w as f32)
+ .round()
+ .clamp(0.0, img_w as f32) as u32;
+ let y2 = (box_xyxy[3] * img_h as f32)
+ .round()
+ .clamp(0.0, img_h as f32) as u32;
let crop_w = x2.saturating_sub(x1);
let crop_h = y2.saturating_sub(y1);
if crop_w == 0 || crop_h == 0 {
- return Err(MlError::Preprocess(
- "crop region has zero area".to_string(),
- ));
+ return Err(MlError::Preprocess("crop region has zero area".to_string()));
}
let mut crop = Vec::with_capacity((crop_w as usize) * (crop_h as usize) * 3);
@@ -114,7 +118,10 @@ pub fn extract_crop(
if row_end > decoded.rgb.len() || row_start > decoded.rgb.len() {
return Err(MlError::Preprocess(format!(
"crop row {} out of bounds: start={}, end={}, buffer_len={}",
- row, row_start, row_end, decoded.rgb.len()
+ row,
+ row_start,
+ row_end,
+ decoded.rgb.len()
)));
}
crop.extend_from_slice(&decoded.rgb[row_start..row_end]);
diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rs
index ab625fd702..43f309729a 100644
--- a/mobile/apps/photos/rust/src/ml/runtime.rs
+++ b/mobile/apps/photos/rust/src/ml/runtime.rs
@@ -1,6 +1,9 @@
-use std::sync::RwLock;
+use std::{
+ ops::Deref,
+ sync::{Mutex, MutexGuard},
+};
-use once_cell::sync::{Lazy, OnceCell};
+use once_cell::sync::Lazy;
use ort::Session;
use crate::ml::{
@@ -22,7 +25,9 @@ fn rt_log(msg: &str) {
use std::ffi::CString;
let tag = CString::new("ml_rt").unwrap();
let cmsg = CString::new(msg).unwrap_or_else(|_| CString::new("(invalid)").unwrap());
- unsafe { __android_log_write(4, tag.as_ptr(), cmsg.as_ptr()); }
+ unsafe {
+ __android_log_write(4, tag.as_ptr(), cmsg.as_ptr());
+ }
}
#[cfg(not(target_os = "android"))]
{
@@ -63,314 +68,454 @@ pub struct ModelPaths {
pub pet_body_embedding_cat: String,
}
-impl ModelPaths {
- /// Check whether the existing runtime can serve a request with `requested` paths.
- /// An empty path in `requested` means "not needed" and is always compatible.
- fn can_serve(&self, requested: &ModelPaths) -> bool {
- fn ok(existing: &str, requested: &str) -> bool {
- requested.is_empty() || existing == requested
- }
- ok(&self.face_detection, &requested.face_detection)
- && ok(&self.face_embedding, &requested.face_embedding)
- && ok(&self.clip_image, &requested.clip_image)
- && ok(&self.clip_text, &requested.clip_text)
- && ok(&self.pet_face_detection, &requested.pet_face_detection)
- && ok(&self.pet_face_embedding_dog, &requested.pet_face_embedding_dog)
- && ok(&self.pet_face_embedding_cat, &requested.pet_face_embedding_cat)
- && ok(&self.pet_body_detection, &requested.pet_body_detection)
- && ok(&self.pet_body_embedding_dog, &requested.pet_body_embedding_dog)
- && ok(&self.pet_body_embedding_cat, &requested.pet_body_embedding_cat)
- }
-
- /// Merge two configs: keep existing non-empty paths, override with non-empty
- /// paths from `other`.
- fn merge(&self, other: &ModelPaths) -> ModelPaths {
- fn pick(existing: &str, new: &str) -> String {
- if new.is_empty() { existing.to_string() } else { new.to_string() }
- }
- ModelPaths {
- face_detection: pick(&self.face_detection, &other.face_detection),
- face_embedding: pick(&self.face_embedding, &other.face_embedding),
- clip_image: pick(&self.clip_image, &other.clip_image),
- clip_text: pick(&self.clip_text, &other.clip_text),
- pet_face_detection: pick(&self.pet_face_detection, &other.pet_face_detection),
- pet_face_embedding_dog: pick(&self.pet_face_embedding_dog, &other.pet_face_embedding_dog),
- pet_face_embedding_cat: pick(&self.pet_face_embedding_cat, &other.pet_face_embedding_cat),
- pet_body_detection: pick(&self.pet_body_detection, &other.pet_body_detection),
- pet_body_embedding_dog: pick(&self.pet_body_embedding_dog, &other.pet_body_embedding_dog),
- pet_body_embedding_cat: pick(&self.pet_body_embedding_cat, &other.pet_body_embedding_cat),
- }
- }
-}
-
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MlRuntimeConfig {
pub model_paths: ModelPaths,
pub provider_policy: ExecutionProviderPolicy,
}
-/// A lazily-initialized ONNX session that is thread-safe for concurrent reads.
-///
-/// `OnceLock` ensures the session is loaded exactly once (on first use) and
-/// then shared via `&Session` for concurrent inference β€” `ort::Session::run()`
-/// takes `&self` and is `Send + Sync`.
#[derive(Debug)]
-struct LazySession {
+struct ModelSlotState {
path: String,
- policy: ExecutionProviderPolicy,
- session: OnceCell<Session>,
+ requested_policy: ExecutionProviderPolicy,
+ fell_back_to_cpu: bool,
+ pin_count: usize,
+ session: Option<Session>,
}
-impl LazySession {
- fn new(path: String, policy: ExecutionProviderPolicy) -> Self {
+#[derive(Debug)]
+struct ModelSlot {
+ state: Mutex<ModelSlotState>,
+}
+
+pub struct ModelSessionGuard<'a> {
+ state: MutexGuard<'a, ModelSlotState>,
+}
+
+pub struct MlRuntimeView<'a> {
+ runtime: &'a MlRuntime,
+ config: &'a MlRuntimeConfig,
+}
+
+impl Deref for ModelSessionGuard<'_> {
+ type Target = Session;
+
+ fn deref(&self) -> &Self::Target {
+ self.state
+ .session
+ .as_ref()
+ .expect("session must be loaded before creating ModelSessionGuard")
+ }
+}
+
+impl ModelSlot {
+ fn new() -> Self {
Self {
- path,
- policy,
- session: OnceCell::new(),
+ state: Mutex::new(ModelSlotState {
+ path: String::new(),
+ requested_policy: ExecutionProviderPolicy::default(),
+ fell_back_to_cpu: false,
+ pin_count: 0,
+ session: None,
+ }),
+ }
+ }
+
+ fn lock_state(&self) -> MutexGuard<'_, ModelSlotState> {
+ match self.state.lock() {
+ Ok(guard) => guard,
+ Err(poisoned) => poisoned.into_inner(),
+ }
+ }
+
+ fn configure_if_requested(&self, path: &str, policy: &ExecutionProviderPolicy) {
+ if path.trim().is_empty() {
+ return;
+ }
+ let mut state = self.lock_state();
+ Self::set_config_locked(&mut state, path, policy);
+ }
+
+ fn sync_indexing_residency(
+ &self,
+ path: &str,
+ policy: &ExecutionProviderPolicy,
+ error_msg: &str,
+ ) -> MlResult<()> {
+ let mut state = self.lock_state();
+ if path.trim().is_empty() {
+ state.path.clear();
+ state.fell_back_to_cpu = false;
+ state.pin_count = 0;
+ state.session = None;
+ return Ok(());
+ }
+
+ Self::set_config_locked(&mut state, path, policy);
+ state.pin_count = 1;
+ Self::ensure_loaded_locked(&mut state, error_msg)?;
+ Ok(())
+ }
+
+ fn release_indexing_residency(&self) {
+ let mut state = self.lock_state();
+ if state.pin_count > 0 {
+ state.pin_count -= 1;
+ }
+ if state.pin_count == 0 {
+ state.session = None;
+ }
+ }
+
+ fn force_cpu_fallback_if_configured(&self, path: &str) {
+ if path.trim().is_empty() {
+ return;
+ }
+
+ let mut state = self.lock_state();
+ if state.path != path {
+ return;
}
+ if !state.requested_policy.allow_cpu_fallback {
+ return;
+ }
+ if cpu_only_policy(&state.requested_policy) == state.requested_policy
+ || state.fell_back_to_cpu
+ {
+ return;
+ }
+
+ state.fell_back_to_cpu = true;
+ state.session = None;
}
- fn get(&self, error_msg: &str) -> MlResult<&Session> {
- if self.path.trim().is_empty() {
+ fn session_guard_for(
+ &self,
+ path: &str,
+ policy: &ExecutionProviderPolicy,
+ error_msg: &str,
+ ) -> MlResult<ModelSessionGuard<'_>> {
+ if path.trim().is_empty() {
return Err(MlError::InvalidRequest(error_msg.to_string()));
}
- self.session
- .get_or_try_init(|| {
- let model_name = self.path.rsplit('/').next().unwrap_or(&self.path);
- rt_log(&format!("loading {model_name}"));
- let t = std::time::Instant::now();
- let s = onnx::build_session(&self.path, &self.policy)?;
- rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));
- Ok(s)
- })
+
+ let mut state = self.lock_state();
+ Self::set_config_locked(&mut state, path, policy);
+ Self::ensure_loaded_locked(&mut state, error_msg)?;
+ Ok(ModelSessionGuard { state })
+ }
+
+ fn set_config_locked(state: &mut ModelSlotState, path: &str, policy: &ExecutionProviderPolicy) {
+ if state.path == path && state.requested_policy == *policy {
+ return;
+ }
+ state.path = path.to_string();
+ state.requested_policy = policy.clone();
+ state.fell_back_to_cpu = false;
+ state.session = None;
+ }
+
+ fn ensure_loaded_locked(state: &mut ModelSlotState, error_msg: &str) -> MlResult<()> {
+ if state.path.trim().is_empty() {
+ return Err(MlError::InvalidRequest(error_msg.to_string()));
+ }
+ if state.session.is_some() {
+ return Ok(());
+ }
+
+ let model_name = state.path.rsplit('/').next().unwrap_or(&state.path);
+ rt_log(&format!("loading {model_name}"));
+ let t = std::time::Instant::now();
+ let session = onnx::build_session(&state.path, &effective_policy(state))?;
+ rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));
+ state.session = Some(session);
+ Ok(())
}
}
-#[derive(Debug)]
-pub struct MlRuntime {
- face_detection: LazySession,
- face_embedding: LazySession,
- clip_image: LazySession,
- clip_text: LazySession,
- pet_face_detection: LazySession,
- pet_face_embedding_dog: LazySession,
- pet_face_embedding_cat: LazySession,
- pet_body_detection: LazySession,
- pet_body_embedding_dog: LazySession,
- pet_body_embedding_cat: LazySession,
+fn effective_policy(state: &ModelSlotState) -> ExecutionProviderPolicy {
+ if state.fell_back_to_cpu && state.requested_policy.allow_cpu_fallback {
+ cpu_only_policy(&state.requested_policy)
+ } else {
+ state.requested_policy.clone()
+ }
+}
+
+fn cpu_only_policy(policy: &ExecutionProviderPolicy) -> ExecutionProviderPolicy {
+ ExecutionProviderPolicy {
+ prefer_coreml: false,
+ prefer_nnapi: false,
+ prefer_xnnpack: false,
+ allow_cpu_fallback: policy.allow_cpu_fallback,
+ }
}
#[derive(Debug)]
-struct RuntimeState {
- config: MlRuntimeConfig,
- runtime: MlRuntime,
- /// Set after a hardware EP failure triggers a successful CPU-only fallback.
- /// While true, `ensure_runtime` treats a CPU-only runtime as compatible
- /// with requests that prefer hardware acceleration (when
- /// `allow_cpu_fallback` is set), avoiding repeated rebuild/retry cycles
- /// on devices where NNAPI/CoreML is broken.
- fell_back_to_cpu: bool,
+pub struct MlRuntime {
+ face_detection: ModelSlot,
+ face_embedding: ModelSlot,
+ clip_image: ModelSlot,
+ clip_text: ModelSlot,
+ pet_face_detection: ModelSlot,
+ pet_face_embedding_dog: ModelSlot,
+ pet_face_embedding_cat: ModelSlot,
+ pet_body_detection: ModelSlot,
+ pet_body_embedding_dog: ModelSlot,
+ pet_body_embedding_cat: ModelSlot,
}
-static GLOBAL_RUNTIME: Lazy<RwLock<Option<RuntimeState>>> = Lazy::new(|| RwLock::new(None));
+static GLOBAL_RUNTIME: Lazy<MlRuntime> = Lazy::new(MlRuntime::new);
-fn create_runtime(config: &MlRuntimeConfig) -> MlRuntime {
- let p = &config.provider_policy;
+fn pet_policy() -> ExecutionProviderPolicy {
// Pet models use CPU-only to avoid NNAPI/CoreML driver issues with
// FP16 models on some devices.
// TODO: Make pet EP policy configurable so hardware acceleration can be
// re-enabled once driver issues are resolved.
- let pet_policy = ExecutionProviderPolicy {
+ ExecutionProviderPolicy {
prefer_coreml: false,
prefer_nnapi: false,
prefer_xnnpack: false,
allow_cpu_fallback: true,
- };
- MlRuntime {
- face_detection: LazySession::new(config.model_paths.face_detection.clone(), p.clone()),
- face_embedding: LazySession::new(config.model_paths.face_embedding.clone(), p.clone()),
- clip_image: LazySession::new(config.model_paths.clip_image.clone(), p.clone()),
- clip_text: LazySession::new(config.model_paths.clip_text.clone(), p.clone()),
- pet_face_detection: LazySession::new(config.model_paths.pet_face_detection.clone(), pet_policy.clone()),
- pet_face_embedding_dog: LazySession::new(config.model_paths.pet_face_embedding_dog.clone(), pet_policy.clone()),
- pet_face_embedding_cat: LazySession::new(config.model_paths.pet_face_embedding_cat.clone(), pet_policy.clone()),
- pet_body_detection: LazySession::new(config.model_paths.pet_body_detection.clone(), pet_policy.clone()),
- pet_body_embedding_dog: LazySession::new(config.model_paths.pet_body_embedding_dog.clone(), pet_policy.clone()),
- pet_body_embedding_cat: LazySession::new(config.model_paths.pet_body_embedding_cat.clone(), pet_policy),
}
}
impl MlRuntime {
- pub fn face_detection_session(&self) -> MlResult<&Session> {
- self.face_detection.get(
+ fn new() -> Self {
+ 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(),
+ }
+ }
+
+ fn configure_requested_models(&self, config: &MlRuntimeConfig) {
+ let shared_policy = &config.provider_policy;
+ let pet_policy = pet_policy();
+
+ self.face_detection
+ .configure_if_requested(&config.model_paths.face_detection, shared_policy);
+ self.face_embedding
+ .configure_if_requested(&config.model_paths.face_embedding, shared_policy);
+ self.clip_image
+ .configure_if_requested(&config.model_paths.clip_image, shared_policy);
+ self.clip_text
+ .configure_if_requested(&config.model_paths.clip_text, shared_policy);
+ self.pet_face_detection
+ .configure_if_requested(&config.model_paths.pet_face_detection, &pet_policy);
+ self.pet_face_embedding_dog
+ .configure_if_requested(&config.model_paths.pet_face_embedding_dog, &pet_policy);
+ self.pet_face_embedding_cat
+ .configure_if_requested(&config.model_paths.pet_face_embedding_cat, &pet_policy);
+ self.pet_body_detection
+ .configure_if_requested(&config.model_paths.pet_body_detection, &pet_policy);
+ self.pet_body_embedding_dog
+ .configure_if_requested(&config.model_paths.pet_body_embedding_dog, &pet_policy);
+ self.pet_body_embedding_cat
+ .configure_if_requested(&config.model_paths.pet_body_embedding_cat, &pet_policy);
+ }
+
+ fn prepare_indexing_models(&self, config: &MlRuntimeConfig) -> MlResult<()> {
+ let shared_policy = &config.provider_policy;
+ let pet_policy = pet_policy();
+
+ self.face_detection.sync_indexing_residency(
+ &config.model_paths.face_detection,
+ shared_policy,
+ "missing model path: faceDetectionModelPath is required when runFaces is true",
+ )?;
+ self.face_embedding.sync_indexing_residency(
+ &config.model_paths.face_embedding,
+ shared_policy,
+ "missing model path: faceEmbeddingModelPath is required when runFaces is true",
+ )?;
+ self.clip_image.sync_indexing_residency(
+ &config.model_paths.clip_image,
+ shared_policy,
+ "missing model path: clipImageModelPath is required when runClip is true",
+ )?;
+ self.pet_face_detection.sync_indexing_residency(
+ &config.model_paths.pet_face_detection,
+ &pet_policy,
+ "missing model path: petFaceDetectionModelPath is required when runPets is true",
+ )?;
+ self.pet_face_embedding_dog.sync_indexing_residency(
+ &config.model_paths.pet_face_embedding_dog,
+ &pet_policy,
+ "missing model path: petFaceEmbeddingDogModelPath is required",
+ )?;
+ self.pet_face_embedding_cat.sync_indexing_residency(
+ &config.model_paths.pet_face_embedding_cat,
+ &pet_policy,
+ "missing model path: petFaceEmbeddingCatModelPath is required",
+ )?;
+ self.pet_body_detection.sync_indexing_residency(
+ &config.model_paths.pet_body_detection,
+ &pet_policy,
+ "missing model path: petBodyDetectionModelPath is required when runPets is true",
+ )?;
+ self.pet_body_embedding_dog.sync_indexing_residency(
+ &config.model_paths.pet_body_embedding_dog,
+ &pet_policy,
+ "missing model path: petBodyEmbeddingDogModelPath is required",
+ )?;
+ self.pet_body_embedding_cat.sync_indexing_residency(
+ &config.model_paths.pet_body_embedding_cat,
+ &pet_policy,
+ "missing model path: petBodyEmbeddingCatModelPath is required",
+ )?;
+
+ Ok(())
+ }
+
+ fn release_indexing_models(&self) {
+ self.face_detection.release_indexing_residency();
+ self.face_embedding.release_indexing_residency();
+ self.clip_image.release_indexing_residency();
+ self.pet_face_detection.release_indexing_residency();
+ self.pet_face_embedding_dog.release_indexing_residency();
+ self.pet_face_embedding_cat.release_indexing_residency();
+ self.pet_body_detection.release_indexing_residency();
+ self.pet_body_embedding_dog.release_indexing_residency();
+ self.pet_body_embedding_cat.release_indexing_residency();
+ }
+
+ fn force_cpu_only_for_requested_models(&self, config: &MlRuntimeConfig) {
+ self.face_detection
+ .force_cpu_fallback_if_configured(&config.model_paths.face_detection);
+ self.face_embedding
+ .force_cpu_fallback_if_configured(&config.model_paths.face_embedding);
+ self.clip_image
+ .force_cpu_fallback_if_configured(&config.model_paths.clip_image);
+ self.clip_text
+ .force_cpu_fallback_if_configured(&config.model_paths.clip_text);
+ self.pet_face_detection
+ .force_cpu_fallback_if_configured(&config.model_paths.pet_face_detection);
+ self.pet_face_embedding_dog
+ .force_cpu_fallback_if_configured(&config.model_paths.pet_face_embedding_dog);
+ self.pet_face_embedding_cat
+ .force_cpu_fallback_if_configured(&config.model_paths.pet_face_embedding_cat);
+ self.pet_body_detection
+ .force_cpu_fallback_if_configured(&config.model_paths.pet_body_detection);
+ self.pet_body_embedding_dog
+ .force_cpu_fallback_if_configured(&config.model_paths.pet_body_embedding_dog);
+ self.pet_body_embedding_cat
+ .force_cpu_fallback_if_configured(&config.model_paths.pet_body_embedding_cat);
+ }
+
+ fn view<'a>(&'a self, config: &'a MlRuntimeConfig) -> MlRuntimeView<'a> {
+ MlRuntimeView {
+ runtime: self,
+ config,
+ }
+ }
+}
+
+impl MlRuntimeView<'_> {
+ pub fn face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {
+ self.runtime.face_detection.session_guard_for(
+ &self.config.model_paths.face_detection,
+ &self.config.provider_policy,
"missing model path: faceDetectionModelPath is required when runFaces is true",
)
}
- pub fn face_embedding_session(&self) -> MlResult<&Session> {
- self.face_embedding.get(
+ pub fn face_embedding_session(&self) -> MlResult<ModelSessionGuard<'_>> {
+ self.runtime.face_embedding.session_guard_for(
+ &self.config.model_paths.face_embedding,
+ &self.config.provider_policy,
"missing model path: faceEmbeddingModelPath is required when runFaces is true",
)
}
- pub fn clip_image_session(&self) -> MlResult<&Session> {
- self.clip_image.get(
+ pub fn clip_image_session(&self) -> MlResult<ModelSessionGuard<'_>> {
+ self.runtime.clip_image.session_guard_for(
+ &self.config.model_paths.clip_image,
+ &self.config.provider_policy,
"missing model path: clipImageModelPath is required when runClip is true",
)
}
- pub fn clip_text_session(&self) -> MlResult<&Session> {
- self.clip_text.get(
+ pub fn clip_text_session(&self) -> MlResult<ModelSessionGuard<'_>> {
+ self.runtime.clip_text.session_guard_for(
+ &self.config.model_paths.clip_text,
+ &self.config.provider_policy,
"missing model path: clipTextModelPath is required when running clip text",
)
}
- pub fn pet_face_detection_session(&self) -> MlResult<&Session> {
- self.pet_face_detection.get(
+ pub fn pet_face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {
+ self.runtime.pet_face_detection.session_guard_for(
+ &self.config.model_paths.pet_face_detection,
+ &pet_policy(),
"missing model path: petFaceDetectionModelPath is required when runPets is true",
)
}
- pub fn pet_face_embedding_dog_session(&self) -> MlResult<&Session> {
- self.pet_face_embedding_dog
- .get("missing model path: petFaceEmbeddingDogModelPath is required")
+ 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,
+ &pet_policy(),
+ "missing model path: petFaceEmbeddingDogModelPath is required",
+ )
}
- pub fn pet_face_embedding_cat_session(&self) -> MlResult<&Session> {
- self.pet_face_embedding_cat
- .get("missing model path: petFaceEmbeddingCatModelPath 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,
+ &pet_policy(),
+ "missing model path: petFaceEmbeddingCatModelPath is required",
+ )
}
- pub fn pet_body_detection_session(&self) -> MlResult<&Session> {
- self.pet_body_detection.get(
+ pub fn pet_body_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {
+ self.runtime.pet_body_detection.session_guard_for(
+ &self.config.model_paths.pet_body_detection,
+ &pet_policy(),
"missing model path: petBodyDetectionModelPath is required when runPets is true",
)
}
- pub fn pet_body_embedding_dog_session(&self) -> MlResult<&Session> {
- self.pet_body_embedding_dog
- .get("missing model path: petBodyEmbeddingDogModelPath is required")
- }
-
- pub fn pet_body_embedding_cat_session(&self) -> MlResult<&Session> {
- self.pet_body_embedding_cat
- .get("missing model path: petBodyEmbeddingCatModelPath is required")
- }
-}
-
-fn read_runtime() -> std::sync::RwLockReadGuard<'static, Option<RuntimeState>> {
- match GLOBAL_RUNTIME.read() {
- Ok(guard) => guard,
- Err(poisoned) => poisoned.into_inner(),
+ 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,
+ &pet_policy(),
+ "missing model path: petBodyEmbeddingDogModelPath is required",
+ )
}
-}
-fn write_runtime() -> std::sync::RwLockWriteGuard<'static, Option<RuntimeState>> {
- match GLOBAL_RUNTIME.write() {
- Ok(guard) => guard,
- Err(poisoned) => {
- let mut guard = poisoned.into_inner();
- *guard = None;
- guard
- }
+ 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,
+ &pet_policy(),
+ "missing model path: petBodyEmbeddingCatModelPath is required",
+ )
}
}
-/// A CPU-only runtime satisfies a hardware-preferring request when the
-/// runtime was installed via EP fallback and the caller allows CPU fallback.
-fn policy_compatible(existing: &RuntimeState, requested: &ExecutionProviderPolicy) -> bool {
- existing.config.provider_policy == *requested
- || (existing.fell_back_to_cpu && requested.allow_cpu_fallback)
-}
-
pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
- ensure_runtime_inner(config, false)
+ GLOBAL_RUNTIME.configure_requested_models(config);
+ Ok(())
}
-/// When `mark_as_fallback` is true the installed runtime is atomically
-/// tagged with `fell_back_to_cpu = true` inside the same write lock,
-/// preventing a concurrent caller from observing an un-tagged CPU runtime
-/// and replacing it with a hardware EP runtime before the flag is set.
-fn ensure_runtime_inner(config: &MlRuntimeConfig, mark_as_fallback: bool) -> MlResult<()> {
- // Fast path: check under read lock whether the current runtime can serve.
- // Skip the fast path when marking a fallback β€” we need the write lock to
- // set `fell_back_to_cpu` atomically.
- if !mark_as_fallback {
- let guard = read_runtime();
- if let Some(existing) = guard.as_ref()
- && policy_compatible(existing, &config.provider_policy)
- && existing.config.model_paths.can_serve(&config.model_paths)
- {
- return Ok(()); // existing runtime handles this request
- }
- }
-
- // Slow path: acquire write lock, re-check (another thread may have
- // already merged), compute the merged config, build, and install.
- let mut guard = write_runtime();
- let (merged, preserve_fallback) = match guard.as_ref() {
- Some(existing) => {
- // Re-check: a concurrent caller may have updated since the
- // read-lock check above.
- if policy_compatible(existing, &config.provider_policy)
- && existing.config.model_paths.can_serve(&config.model_paths)
- {
- // Runtime already compatible β€” just ensure the fallback
- // flag is set when requested.
- if mark_as_fallback
- && let Some(state) = guard.as_mut()
- {
- state.fell_back_to_cpu = true;
- }
- return Ok(());
- }
- // If we previously fell back to CPU, keep the CPU-only policy
- // for the merged config instead of re-trying the broken EP.
- let effective_policy =
- if existing.fell_back_to_cpu && config.provider_policy.allow_cpu_fallback {
- existing.config.provider_policy.clone()
- } else {
- config.provider_policy.clone()
- };
- (
- MlRuntimeConfig {
- model_paths: existing.config.model_paths.merge(&config.model_paths),
- provider_policy: effective_policy,
- },
- existing.fell_back_to_cpu,
- )
- }
- None => (config.clone(), false),
- };
-
- let runtime = create_runtime(&merged);
- *guard = Some(RuntimeState {
- config: merged,
- runtime,
- fell_back_to_cpu: preserve_fallback || mark_as_fallback,
- });
- Ok(())
+pub fn prepare_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
+ GLOBAL_RUNTIME.prepare_indexing_models(config)
}
-/// Run a function with a shared (read) reference to the runtime.
-///
-/// Multiple callers can hold the read lock concurrently, so CLIP text
-/// queries no longer block on image indexing and vice versa. The write
-/// lock is only acquired during `ensure_runtime` to swap the config.
pub fn with_runtime<F, R>(config: &MlRuntimeConfig, func: F) -> MlResult<R>
where
- F: Fn(&MlRuntime) -> MlResult<R>,
+ F: for<'a> Fn(&MlRuntimeView<'a>) -> MlResult<R>,
{
ensure_runtime(config)?;
- let first_result = {
- let guard = read_runtime();
- let state = guard
- .as_ref()
- .ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;
- func(&state.runtime)
- };
-
+ let runtime_view = GLOBAL_RUNTIME.view(config);
+ let first_result = func(&runtime_view);
match first_result {
Ok(result) => Ok(result),
Err(first_error) => {
@@ -378,24 +523,21 @@ where
return Err(first_error);
}
- let fallback_config = cpu_only_runtime_config(config);
- rt_log(&format!("execution provider failed, retrying with CPU-only runtime: {first_error}"));
- // Install the CPU-only runtime and atomically mark it as a
- // fallback so concurrent callers see `fell_back_to_cpu = true`
- // immediately and don't rebuild a hardware EP runtime.
- ensure_runtime_inner(&fallback_config, true)?;
-
- {
- let guard = read_runtime();
- let state = guard
- .as_ref()
- .ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;
- func(&state.runtime)
- }
+ 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);
+ func(&runtime_view)
}
}
}
+pub fn release_runtime() -> MlResult<()> {
+ GLOBAL_RUNTIME.release_indexing_models();
+ Ok(())
+}
+
fn should_retry_with_cpu_only_runtime(config: &MlRuntimeConfig, error: &MlError) -> bool {
if !config.provider_policy.allow_cpu_fallback {
return false;
@@ -403,15 +545,7 @@ fn should_retry_with_cpu_only_runtime(config: &MlRuntimeConfig, error: &MlError)
if !is_execution_provider_failure(error) {
return false;
}
- cpu_only_runtime_config(config) != *config
-}
-
-fn cpu_only_runtime_config(config: &MlRuntimeConfig) -> MlRuntimeConfig {
- let mut fallback = config.clone();
- fallback.provider_policy.prefer_coreml = false;
- fallback.provider_policy.prefer_nnapi = false;
- fallback.provider_policy.prefer_xnnpack = false;
- fallback
+ cpu_only_policy(&config.provider_policy) != config.provider_policy
}
fn is_execution_provider_failure(error: &MlError) -> bool {
@@ -427,8 +561,102 @@ fn is_execution_provider_failure(error: &MlError) -> bool {
|| normalized.contains("ep error")
}
-pub fn release_runtime() -> MlResult<()> {
- let mut guard = write_runtime();
- *guard = None;
- Ok(())
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_policy() -> ExecutionProviderPolicy {
+ ExecutionProviderPolicy {
+ prefer_coreml: false,
+ prefer_nnapi: false,
+ prefer_xnnpack: false,
+ allow_cpu_fallback: true,
+ }
+ }
+
+ fn empty_paths() -> ModelPaths {
+ ModelPaths {
+ face_detection: String::new(),
+ face_embedding: String::new(),
+ clip_image: String::new(),
+ clip_text: String::new(),
+ 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(),
+ }
+ }
+
+ #[test]
+ fn configure_requested_models_preserves_unrequested_slots() {
+ let runtime = MlRuntime::new();
+ let policy = test_policy();
+
+ runtime.configure_requested_models(&MlRuntimeConfig {
+ model_paths: ModelPaths {
+ clip_text: "clip_text.onnx".to_string(),
+ ..empty_paths()
+ },
+ provider_policy: policy.clone(),
+ });
+
+ runtime.configure_requested_models(&MlRuntimeConfig {
+ model_paths: ModelPaths {
+ face_detection: "face.onnx".to_string(),
+ ..empty_paths()
+ },
+ provider_policy: policy,
+ });
+
+ let clip_text = runtime.clip_text.lock_state();
+ assert_eq!(clip_text.path, "clip_text.onnx");
+ }
+
+ #[test]
+ fn release_indexing_models_keeps_clip_text_state() {
+ let runtime = MlRuntime::new();
+
+ {
+ let mut clip_text = runtime.clip_text.lock_state();
+ clip_text.path = "clip_text.onnx".to_string();
+ clip_text.pin_count = 0;
+ }
+ {
+ let mut face_detection = runtime.face_detection.lock_state();
+ face_detection.path = "face.onnx".to_string();
+ face_detection.pin_count = 1;
+ }
+
+ runtime.release_indexing_models();
+
+ let clip_text = runtime.clip_text.lock_state();
+ assert_eq!(clip_text.path, "clip_text.onnx");
+ assert_eq!(clip_text.pin_count, 0);
+
+ let face_detection = runtime.face_detection.lock_state();
+ assert_eq!(face_detection.pin_count, 0);
+ }
+
+ #[test]
+ fn sync_indexing_residency_clears_disabled_slots() {
+ let slot = ModelSlot::new();
+
+ {
+ let mut state = slot.lock_state();
+ state.path = "pet.onnx".to_string();
+ state.pin_count = 1;
+ state.fell_back_to_cpu = true;
+ }
+
+ slot.sync_indexing_residency("", &test_policy(), "unused")
+ .unwrap();
+
+ let state = slot.lock_state();
+ assert!(state.path.is_empty());
+ assert_eq!(state.pin_count, 0);
+ assert!(!state.fell_back_to_cpu);
+ assert!(state.session.is_none());
+ }
}