Skip to content

armgit / ente

Public Imported from GitHub
0

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

exact simsimd comparisons in rust test

laurenspriem4319d80395b1
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 ababaed1bc..a8131fd940 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
@@ -206,13 +206,33 @@ class MLComputer extends SuperIsolate {
}
}
+ Future<Map<String, List<QueryResult>>> computeBulkSimilaritiesWithRust(
+ Map<String, List<double>> textQueryToEmbeddingMap,
+ Map<String, double> minimumSimilarityMap,
+ ) async {
+ try {
+ final queryToResults =
+ await runInIsolate(IsolateOperation.computeBulkSimilaritiesWithRust, {
+ "textQueryToEmbeddingMap": textQueryToEmbeddingMap,
+ "minimumSimilarityMap": minimumSimilarityMap,
+ }) as Map<String, List<QueryResult>>;
+ return queryToResults;
+ } catch (e, s) {
+ _logger.severe(
+ "Could not bulk compare embeddings with rust inside MLComputer isolate",
+ e,
+ s,
+ );
+ rethrow;
+ }
+ }
+
Future<void> cacheImageEmbeddings(List<EmbeddingVector> embeddings) async {
try {
await runInIsolate(
- IsolateOperation.setIsolateCache,
+ IsolateOperation.cacheImageEmbeddings,
{
- 'key': imageEmbeddingsKey,
- 'value': embeddings,
+ 'embeddings': embeddings,
},
) as bool;
_logger.info(
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index 4c03669dfe..7b3c17f9c5 100644
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -74,6 +74,14 @@ class SemanticSearchService {
return _prepareVectorDbFuture!;
}
+ bool get _shouldUseRustExactSearch =>
+ flagService.internalUser &&
+ flagService.usearchForSearch &&
+ localSettings.semanticSearchExactInRustEnabled;
+
+ bool get _shouldUseVectorDbApproximateSearch =>
+ flagService.usearchForSearch && !_shouldUseRustExactSearch;
+
void _initializeIfNeeded() {
if (_hasInitialized) {
return;
@@ -91,7 +99,7 @@ class SemanticSearchService {
}
void _scheduleWarmup({required bool delayTextModelLoad}) {
- if (flagService.usearchForSearch) {
+ if (_shouldUseVectorDbApproximateSearch) {
unawaited(_prepareVectorDbForSearch());
}
@@ -104,11 +112,11 @@ class SemanticSearchService {
Future<void> _prepareVectorDbForSearchInternal() async {
try {
- if (!flagService.usearchForSearch) return;
+ if (!_shouldUseVectorDbApproximateSearch) return;
if (!flagService.hasGrantedMLConsent) return;
if (!await _vectorDB.checkIfMigrationDone()) {
await Future.delayed(_vectorDbMigrationDelay);
- if (!flagService.usearchForSearch) return;
+ if (!_shouldUseVectorDbApproximateSearch) return;
if (!flagService.hasGrantedMLConsent) return;
await _mlDataDB.checkMigrateFillClipVectorDB();
}
@@ -423,6 +431,32 @@ class SemanticSearchService {
}
await _cacheClipVectors();
+ if (_shouldUseRustExactSearch) {
+ final startTime = DateTime.now();
+ try {
+ final queryResults =
+ await MLComputer.instance.computeBulkSimilaritiesWithRust(
+ textQueryToEmbeddingMap,
+ minimumSimilarityMap,
+ );
+ final endTime = DateTime.now();
+ _logger.info(
+ "computingSimilarities (rust simsimd exact) took for ${textQueryToEmbeddingMap.length} queries " +
+ (endTime.millisecondsSinceEpoch -
+ startTime.millisecondsSinceEpoch)
+ .toString() +
+ "ms",
+ );
+ return queryResults;
+ } catch (e, s) {
+ _logger.severe(
+ "Rust exact similarity search failed, falling back to Dart in-memory dot-product",
+ e,
+ s,
+ );
+ }
+ }
+
final startTime = DateTime.now();
final Map<String, List<QueryResult>> queryResults =
await MLComputer.instance.computeBulkSimilarities(
@@ -464,7 +498,7 @@ class SemanticSearchService {
}
Future<bool> _canUseVectorDbForSearch() async {
- if (!flagService.usearchForSearch) return false;
+ if (!_shouldUseVectorDbApproximateSearch) return false;
if (!flagService.hasGrantedMLConsent) return false;
if (await _vectorDB.checkIfMigrationDone()) return true;
// Keep interactive search responsive: prepare/migrate in the background and
diff --git a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
index 6ebf62dffa..13618116a0 100644
--- a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
@@ -203,6 +203,18 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
onChanged: _onPetRecognitionChanged,
),
),
+ if (flagService.internalUser && flagService.usearchForSearch)
+ MenuItemWidgetNew(
+ title: "Exact semantic search (SimSIMD)",
+ leadingIconWidget: _buildIconWidget(
+ context,
+ HugeIcons.strokeRoundedAiSearch,
+ ),
+ trailingWidget: ToggleSwitchWidget(
+ value: () => localSettings.semanticSearchExactInRustEnabled,
+ onChanged: _onSemanticSearchExactChanged,
+ ),
+ ),
],
);
}
@@ -746,6 +758,25 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
}
}
+ Future<void> _onSemanticSearchExactChanged() async {
+ try {
+ final enabled = !localSettings.semanticSearchExactInRustEnabled;
+ await localSettings.setSemanticSearchExactInRustEnabled(enabled);
+ await SemanticSearchService.instance.prepareForInteractiveSearch();
+ logger.info(
+ 'exact semantic search in rust is turned ${enabled ? 'on' : 'off'}',
+ );
+ if (mounted) {
+ setState(() {});
+ }
+ } catch (e, s) {
+ logger.warning('exact semantic search toggle failed ', e, s);
+ if (mounted) {
+ await showGenericErrorDialog(context: context, error: e);
+ }
+ }
+ }
+
Future<void> _onTriggerRunML(BuildContext context) async {
try {
MLService.instance.debugIndexingDisabled = false;
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index 859a7a4779..f4cc67c842 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -1,6 +1,8 @@
import 'dart:typed_data' show Float32List, Uint8List;
import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;
+import "package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart"
+ show Int64List;
import "package:ml_linalg/linalg.dart";
import "package:photos/db/ml/clip_vector_db.dart";
import "package:photos/models/ml/face/box.dart";
@@ -15,6 +17,7 @@ import "package:photos/services/machine_learning/semantic_search/query_result.da
import "package:photos/src/rust/api/image_processing_api.dart"
as rust_image_processing;
import "package:photos/src/rust/api/ml_indexing_api.dart" as rust_ml;
+import "package:photos/src/rust/api/usearch_api.dart" as rust_usearch;
import "package:photos/src/rust/frb_generated.dart" show EntePhotosRust;
import "package:photos/utils/image_ml_util.dart";
import "package:photos/utils/ml_util.dart";
@@ -54,6 +57,9 @@ enum IsolateOperation {
/// [MLComputer]
computeBulkSimilarities,
+ /// [MLComputer]
+ computeBulkSimilaritiesWithRust,
+
/// [MLComputer]
bulkVectorSearch,
@@ -64,11 +70,24 @@ enum IsolateOperation {
linearIncrementalClustering,
/// Cache operations
+ cacheImageEmbeddings,
setIsolateCache,
clearIsolateCache,
clearAllIsolateCache,
}
+class _CachedImageEmbeddings {
+ const _CachedImageEmbeddings({
+ required this.embeddingVectors,
+ required this.imageFileIds,
+ required this.imageEmbeddings,
+ });
+
+ final List<EmbeddingVector> embeddingVectors;
+ final Int64List imageFileIds;
+ final List<Float32List> imageEmbeddings;
+}
+
/// WARNING: Only return primitives unless you know the method is only going
/// to be used on regular isolates as opposed to DartUI and Flutter isolates
/// https://api.flutter.dev/flutter/dart-isolate/SendPort/send.html
@@ -243,8 +262,7 @@ Future<dynamic> isolateFunction(
/// MLComputer
case IsolateOperation.computeBulkSimilarities:
- final imageEmbeddings =
- _isolateCache[imageEmbeddingsKey] as List<EmbeddingVector>;
+ final cachedEmbeddings = _getCachedImageEmbeddings();
final textEmbedding =
args["textQueryToEmbeddingMap"] as Map<String, List<double>>;
final minimumSimilarityMap =
@@ -256,7 +274,7 @@ Future<dynamic> isolateFunction(
final textVector = Vector.fromList(entry.value);
final minimumSimilarity = minimumSimilarityMap[query]!;
final queryResults = <QueryResult>[];
- for (final imageEmbedding in imageEmbeddings) {
+ for (final imageEmbedding in cachedEmbeddings.embeddingVectors) {
final similarity = imageEmbedding.vector.dot(textVector);
if (similarity >= minimumSimilarity) {
queryResults.add(QueryResult(imageEmbedding.fileID, similarity));
@@ -268,6 +286,43 @@ Future<dynamic> isolateFunction(
}
return result;
+ /// MLComputer
+ case IsolateOperation.computeBulkSimilaritiesWithRust:
+ await _ensureRustLoaded();
+ final cachedEmbeddings = _getCachedImageEmbeddings();
+ final textEmbedding =
+ args["textQueryToEmbeddingMap"] as Map<String, List<double>>;
+ final minimumSimilarityMap =
+ args["minimumSimilarityMap"] as Map<String, double>;
+ final queryKeys = textEmbedding.keys.toList(growable: false);
+ final response = await rust_usearch.semanticSearchExact(
+ req: rust_usearch.SemanticSearchExactRequest(
+ imageFileIds: cachedEmbeddings.imageFileIds,
+ imageEmbeddings: cachedEmbeddings.imageEmbeddings,
+ queryEmbeddings: queryKeys
+ .map((query) => Float32List.fromList(textEmbedding[query]!))
+ .toList(growable: false),
+ minimumSimilarities: Float32List.fromList(
+ queryKeys
+ .map((query) => minimumSimilarityMap[query]!)
+ .toList(growable: false),
+ ),
+ ),
+ );
+ final result = <String, List<QueryResult>>{};
+ for (int i = 0; i < queryKeys.length; i++) {
+ final matches = response.matchesPerQuery[i];
+ result[queryKeys[i]] = matches
+ .map(
+ (match) => QueryResult(
+ match.fileId,
+ match.score,
+ ),
+ )
+ .toList(growable: false);
+ }
+ return result;
+
/// Cases for MLComputer end here
/// Cases for FaceClusteringService start here
@@ -281,6 +336,24 @@ Future<dynamic> isolateFunction(
/// Cases for Caching start here
+ /// Caching
+ case IsolateOperation.cacheImageEmbeddings:
+ final embeddings = args['embeddings'] as List<EmbeddingVector>;
+ _isolateCache[imageEmbeddingsKey] = _CachedImageEmbeddings(
+ embeddingVectors: embeddings,
+ imageFileIds: Int64List.fromList(
+ embeddings.map((embedding) => embedding.fileID).toList(),
+ ),
+ imageEmbeddings: embeddings
+ .map(
+ (embedding) => Float32List.fromList(
+ embedding.vector.toList(),
+ ),
+ )
+ .toList(growable: false),
+ );
+ return true;
+
/// Caching
case IsolateOperation.setIsolateCache:
final key = args['key'] as String;
@@ -304,6 +377,14 @@ Future<dynamic> isolateFunction(
}
}
+_CachedImageEmbeddings _getCachedImageEmbeddings() {
+ final cachedEmbeddings = _isolateCache[imageEmbeddingsKey];
+ if (cachedEmbeddings is! _CachedImageEmbeddings) {
+ throw StateError("Image embeddings are not cached in MLComputer isolate");
+ }
+ return cachedEmbeddings;
+}
+
Future<void> _ensureRustLoaded() async {
final bool loaded = _isolateCache[_rustLibLoadedCacheKey] as bool? ?? false;
if (!loaded) {
diff --git a/mobile/apps/photos/lib/utils/local_settings.dart b/mobile/apps/photos/lib/utils/local_settings.dart
index 12aa544305..ccdb1428bc 100644
--- a/mobile/apps/photos/lib/utils/local_settings.dart
+++ b/mobile/apps/photos/lib/utils/local_settings.dart
@@ -88,6 +88,8 @@ class LocalSettings {
"ml_debug.default_clustering_distance";
static const _kRunMLDuringInteractionOverride =
"ml_debug.run_ml_during_interaction";
+ static const _kSemanticSearchExactInRustEnabled =
+ "ml_debug.semantic_search_exact_in_rust";
static const _kAppMode = "ls.app_mode";
static const _kShowOfflineModeOption = "ls.show_offline_mode_option";
@@ -308,6 +310,13 @@ class LocalSettings {
await _prefs.setBool(_kRunMLDuringInteractionOverride, value);
}
+ bool get semanticSearchExactInRustEnabled =>
+ _prefs.getBool(_kSemanticSearchExactInRustEnabled) ?? false;
+
+ Future<void> setSemanticSearchExactInRustEnabled(bool value) async {
+ await _prefs.setBool(_kSemanticSearchExactInRustEnabled, value);
+ }
+
Future<bool> setSmartMemories(bool value) async {
await _prefs.setBool(kCuratedMemoriesEnabled, value);
return value;
diff --git a/mobile/apps/photos/rust/Cargo.lock b/mobile/apps/photos/rust/Cargo.lock
index c118e3e30c..2669b80591 100644
--- a/mobile/apps/photos/rust/Cargo.lock
+++ b/mobile/apps/photos/rust/Cargo.lock
@@ -778,6 +778,7 @@ version = "0.0.1"
dependencies = [
"ente_media_inspector",
"flutter_rust_bridge",
+ "simsimd",
]
[[package]]
@@ -2715,6 +2716,15 @@ dependencies = [
"quote",
]
+[[package]]
+name = "simsimd"
+version = "6.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35185e4ac5ccaa9b8550d0dbdfaca87a6cabd68d5fe2db81ad270692f827bdb1"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "siphasher"
version = "1.0.2"
diff --git a/mobile/apps/photos/rust/Cargo.toml b/mobile/apps/photos/rust/Cargo.toml
index 3d543ea51e..1b39cb1d4f 100644
--- a/mobile/apps/photos/rust/Cargo.toml
+++ b/mobile/apps/photos/rust/Cargo.toml
@@ -8,6 +8,7 @@ crate-type = ["cdylib", "staticlib"]
[dependencies]
flutter_rust_bridge = "=2.11.1"
+simsimd = "=6.5.5"
ente_media_inspector = { path = "../../../../rust/photos" }
[lints.rust]
diff --git a/mobile/apps/photos/rust/src/api/usearch_api.rs b/mobile/apps/photos/rust/src/api/usearch_api.rs
index ec75b23cf0..17e26b5646 100644
--- a/mobile/apps/photos/rust/src/api/usearch_api.rs
+++ b/mobile/apps/photos/rust/src/api/usearch_api.rs
@@ -1,10 +1,92 @@
use ente_media_inspector::vector_db;
use flutter_rust_bridge::frb;
+use simsimd::SpatialSimilarity;
type SearchMatch = (Vec<u64>, Vec<f32>);
type BulkSearchMatch = (Vec<Vec<u64>>, Vec<Vec<f32>>);
type BulkSearchByKeyMatch = (Vec<u64>, Vec<Vec<u64>>, Vec<Vec<f32>>);
+#[derive(Clone, Debug)]
+pub struct SemanticSearchExactRequest {
+ pub image_file_ids: Vec<i64>,
+ pub image_embeddings: Vec<Vec<f32>>,
+ pub query_embeddings: Vec<Vec<f32>>,
+ pub minimum_similarities: Vec<f32>,
+}
+
+#[derive(Clone, Debug)]
+pub struct SemanticSearchExactMatch {
+ pub file_id: i64,
+ pub score: f64,
+}
+
+#[derive(Clone, Debug)]
+pub struct SemanticSearchExactResponse {
+ pub matches_per_query: Vec<Vec<SemanticSearchExactMatch>>,
+}
+
+pub fn semantic_search_exact(
+ req: SemanticSearchExactRequest,
+) -> Result<SemanticSearchExactResponse, String> {
+ if req.image_file_ids.len() != req.image_embeddings.len() {
+ return Err(format!(
+ "image_file_ids length {} does not match image_embeddings length {}",
+ req.image_file_ids.len(),
+ req.image_embeddings.len()
+ ));
+ }
+
+ if req.query_embeddings.len() != req.minimum_similarities.len() {
+ return Err(format!(
+ "query_embeddings length {} does not match minimum_similarities length {}",
+ req.query_embeddings.len(),
+ req.minimum_similarities.len()
+ ));
+ }
+
+ let matches_per_query = req
+ .query_embeddings
+ .iter()
+ .zip(req.minimum_similarities.iter())
+ .map(|(query_embedding, minimum_similarity)| {
+ let minimum_similarity = f64::from(*minimum_similarity);
+ let mut query_matches = Vec::new();
+
+ for (file_id, image_embedding) in
+ req.image_file_ids.iter().zip(req.image_embeddings.iter())
+ {
+ if image_embedding.len() != query_embedding.len() {
+ return Err(format!(
+ "embedding dimension mismatch for file_id {file_id}: image={} query={}",
+ image_embedding.len(),
+ query_embedding.len()
+ ));
+ }
+
+ let Some(score) = <f32 as SpatialSimilarity>::dot(image_embedding, query_embedding)
+ else {
+ return Err(format!(
+ "failed to compute dot product for file_id {file_id} with dimension {}",
+ image_embedding.len()
+ ));
+ };
+
+ if score >= minimum_similarity {
+ query_matches.push(SemanticSearchExactMatch {
+ file_id: *file_id,
+ score,
+ });
+ }
+ }
+
+ query_matches.sort_by(|left, right| right.score.total_cmp(&left.score));
+ Ok(query_matches)
+ })
+ .collect::<Result<Vec<_>, String>>()?;
+
+ Ok(SemanticSearchExactResponse { matches_per_query })
+}
+
#[frb(opaque)]
pub struct VectorDB {
inner: vector_db::VectorDB,
@@ -127,3 +209,68 @@ impl VectorDB {
self.inner.get_index_stats()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::{SemanticSearchExactRequest, semantic_search_exact};
+
+ #[test]
+ fn semantic_search_exact_filters_and_sorts_matches() {
+ let response = semantic_search_exact(SemanticSearchExactRequest {
+ image_file_ids: vec![101, 102, 103],
+ image_embeddings: vec![
+ vec![1.0, 0.0, 0.0],
+ vec![0.8, 0.6, 0.0],
+ vec![0.0, 1.0, 0.0],
+ ],
+ query_embeddings: vec![vec![1.0, 0.0, 0.0]],
+ minimum_similarities: vec![0.7],
+ })
+ .expect("semantic search exact should succeed");
+
+ let matches = &response.matches_per_query[0];
+ assert_eq!(matches.len(), 2);
+ assert_eq!(matches[0].file_id, 101);
+ assert_eq!(matches[1].file_id, 102);
+ assert!(matches[0].score > matches[1].score);
+ }
+
+ #[test]
+ fn semantic_search_exact_supports_multiple_queries() {
+ let response = semantic_search_exact(SemanticSearchExactRequest {
+ image_file_ids: vec![201, 202, 203],
+ image_embeddings: vec![vec![1.0, 0.0], vec![0.0, 1.0], vec![0.70710677, 0.70710677]],
+ query_embeddings: vec![vec![1.0, 0.0], vec![0.0, 1.0]],
+ minimum_similarities: vec![0.5, 0.5],
+ })
+ .expect("semantic search exact should succeed");
+
+ assert_eq!(
+ response.matches_per_query[0]
+ .iter()
+ .map(|entry| entry.file_id)
+ .collect::<Vec<_>>(),
+ vec![201, 203]
+ );
+ assert_eq!(
+ response.matches_per_query[1]
+ .iter()
+ .map(|entry| entry.file_id)
+ .collect::<Vec<_>>(),
+ vec![202, 203]
+ );
+ }
+
+ #[test]
+ fn semantic_search_exact_rejects_dimension_mismatch() {
+ let err = semantic_search_exact(SemanticSearchExactRequest {
+ image_file_ids: vec![301],
+ image_embeddings: vec![vec![1.0, 0.0]],
+ query_embeddings: vec![vec![1.0, 0.0, 0.0]],
+ minimum_similarities: vec![0.1],
+ })
+ .expect_err("semantic search exact should fail on dimension mismatch");
+
+ assert!(err.contains("embedding dimension mismatch"));
+ }
+}