π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Optimize ML indexing postprocessing
laurenspriem7571009d6eb3
diff --git a/rust/crates/photos/src/ml/face/detect.rs b/rust/crates/photos/src/ml/face/detect.rsindex ae9b33a656..61ff675c3a 100644--- a/rust/crates/photos/src/ml/face/detect.rs+++ b/rust/crates/photos/src/ml/face/detect.rs@@ -14,7 +14,7 @@ pub(crate) fn run_face_detection(input: &YoloInput,) -> MlResult<Vec<FaceDetection>> {let mut face_detection = runtime.face_detection_session()?;- onnx::with_prepared_f32_output(+ onnx::with_prepared_float_output(&mut face_detection,&input.tensor,[1, 3, YOLO_INPUT_SIZE as i64, YOLO_INPUT_SIZE as i64],@@ -23,7 +23,17 @@ pub(crate) fn run_face_detection(}fn postprocess_face_detections(- output_data: &[f32],+ output_data: onnx::BorrowedFloatTensor<'_>,+ input: &YoloInput,+) -> MlResult<Vec<FaceDetection>> {+ match output_data {+ onnx::BorrowedFloatTensor::F32(data) => postprocess_face_tensor(data, input),+ onnx::BorrowedFloatTensor::F16(data) => postprocess_face_tensor(data, input),+ }+}++fn postprocess_face_tensor<T: onnx::FloatTensorData>(+ output_data: T,input: &YoloInput,) -> MlResult<Vec<FaceDetection>> {let row_len = 16usize;@@ -34,19 +44,22 @@ fn postprocess_face_detections(}let detection_rows = output_data.len() / row_len;- let mut detections = Vec::with_capacity(detection_rows);+ let mut detections = Vec::new();for i in 0..detection_rows {let start = i * row_len;- let row = &output_data[start..(start + row_len)];- let score = row[4];+ let score = output_data.value(start + 4);if score < MIN_SCORE_THRESHOLD {continue;}- let x_min_abs = row[0] - row[2] / 2.0;- let y_min_abs = row[1] - row[3] / 2.0;- let x_max_abs = row[0] + row[2] / 2.0;- let y_max_abs = row[1] + row[3] / 2.0;+ let x = output_data.value(start);+ let y = output_data.value(start + 1);+ let width = output_data.value(start + 2);+ let height = output_data.value(start + 3);+ let x_min_abs = x - width / 2.0;+ let y_min_abs = y - height / 2.0;+ let x_max_abs = x + width / 2.0;+ let y_max_abs = y + height / 2.0;let mut box_xyxy = [x_min_abs / YOLO_INPUT_SIZE as f32,@@ -56,24 +69,24 @@ fn postprocess_face_detections(];let mut keypoints = [[- row[5] / YOLO_INPUT_SIZE as f32,- row[6] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 5) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 6) / YOLO_INPUT_SIZE as f32,],[- row[7] / YOLO_INPUT_SIZE as f32,- row[8] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 7) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 8) / YOLO_INPUT_SIZE as f32,],[- row[9] / YOLO_INPUT_SIZE as f32,- row[10] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 9) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 10) / YOLO_INPUT_SIZE as f32,],[- row[11] / YOLO_INPUT_SIZE as f32,- row[12] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 11) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 12) / YOLO_INPUT_SIZE as f32,],[- row[13] / YOLO_INPUT_SIZE as f32,- row[14] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 13) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 14) / YOLO_INPUT_SIZE as f32,],];diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rsindex 51bd9c9277..22fdfec918 100644--- a/rust/crates/photos/src/ml/onnx.rs+++ b/rust/crates/photos/src/ml/onnx.rs@@ -35,6 +35,39 @@ pub(crate) struct PreparedF32Input {f16_data: OnceCell<Vec<half::f16>>,}+#[derive(Clone, Copy)]+pub(crate) enum BorrowedFloatTensor<'a> {+ F32(&'a [f32]),+ F16(&'a [half::f16]),+}++pub(crate) trait FloatTensorData: Copy {+ fn len(self) -> usize;+ fn value(self, index: usize) -> f32;+}++impl FloatTensorData for &[f32] {+ fn len(self) -> usize {+ <[f32]>::len(self)+ }++ #[inline]+ fn value(self, index: usize) -> f32 {+ self[index]+ }+}++impl FloatTensorData for &[half::f16] {+ fn len(self) -> usize {+ <[half::f16]>::len(self)+ }++ #[inline]+ fn value(self, index: usize) -> f32 {+ self[index].to_f32()+ }+}+impl PreparedF32Input {pub(crate) fn new(data: Vec<f32>) -> Self {Self {@@ -394,14 +427,13 @@ pub(crate) fn run_f32<const N: usize>(}/// Run inference using a reusable input and process the first output in place.-///-/// Native f32 output is borrowed directly from ONNX Runtime. FP16 output uses-/// a temporary f32 conversion buffer because postprocessing operates on f32.-pub(crate) fn with_prepared_f32_output<const N: usize, T>(+/// Both f32 and f16 outputs remain borrowed from ONNX Runtime; consumers+/// convert only the values they inspect.+pub(crate) fn with_prepared_float_output<const N: usize, T>(session: &mut Session,input: &PreparedF32Input,input_shape: [i64; N],- consume: impl FnOnce(&[i64], &[f32]) -> MlResult<T>,+ consume: impl FnOnce(&[i64], BorrowedFloatTensor<'_>) -> MlResult<T>,) -> MlResult<T> {let outputs = if session_expects_f16(session) {let input_tensor =@@ -418,12 +450,10 @@ pub(crate) fn with_prepared_f32_output<const N: usize, T>(}let output = &outputs[0];if let Ok((tensor_shape, tensor_data)) = output.try_extract_tensor::<f32>() {- consume(tensor_shape, tensor_data)+ consume(tensor_shape, BorrowedFloatTensor::F32(tensor_data))} else {let (tensor_shape, tensor_data) = output.try_extract_tensor::<half::f16>()?;- let mut data = vec![0.0; tensor_data.len()];- tensor_data.convert_to_f32_slice(&mut data);- consume(tensor_shape, &data)+ consume(tensor_shape, BorrowedFloatTensor::F16(tensor_data))}}diff --git a/rust/crates/photos/src/ml/pet/align.rs b/rust/crates/photos/src/ml/pet/align.rsindex 5d90eb924b..acc51ced87 100644--- a/rust/crates/photos/src/ml/pet/align.rs+++ b/rust/crates/photos/src/ml/pet/align.rs@@ -109,8 +109,6 @@ pub(crate) 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(®ion, angle_rad as f64, local_cx, local_cy);-// Crop coordinates relative to the regionlet 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;@@ -123,7 +121,19 @@ pub(crate) fn run_pet_face_alignment(if crop_w == 0 || crop_h == 0 {continue;}- crop_and_resize_rgb(&mut crop_resizer, &rotated, nx1, ny1, crop_w, crop_h)?+ let rotated_crop = rotate_crop_around_center(+ ®ion,+ angle_rad as f64,+ local_cx,+ local_cy,+ PixelCrop {+ x: nx1,+ y: ny1,+ width: crop_w,+ height: crop_h,+ },+ );+ crop_and_resize_rgb(&mut crop_resizer, &rotated_crop, 0, 0, crop_w, crop_h)?};let result_index = face_results.len();@@ -158,11 +168,15 @@ pub(crate) fn run_pet_face_alignment(Ok((aligned_inputs, face_results))}-/// Rotate an image around a center point using bilinear interpolation-/// with BORDER_REPLICATE behaviour (clamp to nearest edge pixel).-fn rotate_around_center(source: &RgbRegion<'_>, angle_rad: f64, cx: f64, cy: f64) -> RgbImage {- let w = source.width;- let h = source.height;+/// Render a crop of an image rotated around a center point using bilinear+/// interpolation with BORDER_REPLICATE behaviour.+fn rotate_crop_around_center(+ source: &RgbRegion<'_>,+ angle_rad: f64,+ cx: f64,+ cy: f64,+ crop: PixelCrop,+) -> RgbImage {let cos_a = angle_rad.cos();let sin_a = angle_rad.sin();@@ -170,12 +184,14 @@ fn rotate_around_center(source: &RgbRegion<'_>, angle_rad: f64, cx: f64, cy: f64// x_in = cos_a * (x_out - cx) + sin_a * (y_out - cy) + cx// y_in = -sin_a * (x_out - cx) + cos_a * (y_out - cy) + cy- let mut output = RgbImage::new(w, h);- let w_f = w as f64;- let h_f = h as f64;+ let mut output = RgbImage::new(crop.width, crop.height);+ let w_f = source.width as f64;+ let h_f = source.height as f64;- for out_y in 0..h {- for out_x in 0..w {+ for crop_y in 0..crop.height {+ let out_y = crop.y + crop_y;+ for crop_x in 0..crop.width {+ let out_x = crop.x + crop_x;let dx = out_x as f64 - cx;let dy = out_y as f64 - cy;let src_x = cos_a * dx + sin_a * dy + cx;@@ -188,8 +204,8 @@ fn rotate_around_center(source: &RgbRegion<'_>, angle_rad: f64, cx: f64, cy: f64// Bilinear interpolationlet x0 = sx.floor() as u32;let y0 = sy.floor() as u32;- let x1 = (x0 + 1).min(w - 1);- let y1 = (y0 + 1).min(h - 1);+ let x1 = (x0 + 1).min(source.width - 1);+ let y1 = (y0 + 1).min(source.height - 1);let fx = (sx - sx.floor()) as f32;let fy = (sy - sy.floor()) as f32;@@ -206,7 +222,7 @@ fn rotate_around_center(source: &RgbRegion<'_>, angle_rad: f64, cx: f64, cy: f64+ p11[c] as f32 * fx * fy;px[c] = v.round().clamp(0.0, 255.0) as u8;}- output.put_pixel(out_x, out_y, Rgb(px));+ output.put_pixel(crop_x, crop_y, Rgb(px));}}@@ -327,3 +343,50 @@ impl<'a> RgbRegion<'a> {[self.rgb[pixel], self.rgb[pixel + 1], self.rgb[pixel + 2]]}}++#[cfg(test)]+mod tests {+ use super::{PixelCrop, RgbRegion, rotate_crop_around_center};+ use crate::ml::types::{DecodedImage, Dimensions};++ #[test]+ fn cropped_rotation_matches_the_same_region_of_a_full_rotation() {+ let decoded = DecodedImage {+ dimensions: Dimensions {+ width: 11,+ height: 9,+ },+ rgb: (0..11 * 9 * 3).map(|value| (value % 251) as u8).collect(),+ };+ let source = RgbRegion::new(&decoded, 1, 1, 9, 7).unwrap();+ let crop = PixelCrop {+ x: 2,+ y: 1,+ width: 5,+ height: 4,+ };++ let full = rotate_crop_around_center(+ &source,+ 0.37,+ 4.25,+ 3.75,+ PixelCrop {+ x: 0,+ y: 0,+ width: source.width,+ height: source.height,+ },+ );+ let cropped = rotate_crop_around_center(&source, 0.37, 4.25, 3.75, crop);++ for y in 0..crop.height {+ for x in 0..crop.width {+ assert_eq!(+ cropped.get_pixel(x, y),+ full.get_pixel(crop.x + x, crop.y + y)+ );+ }+ }+ }+}diff --git a/rust/crates/photos/src/ml/pet/detect.rs b/rust/crates/photos/src/ml/pet/detect.rsindex 3b2e40a109..ec5d0511cc 100644--- a/rust/crates/photos/src/ml/pet/detect.rs+++ b/rust/crates/photos/src/ml/pet/detect.rs@@ -32,7 +32,7 @@ pub(crate) fn run_pet_face_detection(input: &YoloInput,) -> MlResult<Vec<PetFaceDetection>> {let mut pet_face_detection = runtime.pet_face_detection_session()?;- onnx::with_prepared_f32_output(+ onnx::with_prepared_float_output(&mut pet_face_detection,&input.tensor,[1, 3, YOLO_INPUT_SIZE as i64, YOLO_INPUT_SIZE as i64],@@ -44,7 +44,22 @@ pub(crate) fn run_pet_face_detection(fn postprocess_pet_face_detections(output_shape: &[i64],- output_data: &[f32],+ output_data: onnx::BorrowedFloatTensor<'_>,+ input: &YoloInput,+) -> MlResult<Vec<PetFaceDetection>> {+ match output_data {+ onnx::BorrowedFloatTensor::F32(data) => {+ postprocess_pet_face_tensor(output_shape, data, input)+ }+ onnx::BorrowedFloatTensor::F16(data) => {+ postprocess_pet_face_tensor(output_shape, data, input)+ }+ }+}++fn postprocess_pet_face_tensor<T: onnx::FloatTensorData>(+ output_shape: &[i64],+ output_data: T,input: &YoloInput,) -> MlResult<Vec<PetFaceDetection>> {// Row format: [x, y, w, h, conf, lm_x1, lm_y1, lm_x2, lm_y2, lm_x3, lm_y3, cls0, cls1]@@ -95,20 +110,23 @@ fn postprocess_pet_face_detections(}let detection_rows = output_data.len() / row_len;- let mut detections = Vec::with_capacity(detection_rows);+ let mut detections = Vec::new();for i in 0..detection_rows {let start = i * row_len;- let row = &output_data[start..(start + row_len)];- let score = row[4];+ let score = output_data.value(start + 4);if score < PET_FACE_MIN_SCORE {continue;}- let x_min_abs = row[0] - row[2] / 2.0;- let y_min_abs = row[1] - row[3] / 2.0;- let x_max_abs = row[0] + row[2] / 2.0;- let y_max_abs = row[1] + row[3] / 2.0;+ let x = output_data.value(start);+ let y = output_data.value(start + 1);+ let width = output_data.value(start + 2);+ let height = output_data.value(start + 3);+ let x_min_abs = x - width / 2.0;+ let y_min_abs = y - height / 2.0;+ let x_max_abs = x + width / 2.0;+ let y_max_abs = y + height / 2.0;let mut box_xyxy = [x_min_abs / YOLO_INPUT_SIZE as f32,@@ -120,16 +138,16 @@ fn postprocess_pet_face_detections(// 3 keypoints: left_eye, right_eye, noselet mut keypoints = [[- row[5] / YOLO_INPUT_SIZE as f32,- row[6] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 5) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 6) / YOLO_INPUT_SIZE as f32,],[- row[7] / YOLO_INPUT_SIZE as f32,- row[8] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 7) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 8) / YOLO_INPUT_SIZE as f32,],[- row[9] / YOLO_INPUT_SIZE as f32,- row[10] / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 9) / YOLO_INPUT_SIZE as f32,+ output_data.value(start + 10) / YOLO_INPUT_SIZE as f32,],];@@ -140,7 +158,7 @@ fn postprocess_pet_face_detections(// For a 1-class model (row_len == 12): row[11] is the single class// score; class is always 0 (dog).let class_id: u8 = if row_len >= 13 {- if row[12] > row[11] {+ if output_data.value(start + 12) > output_data.value(start + 11) {PET_SPECIES_DOG} else {PET_SPECIES_CAT@@ -171,7 +189,7 @@ pub(crate) fn run_pet_body_detection(input: &YoloInput,) -> MlResult<Vec<PetBodyDetection>> {let mut body_detection = runtime.pet_body_detection_session()?;- onnx::with_prepared_f32_output(+ onnx::with_prepared_float_output(&mut body_detection,&input.tensor,[1, 3, YOLO_INPUT_SIZE as i64, YOLO_INPUT_SIZE as i64],@@ -180,7 +198,17 @@ pub(crate) fn run_pet_body_detection(}fn postprocess_pet_body_detections(- output_data: &[f32],+ output_data: onnx::BorrowedFloatTensor<'_>,+ input: &YoloInput,+) -> MlResult<Vec<PetBodyDetection>> {+ match output_data {+ onnx::BorrowedFloatTensor::F32(data) => postprocess_pet_body_tensor(data, input),+ onnx::BorrowedFloatTensor::F16(data) => postprocess_pet_body_tensor(data, input),+ }+}++fn postprocess_pet_body_tensor<T: onnx::FloatTensorData>(+ output_data: T,input: &YoloInput,) -> MlResult<Vec<PetBodyDetection>> {// YOLOv5 output format: [x, y, w, h, obj_conf, cls0, cls1, ..., cls79]@@ -195,31 +223,18 @@ fn postprocess_pet_body_detections(for i in 0..detection_rows {let start = i * row_len;- let row = &output_data[start..(start + row_len)];- let obj_conf = row[4];-- // Find the winning class across all 80 COCO classes and only- // keep detections whose predicted class is cat (15) or dog (16).- let class_logits = &row[5..85];- let (best_cls, best_logit) = class_logits- .iter()- .enumerate()- .max_by(|a, b| a.1.total_cmp(b.1))- .unwrap();- let best_cls = best_cls as u8;- if best_cls != COCO_CAT && best_cls != COCO_DOG {- continue;- }- let class_score = best_logit * obj_conf;- if class_score < BODY_MIN_SCORE {+ let Some((class_id, class_score)) = winning_pet_body_class(output_data, start) else {continue;- }- let class_id = best_cls;+ };- let x_min_abs = row[0] - row[2] / 2.0;- let y_min_abs = row[1] - row[3] / 2.0;- let x_max_abs = row[0] + row[2] / 2.0;- let y_max_abs = row[1] + row[3] / 2.0;+ let x = output_data.value(start);+ let y = output_data.value(start + 1);+ let width = output_data.value(start + 2);+ let height = output_data.value(start + 3);+ let x_min_abs = x - width / 2.0;+ let y_min_abs = y - height / 2.0;+ let x_max_abs = x + width / 2.0;+ let y_max_abs = y + height / 2.0;let mut box_xyxy = [x_min_abs / YOLO_INPUT_SIZE as f32,@@ -240,6 +255,43 @@ fn postprocess_pet_body_detections(Ok(naive_nms_pet_body(detections, BODY_IOU_THRESHOLD))}+fn winning_pet_body_class<T: onnx::FloatTensorData>(+ output_data: T,+ row_start: usize,+) -> Option<(u8, f32)> {+ let obj_conf = output_data.value(row_start + 4);++ // Most detector rows cannot produce a cat or dog above the score+ // threshold. Reject those before scanning all 80 COCO classes.+ let cat_logit = output_data.value(row_start + 5 + COCO_CAT as usize);+ let dog_logit = output_data.value(row_start + 5 + COCO_DOG as usize);+ let best_pet_logit = if dog_logit.total_cmp(&cat_logit).is_ge() {+ dog_logit+ } else {+ cat_logit+ };+ if best_pet_logit * obj_conf < BODY_MIN_SCORE {+ return None;+ }++ // A sufficiently strong pet score still needs to win against every other+ // COCO class. Keep the original total ordering and tie behaviour here.+ let mut best_cls = 0u8;+ let mut best_logit = output_data.value(row_start + 5);+ for class in 1u8..80 {+ let logit = output_data.value(row_start + 5 + class as usize);+ if logit.total_cmp(&best_logit).is_ge() {+ best_cls = class;+ best_logit = logit;+ }+ }+ if best_cls != COCO_CAT && best_cls != COCO_DOG {+ return None;+ }++ Some((best_cls, best_logit * obj_conf))+}+fn calculate_iou_4(a: &[f32; 4], b: &[f32; 4]) -> f32 {let area_a = (a[2] - a[0]).max(0.0) * (a[3] - a[1]).max(0.0);let area_b = (b[2] - b[0]).max(0.0) * (b[3] - b[1]).max(0.0);@@ -323,3 +375,65 @@ fn naive_nms_pet_body(.filter_map(|(d, s)| if s { None } else { Some(d) }).collect()}++#[cfg(test)]+mod tests {+ use super::{BODY_MIN_SCORE, COCO_CAT, COCO_DOG, winning_pet_body_class};++ #[test]+ fn pet_body_class_prefilter_matches_full_scan() {+ let mut rows = Vec::new();++ rows.push(body_row(0.9, &[(COCO_CAT, 0.2), (COCO_DOG, 0.1)]));+ rows.push(body_row(0.9, &[(COCO_CAT, 0.8), (COCO_DOG, 0.7)]));+ rows.push(body_row(0.9, &[(COCO_CAT, 0.8), (3, 0.9)]));+ rows.push(body_row(1.0, &[(COCO_CAT, BODY_MIN_SCORE)]));+ rows.push(body_row(+ 1.0,+ &[(COCO_CAT, BODY_MIN_SCORE), (COCO_DOG, BODY_MIN_SCORE)],+ ));+ rows.push(body_row(1.0, &[(COCO_DOG, 0.8), (79, 0.8)]));++ for row in rows {+ assert_eq!(winning_pet_body_class(row.as_slice(), 0), full_scan(&row));++ let f16_row = row+ .iter()+ .copied()+ .map(half::f16::from_f32)+ .collect::<Vec<_>>();+ let converted_row = f16_row+ .iter()+ .map(|value| value.to_f32())+ .collect::<Vec<_>>();+ assert_eq!(+ winning_pet_body_class(f16_row.as_slice(), 0),+ full_scan(&converted_row),+ );+ }+ }++ fn body_row(object_confidence: f32, scores: &[(u8, f32)]) -> Vec<f32> {+ let mut row = vec![0.0; 85];+ row[4] = object_confidence;+ for &(class, score) in scores {+ row[5 + class as usize] = score;+ }+ row+ }++ fn full_scan(row: &[f32]) -> Option<(u8, f32)> {+ let (best_class, best_logit) = row[5..85]+ .iter()+ .enumerate()+ .max_by(|a, b| a.1.total_cmp(b.1))+ .unwrap();+ let best_class = best_class as u8;+ if best_class != COCO_CAT && best_class != COCO_DOG {+ return None;+ }++ let score = best_logit * row[4];+ (score >= BODY_MIN_SCORE).then_some((best_class, score))+ }+}