Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add FP16 model support, lazy session loading, and pet recognition types

Amrithesh Kakkoth Ente228f1e750247
diff --git a/mobile/apps/photos/rust/Cargo.lock b/mobile/apps/photos/rust/Cargo.lock
index 7ed8a498f9..ff0dad92db 100644
--- a/mobile/apps/photos/rust/Cargo.lock
+++ b/mobile/apps/photos/rust/Cargo.lock
@@ -645,9 +645,11 @@ dependencies = [
"ente_media_inspector",
"fast_image_resize",
"flutter_rust_bridge",
+ "half",
"image",
"imageproc",
"kamadak-exif",
+ "libc",
"libheic-rs",
"nalgebra 0.33.2",
"ndarray 0.16.1",
@@ -1520,6 +1522,7 @@ version = "2.0.0-rc.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86d83095ae3c1258738d70ae7a06195c94d966a8e546f0d3609dc90885fb61f5"
dependencies = [
+ "half",
"js-sys",
"libloading",
"ndarray 0.15.6",
diff --git a/mobile/apps/photos/rust/Cargo.toml b/mobile/apps/photos/rust/Cargo.toml
index d8a81bb0bd..616a8eee47 100644
--- a/mobile/apps/photos/rust/Cargo.toml
+++ b/mobile/apps/photos/rust/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.0.1"
edition = "2024"
[lib]
-crate-type = ["cdylib", "staticlib"]
+crate-type = ["cdylib", "staticlib", "rlib"]
[dependencies]
flutter_rust_bridge = "=2.11.1"
@@ -19,12 +19,15 @@ libheic-rs = { git = "https://github.com/laurens-pilot/libheic-rs.git", tag = "v
] }
nalgebra = "0.33.2"
ndarray = "0.16.1"
+half = "2.1"
once_cell = "1.20.2"
thiserror = "2.0.11"
+libc = "0.2"
[target.'cfg(target_os = "ios")'.dependencies]
ort = { version = "=2.0.0-rc.4", default-features = false, features = [
"ndarray",
+ "half",
# Temporarily disabled to avoid iOS duplicate ObjC class collisions
# when both Dart ONNXRuntime and Rust ONNXRuntime are linked.
# Re-enable once we move to a single shared ORT runtime.
@@ -35,6 +38,7 @@ ort = { version = "=2.0.0-rc.4", default-features = false, features = [
[target.'cfg(not(target_os = "ios"))'.dependencies]
ort = { version = "=2.0.0-rc.4", default-features = false, features = [
"ndarray",
+ "half",
"load-dynamic",
"copy-dylibs",
"coreml",
@@ -45,5 +49,8 @@ ort = { version = "=2.0.0-rc.4", default-features = false, features = [
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] }
+[profile.dev]
+opt-level = 3
+
[features]
default = []
diff --git a/mobile/apps/photos/rust/src/ml/mod.rs b/mobile/apps/photos/rust/src/ml/mod.rs
index 7d69c32d2e..e3053a649b 100644
--- a/mobile/apps/photos/rust/src/ml/mod.rs
+++ b/mobile/apps/photos/rust/src/ml/mod.rs
@@ -2,6 +2,7 @@ pub mod clip;
pub mod error;
pub mod face;
pub mod onnx;
+pub mod pet;
pub mod preprocess;
pub mod runtime;
pub mod types;
diff --git a/mobile/apps/photos/rust/src/ml/onnx.rs b/mobile/apps/photos/rust/src/ml/onnx.rs
index 56ede40ee7..8a8c776ddb 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, Tensor,
- XNNPACKExecutionProvider,
+ CPUExecutionProvider, ExecutionProviderDispatch, GraphOptimizationLevel, Session,
+ TensorElementType, Tensor, ValueType, XNNPACKExecutionProvider,
};
// Temporarily disabled on Rust side to avoid iOS duplicate ObjC class collisions
@@ -83,11 +83,7 @@ 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().build());
}
providers
@@ -98,7 +94,7 @@ fn build_session_with_providers(
providers: Vec<ExecutionProviderDispatch>,
) -> MlResult<Session> {
let mut builder = Session::builder()?
- .with_optimization_level(GraphOptimizationLevel::Level3)?
+ .with_optimization_level(GraphOptimizationLevel::Level1)?
.with_intra_threads(1)?
.with_inter_threads(1)?;
@@ -108,21 +104,54 @@ fn build_session_with_providers(
Ok(session)
}
+/// Returns true if the session's first input expects FP16 tensors.
+fn session_expects_f16(session: &Session) -> bool {
+ session
+ .inputs
+ .first()
+ .and_then(|i| match &i.input_type {
+ ValueType::Tensor { ty, .. } => Some(*ty == TensorElementType::Float16),
+ _ => None,
+ })
+ .unwrap_or(false)
+}
+
+/// Run inference accepting f32 data and returning f32 results.
+/// Automatically converts inputs/outputs for FP16 models.
pub fn run_f32<const N: usize>(
session: &mut Session,
input: Vec<f32>,
input_shape: [i64; N],
) -> MlResult<(Vec<i64>, Vec<f32>)> {
- let input_tensor = Tensor::<f32>::from_array((input_shape, input))?;
- let outputs = session.run(ort::inputs![input_tensor]?)?;
+ let outputs = if session_expects_f16(session) {
+ // Convert f32->f16 in-place: drop the f32 vec first to avoid holding both.
+ let f16_input: Vec<half::f16> = {
+ let converted: Vec<half::f16> = input.into_iter().map(half::f16::from_f32).collect();
+ converted
+ };
+ let input_tensor = Tensor::<half::f16>::from_array((input_shape, f16_input))?;
+ session.run(ort::inputs![input_tensor]?)?
+ } else {
+ let input_tensor = Tensor::<f32>::from_array((input_shape, input))?;
+ session.run(ort::inputs![input_tensor]?)?
+ };
+
if outputs.is_empty() {
return Err(MlError::Ort("missing first output tensor".to_string()));
}
let output = &outputs[0];
- let tensor = output.try_extract_tensor::<f32>()?;
- let shape = tensor.shape().iter().map(|d| *d as i64).collect::<Vec<_>>();
- let data = tensor.iter().copied().collect::<Vec<_>>();
- Ok((shape, data))
+
+ // Extract output: try f32 first, fall back to f16 with conversion.
+ if let Ok(tensor) = output.try_extract_tensor::<f32>() {
+ let shape = tensor.shape().iter().map(|d| *d as i64).collect::<Vec<_>>();
+ let data = tensor.iter().copied().collect::<Vec<_>>();
+ Ok((shape, data))
+ } 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<_>>();
+ Ok((shape, data))
+ }
}
pub fn run_f32_data<const N: usize>(
diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rs
index a1ad457bfa..aac6d4aa42 100644
--- a/mobile/apps/photos/rust/src/ml/runtime.rs
+++ b/mobile/apps/photos/rust/src/ml/runtime.rs
@@ -8,6 +8,28 @@ use crate::ml::{
onnx,
};
+/// Log to Android logcat or stderr.
+fn rt_log(msg: &str) {
+ #[cfg(target_os = "android")]
+ {
+ unsafe extern "C" {
+ unsafe fn __android_log_write(
+ prio: std::ffi::c_int,
+ tag: *const std::ffi::c_char,
+ text: *const std::ffi::c_char,
+ ) -> std::ffi::c_int;
+ }
+ 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()); }
+ }
+ #[cfg(not(target_os = "android"))]
+ {
+ eprintln!("[ml][rt] {msg}");
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExecutionProviderPolicy {
pub prefer_coreml: bool,
@@ -32,6 +54,12 @@ pub struct ModelPaths {
pub face_detection: String,
pub face_embedding: String,
pub clip_image: String,
+ pub pet_face_detection: String,
+ pub pet_face_embedding_dog: String,
+ pub pet_face_embedding_cat: String,
+ pub pet_body_detection: String,
+ pub pet_body_embedding_dog: String,
+ pub pet_body_embedding_cat: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -40,11 +68,76 @@ pub struct MlRuntimeConfig {
pub provider_policy: ExecutionProviderPolicy,
}
+#[derive(Debug)]
+struct LazySession {
+ path: String,
+ policy: ExecutionProviderPolicy,
+ session: Option<Session>,
+}
+
+impl LazySession {
+ fn new(path: String, policy: ExecutionProviderPolicy) -> Self {
+ Self {
+ path,
+ policy,
+ session: None,
+ }
+ }
+
+ fn get_mut(&mut self, error_msg: &str) -> MlResult<&mut Session> {
+ if self.path.trim().is_empty() {
+ return Err(MlError::InvalidRequest(error_msg.to_string()));
+ }
+ if self.session.is_none() {
+ let model_name = self.path.rsplit('/').next().unwrap_or(&self.path);
+ rt_log(&format!("loading {model_name}"));
+ let t = std::time::Instant::now();
+ // Lazy sessions load while the runtime mutex is held (inside func()),
+ // so the with_runtime_mut_inner EP fallback cannot catch hangs or OOM
+ // during session building. Use CPU-friendly policy to avoid NNAPI/CoreML
+ // driver issues (e.g. NNAPI on some MTK devices hangs or OOMs even when
+ // it only accelerates <1% of graph nodes).
+ let load_policy = ExecutionProviderPolicy {
+ prefer_coreml: false,
+ prefer_nnapi: false,
+ prefer_xnnpack: self.policy.prefer_xnnpack,
+ allow_cpu_fallback: true,
+ };
+ self.session = Some(onnx::build_session(&self.path, &load_policy)?);
+ rt_log(&format!("loaded {model_name} in {:?}", t.elapsed()));
+ }
+ Ok(self.session.as_mut().unwrap())
+ }
+
+ fn unload(&mut self) {
+ if self.session.is_some() {
+ let model_name = self.path.rsplit('/').next().unwrap_or(&self.path);
+ rt_log(&format!("unloading {model_name}"));
+ }
+ self.session = None;
+ #[cfg(target_os = "android")]
+ unsafe {
+ let name = b"malloc_trim\0";
+ let sym = libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast());
+ if !sym.is_null() {
+ let f: unsafe extern "C" fn(usize) -> i32 = core::mem::transmute(sym);
+ f(0);
+ }
+ }
+ }
+}
+
#[derive(Debug)]
pub struct MlRuntime {
- face_detection: Option<Session>,
- face_embedding: Option<Session>,
- clip_image: Option<Session>,
+ face_detection: LazySession,
+ face_embedding: LazySession,
+ clip_image: 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,
}
#[derive(Debug)]
@@ -55,56 +148,99 @@ struct RuntimeState {
static GLOBAL_RUNTIME: Lazy<Mutex<Option<RuntimeState>>> = Lazy::new(|| Mutex::new(None));
-fn create_runtime(config: &MlRuntimeConfig) -> MlResult<MlRuntime> {
- let face_detection =
- build_optional_session(&config.model_paths.face_detection, &config.provider_policy)?;
- let face_embedding =
- build_optional_session(&config.model_paths.face_embedding, &config.provider_policy)?;
- let clip_image =
- build_optional_session(&config.model_paths.clip_image, &config.provider_policy)?;
- Ok(MlRuntime {
- face_detection,
- face_embedding,
- clip_image,
- })
-}
-
-fn build_optional_session(
- model_path: &str,
- provider_policy: &ExecutionProviderPolicy,
-) -> MlResult<Option<Session>> {
- if model_path.trim().is_empty() {
- return Ok(None);
+fn create_runtime(config: &MlRuntimeConfig) -> MlRuntime {
+ let p = &config.provider_policy;
+ 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()),
+ pet_face_detection: LazySession::new(config.model_paths.pet_face_detection.clone(), p.clone()),
+ pet_face_embedding_dog: LazySession::new(config.model_paths.pet_face_embedding_dog.clone(), p.clone()),
+ pet_face_embedding_cat: LazySession::new(config.model_paths.pet_face_embedding_cat.clone(), p.clone()),
+ pet_body_detection: LazySession::new(config.model_paths.pet_body_detection.clone(), p.clone()),
+ pet_body_embedding_dog: LazySession::new(config.model_paths.pet_body_embedding_dog.clone(), p.clone()),
+ pet_body_embedding_cat: LazySession::new(config.model_paths.pet_body_embedding_cat.clone(), p.clone()),
}
- Ok(Some(onnx::build_session(model_path, provider_policy)?))
}
impl MlRuntime {
pub fn face_detection_session_mut(&mut self) -> MlResult<&mut Session> {
- self.face_detection.as_mut().ok_or_else(|| {
- MlError::InvalidRequest(
- "missing model path: faceDetectionModelPath is required when runFaces is true"
- .to_string(),
- )
- })
+ self.face_detection.get_mut(
+ "missing model path: faceDetectionModelPath is required when runFaces is true",
+ )
}
pub fn face_embedding_session_mut(&mut self) -> MlResult<&mut Session> {
- self.face_embedding.as_mut().ok_or_else(|| {
- MlError::InvalidRequest(
- "missing model path: faceEmbeddingModelPath is required when runFaces is true"
- .to_string(),
- )
- })
+ self.face_embedding.get_mut(
+ "missing model path: faceEmbeddingModelPath is required when runFaces is true",
+ )
}
pub fn clip_image_session_mut(&mut self) -> MlResult<&mut Session> {
- self.clip_image.as_mut().ok_or_else(|| {
- MlError::InvalidRequest(
- "missing model path: clipImageModelPath is required when runClip is true"
- .to_string(),
- )
- })
+ self.clip_image.get_mut(
+ "missing model path: clipImageModelPath is required when runClip is true",
+ )
+ }
+
+ pub fn pet_face_detection_session_mut(&mut self) -> MlResult<&mut Session> {
+ self.pet_face_detection.get_mut(
+ "missing model path: petFaceDetectionModelPath is required when runPets is true",
+ )
+ }
+
+ pub fn pet_face_embedding_dog_session_mut(&mut self) -> MlResult<&mut Session> {
+ self.pet_face_embedding_dog
+ .get_mut("missing model path: petFaceEmbeddingDogModelPath is required")
+ }
+
+ pub fn pet_face_embedding_cat_session_mut(&mut self) -> MlResult<&mut Session> {
+ self.pet_face_embedding_cat
+ .get_mut("missing model path: petFaceEmbeddingCatModelPath is required")
+ }
+
+ pub fn pet_body_detection_session_mut(&mut self) -> MlResult<&mut Session> {
+ self.pet_body_detection.get_mut(
+ "missing model path: petBodyDetectionModelPath is required when runPets is true",
+ )
+ }
+
+ pub fn pet_body_embedding_dog_session_mut(&mut self) -> MlResult<&mut Session> {
+ self.pet_body_embedding_dog
+ .get_mut("missing model path: petBodyEmbeddingDogModelPath is required")
+ }
+
+ pub fn pet_body_embedding_cat_session_mut(&mut self) -> MlResult<&mut Session> {
+ self.pet_body_embedding_cat
+ .get_mut("missing model path: petBodyEmbeddingCatModelPath is required")
+ }
+
+ /// Drop loaded face sessions to free native memory between analysis phases.
+ pub fn unload_face_sessions(&mut self) {
+ self.face_detection.unload();
+ self.face_embedding.unload();
+ }
+
+ /// Drop the loaded CLIP session to free native memory between analysis phases.
+ pub fn unload_clip_session(&mut self) {
+ self.clip_image.unload();
+ }
+
+ /// Drop loaded pet detection sessions to free native memory between analysis phases.
+ pub fn unload_pet_detection_sessions(&mut self) {
+ self.pet_face_detection.unload();
+ self.pet_body_detection.unload();
+ }
+
+ /// Drop loaded pet face embedding sessions to free native memory between analysis phases.
+ pub fn unload_pet_face_embedding_sessions(&mut self) {
+ self.pet_face_embedding_dog.unload();
+ self.pet_face_embedding_cat.unload();
+ }
+
+ /// Drop loaded pet body embedding sessions to free native memory between analysis phases.
+ pub fn unload_pet_body_embedding_sessions(&mut self) {
+ self.pet_body_embedding_dog.unload();
+ self.pet_body_embedding_cat.unload();
}
}
@@ -130,7 +266,7 @@ pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
};
if should_rebuild {
- let runtime = create_runtime(config)?;
+ let runtime = create_runtime(config);
let mut guard = lock_runtime();
*guard = Some(RuntimeState {
config: config.clone(),
@@ -169,9 +305,7 @@ where
}
let fallback_config = cpu_only_runtime_config(config);
- eprintln!(
- "[ml][runtime] execution provider failed, retrying with CPU-only runtime: {first_error}"
- );
+ rt_log(&format!("execution provider failed, retrying with CPU-only runtime: {first_error}"));
ensure_runtime(&fallback_config)?;
let retry_result = {
let mut guard = lock_runtime();
diff --git a/mobile/apps/photos/rust/src/ml/types.rs b/mobile/apps/photos/rust/src/ml/types.rs
index bcca365e57..25a245d5c4 100644
--- a/mobile/apps/photos/rust/src/ml/types.rs
+++ b/mobile/apps/photos/rust/src/ml/types.rs
@@ -55,3 +55,45 @@ pub fn to_face_id(file_id: i64, box_xyxy: [f32; 4]) -> String {
let y_max = to_face_segment(box_xyxy[3]);
format!("{file_id}_{x_min}_{y_min}_{x_max}_{y_max}")
}
+
+// ── Pet Recognition Types ──────────────────────────────────────────────
+
+#[derive(Clone, Debug)]
+pub struct PetFaceDetection {
+ pub score: f32,
+ pub box_xyxy: [f32; 4],
+ /// 3 keypoints: [left_eye, right_eye, nose]
+ pub keypoints: [[f32; 2]; 3],
+}
+
+#[derive(Clone, Debug)]
+pub struct PetAlignmentResult {
+ pub center: [f32; 2],
+ pub angle: f32,
+ pub crop_size: f32,
+}
+
+#[derive(Clone, Debug)]
+pub struct PetFaceResult {
+ pub detection: PetFaceDetection,
+ /// 0 = dog, 1 = cat
+ pub species: u8,
+ pub face_embedding: Vec<f32>,
+ pub pet_face_id: String,
+ pub alignment: PetAlignmentResult,
+}
+
+#[derive(Clone, Debug)]
+pub struct PetBodyDetection {
+ pub score: f32,
+ pub box_xyxy: [f32; 4],
+ /// COCO class: 15 = cat, 16 = dog
+ pub coco_class: u8,
+}
+
+#[derive(Clone, Debug)]
+pub struct PetBodyResult {
+ pub detection: PetBodyDetection,
+ pub pet_body_id: String,
+ pub body_embedding: Vec<f32>,
+}