Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use Rust CLIP text inference when Rust ML is enabled

laurenspriembd48fca9a58b
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
index 7eb58d401c..eb64009134 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
@@ -1,10 +1,12 @@
import 'dart:async';
+import "dart:io" show Platform;
import "dart:typed_data" show Float32List;
import "package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart"
show Uint64List;
import "package:logging/logging.dart";
import "package:photos/models/ml/vector.dart";
+import "package:photos/service_locator.dart" show flagService, isOfflineMode;
import "package:photos/services/machine_learning/ml_constants.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
@@ -20,6 +22,8 @@ class MLComputer extends SuperIsolate {
final _logger = Logger('MLComputer');
final _initModelLock = Lock();
+ bool _isClipTokenizerInitialized = false;
+ String? _clipTextModelPath;
@override
bool get isDartUiIsolate => false;
@@ -30,6 +34,8 @@ class MLComputer extends SuperIsolate {
@override
bool get shouldAutomaticDispose => false;
+ bool get _shouldUseRustMl => flagService.useRustForML || isOfflineMode;
+
// Singleton pattern
MLComputer._privateConstructor();
static final MLComputer instance = MLComputer._privateConstructor();
@@ -71,11 +77,26 @@ class MLComputer extends SuperIsolate {
Future<List<double>> runClipText(String query) async {
try {
- await _ensureLoadedClipTextModel();
- final int clipAddress = ClipTextEncoder.instance.sessionAddress;
+ final useRustMl = _shouldUseRustMl;
+ await _ensureLoadedClipTextModel(useRustMl);
+ final modelPath = _clipTextModelPath;
+ if (useRustMl && (modelPath == null || modelPath.trim().isEmpty)) {
+ throw Exception(
+ "RustMLMissingModelPath: Missing required model path: clipTextModelPath",
+ );
+ }
final textEmbedding = await runInIsolate(IsolateOperation.runClipText, {
"text": query,
- "address": clipAddress,
+ "useRustMl": useRustMl,
+ if (useRustMl) ...{
+ "clipTextModelPath": modelPath,
+ "preferCoreml": Platform.isIOS,
+ "preferNnapi": Platform.isAndroid,
+ "preferXnnpack": Platform.isAndroid,
+ "allowCpuFallback": true,
+ } else ...{
+ "address": ClipTextEncoder.instance.sessionAddress,
+ },
}) as List<double>;
return textEmbedding;
} catch (e, s) {
@@ -84,32 +105,46 @@ class MLComputer extends SuperIsolate {
}
}
- Future<void> _ensureLoadedClipTextModel() async {
+ Future<void> _ensureLoadedClipTextModel(bool useRustMl) async {
return _initModelLock.synchronized(() async {
- if (ClipTextEncoder.instance.isInitialized) return;
try {
+ if (_isClipTokenizerInitialized &&
+ _clipTextModelPath != null &&
+ (useRustMl || ClipTextEncoder.instance.isInitialized)) {
+ return;
+ }
+
// Initialize ClipText tokenizer
- final String tokenizerRemotePath =
- ClipTextEncoder.instance.vocabRemotePath;
- final String tokenizerVocabPath = await RemoteAssetsService.instance
- .getAssetPath(tokenizerRemotePath);
- await runInIsolate(
- IsolateOperation.initializeClipTokenizer,
- {'vocabPath': tokenizerVocabPath},
- );
+ if (!_isClipTokenizerInitialized) {
+ final String tokenizerRemotePath =
+ ClipTextEncoder.instance.vocabRemotePath;
+ final String tokenizerVocabPath = await RemoteAssetsService.instance
+ .getAssetPath(tokenizerRemotePath);
+ await runInIsolate(
+ IsolateOperation.initializeClipTokenizer,
+ {'vocabPath': tokenizerVocabPath},
+ );
+ _isClipTokenizerInitialized = true;
+ }
// Load ClipText model
- final String modelName = ClipTextEncoder.instance.modelName;
- final String? modelPath =
+ final String? downloadedModelPath =
await ClipTextEncoder.instance.downloadModelSafe();
- if (modelPath == null) {
+ if (downloadedModelPath == null) {
throw Exception("Could not download clip text model, no wifi");
}
+ _clipTextModelPath = downloadedModelPath;
+
+ if (useRustMl || ClipTextEncoder.instance.isInitialized) {
+ return;
+ }
+
+ final String modelName = ClipTextEncoder.instance.modelName;
final address = await runInIsolate(
IsolateOperation.loadModel,
{
'modelName': modelName,
- 'modelPath': modelPath,
+ 'modelPath': downloadedModelPath,
},
) as int;
ClipTextEncoder.instance.storeSessionAddress(address);
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index c2c7a63b29..d84c8f910b 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -1,4 +1,4 @@
-import 'dart:typed_data' show Uint8List, Float32List;
+import 'dart:typed_data' show Float32List, Int32List, Uint8List;
import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;
import "package:ml_linalg/linalg.dart";
@@ -204,8 +204,35 @@ Future<dynamic> isolateFunction(
/// MLComputer
case IsolateOperation.runClipText:
- final textEmbedding = await ClipTextEncoder.predict(args);
- return List<double>.from(textEmbedding, growable: false);
+ final useRustMl = args["useRustMl"] as bool? ?? false;
+ if (!useRustMl) {
+ final textEmbedding = await ClipTextEncoder.predict(args);
+ return List<double>.from(textEmbedding, growable: false);
+ }
+
+ await _ensureRustLoaded();
+ final text = args["text"] as String;
+ final clipTextModelPath = args["clipTextModelPath"] as String?;
+ if (clipTextModelPath == null || clipTextModelPath.trim().isEmpty) {
+ throw Exception(
+ "RustMLMissingModelPath: Missing required model path: clipTextModelPath",
+ );
+ }
+
+ final tokenIds = await ClipTextTokenizer.instance.tokenize(text);
+ final result = await rust_ml.runClipTextRust(
+ req: rust_ml.RunClipTextRequest(
+ tokenIds: Int32List.fromList(tokenIds),
+ modelPath: clipTextModelPath,
+ providerPolicy: rust_ml.RustExecutionProviderPolicy(
+ preferCoreml: args["preferCoreml"] as bool? ?? true,
+ preferNnapi: args["preferNnapi"] as bool? ?? true,
+ preferXnnpack: args["preferXnnpack"] as bool? ?? false,
+ allowCpuFallback: args["allowCpuFallback"] as bool? ?? true,
+ ),
+ ),
+ );
+ return List<double>.from(result.embedding, growable: false);
/// MLComputer
case IsolateOperation.computeBulkSimilarities:
@@ -292,6 +319,7 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {
faceDetection: (args["faceDetectionModelPath"] as String?) ?? "",
faceEmbedding: (args["faceEmbeddingModelPath"] as String?) ?? "",
clipImage: (args["clipImageModelPath"] as String?) ?? "",
+ clipText: (args["clipTextModelPath"] as String?) ?? "",
);
final providerPolicy = rust_ml.RustExecutionProviderPolicy(
preferCoreml: args["preferCoreml"] as bool? ?? true,
@@ -352,6 +380,7 @@ String _runtimeConfigCacheKey(
modelPaths.faceDetection,
modelPaths.faceEmbedding,
modelPaths.clipImage,
+ modelPaths.clipText,
providerPolicy.preferCoreml,
providerPolicy.preferNnapi,
providerPolicy.preferXnnpack,
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 7ae705f744..da11b60c50 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -635,6 +635,7 @@ Future<MLResult> analyzeImageRust(Map args) async {
faceDetection: faceDetectionModelPath ?? "",
faceEmbedding: faceEmbeddingModelPath ?? "",
clipImage: clipImageModelPath ?? "",
+ clipText: "",
);
final providerPolicy = rust_ml.RustExecutionProviderPolicy(
preferCoreml: preferCoreml,
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 fde0fe6f07..05ad7f8b2d 100644
--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
@@ -1,6 +1,6 @@
use crate::image::decode::decode_image_from_path;
use crate::ml::{
- clip::image::run_clip_image,
+ clip::{image::run_clip_image, text::run_clip_text},
error::{MlError, MlResult},
face::{align::run_face_alignment, detect::run_face_detection, embed::run_face_embedding},
runtime::{self, ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},
@@ -30,6 +30,7 @@ pub struct RustModelPaths {
pub face_detection: String,
pub face_embedding: String,
pub clip_image: String,
+ pub clip_text: String,
}
#[derive(Clone, Debug)]
@@ -91,6 +92,18 @@ pub struct AnalyzeImageResult {
pub clip: Option<RustClipResult>,
}
+#[derive(Clone, Debug)]
+pub struct RunClipTextRequest {
+ pub token_ids: Vec<i32>,
+ pub model_path: String,
+ pub provider_policy: RustExecutionProviderPolicy,
+}
+
+#[derive(Clone, Debug)]
+pub struct RunClipTextResult {
+ pub embedding: Vec<f64>,
+}
+
pub fn init_ml_runtime(config: RustMlRuntimeConfig) -> Result<(), String> {
runtime::ensure_runtime(&to_runtime_config(&config)).map_err(|e| e.to_string())
}
@@ -103,6 +116,10 @@ pub fn analyze_image_rust(req: AnalyzeImageRequest) -> Result<AnalyzeImageResult
analyze_image_rust_inner(req).map_err(|e| e.to_string())
}
+pub fn run_clip_text_rust(req: RunClipTextRequest) -> Result<RunClipTextResult, String> {
+ run_clip_text_rust_inner(req).map_err(|e| e.to_string())
+}
+
fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
validate_request_model_paths(&req)?;
@@ -150,6 +167,41 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRe
})
}
+fn run_clip_text_rust_inner(req: RunClipTextRequest) -> MlResult<RunClipTextResult> {
+ let RunClipTextRequest {
+ token_ids,
+ model_path,
+ provider_policy,
+ } = req;
+
+ if model_path.trim().is_empty() {
+ return Err(MlError::InvalidRequest(
+ "missing model path: clipTextModelPath".to_string(),
+ ));
+ }
+
+ let runtime_config = MlRuntimeConfig {
+ model_paths: ModelPaths {
+ face_detection: String::new(),
+ face_embedding: String::new(),
+ clip_image: String::new(),
+ clip_text: model_path,
+ },
+ provider_policy: to_provider_policy(&provider_policy),
+ };
+
+ runtime::with_runtime_mut(&runtime_config, move |runtime| {
+ let clip = run_clip_text(runtime, &token_ids)?;
+ Ok(RunClipTextResult {
+ embedding: clip
+ .embedding
+ .into_iter()
+ .map(|value| value as f64)
+ .collect(),
+ })
+ })
+}
+
fn validate_request_model_paths(req: &AnalyzeImageRequest) -> MlResult<()> {
let mut missing = Vec::new();
if req.run_faces {
@@ -185,6 +237,7 @@ fn to_model_paths(paths: &RustModelPaths) -> ModelPaths {
face_detection: paths.face_detection.clone(),
face_embedding: paths.face_embedding.clone(),
clip_image: paths.clip_image.clone(),
+ clip_text: paths.clip_text.clone(),
}
}
diff --git a/mobile/apps/photos/rust/src/ml/clip/mod.rs b/mobile/apps/photos/rust/src/ml/clip/mod.rs
index 14995d4228..ab1ed42573 100644
--- a/mobile/apps/photos/rust/src/ml/clip/mod.rs
+++ b/mobile/apps/photos/rust/src/ml/clip/mod.rs
@@ -1 +1,2 @@
pub mod image;
+pub mod text;
diff --git a/mobile/apps/photos/rust/src/ml/clip/text.rs b/mobile/apps/photos/rust/src/ml/clip/text.rs
new file mode 100644
index 0000000000..a9d929543c
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/clip/text.rs
@@ -0,0 +1,58 @@
+use crate::ml::{
+ error::{MlError, MlResult},
+ onnx,
+ runtime::MlRuntime,
+ types::ClipResult,
+};
+
+const CLIP_TEXT_TOKEN_COUNT: usize = 77;
+
+pub fn run_clip_text(runtime: &mut MlRuntime, 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 {}",
+ token_ids.len()
+ )));
+ }
+
+ let clip_text = runtime.clip_text_session_mut()?;
+ let (shape, output) = onnx::run_i32_f32(
+ clip_text,
+ token_ids.to_vec(),
+ vec![1, CLIP_TEXT_TOKEN_COUNT as i64],
+ )?;
+
+ let mut embedding = if shape.len() == 2 {
+ if shape[0] != 1 {
+ return Err(MlError::Postprocess(format!(
+ "unexpected CLIP text batch size in shape {:?}",
+ shape
+ )));
+ }
+ output
+ } else if shape.len() == 1 {
+ output
+ } else {
+ return Err(MlError::Postprocess(format!(
+ "unsupported CLIP text output shape {:?}",
+ shape
+ )));
+ };
+
+ normalize_embedding(&mut embedding);
+ Ok(ClipResult { embedding })
+}
+
+fn normalize_embedding(embedding: &mut [f32]) {
+ let mut norm = 0.0f32;
+ for value in embedding.iter() {
+ norm += value * value;
+ }
+ let norm = norm.sqrt();
+ if norm <= f32::EPSILON {
+ return;
+ }
+ for value in embedding.iter_mut() {
+ *value /= norm;
+ }
+}
diff --git a/mobile/apps/photos/rust/src/ml/onnx.rs b/mobile/apps/photos/rust/src/ml/onnx.rs
index 4bf4471d61..b254f8fa73 100644
--- a/mobile/apps/photos/rust/src/ml/onnx.rs
+++ b/mobile/apps/photos/rust/src/ml/onnx.rs
@@ -124,3 +124,20 @@ pub fn run_f32(
let data = tensor.iter().copied().collect::<Vec<_>>();
Ok((shape, data))
}
+
+pub fn run_i32_f32(
+ session: &mut Session,
+ input: Vec<i32>,
+ input_shape: Vec<i64>,
+) -> MlResult<(Vec<i64>, Vec<f32>)> {
+ let input_tensor = Tensor::<i32>::from_array((input_shape, input))?;
+ let outputs = 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))
+}
diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rs
index a1ad457bfa..091e3d7d49 100644
--- a/mobile/apps/photos/rust/src/ml/runtime.rs
+++ b/mobile/apps/photos/rust/src/ml/runtime.rs
@@ -32,6 +32,7 @@ pub struct ModelPaths {
pub face_detection: String,
pub face_embedding: String,
pub clip_image: String,
+ pub clip_text: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -45,6 +46,7 @@ pub struct MlRuntime {
face_detection: Option<Session>,
face_embedding: Option<Session>,
clip_image: Option<Session>,
+ clip_text: Option<Session>,
}
#[derive(Debug)]
@@ -62,10 +64,12 @@ fn create_runtime(config: &MlRuntimeConfig) -> MlResult<MlRuntime> {
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)?;
+ let clip_text = build_optional_session(&config.model_paths.clip_text, &config.provider_policy)?;
Ok(MlRuntime {
face_detection,
face_embedding,
clip_image,
+ clip_text,
})
}
@@ -106,6 +110,15 @@ impl MlRuntime {
)
})
}
+
+ pub fn clip_text_session_mut(&mut self) -> MlResult<&mut Session> {
+ self.clip_text.as_mut().ok_or_else(|| {
+ MlError::InvalidRequest(
+ "missing model path: clipTextModelPath is required when running clip text"
+ .to_string(),
+ )
+ })
+ }
}
fn lock_runtime() -> std::sync::MutexGuard<'static, Option<RuntimeState>> {