π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Optimize shared detector preprocessing
laurenspriemdb2ac576de96
diff --git a/rust/crates/photos/src/ml/face/detect.rs b/rust/crates/photos/src/ml/face/detect.rsindex c7cd00e61a..d17b2891e9 100644--- a/rust/crates/photos/src/ml/face/detect.rs+++ b/rust/crates/photos/src/ml/face/detect.rs@@ -1,8 +1,9 @@use crate::ml::{error::{MlError, MlResult},- onnx, preprocess,+ onnx,+ preprocess::YoloInput,runtime::MlRuntimeView,- types::{DecodedImage, FaceDetection},+ types::FaceDetection,};const INPUT_WIDTH: f32 = 640.0;@@ -10,16 +11,14 @@ const INPUT_HEIGHT: f32 = 640.0;const IOU_THRESHOLD: f32 = 0.4;const MIN_SCORE_THRESHOLD: f32 = 0.5;-pub fn run_face_detection(+pub(crate) fn run_face_detection(runtime: &MlRuntimeView<'_>,- decoded: &DecodedImage,+ input: &YoloInput,) -> MlResult<Vec<FaceDetection>> {- let (input, scaled_width, scaled_height, pad_left, pad_top) =- preprocess::preprocess_yolo(decoded)?;let mut face_detection = runtime.face_detection_session()?;- let output_data = onnx::run_f32_data(+ let output_data = onnx::run_prepared_f32_data(&mut face_detection,- input,+ &input.tensor,[1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],)?;@@ -62,10 +61,10 @@ pub fn run_face_detection(correct_for_maintained_aspect_ratio(&mut box_xyxy,&mut keypoints,- scaled_width,- scaled_height,- pad_left,- pad_top,+ input.scaled_width,+ input.scaled_height,+ input.pad_left,+ input.pad_top,);detections.push(FaceDetection {diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rsindex 9429aa21a8..c7026ed381 100644--- a/rust/crates/photos/src/ml/indexing.rs+++ b/rust/crates/photos/src/ml/indexing.rs@@ -10,6 +10,7 @@ use crate::ml::{detect::{run_pet_body_detection, run_pet_face_detection},embed::{run_pet_body_embedding, run_pet_face_embedding},},+ preprocess,runtime::{self, ModelPaths},types::{self, ClipResult, Dimensions, FaceResult, PetBodyResult, PetFaceResult},};@@ -70,9 +71,17 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {runtime::with_runtime(&model_paths, |runtime| {let decoded = decode_image_from_path(&image_path)?;let dims = decoded.dimensions.clone();+ let detector_input = (run_faces || run_pets)+ .then(|| preprocess::preprocess_yolo(&decoded))+ .transpose()?;let faces = if run_faces {- let detections = run_face_detection(runtime, &decoded)?;+ let detections = run_face_detection(+ runtime,+ detector_input+ .as_ref()+ .expect("detector input is prepared when face indexing is enabled"),+ )?;if detections.is_empty() {Some(Vec::new())} else {@@ -92,8 +101,11 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {};let (pet_faces, pet_bodies) = if run_pets {- let pet_face_detections = run_pet_face_detection(runtime, &decoded)?;- let body_detections = run_pet_body_detection(runtime, &decoded)?;+ let detector_input = detector_input+ .as_ref()+ .expect("detector input is prepared when pet indexing is enabled");+ let pet_face_detections = run_pet_face_detection(runtime, detector_input)?;+ let body_detections = run_pet_body_detection(runtime, detector_input)?;let pet_face_results = if !pet_face_detections.is_empty() {let (aligned, mut pet_results) =diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rsindex 4feec00b80..4a30ee7408 100644--- a/rust/crates/photos/src/ml/onnx.rs+++ b/rust/crates/photos/src/ml/onnx.rs@@ -1,8 +1,11 @@use ort::{ep::{CPU, ExecutionProviderDispatch},session::{Session, builder::GraphOptimizationLevel},- value::{Tensor, TensorElementType, ValueType},+ value::{Tensor, TensorElementType, TensorRef, ValueType},};+use std::cell::OnceCell;++use half::prelude::{HalfFloatSliceExt, HalfFloatVecExt};#[cfg(target_os = "android")]use ort::ep::XNNPACK;@@ -16,6 +19,29 @@ use std::num::NonZeroUsize;use crate::ml::error::{MlError, MlResult};+/// An f32 model input that can be borrowed by multiple sessions.+///+/// The FP16 representation is created lazily and retained so that a shared+/// preprocessing result only pays the conversion cost once.+pub(crate) struct PreparedF32Input {+ f32_data: Vec<f32>,+ f16_data: OnceCell<Vec<half::f16>>,+}++impl PreparedF32Input {+ pub(crate) fn new(data: Vec<f32>) -> Self {+ Self {+ f32_data: data,+ f16_data: OnceCell::new(),+ }+ }++ fn f16_data(&self) -> &[half::f16] {+ self.f16_data+ .get_or_init(|| Vec::<half::f16>::from_f32_slice(&self.f32_data))+ }+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum ExecutionMode {PlatformDefault,@@ -156,7 +182,7 @@ pub fn run_f32<const N: usize>(input_shape: [i64; N],) -> MlResult<(Vec<i64>, Vec<f32>)> {let outputs = if session_expects_f16(session) {- let f16_input: Vec<half::f16> = input.into_iter().map(half::f16::from_f32).collect();+ let f16_input = Vec::<half::f16>::from_f32_slice(&input);let input_tensor = Tensor::<half::f16>::from_array((input_shape, f16_input))?;session.run(ort::inputs![input_tensor])?} else {@@ -177,21 +203,61 @@ pub fn run_f32<const N: usize>(} else {let (tensor_shape, tensor_data) = output.try_extract_tensor::<half::f16>()?;let shape = tensor_shape.iter().copied().collect::<Vec<_>>();- let data = tensor_data- .iter()- .map(|v: &half::f16| v.to_f32())- .collect::<Vec<_>>();+ let mut data = vec![0.0; tensor_data.len()];+ tensor_data.convert_to_f32_slice(&mut data);Ok((shape, data))}}+/// Run inference using a reusable, borrowed f32 input.+///+/// Automatically uses the lazily cached FP16 representation for FP16 models.+pub(crate) fn run_prepared_f32<const N: usize>(+ session: &mut Session,+ input: &PreparedF32Input,+ input_shape: [i64; N],+) -> MlResult<(Vec<i64>, Vec<f32>)> {+ let outputs = if session_expects_f16(session) {+ let input_tensor =+ TensorRef::<half::f16>::from_array_view((input_shape, input.f16_data()))?;+ session.run(ort::inputs![input_tensor])?+ } else {+ let input_tensor =+ TensorRef::<f32>::from_array_view((input_shape, input.f32_data.as_slice()))?;+ session.run(ort::inputs![input_tensor])?+ };++ if outputs.len() == 0 {+ return Err(MlError::Ort("missing first output tensor".to_string()));+ }+ let output = &outputs[0];+ if let Ok((tensor_shape, tensor_data)) = output.try_extract_tensor::<f32>() {+ let shape = tensor_shape.iter().copied().collect::<Vec<_>>();+ Ok((shape, tensor_data.to_vec()))+ } else {+ let (tensor_shape, tensor_data) = output.try_extract_tensor::<half::f16>()?;+ let shape = tensor_shape.iter().copied().collect::<Vec<_>>();+ let mut data = vec![0.0; tensor_data.len()];+ tensor_data.convert_to_f32_slice(&mut data);+ Ok((shape, data))+ }+}++pub(crate) fn run_prepared_f32_data<const N: usize>(+ session: &mut Session,+ input: &PreparedF32Input,+ input_shape: [i64; N],+) -> MlResult<Vec<f32>> {+ run_prepared_f32(session, input, input_shape).map(|(_, data)| data)+}+pub fn run_f32_data<const N: usize>(session: &mut Session,input: Vec<f32>,input_shape: [i64; N],) -> MlResult<Vec<f32>> {let outputs = if session_expects_f16(session) {- let f16_input: Vec<half::f16> = input.into_iter().map(half::f16::from_f32).collect();+ let f16_input = Vec::<half::f16>::from_f32_slice(&input);let input_tensor = Tensor::<half::f16>::from_array((input_shape, f16_input))?;session.run(ort::inputs![input_tensor])?} else {@@ -206,10 +272,9 @@ pub fn run_f32_data<const N: usize>(Ok(tensor_data.to_vec())} else {let (_tensor_shape, tensor_data) = output.try_extract_tensor::<half::f16>()?;- Ok(tensor_data- .iter()- .map(|v: &half::f16| v.to_f32())- .collect::<Vec<_>>())+ let mut data = vec![0.0; tensor_data.len()];+ tensor_data.convert_to_f32_slice(&mut data);+ Ok(data)}}diff --git a/rust/crates/photos/src/ml/pet/detect.rs b/rust/crates/photos/src/ml/pet/detect.rsindex 463a93a47f..1a88715a20 100644--- a/rust/crates/photos/src/ml/pet/detect.rs+++ b/rust/crates/photos/src/ml/pet/detect.rs@@ -1,8 +1,9 @@use crate::ml::{error::{MlError, MlResult},- onnx, preprocess,+ onnx,+ preprocess::YoloInput,runtime::MlRuntimeView,- types::{DecodedImage, PetBodyDetection, PetFaceDetection},+ types::{PetBodyDetection, PetFaceDetection},};const INPUT_WIDTH: f32 = 640.0;@@ -31,17 +32,14 @@ const COCO_DOG: u8 = 16;/// 3 keypoints: left_eye, right_eye, nose (6 values for coords).////// This mirrors `pet_pipeline/detection.py` `FaceDetector.detect()`.-pub fn run_pet_face_detection(+pub(crate) fn run_pet_face_detection(runtime: &MlRuntimeView<'_>,- decoded: &DecodedImage,+ input: &YoloInput,) -> MlResult<Vec<PetFaceDetection>> {- let (input, scaled_width, scaled_height, pad_left, pad_top) =- preprocess::preprocess_yolo(decoded)?;-let mut pet_face_detection = runtime.pet_face_detection_session()?;- let (output_shape, output_data) = onnx::run_f32(+ let (output_shape, output_data) = onnx::run_prepared_f32(&mut pet_face_detection,- input,+ &input.tensor,[1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],)?;@@ -122,10 +120,10 @@ pub fn run_pet_face_detection(correct_for_maintained_aspect_ratio_3kp(&mut box_xyxy,&mut keypoints,- scaled_width,- scaled_height,- pad_left,- pad_top,+ input.scaled_width,+ input.scaled_height,+ input.pad_left,+ input.pad_top,);// For a 2-class model (row_len >= 13): row[11] = cat score,@@ -155,17 +153,14 @@ pub fn run_pet_face_detection(/// Returns all qualifying detections after NMS.////// This mirrors `pet_pipeline/detection.py` `BodyDetector.detect()`.-pub fn run_pet_body_detection(+pub(crate) fn run_pet_body_detection(runtime: &MlRuntimeView<'_>,- decoded: &DecodedImage,+ input: &YoloInput,) -> MlResult<Vec<PetBodyDetection>> {- let (input, scaled_width, scaled_height, pad_left, pad_top) =- preprocess::preprocess_yolo(decoded)?;-let mut body_detection = runtime.pet_body_detection_session()?;- let (_output_shape, output_data) = onnx::run_f32(+ let (_output_shape, output_data) = onnx::run_prepared_f32(&mut body_detection,- input,+ &input.tensor,[1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],)?;@@ -216,10 +211,10 @@ pub fn run_pet_body_detection(correct_box_for_aspect_ratio(&mut box_xyxy,- scaled_width,- scaled_height,- pad_left,- pad_top,+ input.scaled_width,+ input.scaled_height,+ input.pad_left,+ input.pad_top,);detections.push(PetBodyDetection {diff --git a/rust/crates/photos/src/ml/preprocess.rs b/rust/crates/photos/src/ml/preprocess.rsindex 15a7d8fe3f..ab65155b19 100644--- a/rust/crates/photos/src/ml/preprocess.rs+++ b/rust/crates/photos/src/ml/preprocess.rs@@ -5,6 +5,7 @@ use fast_image_resize::{use crate::ml::{error::{MlError, MlResult},+ onnx::PreparedF32Input,types::DecodedImage,};@@ -14,7 +15,15 @@ const CLIP_INPUT_WIDTH: usize = 256;const CLIP_INPUT_HEIGHT: usize = 256;const PAD_VALUE: f32 = 114.0;-pub fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<(Vec<f32>, usize, usize, usize, usize)> {+pub(crate) struct YoloInput {+ pub(crate) tensor: PreparedF32Input,+ pub(crate) scaled_width: usize,+ pub(crate) scaled_height: usize,+ pub(crate) pad_left: usize,+ pub(crate) pad_top: usize,+}++pub(crate) fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<YoloInput> {if decoded.dimensions.width == 0 || decoded.dimensions.height == 0 {return Err(MlError::Preprocess("image dimensions cannot be zero".to_string(),@@ -66,13 +75,13 @@ pub fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<(Vec<f32>, usize, usi}}- Ok((- output,- scaled_width_usize,- scaled_height_usize,+ Ok(YoloInput {+ tensor: PreparedF32Input::new(output),+ scaled_width: scaled_width_usize,+ scaled_height: scaled_height_usize,pad_left,pad_top,- ))+ })}pub fn preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {