Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mobile][photos] Split ML vector DB wrappers by backend

laurenspriem290b3a4d35e2
diff --git a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart b/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
index 22f7254807..8404c685db 100644
--- a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
+++ b/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
@@ -1,469 +1,21 @@
-import "dart:io" show File;
-import "dart:typed_data" show Float32List;
-
-import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;
-import "package:logging/logging.dart";
-import "package:path/path.dart";
-import "package:path_provider/path_provider.dart";
-import "package:photos/models/ml/vector.dart";
+import "package:photos/db/ml/usearch_clip_vector_db.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
-import "package:photos/src/rust/api/usearch_api.dart";
-import "package:shared_preferences/shared_preferences.dart";
-import "package:synchronized/synchronized.dart";
-
-class ClipVectorDB {
- static final Logger _logger = Logger("ClipVectorDB");
- static const int embeddingDimensions = 512;
- static const int embeddingBytesLength = embeddingDimensions * 4;
-
- final String _databaseName;
- final String _migrationKey;
-
- static final BigInt _embeddingDimension = BigInt.from(embeddingDimensions);
-
- static Logger get logger => _logger;
-
- ClipVectorDB._privateConstructor(this._databaseName, this._migrationKey);
- static final instance = ClipVectorDB._privateConstructor(
- "ente.ml.vectordb.clip.usearch",
- "clip_vectordb_migration",
- );
- static final localGalleryInstance = ClipVectorDB._privateConstructor(
- "ente.ml.offline.vectordb.clip.usearch",
- "clip_vectordb_migration_offline",
- );
- factory ClipVectorDB() => instance;
-
- Future<VectorDb>? _vectorDbFuture;
- Future<void>? _warmupFuture;
- final Lock _writeLock = Lock();
-
- Future<VectorDb> get _vectorDB async {
- _vectorDbFuture ??= _initVectorDB();
- return _vectorDbFuture!;
- }
-
- bool? _migrationDone;
-
- Future<VectorDb> _initVectorDB() async {
- final documentsDirectory = await getApplicationDocumentsDirectory();
- final String dbPath = join(documentsDirectory.path, _databaseName);
- _logger.info("Opening vectorDB access: DB path " + dbPath);
- final indexFile = File(dbPath);
- if (!await indexFile.exists() && await checkIfMigrationDone()) {
- _logger.severe(
- "VectorDB file is missing while migration is marked done. Invalidating migration state.",
- );
- await invalidateMigrationState();
- }
- late VectorDb vectorDB;
- try {
- vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
- } catch (e, s) {
- _logger.severe("Could not open VectorDB at path $dbPath", e, s);
- _logger.severe("Deleting the index file and trying again");
- await deleteIndexFile();
- try {
- vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
- } catch (e, s) {
- _logger.severe("Still can't open VectorDB at path $dbPath", e, s);
- rethrow;
- }
- }
- final stats = await getIndexStats(vectorDB);
- _logger.info("VectorDB connection opened with stats: ${stats.toString()}");
-
- return vectorDB;
- }
-
- Future<bool> checkIfMigrationDone() async {
- if (_migrationDone != null) return _migrationDone!;
- _logger.info("Checking if ClipVectorDB migration has run");
- final prefs = await SharedPreferences.getInstance();
- final migrationDone = prefs.getBool(_migrationKey) ?? false;
- if (migrationDone) {
- _logger.info("ClipVectorDB migration already done");
- _migrationDone = true;
- return _migrationDone!;
- } else {
- _logger.info("ClipVectorDB migration not done");
- _migrationDone = false;
- return _migrationDone!;
- }
- }
-
- Future<void> setMigrationDone() async {
- _logger.info("Setting ClipVectorDB migration done");
- final prefs = await SharedPreferences.getInstance();
- await prefs.setBool(_migrationKey, true);
- _migrationDone = true;
- }
-
- Future<void> invalidateMigrationState() async {
- _logger.info("Invalidating ClipVectorDB migration state");
- final prefs = await SharedPreferences.getInstance();
- await prefs.setBool(_migrationKey, false);
- _migrationDone = false;
- }
-
- Future<void> _runWriteOperation(
- Future<void> Function(VectorDb db) operation,
- ) async {
- final db = await _vectorDB;
- await _writeLock.synchronized(() async {
- await operation(db);
- });
- }
-
- Future<void> insertEmbedding({
- required int fileID,
- required List<double> embedding,
- }) async {
- try {
- await _runWriteOperation((db) async {
- await db.addVector(key: BigInt.from(fileID), vector: embedding);
- });
- } catch (e, s) {
- _logger.severe("Error inserting embedding", e, s);
- rethrow;
- }
- }
-
- Future<void> bulkInsertEmbeddings({
- required List<int> fileIDs,
- required List<Float32List> embeddings,
- }) async {
- if (fileIDs.isEmpty || embeddings.isEmpty) {
- return;
- }
- final bigKeys = Uint64List.fromList(fileIDs);
- try {
- await _runWriteOperation((db) async {
- await db.bulkAddVectors(keys: bigKeys, vectors: embeddings);
- });
- } catch (e, s) {
- _logger.severe("Error bulk inserting embeddings", e, s);
- rethrow;
- }
- }
-
- Future<List<EmbeddingVector>> getEmbeddings(List<int> fileIDs) async {
- final db = await _vectorDB;
- try {
- final keys = Uint64List.fromList(fileIDs);
- final vectors = await db.bulkGetVectors(keys: keys);
- return List.generate(
- vectors.length,
- (index) =>
- EmbeddingVector(fileID: fileIDs[index], embedding: vectors[index]),
- );
- } catch (e, s) {
- _logger.severe("Error getting embeddings", e, s);
- rethrow;
- }
- }
- Future<void> deleteEmbeddings(List<int> fileIDs) async {
- if (fileIDs.isEmpty) {
- return;
- }
- try {
- BigInt deletedCount = BigInt.zero;
- await _runWriteOperation((db) async {
- deletedCount = await db.bulkRemoveVectors(
- keys: Uint64List.fromList(fileIDs),
- );
- });
- _logger.info(
- "Deleted $deletedCount embeddings, from ${fileIDs.length} keys",
- );
- } catch (e, s) {
- _logger.severe("Error bulk deleting specific embeddings", e, s);
- rethrow;
- }
- }
+abstract class ClipVectorDB {
+ static ClipVectorDB get instance => UsearchClipVectorDB.instance;
+ static ClipVectorDB get localGalleryInstance =>
+ UsearchClipVectorDB.localGalleryInstance;
- Future<void> deleteAllEmbeddings() async {
- await invalidateMigrationState();
- try {
- await _runWriteOperation((db) async {
- await db.resetIndex();
- });
- } catch (e, s) {
- _logger.severe("Error deleting all embeddings", e, s);
- rethrow;
- }
- }
-
- Future<VectorDbStats> getIndexStats([VectorDb? db]) async {
- db ??= await _vectorDB;
- try {
- final stats = await db.getIndexStats();
- return VectorDbStats(
- size: stats.$1.toInt(),
- capacity: stats.$2.toInt(),
- dimensions: stats.$3.toInt(),
- fileSize: stats.$4.toInt(),
- memoryUsage: stats.$5.toInt(),
- expansionAdd: stats.$6.toInt(),
- expansionSearch: stats.$7.toInt(),
- );
- } catch (e, s) {
- _logger.severe("Error getting index stats", e, s);
- rethrow;
- }
- }
-
- Future<(Uint64List, Float32List)> searchClosestVectors(
- List<double> query,
- int count, {
- bool exact = false,
- }) async {
- final db = await _vectorDB;
- try {
- final result = await db.searchVectors(
- query: query,
- count: BigInt.from(count),
- exact: exact,
- );
- return result;
- } catch (e, s) {
- _logger.severe("Error searching closest vectors", e, s);
- rethrow;
- }
- }
-
- Future<(BigInt, double)> searchClosestVector(
- List<double> query, {
- bool exact = false,
- }) async {
- final db = await _vectorDB;
- try {
- final result = await db.searchVectors(
- query: query,
- count: BigInt.one,
- exact: exact,
- );
- return (result.$1[0], result.$2[0]);
- } catch (e, s) {
- _logger.severe("Error searching closest vector", e, s);
- rethrow;
- }
- }
-
- Future<void> warmupApproxSearch() async {
- _warmupFuture ??= _warmupApproxSearchInternal();
- await _warmupFuture;
- }
-
- Future<void> _warmupApproxSearchInternal() async {
- final stopwatch = Stopwatch()..start();
- try {
- final db = await _vectorDB;
- final stats = await getIndexStats(db);
- if (stats.size == 0) {
- _logger.info("Skipping VectorDB warmup: index is empty");
- return;
- }
-
- final warmupQuery = List<double>.filled(
- stats.dimensions,
- 0.0,
- growable: false,
- );
- await db.searchVectors(
- query: warmupQuery,
- count: BigInt.one,
- exact: false,
- );
- _logger.info(
- "VectorDB warmup finished in ${stopwatch.elapsedMilliseconds} ms",
- );
- } catch (e, s) {
- _logger.warning("VectorDB warmup failed", e, s);
- _warmupFuture = null;
- } finally {
- stopwatch.stop();
- }
- }
-
- Future<List<QueryResult>> searchApproxSimilaritiesWithinThreshold(
+ Future<bool> isReady();
+ Future<void> warmup();
+ Future<List<QueryResult>> searchSimilaritiesWithinThreshold(
List<double> query,
double minimumSimilarity,
- ) async {
- final db = await _vectorDB;
- if (!await checkIfMigrationDone()) {
- throw StateError(
- "ClipVectorDB migration is not done, cannot run approximate search",
- );
- }
- try {
- final result = await db.approxSearchVectorsWithinSimilarity(
- query: query,
- minimumSimilarity: minimumSimilarity,
- );
- final keys = result.$1;
- final distances = result.$2;
- final queryResults = <QueryResult>[];
- for (var i = 0; i < keys.length; i++) {
- queryResults.add(QueryResult(keys[i].toInt(), 1.0 - distances[i]));
- }
- return queryResults;
- } catch (e, s) {
- _logger.severe("Error searching approximate similarities", e, s);
- rethrow;
- }
- }
-
- Future<(List<Uint64List>, List<Float32List>)> bulkSearchVectors(
- List<Float32List> queries,
- BigInt count, {
- bool exact = false,
- }) async {
- final db = await _vectorDB;
- try {
- final result = await db.bulkSearchVectors(
- queries: queries,
- count: count,
- exact: exact,
- );
- return result;
- } catch (e, s) {
- _logger.severe("Error bulk searching vectors", e, s);
- rethrow;
- }
- }
-
- Future<(Uint64List, List<Uint64List>, List<Float32List>)> bulkSearchWithKeys(
- Uint64List potentialKeys,
- BigInt count, {
- bool exact = false,
- }) async {
- final db = await _vectorDB;
- try {
- final result = await db.bulkSearchKeys(
- potentialKeys: potentialKeys,
- count: count,
- exact: exact,
- );
- return result;
- } catch (e, s) {
- _logger.severe("Error bulk searching vectors with potential keys", e, s);
- rethrow;
- }
- }
-
- Future<Map<String, List<QueryResult>>> computeBulkSimilarities(
- Map<String, List<double>> textQueryToEmbeddingMap,
- Map<String, double> minimumSimilarityMap, {
- int? maxResults,
- }) async {
- try {
- int? resolvedMaxResults = maxResults;
- if (resolvedMaxResults == null || resolvedMaxResults <= 0) {
- final stats = await getIndexStats();
- resolvedMaxResults = stats.size;
- }
- if (resolvedMaxResults == 0) {
- return {
- for (final query in textQueryToEmbeddingMap.keys)
- query: <QueryResult>[],
- };
- }
- final queryToResults = <String, List<QueryResult>>{};
- for (final MapEntry<String, List<double>> entry
- in textQueryToEmbeddingMap.entries) {
- final query = entry.key;
- final minimumSimilarity = minimumSimilarityMap[query]!;
- final textEmbedding = entry.value;
- final (potentialFileIDs, distances) = await searchClosestVectors(
- textEmbedding,
- resolvedMaxResults,
- );
- final queryResults = <QueryResult>[];
- for (var i = 0; i < potentialFileIDs.length; i++) {
- final similarity = 1 - distances[i];
- if (similarity >= minimumSimilarity) {
- queryResults.add(
- QueryResult(potentialFileIDs[i].toInt(), similarity),
- );
- } else {
- break;
- }
- }
- queryToResults[query] = queryResults;
- }
- return queryToResults;
- } catch (e, s) {
- _logger.severe(
- "Could not bulk find embeddings similarities using vector DB",
- e,
- s,
- );
- rethrow;
- }
- }
-
- Future<void> deleteIndex() async {
- await invalidateMigrationState();
- final db = await _vectorDB;
- try {
- await _writeLock.synchronized(() async {
- await db.deleteIndex();
- _vectorDbFuture = null;
- _warmupFuture = null;
- });
- } catch (e, s) {
- _logger.severe("Error deleting index", e, s);
- rethrow;
- }
- }
-
- Future<void> deleteIndexFile() async {
- await _writeLock.synchronized(() async {
- try {
- final documentsDirectory = await getApplicationDocumentsDirectory();
- final String dbPath = join(documentsDirectory.path, _databaseName);
- _logger.info("Delete index file: DB path " + dbPath);
- final file = File(dbPath);
- if (await file.exists()) {
- await file.delete();
- }
- _logger.info("Deleted index file on disk");
- _vectorDbFuture = null;
- _warmupFuture = null;
- await invalidateMigrationState();
- } catch (e, s) {
- _logger.severe("Error deleting index file on disk", e, s);
- rethrow;
- }
- });
- }
-}
-
-class VectorDbStats {
- final int size;
- final int capacity;
- final int dimensions;
-
- final int fileSize;
- final int memoryUsage;
-
- final int expansionAdd;
- final int expansionSearch;
-
- VectorDbStats({
- required this.size,
- required this.capacity,
- required this.dimensions,
- required this.fileSize,
- required this.memoryUsage,
- required this.expansionAdd,
- required this.expansionSearch,
+ );
+ Future<Map<int, List<(int, double)>>> bulkSearchNearestForFiles(
+ List<int> fileIDs, {
+ required int count,
+ required double maxDistance,
+ required bool exact,
});
-
- @override
- String toString() {
- return "VectorDbStats(size: $size, capacity: $capacity, dimensions: $dimensions, file size on disk (bytes): $fileSize, memory usage (bytes): $memoryUsage, expansionAdd: $expansionAdd, expansionSearch: $expansionSearch)";
- }
}
diff --git a/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart b/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart
index 1d1a455af5..628a26fca6 100644
--- a/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart
+++ b/mobile/apps/photos/lib/db/ml/cluster_centroid_vector_db.dart
@@ -1,471 +1,28 @@
-import "dart:io" show File;
-import "dart:typed_data" show Float32List;
-
-import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;
-import "package:logging/logging.dart";
-import "package:path/path.dart";
-import "package:path_provider/path_provider.dart";
-import "package:photos/src/rust/api/usearch_api.dart";
-import "package:shared_preferences/shared_preferences.dart";
-import "package:synchronized/synchronized.dart";
-
-class ClusterCentroidVectorDB {
- static final Logger _logger = Logger("ClusterCentroidVectorDB");
-
- final String _databaseName;
- final String _migrationKey;
-
- static const int embeddingDimensions = 192;
- static final BigInt _embeddingDimension = BigInt.from(embeddingDimensions);
-
- static Logger get logger => _logger;
-
- ClusterCentroidVectorDB._privateConstructor(
- this._databaseName,
- this._migrationKey,
- );
-
- static final instance = ClusterCentroidVectorDB._privateConstructor(
- "ente.ml.vectordb.cluster_centroid.usearch",
- "cluster_centroid_vectordb_migration",
- );
- static final localGalleryInstance =
- ClusterCentroidVectorDB._privateConstructor(
- "ente.ml.offline.vectordb.cluster_centroid.usearch",
- "cluster_centroid_vectordb_migration_offline",
- );
-
- factory ClusterCentroidVectorDB() => instance;
-
- Future<VectorDb>? _vectorDbFuture;
- Future<void>? _warmupFuture;
- final Lock _writeLock = Lock();
-
- Future<VectorDb> get _vectorDB async {
- _vectorDbFuture ??= _initVectorDB();
- return _vectorDbFuture!;
- }
-
- bool? _migrationDone;
-
- Future<VectorDb> _initVectorDB() async {
- final documentsDirectory = await getApplicationDocumentsDirectory();
- final String dbPath = join(documentsDirectory.path, _databaseName);
- _logger.info("Opening cluster centroid vector DB access: DB path $dbPath");
- final indexFile = File(dbPath);
- if (!await indexFile.exists() && await checkIfMigrationDone()) {
- _logger.severe(
- "Cluster centroid vector DB file is missing while migration is marked done. Invalidating migration state.",
- );
- await invalidateMigrationState();
- }
-
- late VectorDb vectorDB;
- try {
- vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
- } catch (e, s) {
- _logger.severe(
- "Could not open cluster centroid vector DB at path $dbPath",
- e,
- s,
- );
- _logger.severe("Deleting the index file and trying again");
- await deleteIndexFile();
- try {
- vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
- } catch (e, s) {
- _logger.severe(
- "Still can't open cluster centroid vector DB at path $dbPath",
- e,
- s,
- );
- rethrow;
- }
- }
-
- final stats = await getIndexStats(vectorDB);
- _logger.info(
- "Cluster centroid vector DB connection opened with stats: ${stats.toString()}",
- );
-
- return vectorDB;
- }
-
- Future<bool> checkIfMigrationDone() async {
- if (_migrationDone != null) return _migrationDone!;
- _logger.info("Checking if cluster centroid vector DB migration has run");
- final prefs = await SharedPreferences.getInstance();
- final migrationDone = prefs.getBool(_migrationKey) ?? false;
- if (migrationDone) {
- _logger.info("Cluster centroid vector DB migration already done");
- _migrationDone = true;
- return _migrationDone!;
- } else {
- _logger.info("Cluster centroid vector DB migration not done");
- _migrationDone = false;
- return _migrationDone!;
- }
- }
-
- Future<void> setMigrationDone() async {
- _logger.info("Setting cluster centroid vector DB migration done");
- final prefs = await SharedPreferences.getInstance();
- await prefs.setBool(_migrationKey, true);
- _migrationDone = true;
- }
-
- Future<void> invalidateMigrationState() async {
- _logger.info("Invalidating cluster centroid vector DB migration state");
- final prefs = await SharedPreferences.getInstance();
- await prefs.setBool(_migrationKey, false);
- _migrationDone = false;
- }
-
- Future<void> _runWriteOperation(
- Future<void> Function(VectorDb db) operation,
- ) async {
- final db = await _vectorDB;
- await _writeLock.synchronized(() async {
- await operation(db);
- });
- }
-
- Future<void> insertCentroid({
- required int clusterVectorID,
- required List<double> centroid,
- }) async {
- try {
- await _runWriteOperation((db) async {
- await db.addVector(key: BigInt.from(clusterVectorID), vector: centroid);
- });
- } catch (e, s) {
- _logger.severe("Error inserting cluster centroid", e, s);
- rethrow;
- }
- }
-
- Future<void> bulkInsertCentroids({
- required List<int> clusterVectorIDs,
- required List<Float32List> centroids,
- }) async {
- if (clusterVectorIDs.isEmpty || centroids.isEmpty) {
- return;
- }
- try {
- await _runWriteOperation((db) async {
- await db.bulkAddVectors(
- keys: Uint64List.fromList(clusterVectorIDs),
- vectors: centroids,
- );
- });
- } catch (e, s) {
- _logger.severe("Error bulk inserting cluster centroids", e, s);
- rethrow;
- }
- }
-
- Future<void> deleteCentroids(List<int> clusterVectorIDs) async {
- if (clusterVectorIDs.isEmpty) {
- return;
- }
- try {
- BigInt deletedCount = BigInt.zero;
- await _runWriteOperation((db) async {
- deletedCount = await db.bulkRemoveVectors(
- keys: Uint64List.fromList(clusterVectorIDs),
- );
- });
- _logger.info(
- "Deleted $deletedCount centroids from ${clusterVectorIDs.length} keys",
- );
- } catch (e, s) {
- _logger.severe("Error bulk deleting specific centroids", e, s);
- rethrow;
- }
- }
-
- Future<void> deleteAllCentroids() async {
- await invalidateMigrationState();
- try {
- await _runWriteOperation((db) async {
- await db.resetIndex();
- });
- } catch (e, s) {
- _logger.severe("Error deleting all cluster centroids", e, s);
- rethrow;
- }
- }
-
- Future<ClusterCentroidVectorDbStats> getIndexStats([VectorDb? db]) async {
- db ??= await _vectorDB;
- try {
- final stats = await db.getIndexStats();
- return ClusterCentroidVectorDbStats(
- size: stats.$1.toInt(),
- capacity: stats.$2.toInt(),
- dimensions: stats.$3.toInt(),
- fileSize: stats.$4.toInt(),
- memoryUsage: stats.$5.toInt(),
- expansionAdd: stats.$6.toInt(),
- expansionSearch: stats.$7.toInt(),
- );
- } catch (e, s) {
- _logger.severe("Error getting cluster centroid index stats", e, s);
- rethrow;
- }
- }
-
- Future<List<(int, double)>> searchApproxClosestCentroidsWithinDistance(
- List<double> query,
- Set<int> allowedClusterVectorIDs, {
- required double maxDistance,
- int count = 10,
- }) async {
- if (!await checkIfMigrationDone()) {
- throw StateError(
- "Cluster centroid vector DB migration is not done, cannot run approximate search",
- );
- }
- if (count <= 0 || allowedClusterVectorIDs.isEmpty) {
- return const [];
- }
- final db = await _vectorDB;
- try {
- final allowedKeys = Uint64List.fromList(
- allowedClusterVectorIDs.toList(growable: false),
- );
- final result = await db.approxFilteredSearchVectorsWithinDistance(
- query: query,
- allowedKeys: allowedKeys,
- count: BigInt.from(count),
- maxDistance: maxDistance,
- );
- final keys = result.$1;
- final distances = result.$2;
- final output = <(int, double)>[];
- for (var i = 0; i < keys.length; i++) {
- output.add((keys[i].toInt(), distances[i]));
- }
- return output;
- } catch (e, s) {
- _logger.severe("Error searching filtered centroids", e, s);
- rethrow;
- }
- }
-
- Future<List<List<(int, double)>>>
- bulkSearchApproxClosestCentroidsWithinDistance(
+import "package:photos/db/ml/usearch_cluster_centroid_vector_db.dart";
+
+typedef ClusterCentroidMatches = ({
+ List<(String, double)> matches,
+ bool reachedCount,
+});
+
+abstract class ClusterCentroidVectorDB {
+ static ClusterCentroidVectorDB get instance =>
+ UsearchClusterCentroidVectorDB.instance;
+ static ClusterCentroidVectorDB get localGalleryInstance =>
+ UsearchClusterCentroidVectorDB.localGalleryInstance;
+
+ Future<bool> isReady();
+ Future<void> warmup();
+ Future<List<List<(String, double)>>> bulkSearchNearestAllowed(
List<List<double>> queries,
- Set<int> allowedClusterVectorIDs, {
+ Set<String> allowedClusterIDs, {
required double maxDistance,
int count = 10,
- }) async {
- if (!await checkIfMigrationDone()) {
- throw StateError(
- "Cluster centroid vector DB migration is not done, cannot run approximate search",
- );
- }
- if (count <= 0 || queries.isEmpty || allowedClusterVectorIDs.isEmpty) {
- return const <List<(int, double)>>[];
- }
- final db = await _vectorDB;
- try {
- final rustQueries = <Float32List>[];
- for (final query in queries) {
- if (query is Float32List) {
- rustQueries.add(query);
- } else {
- rustQueries.add(Float32List.fromList(query));
- }
- }
- final allowedKeys = Uint64List.fromList(
- allowedClusterVectorIDs.toList(growable: false),
- );
- final result = await db.bulkApproxFilteredSearchVectorsWithinDistance(
- queries: rustQueries,
- allowedKeys: allowedKeys,
- count: BigInt.from(count),
- maxDistance: maxDistance,
- );
-
- final keysPerQuery = result.$1;
- final distancesPerQuery = result.$2;
- final alignedQueryLength = keysPerQuery.length < distancesPerQuery.length
- ? keysPerQuery.length
- : distancesPerQuery.length;
- final output = <List<(int, double)>>[];
- for (var i = 0; i < alignedQueryLength; i++) {
- final keys = keysPerQuery[i];
- final distances = distancesPerQuery[i];
- final alignedLength = keys.length < distances.length
- ? keys.length
- : distances.length;
- final matches = <(int, double)>[];
- for (var j = 0; j < alignedLength; j++) {
- matches.add((keys[j].toInt(), distances[j]));
- }
- output.add(matches);
- }
- return output;
- } catch (e, s) {
- _logger.severe("Error bulk searching filtered centroids", e, s);
- rethrow;
- }
- }
-
- Future<Map<int, List<(int, double)>>>
- bulkSearchApproxClosestCentroidsForKeysWithinDistance(
- Set<int> queryClusterVectorIDs, {
+ });
+ Future<Map<String, ClusterCentroidMatches>> bulkSearchNearestForClusters(
+ Set<String> queryClusterIDs, {
+ required Set<String> candidateClusterIDs,
required int count,
double? maxDistance,
- }) async {
- if (!await checkIfMigrationDone()) {
- throw StateError(
- "Cluster centroid vector DB migration is not done, cannot run approximate search",
- );
- }
- if (count <= 0 || queryClusterVectorIDs.isEmpty) {
- return const {};
- }
- final db = await _vectorDB;
- try {
- final queryKeys = queryClusterVectorIDs.toList(growable: false);
- final result = await db.bulkSearchKeys(
- potentialKeys: Uint64List.fromList(queryKeys),
- count: BigInt.from(count),
- exact: false,
- );
- final containedKeys = result.$1;
- final matchedKeys = result.$2;
- final matchedDistances = result.$3;
-
- final output = <int, List<(int, double)>>{};
- for (var i = 0; i < containedKeys.length; i++) {
- final queryKey = containedKeys[i].toInt();
- final keysForQuery = matchedKeys[i];
- final distancesForQuery = matchedDistances[i];
- final alignedLength = keysForQuery.length < distancesForQuery.length
- ? keysForQuery.length
- : distancesForQuery.length;
- final matches = <(int, double)>[];
- for (var j = 0; j < alignedLength; j++) {
- final distance = distancesForQuery[j];
- if (maxDistance != null && distance > maxDistance) {
- break;
- }
- matches.add((keysForQuery[j].toInt(), distance));
- }
- output[queryKey] = matches;
- }
- return output;
- } catch (e, s) {
- _logger.severe("Error bulk searching centroids", e, s);
- rethrow;
- }
- }
-
- Future<void> warmupApproxSearch() async {
- _warmupFuture ??= _warmupApproxSearchInternal();
- await _warmupFuture;
- }
-
- Future<void> _warmupApproxSearchInternal() async {
- final stopwatch = Stopwatch()..start();
- try {
- final db = await _vectorDB;
- final stats = await getIndexStats(db);
- if (stats.size == 0) {
- _logger.info(
- "Skipping cluster centroid vector DB warmup: index is empty",
- );
- return;
- }
-
- final warmupQuery = List<double>.filled(
- stats.dimensions,
- 0.0,
- growable: false,
- );
- await db.searchVectors(
- query: warmupQuery,
- count: BigInt.one,
- exact: false,
- );
- _logger.info(
- "Cluster centroid vector DB warmup finished in ${stopwatch.elapsedMilliseconds} ms",
- );
- } catch (e, s) {
- _logger.warning("Cluster centroid vector DB warmup failed", e, s);
- _warmupFuture = null;
- } finally {
- stopwatch.stop();
- }
- }
-
- Future<void> deleteIndex() async {
- await invalidateMigrationState();
- final db = await _vectorDB;
- try {
- await _writeLock.synchronized(() async {
- await db.deleteIndex();
- _vectorDbFuture = null;
- _warmupFuture = null;
- });
- } catch (e, s) {
- _logger.severe("Error deleting cluster centroid index", e, s);
- rethrow;
- }
- }
-
- Future<void> deleteIndexFile() async {
- await _writeLock.synchronized(() async {
- try {
- final documentsDirectory = await getApplicationDocumentsDirectory();
- final String dbPath = join(documentsDirectory.path, _databaseName);
- _logger.info("Delete cluster centroid index file: DB path $dbPath");
- final file = File(dbPath);
- if (await file.exists()) {
- await file.delete();
- }
- _logger.info("Deleted cluster centroid index file on disk");
- _vectorDbFuture = null;
- _warmupFuture = null;
- await invalidateMigrationState();
- } catch (e, s) {
- _logger.severe(
- "Error deleting cluster centroid index file on disk",
- e,
- s,
- );
- rethrow;
- }
- });
- }
-}
-
-class ClusterCentroidVectorDbStats {
- final int size;
- final int capacity;
- final int dimensions;
-
- final int fileSize;
- final int memoryUsage;
-
- final int expansionAdd;
- final int expansionSearch;
-
- ClusterCentroidVectorDbStats({
- required this.size,
- required this.capacity,
- required this.dimensions,
- required this.fileSize,
- required this.memoryUsage,
- required this.expansionAdd,
- required this.expansionSearch,
});
-
- @override
- String toString() {
- return "ClusterCentroidVectorDbStats(size: $size, capacity: $capacity, dimensions: $dimensions, file size on disk (bytes): $fileSize, memory usage (bytes): $memoryUsage, expansionAdd: $expansionAdd, expansionSearch: $expansionSearch)";
- }
}
diff --git a/mobile/apps/photos/lib/db/ml/dart_db.dart b/mobile/apps/photos/lib/db/ml/dart_db.dart
index 74351909b4..7a4171b24a 100644
--- a/mobile/apps/photos/lib/db/ml/dart_db.dart
+++ b/mobile/apps/photos/lib/db/ml/dart_db.dart
@@ -8,11 +8,11 @@ import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart';
import "package:photos/db/common/base.dart";
import "package:photos/db/ml/base.dart";
-import "package:photos/db/ml/clip_vector_db.dart";
-import "package:photos/db/ml/cluster_centroid_vector_db.dart";
import "package:photos/db/ml/db_model_mappers.dart";
import "package:photos/db/ml/ml_data_db_orchestration.dart";
import 'package:photos/db/ml/schema.dart';
+import "package:photos/db/ml/usearch_clip_vector_db.dart";
+import "package:photos/db/ml/usearch_cluster_centroid_vector_db.dart";
import "package:photos/models/ml/clip.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/face/face_with_embedding.dart";
@@ -32,27 +32,28 @@ class DartMLDataDB
static const int _maxSqlBindParamsPerQuery = 10000;
final String _databaseName;
- final ClipVectorDB _clipVectorDB;
- final ClusterCentroidVectorDB _clusterCentroidVectorDB;
+ final UsearchClipVectorDB _clipVectorDB;
+ final UsearchClusterCentroidVectorDB _clusterCentroidVectorDB;
final List<String> _migrationScripts;
DartMLDataDB._privateConstructor({
String databaseName = "ente.ml.db",
- ClipVectorDB? clipVectorDB,
- ClusterCentroidVectorDB? clusterCentroidVectorDB,
+ UsearchClipVectorDB? clipVectorDB,
+ UsearchClusterCentroidVectorDB? clusterCentroidVectorDB,
List<String>? migrationScripts,
}) : _databaseName = databaseName,
- _clipVectorDB = clipVectorDB ?? ClipVectorDB.instance,
+ _clipVectorDB = clipVectorDB ?? UsearchClipVectorDB.instance,
_clusterCentroidVectorDB =
- clusterCentroidVectorDB ?? ClusterCentroidVectorDB.instance,
+ clusterCentroidVectorDB ?? UsearchClusterCentroidVectorDB.instance,
_migrationScripts = migrationScripts ?? _defaultMigrationScripts;
static final DartMLDataDB instance = DartMLDataDB._privateConstructor();
static final DartMLDataDB localGalleryInstance =
DartMLDataDB._privateConstructor(
databaseName: "ente.ml.offline.db",
- clipVectorDB: ClipVectorDB.localGalleryInstance,
- clusterCentroidVectorDB: ClusterCentroidVectorDB.localGalleryInstance,
+ clipVectorDB: UsearchClipVectorDB.localGalleryInstance,
+ clusterCentroidVectorDB:
+ UsearchClusterCentroidVectorDB.localGalleryInstance,
migrationScripts: _localGalleryMigrationScripts,
);
@@ -79,10 +80,10 @@ class DartMLDataDB
];
@override
- ClipVectorDB get clipVectorDB => _clipVectorDB;
+ UsearchClipVectorDB get clipVectorDB => _clipVectorDB;
@override
- ClusterCentroidVectorDB get clusterCentroidVectorDB =>
+ UsearchClusterCentroidVectorDB get clusterCentroidVectorDB =>
_clusterCentroidVectorDB;
@override
@@ -1480,7 +1481,9 @@ class DartMLDataDB
final List<EmbeddingVector> embeddings = [];
for (final result in results) {
final bytes = result[embeddingColumn] as Uint8List;
- if (bytes.lengthInBytes != ClipVectorDB.embeddingBytesLength) continue;
+ if (bytes.lengthInBytes != UsearchClipVectorDB.embeddingBytesLength) {
+ continue;
+ }
final embedding = EmbeddingVector(
fileID: result[fileIDColumn],
embedding: Float32List.sublistView(bytes),
@@ -1592,7 +1595,7 @@ class DartMLDataDB
'WHERE $mlVersionColumn >= ? AND LENGTH($embeddingColumn) = ?';
final List<Map<String, dynamic>> maps = await db.getAll(query, [
minimumMlVersion,
- ClipVectorDB.embeddingBytesLength,
+ UsearchClipVectorDB.embeddingBytesLength,
]);
return maps.first['count'] as int;
}
diff --git a/mobile/apps/photos/lib/db/ml/ml_data_db_orchestration.dart b/mobile/apps/photos/lib/db/ml/ml_data_db_orchestration.dart
index dbb7ce73c3..ab2de75c75 100644
--- a/mobile/apps/photos/lib/db/ml/ml_data_db_orchestration.dart
+++ b/mobile/apps/photos/lib/db/ml/ml_data_db_orchestration.dart
@@ -4,8 +4,8 @@ import "dart:typed_data";
import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/db/ml/base.dart";
-import "package:photos/db/ml/clip_vector_db.dart";
-import "package:photos/db/ml/cluster_centroid_vector_db.dart";
+import "package:photos/db/ml/usearch_clip_vector_db.dart";
+import "package:photos/db/ml/usearch_cluster_centroid_vector_db.dart";
import "package:photos/events/embedding_updated_event.dart";
import "package:photos/generated/protos/ente/common/vector.pb.dart";
import "package:photos/main.dart" show isProcessBg;
@@ -28,8 +28,8 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
final Lock _clusterCentroidVectorMigrationLock = Lock();
bool _clusterCentroidVectorDbRecoveryRequested = false;
- ClipVectorDB get clipVectorDB;
- ClusterCentroidVectorDB get clusterCentroidVectorDB;
+ UsearchClipVectorDB get clipVectorDB;
+ UsearchClusterCentroidVectorDB get clusterCentroidVectorDB;
Logger get logger;
@override
@@ -63,7 +63,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
_markClusterSummaryMutated();
if (!flagService.enableVectorDb ||
- !await clusterCentroidVectorDB.checkIfMigrationDone()) {
+ !await clusterCentroidVectorDB.isReady()) {
return;
}
@@ -93,7 +93,8 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
);
continue;
}
- if (centroid.length != ClusterCentroidVectorDB.embeddingDimensions) {
+ if (centroid.length !=
+ UsearchClusterCentroidVectorDB.embeddingDimensions) {
logger.warning(
"Unexpected centroid embedding size ${centroid.length} for cluster ${entry.key}, skipping vector update",
);
@@ -124,7 +125,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
_markClusterSummaryMutated();
if (!flagService.enableVectorDb ||
- !await clusterCentroidVectorDB.checkIfMigrationDone()) {
+ !await clusterCentroidVectorDB.isReady()) {
await deleteClusterCentroidVectorIdMapping(clusterID);
return;
}
@@ -153,7 +154,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
await resetClusterTables(faces: faces);
_markClusterSummaryMutated();
- if (await clusterCentroidVectorDB.checkIfMigrationDone()) {
+ if (await clusterCentroidVectorDB.isReady()) {
await _withClusterCentroidVectorWriteRecovery(
operation: "dropClustersAndPersonTable",
writeOperation: () async {
@@ -170,7 +171,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
Future<void> checkMigrateFillClusterCentroidVectorDB({
bool force = false,
}) async {
- if (!force && await clusterCentroidVectorDB.checkIfMigrationDone()) {
+ if (!force && await clusterCentroidVectorDB.isReady()) {
return;
}
await _runMlOperationExclusive(
@@ -184,8 +185,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
required bool force,
}) async {
await _clusterCentroidVectorMigrationLock.synchronized(() async {
- final migrationDone = await clusterCentroidVectorDB
- .checkIfMigrationDone();
+ final migrationDone = await clusterCentroidVectorDB.isReady();
if (migrationDone && !force) {
logger.info(
"ClusterCentroidVectorDB migration not needed, already done",
@@ -377,7 +377,8 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
);
continue;
}
- if (centroid.length == ClusterCentroidVectorDB.embeddingDimensions) {
+ if (centroid.length ==
+ UsearchClusterCentroidVectorDB.embeddingDimensions) {
clusterIDs.add(clusterID);
clusterIDToCentroid[clusterID] = centroid;
} else {
@@ -454,7 +455,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
@override
Future<void> checkMigrateFillClipVectorDB({bool force = false}) async {
- if (!force && await clipVectorDB.checkIfMigrationDone()) {
+ if (!force && await clipVectorDB.isReady()) {
return;
}
await _runMlOperationExclusive(
@@ -466,7 +467,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
Future<void> _checkMigrateFillClipVectorDB({required bool force}) async {
await _clipVectorMigrationLock.synchronized(() async {
- final migrationDone = await clipVectorDB.checkIfMigrationDone();
+ final migrationDone = await clipVectorDB.isReady();
if (migrationDone && !force) {
logger.info("ClipVectorDB migration not needed, already done");
return;
@@ -523,7 +524,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
final List<Float32List> embeddings = [];
for (final (fileID, embeddingBytes) in results) {
final embedding = Float32List.view(embeddingBytes.buffer);
- if (embedding.length == ClipVectorDB.embeddingDimensions) {
+ if (embedding.length == UsearchClipVectorDB.embeddingDimensions) {
fileIDs.add(fileID);
embeddings.add(Float32List.view(embeddingBytes.buffer));
} else if (embedding.isEmpty) {
@@ -654,7 +655,8 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
}
bool _isVectorizableClipEmbedding(ClipEmbedding embedding) {
- return embedding.embedding.length == ClipVectorDB.embeddingDimensions;
+ return embedding.embedding.length ==
+ UsearchClipVectorDB.embeddingDimensions;
}
List<ClipEmbedding> _vectorizableClipEmbeddings(
@@ -675,7 +677,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
for (final (fileID, length) in skippedNonEmpty) {
logger.warning(
- "Skipping ClipVectorDB write for fileID $fileID because embedding length $length does not match expected ${ClipVectorDB.embeddingDimensions}",
+ "Skipping ClipVectorDB write for fileID $fileID because embedding length $length does not match expected ${UsearchClipVectorDB.embeddingDimensions}",
);
}
@@ -741,7 +743,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
if (embeddings.length == 1) {
if (flagService.enableVectorDb &&
vectorizableEmbeddings.isNotEmpty &&
- await clipVectorDB.checkIfMigrationDone()) {
+ await clipVectorDB.isReady()) {
await _withClipVectorWriteRecovery(
operation: "putClip(single)",
writeOperation: () async {
@@ -755,7 +757,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
} else {
if (flagService.enableVectorDb &&
vectorizableEmbeddings.isNotEmpty &&
- await clipVectorDB.checkIfMigrationDone()) {
+ await clipVectorDB.isReady()) {
await _withClipVectorWriteRecovery(
operation: "putClip(bulk)",
writeOperation: () async {
@@ -775,8 +777,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
@override
Future<void> deleteClipEmbeddings(List<int> fileIDs) async {
await deleteClipRows(fileIDs);
- if (flagService.enableVectorDb &&
- await clipVectorDB.checkIfMigrationDone()) {
+ if (flagService.enableVectorDb && await clipVectorDB.isReady()) {
await _withClipVectorWriteRecovery(
operation: "deleteClipEmbeddings",
writeOperation: () async {
@@ -790,8 +791,7 @@ mixin MLDataDBOrchestration implements IMLDataDB<int> {
@override
Future<void> deleteClipIndexes() async {
await deleteAllClipRows();
- if (flagService.enableVectorDb &&
- await clipVectorDB.checkIfMigrationDone()) {
+ if (flagService.enableVectorDb && await clipVectorDB.isReady()) {
await _withClipVectorWriteRecovery(
operation: "deleteClipIndexes",
writeOperation: () async {
diff --git a/mobile/apps/photos/lib/db/ml/rust_db.dart b/mobile/apps/photos/lib/db/ml/rust_db.dart
index c52b0f5a6c..368e84e142 100644
--- a/mobile/apps/photos/lib/db/ml/rust_db.dart
+++ b/mobile/apps/photos/lib/db/ml/rust_db.dart
@@ -6,10 +6,10 @@ import "package:path/path.dart" show join;
import "package:path_provider/path_provider.dart";
import "package:photos/db/common/base.dart";
import "package:photos/db/ml/base.dart";
-import "package:photos/db/ml/clip_vector_db.dart";
-import "package:photos/db/ml/cluster_centroid_vector_db.dart";
import "package:photos/db/ml/ml_data_db_orchestration.dart";
import "package:photos/db/ml/rust_db_model_mappers.dart" as mappers;
+import "package:photos/db/ml/usearch_clip_vector_db.dart";
+import "package:photos/db/ml/usearch_cluster_centroid_vector_db.dart";
import "package:photos/models/ml/clip.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/face/face_with_embedding.dart";
@@ -24,31 +24,32 @@ class RustMLDataDB with MLDataDBOrchestration implements IMLDataDB<int> {
static final Logger _logger = Logger("MLDataDB");
final String _databaseName;
- final ClipVectorDB _clipVectorDB;
- final ClusterCentroidVectorDB _clusterCentroidVectorDB;
+ final UsearchClipVectorDB _clipVectorDB;
+ final UsearchClusterCentroidVectorDB _clusterCentroidVectorDB;
RustMLDataDB._privateConstructor({
String databaseName = "ente.ml.db",
- ClipVectorDB? clipVectorDB,
- ClusterCentroidVectorDB? clusterCentroidVectorDB,
+ UsearchClipVectorDB? clipVectorDB,
+ UsearchClusterCentroidVectorDB? clusterCentroidVectorDB,
}) : _databaseName = databaseName,
- _clipVectorDB = clipVectorDB ?? ClipVectorDB.instance,
+ _clipVectorDB = clipVectorDB ?? UsearchClipVectorDB.instance,
_clusterCentroidVectorDB =
- clusterCentroidVectorDB ?? ClusterCentroidVectorDB.instance;
+ clusterCentroidVectorDB ?? UsearchClusterCentroidVectorDB.instance;
static final RustMLDataDB instance = RustMLDataDB._privateConstructor();
static final RustMLDataDB localGalleryInstance =
RustMLDataDB._privateConstructor(
databaseName: "ente.ml.offline.db",
- clipVectorDB: ClipVectorDB.localGalleryInstance,
- clusterCentroidVectorDB: ClusterCentroidVectorDB.localGalleryInstance,
+ clipVectorDB: UsearchClipVectorDB.localGalleryInstance,
+ clusterCentroidVectorDB:
+ UsearchClusterCentroidVectorDB.localGalleryInstance,
);
@override
- ClipVectorDB get clipVectorDB => _clipVectorDB;
+ UsearchClipVectorDB get clipVectorDB => _clipVectorDB;
@override
- ClusterCentroidVectorDB get clusterCentroidVectorDB =>
+ UsearchClusterCentroidVectorDB get clusterCentroidVectorDB =>
_clusterCentroidVectorDB;
@override
@@ -529,7 +530,8 @@ class RustMLDataDB with MLDataDBOrchestration implements IMLDataDB<int> {
final rows = await db.getAllClipVectors();
return rows
.where(
- (row) => row.embedding.length == ClipVectorDB.embeddingDimensions,
+ (row) =>
+ row.embedding.length == UsearchClipVectorDB.embeddingDimensions,
)
.map(mappers.toEmbeddingVector)
.toList();
diff --git a/mobile/apps/photos/lib/db/ml/usearch_clip_vector_db.dart b/mobile/apps/photos/lib/db/ml/usearch_clip_vector_db.dart
new file mode 100644
index 0000000000..017360806b
--- /dev/null
+++ b/mobile/apps/photos/lib/db/ml/usearch_clip_vector_db.dart
@@ -0,0 +1,498 @@
+import "dart:io" show File;
+import "dart:typed_data" show Float32List;
+
+import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;
+import "package:logging/logging.dart";
+import "package:path/path.dart";
+import "package:path_provider/path_provider.dart";
+import "package:photos/db/ml/clip_vector_db.dart";
+import "package:photos/models/ml/vector.dart";
+import "package:photos/services/machine_learning/semantic_search/query_result.dart";
+import "package:photos/src/rust/api/usearch_api.dart";
+import "package:shared_preferences/shared_preferences.dart";
+import "package:synchronized/synchronized.dart";
+
+class UsearchClipVectorDB implements ClipVectorDB {
+ static final Logger _logger = Logger("UsearchClipVectorDB");
+ static const int embeddingDimensions = 512;
+ static const int embeddingBytesLength = embeddingDimensions * 4;
+
+ final String _databaseName;
+ final String _migrationKey;
+
+ static final BigInt _embeddingDimension = BigInt.from(embeddingDimensions);
+
+ static Logger get logger => _logger;
+
+ UsearchClipVectorDB._privateConstructor(
+ this._databaseName,
+ this._migrationKey,
+ );
+ static final instance = UsearchClipVectorDB._privateConstructor(
+ "ente.ml.vectordb.clip.usearch",
+ "clip_vectordb_migration",
+ );
+ static final localGalleryInstance = UsearchClipVectorDB._privateConstructor(
+ "ente.ml.offline.vectordb.clip.usearch",
+ "clip_vectordb_migration_offline",
+ );
+ factory UsearchClipVectorDB() => instance;
+
+ Future<VectorDb>? _vectorDbFuture;
+ Future<void>? _warmupFuture;
+ final Lock _writeLock = Lock();
+
+ Future<VectorDb> get _vectorDB async {
+ _vectorDbFuture ??= _initVectorDB();
+ return _vectorDbFuture!;
+ }
+
+ bool? _migrationDone;
+
+ Future<VectorDb> _initVectorDB() async {
+ final documentsDirectory = await getApplicationDocumentsDirectory();
+ final String dbPath = join(documentsDirectory.path, _databaseName);
+ _logger.info("Opening vectorDB access: DB path " + dbPath);
+ final indexFile = File(dbPath);
+ if (!await indexFile.exists() && await isReady()) {
+ _logger.severe(
+ "VectorDB file is missing while migration is marked done. Invalidating migration state.",
+ );
+ await invalidateMigrationState();
+ }
+ late VectorDb vectorDB;
+ try {
+ vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
+ } catch (e, s) {
+ _logger.severe("Could not open VectorDB at path $dbPath", e, s);
+ _logger.severe("Deleting the index file and trying again");
+ await deleteIndexFile();
+ try {
+ vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
+ } catch (e, s) {
+ _logger.severe("Still can't open VectorDB at path $dbPath", e, s);
+ rethrow;
+ }
+ }
+ final stats = await getIndexStats(vectorDB);
+ _logger.info("VectorDB connection opened with stats: ${stats.toString()}");
+
+ return vectorDB;
+ }
+
+ @override
+ Future<bool> isReady() async {
+ if (_migrationDone != null) return _migrationDone!;
+ _logger.info("Checking if ClipVectorDB migration has run");
+ final prefs = await SharedPreferences.getInstance();
+ final migrationDone = prefs.getBool(_migrationKey) ?? false;
+ if (migrationDone) {
+ _logger.info("ClipVectorDB migration already done");
+ _migrationDone = true;
+ return _migrationDone!;
+ } else {
+ _logger.info("ClipVectorDB migration not done");
+ _migrationDone = false;
+ return _migrationDone!;
+ }
+ }
+
+ Future<void> setMigrationDone() async {
+ _logger.info("Setting ClipVectorDB migration done");
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool(_migrationKey, true);
+ _migrationDone = true;
+ }
+
+ Future<void> invalidateMigrationState() async {
+ _logger.info("Invalidating ClipVectorDB migration state");
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool(_migrationKey, false);
+ _migrationDone = false;
+ }
+
+ Future<void> _runWriteOperation(
+ Future<void> Function(VectorDb db) operation,
+ ) async {
+ final db = await _vectorDB;
+ await _writeLock.synchronized(() async {
+ await operation(db);
+ });
+ }
+
+ Future<void> insertEmbedding({
+ required int fileID,
+ required List<double> embedding,
+ }) async {
+ try {
+ await _runWriteOperation((db) async {
+ await db.addVector(key: BigInt.from(fileID), vector: embedding);
+ });
+ } catch (e, s) {
+ _logger.severe("Error inserting embedding", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> bulkInsertEmbeddings({
+ required List<int> fileIDs,
+ required List<Float32List> embeddings,
+ }) async {
+ if (fileIDs.isEmpty || embeddings.isEmpty) {
+ return;
+ }
+ final bigKeys = Uint64List.fromList(fileIDs);
+ try {
+ await _runWriteOperation((db) async {
+ await db.bulkAddVectors(keys: bigKeys, vectors: embeddings);
+ });
+ } catch (e, s) {
+ _logger.severe("Error bulk inserting embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ Future<List<EmbeddingVector>> getEmbeddings(List<int> fileIDs) async {
+ final db = await _vectorDB;
+ try {
+ final keys = Uint64List.fromList(fileIDs);
+ final vectors = await db.bulkGetVectors(keys: keys);
+ return List.generate(
+ vectors.length,
+ (index) =>
+ EmbeddingVector(fileID: fileIDs[index], embedding: vectors[index]),
+ );
+ } catch (e, s) {
+ _logger.severe("Error getting embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteEmbeddings(List<int> fileIDs) async {
+ if (fileIDs.isEmpty) {
+ return;
+ }
+ try {
+ BigInt deletedCount = BigInt.zero;
+ await _runWriteOperation((db) async {
+ deletedCount = await db.bulkRemoveVectors(
+ keys: Uint64List.fromList(fileIDs),
+ );
+ });
+ _logger.info(
+ "Deleted $deletedCount embeddings, from ${fileIDs.length} keys",
+ );
+ } catch (e, s) {
+ _logger.severe("Error bulk deleting specific embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteAllEmbeddings() async {
+ await invalidateMigrationState();
+ try {
+ await _runWriteOperation((db) async {
+ await db.resetIndex();
+ });
+ } catch (e, s) {
+ _logger.severe("Error deleting all embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ Future<VectorDbStats> getIndexStats([VectorDb? db]) async {
+ db ??= await _vectorDB;
+ try {
+ final stats = await db.getIndexStats();
+ return VectorDbStats(
+ size: stats.$1.toInt(),
+ capacity: stats.$2.toInt(),
+ dimensions: stats.$3.toInt(),
+ fileSize: stats.$4.toInt(),
+ memoryUsage: stats.$5.toInt(),
+ expansionAdd: stats.$6.toInt(),
+ expansionSearch: stats.$7.toInt(),
+ );
+ } catch (e, s) {
+ _logger.severe("Error getting index stats", e, s);
+ rethrow;
+ }
+ }
+
+ Future<(Uint64List, Float32List)> searchClosestVectors(
+ List<double> query,
+ int count, {
+ bool exact = false,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ final result = await db.searchVectors(
+ query: query,
+ count: BigInt.from(count),
+ exact: exact,
+ );
+ return result;
+ } catch (e, s) {
+ _logger.severe("Error searching closest vectors", e, s);
+ rethrow;
+ }
+ }
+
+ Future<(BigInt, double)> searchClosestVector(
+ List<double> query, {
+ bool exact = false,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ final result = await db.searchVectors(
+ query: query,
+ count: BigInt.one,
+ exact: exact,
+ );
+ return (result.$1[0], result.$2[0]);
+ } catch (e, s) {
+ _logger.severe("Error searching closest vector", e, s);
+ rethrow;
+ }
+ }
+
+ @override
+ Future<void> warmup() async {
+ _warmupFuture ??= _warmupInternal();
+ await _warmupFuture;
+ }
+
+ Future<void> _warmupInternal() async {
+ final stopwatch = Stopwatch()..start();
+ try {
+ final db = await _vectorDB;
+ final stats = await getIndexStats(db);
+ if (stats.size == 0) {
+ _logger.info("Skipping VectorDB warmup: index is empty");
+ return;
+ }
+
+ final warmupQuery = List<double>.filled(
+ stats.dimensions,
+ 0.0,
+ growable: false,
+ );
+ await db.searchVectors(
+ query: warmupQuery,
+ count: BigInt.one,
+ exact: false,
+ );
+ _logger.info(
+ "VectorDB warmup finished in ${stopwatch.elapsedMilliseconds} ms",
+ );
+ } catch (e, s) {
+ _logger.warning("VectorDB warmup failed", e, s);
+ _warmupFuture = null;
+ } finally {
+ stopwatch.stop();
+ }
+ }
+
+ @override
+ Future<List<QueryResult>> searchSimilaritiesWithinThreshold(
+ List<double> query,
+ double minimumSimilarity,
+ ) async {
+ final db = await _vectorDB;
+ if (!await isReady()) {
+ throw StateError(
+ "ClipVectorDB migration is not done, cannot run approximate search",
+ );
+ }
+ try {
+ final result = await db.approxSearchVectorsWithinSimilarity(
+ query: query,
+ minimumSimilarity: minimumSimilarity,
+ );
+ final keys = result.$1;
+ final distances = result.$2;
+ final queryResults = <QueryResult>[];
+ for (var i = 0; i < keys.length; i++) {
+ queryResults.add(QueryResult(keys[i].toInt(), 1.0 - distances[i]));
+ }
+ return queryResults;
+ } catch (e, s) {
+ _logger.severe("Error searching approximate similarities", e, s);
+ rethrow;
+ }
+ }
+
+ Future<(List<Uint64List>, List<Float32List>)> bulkSearchVectors(
+ List<Float32List> queries,
+ BigInt count, {
+ bool exact = false,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ final result = await db.bulkSearchVectors(
+ queries: queries,
+ count: count,
+ exact: exact,
+ );
+ return result;
+ } catch (e, s) {
+ _logger.severe("Error bulk searching vectors", e, s);
+ rethrow;
+ }
+ }
+
+ @override
+ Future<Map<int, List<(int, double)>>> bulkSearchNearestForFiles(
+ List<int> fileIDs, {
+ required int count,
+ required double maxDistance,
+ required bool exact,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ final result = await db.bulkSearchKeys(
+ potentialKeys: Uint64List.fromList(fileIDs),
+ count: BigInt.from(count),
+ exact: exact,
+ );
+ final containedKeys = result.$1;
+ final matchedKeys = result.$2;
+ final matchedDistances = result.$3;
+ final output = <int, List<(int, double)>>{};
+ for (var i = 0; i < containedKeys.length; i++) {
+ final keysForQuery = matchedKeys[i];
+ final distancesForQuery = matchedDistances[i];
+ final alignedLength = keysForQuery.length < distancesForQuery.length
+ ? keysForQuery.length
+ : distancesForQuery.length;
+ final matches = <(int, double)>[];
+ for (var j = 0; j < alignedLength; j++) {
+ final distance = distancesForQuery[j];
+ if (distance > maxDistance) {
+ break;
+ }
+ matches.add((keysForQuery[j].toInt(), distance));
+ }
+ output[containedKeys[i].toInt()] = matches;
+ }
+ return output;
+ } catch (e, s) {
+ _logger.severe("Error bulk searching vectors with potential keys", e, s);
+ rethrow;
+ }
+ }
+
+ Future<Map<String, List<QueryResult>>> computeBulkSimilarities(
+ Map<String, List<double>> textQueryToEmbeddingMap,
+ Map<String, double> minimumSimilarityMap, {
+ int? maxResults,
+ }) async {
+ try {
+ int? resolvedMaxResults = maxResults;
+ if (resolvedMaxResults == null || resolvedMaxResults <= 0) {
+ final stats = await getIndexStats();
+ resolvedMaxResults = stats.size;
+ }
+ if (resolvedMaxResults == 0) {
+ return {
+ for (final query in textQueryToEmbeddingMap.keys)
+ query: <QueryResult>[],
+ };
+ }
+ final queryToResults = <String, List<QueryResult>>{};
+ for (final MapEntry<String, List<double>> entry
+ in textQueryToEmbeddingMap.entries) {
+ final query = entry.key;
+ final minimumSimilarity = minimumSimilarityMap[query]!;
+ final textEmbedding = entry.value;
+ final (potentialFileIDs, distances) = await searchClosestVectors(
+ textEmbedding,
+ resolvedMaxResults,
+ );
+ final queryResults = <QueryResult>[];
+ for (var i = 0; i < potentialFileIDs.length; i++) {
+ final similarity = 1 - distances[i];
+ if (similarity >= minimumSimilarity) {
+ queryResults.add(
+ QueryResult(potentialFileIDs[i].toInt(), similarity),
+ );
+ } else {
+ break;
+ }
+ }
+ queryToResults[query] = queryResults;
+ }
+ return queryToResults;
+ } catch (e, s) {
+ _logger.severe(
+ "Could not bulk find embeddings similarities using vector DB",
+ e,
+ s,
+ );
+ rethrow;
+ }
+ }
+
+ Future<void> deleteIndex() async {
+ await invalidateMigrationState();
+ final db = await _vectorDB;
+ try {
+ await _writeLock.synchronized(() async {
+ await db.deleteIndex();
+ _vectorDbFuture = null;
+ _warmupFuture = null;
+ });
+ } catch (e, s) {
+ _logger.severe("Error deleting index", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteIndexFile() async {
+ await _writeLock.synchronized(() async {
+ try {
+ final documentsDirectory = await getApplicationDocumentsDirectory();
+ final String dbPath = join(documentsDirectory.path, _databaseName);
+ _logger.info("Delete index file: DB path " + dbPath);
+ final file = File(dbPath);
+ if (await file.exists()) {
+ await file.delete();
+ }
+ _logger.info("Deleted index file on disk");
+ _vectorDbFuture = null;
+ _warmupFuture = null;
+ await invalidateMigrationState();
+ } catch (e, s) {
+ _logger.severe("Error deleting index file on disk", e, s);
+ rethrow;
+ }
+ });
+ }
+}
+
+class VectorDbStats {
+ final int size;
+ final int capacity;
+ final int dimensions;
+
+ final int fileSize;
+ final int memoryUsage;
+
+ final int expansionAdd;
+ final int expansionSearch;
+
+ VectorDbStats({
+ required this.size,
+ required this.capacity,
+ required this.dimensions,
+ required this.fileSize,
+ required this.memoryUsage,
+ required this.expansionAdd,
+ required this.expansionSearch,
+ });
+
+ @override
+ String toString() {
+ return "VectorDbStats(size: $size, capacity: $capacity, dimensions: $dimensions, file size on disk (bytes): $fileSize, memory usage (bytes): $memoryUsage, expansionAdd: $expansionAdd, expansionSearch: $expansionSearch)";
+ }
+}
diff --git a/mobile/apps/photos/lib/db/ml/usearch_cluster_centroid_vector_db.dart b/mobile/apps/photos/lib/db/ml/usearch_cluster_centroid_vector_db.dart
new file mode 100644
index 0000000000..1ba2a58bda
--- /dev/null
+++ b/mobile/apps/photos/lib/db/ml/usearch_cluster_centroid_vector_db.dart
@@ -0,0 +1,544 @@
+import "dart:io" show File;
+import "dart:typed_data" show Float32List;
+
+import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;
+import "package:logging/logging.dart";
+import "package:path/path.dart";
+import "package:path_provider/path_provider.dart";
+import "package:photos/db/ml/base.dart";
+import "package:photos/db/ml/cluster_centroid_vector_db.dart";
+import "package:photos/db/ml/db.dart";
+import "package:photos/src/rust/api/usearch_api.dart";
+import "package:shared_preferences/shared_preferences.dart";
+import "package:synchronized/synchronized.dart";
+
+class UsearchClusterCentroidVectorDB implements ClusterCentroidVectorDB {
+ static final Logger _logger = Logger("UsearchClusterCentroidVectorDB");
+
+ final String _databaseName;
+ final String _migrationKey;
+ final bool _localGallery;
+
+ static const int embeddingDimensions = 192;
+ static final BigInt _embeddingDimension = BigInt.from(embeddingDimensions);
+
+ static Logger get logger => _logger;
+
+ UsearchClusterCentroidVectorDB._privateConstructor(
+ this._databaseName,
+ this._migrationKey, {
+ required bool localGallery,
+ }) : _localGallery = localGallery;
+
+ static final instance = UsearchClusterCentroidVectorDB._privateConstructor(
+ "ente.ml.vectordb.cluster_centroid.usearch",
+ "cluster_centroid_vectordb_migration",
+ localGallery: false,
+ );
+ static final localGalleryInstance =
+ UsearchClusterCentroidVectorDB._privateConstructor(
+ "ente.ml.offline.vectordb.cluster_centroid.usearch",
+ "cluster_centroid_vectordb_migration_offline",
+ localGallery: true,
+ );
+
+ factory UsearchClusterCentroidVectorDB() => instance;
+
+ IMLDataDB<int> get _mlDataDB =>
+ _localGallery ? MLDataDB.localGalleryInstance : MLDataDB.instance;
+
+ Future<VectorDb>? _vectorDbFuture;
+ Future<void>? _warmupFuture;
+ final Lock _writeLock = Lock();
+
+ Future<VectorDb> get _vectorDB async {
+ _vectorDbFuture ??= _initVectorDB();
+ return _vectorDbFuture!;
+ }
+
+ bool? _migrationDone;
+
+ Future<VectorDb> _initVectorDB() async {
+ final documentsDirectory = await getApplicationDocumentsDirectory();
+ final String dbPath = join(documentsDirectory.path, _databaseName);
+ _logger.info("Opening cluster centroid vector DB access: DB path $dbPath");
+ final indexFile = File(dbPath);
+ if (!await indexFile.exists() && await isReady()) {
+ _logger.severe(
+ "Cluster centroid vector DB file is missing while migration is marked done. Invalidating migration state.",
+ );
+ await invalidateMigrationState();
+ }
+
+ late VectorDb vectorDB;
+ try {
+ vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
+ } catch (e, s) {
+ _logger.severe(
+ "Could not open cluster centroid vector DB at path $dbPath",
+ e,
+ s,
+ );
+ _logger.severe("Deleting the index file and trying again");
+ await deleteIndexFile();
+ try {
+ vectorDB = VectorDb(filePath: dbPath, dimensions: _embeddingDimension);
+ } catch (e, s) {
+ _logger.severe(
+ "Still can't open cluster centroid vector DB at path $dbPath",
+ e,
+ s,
+ );
+ rethrow;
+ }
+ }
+
+ final stats = await getIndexStats(vectorDB);
+ _logger.info(
+ "Cluster centroid vector DB connection opened with stats: ${stats.toString()}",
+ );
+
+ return vectorDB;
+ }
+
+ @override
+ Future<bool> isReady() async {
+ if (_migrationDone != null) return _migrationDone!;
+ _logger.info("Checking if cluster centroid vector DB migration has run");
+ final prefs = await SharedPreferences.getInstance();
+ final migrationDone = prefs.getBool(_migrationKey) ?? false;
+ if (migrationDone) {
+ _logger.info("Cluster centroid vector DB migration already done");
+ _migrationDone = true;
+ return _migrationDone!;
+ } else {
+ _logger.info("Cluster centroid vector DB migration not done");
+ _migrationDone = false;
+ return _migrationDone!;
+ }
+ }
+
+ Future<void> setMigrationDone() async {
+ _logger.info("Setting cluster centroid vector DB migration done");
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool(_migrationKey, true);
+ _migrationDone = true;
+ }
+
+ Future<void> invalidateMigrationState() async {
+ _logger.info("Invalidating cluster centroid vector DB migration state");
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool(_migrationKey, false);
+ _migrationDone = false;
+ }
+
+ Future<void> _runWriteOperation(
+ Future<void> Function(VectorDb db) operation,
+ ) async {
+ final db = await _vectorDB;
+ await _writeLock.synchronized(() async {
+ await operation(db);
+ });
+ }
+
+ Future<void> insertCentroid({
+ required int clusterVectorID,
+ required List<double> centroid,
+ }) async {
+ try {
+ await _runWriteOperation((db) async {
+ await db.addVector(key: BigInt.from(clusterVectorID), vector: centroid);
+ });
+ } catch (e, s) {
+ _logger.severe("Error inserting cluster centroid", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> bulkInsertCentroids({
+ required List<int> clusterVectorIDs,
+ required List<Float32List> centroids,
+ }) async {
+ if (clusterVectorIDs.isEmpty || centroids.isEmpty) {
+ return;
+ }
+ try {
+ await _runWriteOperation((db) async {
+ await db.bulkAddVectors(
+ keys: Uint64List.fromList(clusterVectorIDs),
+ vectors: centroids,
+ );
+ });
+ } catch (e, s) {
+ _logger.severe("Error bulk inserting cluster centroids", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteCentroids(List<int> clusterVectorIDs) async {
+ if (clusterVectorIDs.isEmpty) {
+ return;
+ }
+ try {
+ BigInt deletedCount = BigInt.zero;
+ await _runWriteOperation((db) async {
+ deletedCount = await db.bulkRemoveVectors(
+ keys: Uint64List.fromList(clusterVectorIDs),
+ );
+ });
+ _logger.info(
+ "Deleted $deletedCount centroids from ${clusterVectorIDs.length} keys",
+ );
+ } catch (e, s) {
+ _logger.severe("Error bulk deleting specific centroids", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteAllCentroids() async {
+ await invalidateMigrationState();
+ try {
+ await _runWriteOperation((db) async {
+ await db.resetIndex();
+ });
+ } catch (e, s) {
+ _logger.severe("Error deleting all cluster centroids", e, s);
+ rethrow;
+ }
+ }
+
+ Future<ClusterCentroidVectorDbStats> getIndexStats([VectorDb? db]) async {
+ db ??= await _vectorDB;
+ try {
+ final stats = await db.getIndexStats();
+ return ClusterCentroidVectorDbStats(
+ size: stats.$1.toInt(),
+ capacity: stats.$2.toInt(),
+ dimensions: stats.$3.toInt(),
+ fileSize: stats.$4.toInt(),
+ memoryUsage: stats.$5.toInt(),
+ expansionAdd: stats.$6.toInt(),
+ expansionSearch: stats.$7.toInt(),
+ );
+ } catch (e, s) {
+ _logger.severe("Error getting cluster centroid index stats", e, s);
+ rethrow;
+ }
+ }
+
+ Future<Map<String, int>> _clusterIDToVectorID(Iterable<String> clusterIDs) =>
+ _mlDataDB.getClusterCentroidVectorIdMap(
+ clusterIDs,
+ createIfMissing: false,
+ );
+
+ static Map<int, String> _invert(
+ Map<String, int> clusterIDToVectorID, {
+ required Set<String> within,
+ }) => {
+ for (final entry in clusterIDToVectorID.entries)
+ if (within.contains(entry.key)) entry.value: entry.key,
+ };
+
+ static List<List<(String, double)>> _noMatchesPerQuery(int queryCount) =>
+ List.generate(queryCount, (_) => const <(String, double)>[]);
+
+ static List<(String, double)> _toClusterMatches(
+ List<(int, double)> matches,
+ Map<int, String> vectorIDToClusterID,
+ ) {
+ final output = <(String, double)>[];
+ for (final (vectorID, distance) in matches) {
+ final clusterID = vectorIDToClusterID[vectorID];
+ if (clusterID == null) {
+ continue;
+ }
+ output.add((clusterID, distance));
+ }
+ return output;
+ }
+
+ @override
+ Future<List<List<(String, double)>>> bulkSearchNearestAllowed(
+ List<List<double>> queries,
+ Set<String> allowedClusterIDs, {
+ required double maxDistance,
+ int count = 10,
+ }) async {
+ if (!await isReady()) {
+ throw StateError(
+ "Cluster centroid vector DB migration is not done, cannot run approximate search",
+ );
+ }
+ if (count <= 0 || queries.isEmpty || allowedClusterIDs.isEmpty) {
+ return _noMatchesPerQuery(queries.length);
+ }
+ final vectorIDToClusterID = _invert(
+ await _clusterIDToVectorID(allowedClusterIDs),
+ within: allowedClusterIDs,
+ );
+ if (vectorIDToClusterID.isEmpty) {
+ return _noMatchesPerQuery(queries.length);
+ }
+ final matchesPerQuery = await _bulkSearchNearestAllowedVectorIDs(
+ queries,
+ vectorIDToClusterID.keys.toSet(),
+ maxDistance: maxDistance,
+ count: count,
+ );
+ return [
+ for (var i = 0; i < queries.length; i++)
+ i < matchesPerQuery.length
+ ? _toClusterMatches(matchesPerQuery[i], vectorIDToClusterID)
+ : const <(String, double)>[],
+ ];
+ }
+
+ @override
+ Future<Map<String, ClusterCentroidMatches>> bulkSearchNearestForClusters(
+ Set<String> queryClusterIDs, {
+ required Set<String> candidateClusterIDs,
+ required int count,
+ double? maxDistance,
+ }) async {
+ if (!await isReady()) {
+ throw StateError(
+ "Cluster centroid vector DB migration is not done, cannot run approximate search",
+ );
+ }
+ if (count <= 0 || queryClusterIDs.isEmpty) {
+ return const {};
+ }
+ final clusterIDToVectorID = await _clusterIDToVectorID(
+ queryClusterIDs.union(candidateClusterIDs),
+ );
+ final queryVectorIDToClusterID = _invert(
+ clusterIDToVectorID,
+ within: queryClusterIDs,
+ );
+ if (queryVectorIDToClusterID.isEmpty) {
+ return const {};
+ }
+ final candidateVectorIDToClusterID = _invert(
+ clusterIDToVectorID,
+ within: candidateClusterIDs,
+ );
+ final matchesByQueryVectorID = await _bulkSearchNearestForVectorIDs(
+ queryVectorIDToClusterID.keys.toSet(),
+ count: count,
+ maxDistance: maxDistance,
+ );
+ final output = <String, ClusterCentroidMatches>{};
+ for (final entry in matchesByQueryVectorID.entries) {
+ final queryClusterID = queryVectorIDToClusterID[entry.key];
+ if (queryClusterID == null) {
+ continue;
+ }
+ final rawMatches = entry.value;
+ output[queryClusterID] = (
+ matches: _toClusterMatches(rawMatches, candidateVectorIDToClusterID),
+ reachedCount: rawMatches.length >= count,
+ );
+ }
+ return output;
+ }
+
+ Future<List<List<(int, double)>>> _bulkSearchNearestAllowedVectorIDs(
+ List<List<double>> queries,
+ Set<int> allowedClusterVectorIDs, {
+ required double maxDistance,
+ required int count,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ final rustQueries = <Float32List>[];
+ for (final query in queries) {
+ if (query is Float32List) {
+ rustQueries.add(query);
+ } else {
+ rustQueries.add(Float32List.fromList(query));
+ }
+ }
+ final allowedKeys = Uint64List.fromList(
+ allowedClusterVectorIDs.toList(growable: false),
+ );
+ final result = await db.bulkApproxFilteredSearchVectorsWithinDistance(
+ queries: rustQueries,
+ allowedKeys: allowedKeys,
+ count: BigInt.from(count),
+ maxDistance: maxDistance,
+ );
+
+ final keysPerQuery = result.$1;
+ final distancesPerQuery = result.$2;
+ final alignedQueryLength = keysPerQuery.length < distancesPerQuery.length
+ ? keysPerQuery.length
+ : distancesPerQuery.length;
+ final output = <List<(int, double)>>[];
+ for (var i = 0; i < alignedQueryLength; i++) {
+ final keys = keysPerQuery[i];
+ final distances = distancesPerQuery[i];
+ final alignedLength = keys.length < distances.length
+ ? keys.length
+ : distances.length;
+ final matches = <(int, double)>[];
+ for (var j = 0; j < alignedLength; j++) {
+ matches.add((keys[j].toInt(), distances[j]));
+ }
+ output.add(matches);
+ }
+ return output;
+ } catch (e, s) {
+ _logger.severe("Error bulk searching filtered centroids", e, s);
+ rethrow;
+ }
+ }
+
+ Future<Map<int, List<(int, double)>>> _bulkSearchNearestForVectorIDs(
+ Set<int> queryClusterVectorIDs, {
+ required int count,
+ double? maxDistance,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ final queryKeys = queryClusterVectorIDs.toList(growable: false);
+ final result = await db.bulkSearchKeys(
+ potentialKeys: Uint64List.fromList(queryKeys),
+ count: BigInt.from(count),
+ exact: false,
+ );
+ final containedKeys = result.$1;
+ final matchedKeys = result.$2;
+ final matchedDistances = result.$3;
+
+ final output = <int, List<(int, double)>>{};
+ for (var i = 0; i < containedKeys.length; i++) {
+ final queryKey = containedKeys[i].toInt();
+ final keysForQuery = matchedKeys[i];
+ final distancesForQuery = matchedDistances[i];
+ final alignedLength = keysForQuery.length < distancesForQuery.length
+ ? keysForQuery.length
+ : distancesForQuery.length;
+ final matches = <(int, double)>[];
+ for (var j = 0; j < alignedLength; j++) {
+ final distance = distancesForQuery[j];
+ if (maxDistance != null && distance > maxDistance) {
+ break;
+ }
+ matches.add((keysForQuery[j].toInt(), distance));
+ }
+ output[queryKey] = matches;
+ }
+ return output;
+ } catch (e, s) {
+ _logger.severe("Error bulk searching centroids", e, s);
+ rethrow;
+ }
+ }
+
+ @override
+ Future<void> warmup() async {
+ _warmupFuture ??= _warmupInternal();
+ await _warmupFuture;
+ }
+
+ Future<void> _warmupInternal() async {
+ final stopwatch = Stopwatch()..start();
+ try {
+ final db = await _vectorDB;
+ final stats = await getIndexStats(db);
+ if (stats.size == 0) {
+ _logger.info(
+ "Skipping cluster centroid vector DB warmup: index is empty",
+ );
+ return;
+ }
+
+ final warmupQuery = List<double>.filled(
+ stats.dimensions,
+ 0.0,
+ growable: false,
+ );
+ await db.searchVectors(
+ query: warmupQuery,
+ count: BigInt.one,
+ exact: false,
+ );
+ _logger.info(
+ "Cluster centroid vector DB warmup finished in ${stopwatch.elapsedMilliseconds} ms",
+ );
+ } catch (e, s) {
+ _logger.warning("Cluster centroid vector DB warmup failed", e, s);
+ _warmupFuture = null;
+ } finally {
+ stopwatch.stop();
+ }
+ }
+
+ Future<void> deleteIndex() async {
+ await invalidateMigrationState();
+ final db = await _vectorDB;
+ try {
+ await _writeLock.synchronized(() async {
+ await db.deleteIndex();
+ _vectorDbFuture = null;
+ _warmupFuture = null;
+ });
+ } catch (e, s) {
+ _logger.severe("Error deleting cluster centroid index", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteIndexFile() async {
+ await _writeLock.synchronized(() async {
+ try {
+ final documentsDirectory = await getApplicationDocumentsDirectory();
+ final String dbPath = join(documentsDirectory.path, _databaseName);
+ _logger.info("Delete cluster centroid index file: DB path $dbPath");
+ final file = File(dbPath);
+ if (await file.exists()) {
+ await file.delete();
+ }
+ _logger.info("Deleted cluster centroid index file on disk");
+ _vectorDbFuture = null;
+ _warmupFuture = null;
+ await invalidateMigrationState();
+ } catch (e, s) {
+ _logger.severe(
+ "Error deleting cluster centroid index file on disk",
+ e,
+ s,
+ );
+ rethrow;
+ }
+ });
+ }
+}
+
+class ClusterCentroidVectorDbStats {
+ final int size;
+ final int capacity;
+ final int dimensions;
+
+ final int fileSize;
+ final int memoryUsage;
+
+ final int expansionAdd;
+ final int expansionSearch;
+
+ ClusterCentroidVectorDbStats({
+ required this.size,
+ required this.capacity,
+ required this.dimensions,
+ required this.fileSize,
+ required this.memoryUsage,
+ required this.expansionAdd,
+ required this.expansionSearch,
+ });
+
+ @override
+ String toString() {
+ return "ClusterCentroidVectorDbStats(size: $size, capacity: $capacity, dimensions: $dimensions, file size on disk (bytes): $fileSize, memory usage (bytes): $memoryUsage, expansionAdd: $expansionAdd, expansionSearch: $expansionSearch)";
+ }
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
index b0ae7b08be..872c7646c2 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
@@ -462,46 +462,31 @@ class ClusterFeedbackService<T> {
return [];
}
- final clusterIDToVectorID = await _mlDataDBForCentroidVectorDb
- .getClusterCentroidVectorIdMap(
- clusterAvg.keys,
- createIfMissing: false,
- );
- if (clusterIDToVectorID.isEmpty) {
- return [];
- }
- final vectorIDToClusterID = {
- for (final entry in clusterIDToVectorID.entries) entry.value: entry.key,
- };
-
final personIDToQueryClusters = <String, Set<String>>{};
- final queryVectorIDs = <int>{};
+ final allQueryClusterIDs = <String>{};
for (final entry in personIdToClusters.entries) {
final validClusters = <String>{};
for (final clusterID in entry.value) {
if (!clusterAvg.containsKey(clusterID)) {
continue;
}
- final vectorID = clusterIDToVectorID[clusterID];
- if (vectorID == null) {
- continue;
- }
validClusters.add(clusterID);
- queryVectorIDs.add(vectorID);
+ allQueryClusterIDs.add(clusterID);
}
if (validClusters.isNotEmpty) {
personIDToQueryClusters[entry.key] = validClusters;
}
}
- if (personIDToQueryClusters.isEmpty || queryVectorIDs.isEmpty) {
+ if (personIDToQueryClusters.isEmpty || allQueryClusterIDs.isEmpty) {
return [];
}
- late final Map<int, List<(int, double)>> rawMatchesByQueryVectorID;
+ late final Map<String, ClusterCentroidMatches> resultByQueryCluster;
try {
- rawMatchesByQueryVectorID = await _clusterCentroidVectorDB
- .bulkSearchApproxClosestCentroidsForKeysWithinDistance(
- queryVectorIDs,
+ resultByQueryCluster = await _clusterCentroidVectorDB
+ .bulkSearchNearestForClusters(
+ allQueryClusterIDs,
+ candidateClusterIDs: clusterAvg.keys.toSet(),
count: _allPeopleSuggestionVectorResultCount,
maxDistance: 0.65,
);
@@ -525,31 +510,14 @@ class ClusterFeedbackService<T> {
final queryClustersMissingFromVectorIndex = <String>{};
for (final queryClusters in personIDToQueryClusters.values) {
for (final queryClusterID in queryClusters) {
- final queryVectorID = clusterIDToVectorID[queryClusterID];
- if (queryVectorID == null) {
- continue;
- }
- final hasRawMatchesForQuery = rawMatchesByQueryVectorID.containsKey(
- queryVectorID,
- );
- final rawMatches =
- rawMatchesByQueryVectorID[queryVectorID] ??
- const <(int, double)>[];
- if (!hasRawMatchesForQuery) {
+ final result = resultByQueryCluster[queryClusterID];
+ if (result == null) {
queryClustersMissingFromVectorIndex.add(queryClusterID);
}
queryClusterNeedsFallbackSearch[queryClusterID] =
- !hasRawMatchesForQuery ||
- rawMatches.length >= _allPeopleSuggestionVectorResultCount;
- final mappedMatches = <(String, double)>[];
- for (final match in rawMatches) {
- final matchedClusterID = vectorIDToClusterID[match.$1];
- if (matchedClusterID == null) {
- continue;
- }
- mappedMatches.add((matchedClusterID, match.$2));
- }
- queryClusterToMatches[queryClusterID] = mappedMatches;
+ result == null || result.reachedCount;
+ queryClusterToMatches[queryClusterID] =
+ result?.matches ?? const <(String, double)>[];
}
}
if (queryClustersMissingFromVectorIndex.isNotEmpty) {
@@ -624,33 +592,32 @@ class ClusterFeedbackService<T> {
}
if (personIDToFallbackQueryClusters.isNotEmpty) {
- final personIDToAllowedVectorIDs = <String, Set<int>>{};
+ final personIDToAllowedClusterIDs = <String, Set<String>>{};
- Set<int> getAllowedVectorIDs(String personID) {
- final cached = personIDToAllowedVectorIDs[personID];
+ Set<String> getAllowedClusterIDs(String personID) {
+ final cached = personIDToAllowedClusterIDs[personID];
if (cached != null) {
return cached;
}
final personClusters = personIDToQueryClusters[personID]!;
final ignoredClusters = personIDToIgnoredClusters[personID]!;
- final allowedVectorIDs = <int>{};
- for (final entry in clusterIDToVectorID.entries) {
- final clusterID = entry.key;
+ final allowedClusterIDs = <String>{};
+ for (final clusterID in clusterAvg.keys) {
if (ignoredClusters.contains(clusterID) ||
personClusters.contains(clusterID)) {
continue;
}
- allowedVectorIDs.add(entry.value);
+ allowedClusterIDs.add(clusterID);
}
- personIDToAllowedVectorIDs[personID] = allowedVectorIDs;
- return allowedVectorIDs;
+ personIDToAllowedClusterIDs[personID] = allowedClusterIDs;
+ return allowedClusterIDs;
}
var fallbackQueryCount = 0;
for (final entry in personIDToFallbackQueryClusters.entries) {
final personID = entry.key;
- final allowedVectorIDs = getAllowedVectorIDs(personID);
- if (allowedVectorIDs.isEmpty) {
+ final allowedClusterIDs = getAllowedClusterIDs(personID);
+ if (allowedClusterIDs.isEmpty) {
continue;
}
@@ -668,12 +635,12 @@ class ClusterFeedbackService<T> {
continue;
}
- List<List<(int, double)>> filteredMatchesByQuery;
+ List<List<(String, double)>> filteredMatchesByQuery;
try {
filteredMatchesByQuery = await _clusterCentroidVectorDB
- .bulkSearchApproxClosestCentroidsWithinDistance(
+ .bulkSearchNearestAllowed(
queryVectors,
- allowedVectorIDs,
+ allowedClusterIDs,
maxDistance: 0.65,
count: _allPeopleSuggestionVectorResultCount,
);
@@ -696,19 +663,8 @@ class ClusterFeedbackService<T> {
if (filteredMatches.isEmpty) {
continue;
}
-
- final mappedMatches = <(String, double)>[];
- for (final match in filteredMatches) {
- final matchedClusterID = vectorIDToClusterID[match.$1];
- if (matchedClusterID == null) {
- continue;
- }
- mappedMatches.add((matchedClusterID, match.$2));
- }
- if (mappedMatches.isNotEmpty) {
- queryClusterToMatches[queryClusterID] = mappedMatches;
- fallbackQueryCount++;
- }
+ queryClusterToMatches[queryClusterID] = filteredMatches;
+ fallbackQueryCount++;
}
}
@@ -1542,12 +1498,12 @@ class ClusterFeedbackService<T> {
try {
if (!flagService.usearchForSuggestions) return;
if (!flagService.hasGrantedMLConsent) return;
- if (!await _clusterCentroidVectorDB.checkIfMigrationDone()) {
+ if (!await _clusterCentroidVectorDB.isReady()) {
await _mlDataDBForCentroidVectorDb
.checkMigrateFillClusterCentroidVectorDB();
}
- if (await _clusterCentroidVectorDB.checkIfMigrationDone()) {
- await _clusterCentroidVectorDB.warmupApproxSearch();
+ if (await _clusterCentroidVectorDB.isReady()) {
+ await _clusterCentroidVectorDB.warmup();
}
} catch (e, s) {
_logger.severe(
@@ -1563,7 +1519,7 @@ class ClusterFeedbackService<T> {
Future<bool> _canUseClusterCentroidVectorDbForSuggestions() async {
if (!flagService.usearchForSuggestions) return false;
if (!flagService.hasGrantedMLConsent) return false;
- if (await _clusterCentroidVectorDB.checkIfMigrationDone()) return true;
+ if (await _clusterCentroidVectorDB.isReady()) return true;
unawaited(_prepareClusterCentroidVectorDbForSuggestions());
return false;
}
@@ -2002,30 +1958,6 @@ class ClusterFeedbackService<T> {
return [];
}
- final relevantClusterIDs = <String>{}
- ..addAll(validPersonClusters)
- ..addAll(otherClusters);
- final clusterIDToVectorID = await _mlDataDBForCentroidVectorDb
- .getClusterCentroidVectorIdMap(
- relevantClusterIDs,
- createIfMissing: false,
- );
- if (clusterIDToVectorID.isEmpty) {
- return [];
- }
-
- final baseAllowedVectorIDs = otherClusters
- .map((clusterID) => clusterIDToVectorID[clusterID])
- .whereType<int>()
- .toSet();
- if (baseAllowedVectorIDs.isEmpty) {
- return [];
- }
-
- final vectorIDToClusterID = {
- for (final entry in clusterIDToVectorID.entries) entry.value: entry.key,
- };
-
final orderedPersonClusterIDs = <String>[];
final queryVectors = <List<double>>[];
for (final personClusterID in validPersonClusters) {
@@ -2041,9 +1973,9 @@ class ClusterFeedbackService<T> {
}
final matchesPerQuery = await _clusterCentroidVectorDB
- .bulkSearchApproxClosestCentroidsWithinDistance(
+ .bulkSearchNearestAllowed(
queryVectors,
- baseAllowedVectorIDs,
+ otherClusters,
maxDistance: maxClusterDistance,
count: perClusterResultCount,
);
@@ -2058,10 +1990,7 @@ class ClusterFeedbackService<T> {
final matches = matchesPerQuery[i];
for (final match in matches) {
- final suggestedClusterID = vectorIDToClusterID[match.$1];
- if (suggestedClusterID == null) {
- continue;
- }
+ final suggestedClusterID = match.$1;
if (ignoredClusters.contains(suggestedClusterID) ||
validPersonClusters.contains(suggestedClusterID)) {
continue;
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 7d1ea7a552..9d1c658628 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
@@ -52,12 +52,15 @@ class MLComputer extends SuperIsolate {
}
}
- Future<(Uint64List, List<Uint64List>, List<Float32List>)>
- bulkVectorSearchWithKeys(Uint64List potentialKeys, bool exact) async {
+ Future<Map<int, List<(int, double)>>> bulkVectorSearchWithKeys(
+ List<int> fileIDs, {
+ required double maxDistance,
+ required bool exact,
+ }) async {
try {
final result = await runInIsolate(
IsolateOperation.bulkVectorSearchWithKeys,
- {"potentialKeys": potentialKeys, "exact": exact},
+ {"fileIDs": fileIDs, "maxDistance": maxDistance, "exact": exact},
);
return result;
} catch (e, s) {
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 8cdb2f9981..421cbc1c2b 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
@@ -114,14 +114,14 @@ class SemanticSearchService {
try {
if (!_shouldUseVectorDbApproximateSearch) return;
if (!flagService.hasGrantedMLConsent) return;
- if (!await _vectorDB.checkIfMigrationDone()) {
+ if (!await _vectorDB.isReady()) {
await Future.delayed(_vectorDbMigrationDelay);
if (!_shouldUseVectorDbApproximateSearch) return;
if (!flagService.hasGrantedMLConsent) return;
await _mlDataDB.checkMigrateFillClipVectorDB();
}
- if (await _vectorDB.checkIfMigrationDone()) {
- await _vectorDB.warmupApproxSearch();
+ if (await _vectorDB.isReady()) {
+ await _vectorDB.warmup();
}
} catch (e, s) {
_logger.severe("Failed to prepare VectorDB for search", e, s);
@@ -473,7 +473,7 @@ class SemanticSearchService {
final query = entry.key;
final minimumSimilarity = minimumSimilarityMap[query]!;
final textEmbedding = entry.value;
- final results = await _vectorDB.searchApproxSimilaritiesWithinThreshold(
+ final results = await _vectorDB.searchSimilaritiesWithinThreshold(
textEmbedding,
minimumSimilarity,
);
@@ -489,7 +489,7 @@ class SemanticSearchService {
Future<bool> _canUseVectorDbForSearch() async {
if (!_shouldUseVectorDbApproximateSearch) return false;
if (!flagService.hasGrantedMLConsent) return false;
- if (await _vectorDB.checkIfMigrationDone()) return true;
+ if (await _vectorDB.isReady()) return true;
// Keep interactive search responsive: prepare/migrate in the background and
// immediately fall back to in-memory similarity search for this request.
unawaited(_prepareVectorDbForSearch());
diff --git a/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart b/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart
index 9eb0884767..bc7e840bca 100644
--- a/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/similar_images_service.dart
@@ -3,8 +3,6 @@ import "dart:math" show max;
import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:flutter/foundation.dart" show kDebugMode;
-import "package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart"
- show Uint64List;
import 'package:logging/logging.dart';
import "package:path_provider/path_provider.dart";
import "package:photos/db/ml/db.dart";
@@ -79,7 +77,6 @@ class SimilarImagesService {
fileIDs.add(file.uploadedFileID!);
}
}
- final Uint64List potentialKeys = Uint64List.fromList(fileIDs);
w?.log("getAllFilesForSearch");
final fileIDToPersonIDs = <int, Set<String>>{};
@@ -101,7 +98,7 @@ class SimilarImagesService {
if (forceRefresh) {
final result = await _performFullSearch(
- potentialKeys,
+ fileIDs,
allFileIdsToFile,
fileIDToPersonIDs,
distanceThreshold,
@@ -181,7 +178,7 @@ class SimilarImagesService {
if (cachedData == null || needsFullRefresh) {
final result = await _performFullSearch(
- potentialKeys,
+ fileIDs,
allFileIdsToFile,
fileIDToPersonIDs,
distanceThreshold,
@@ -198,7 +195,7 @@ class SimilarImagesService {
} else {
return await _performIncrementalUpdate(
cachedData,
- potentialKeys,
+ fileIDs,
allFileIdsToFile,
fileIDToPersonIDs,
distanceThreshold,
@@ -209,7 +206,7 @@ class SimilarImagesService {
Future<List<SimilarFiles>> _performIncrementalUpdate(
SimilarFilesCache cachedData,
- Uint64List currentFileIDs,
+ List<int> currentFileIDs,
Map<int, EnteFile> allFileIdsToFile,
Map<int, Set<String>> fileIDToPersonIDs,
double distanceThreshold,
@@ -218,7 +215,7 @@ class SimilarImagesService {
_logger.info("Performing incremental update for similar files");
final existingGroups = await cachedData.similarFilesList();
final cachedFileIDs = cachedData.allCheckedFileIDs;
- final currentFileIDsSet = currentFileIDs.map((id) => id.toInt()).toSet();
+ final currentFileIDsSet = currentFileIDs.toSet();
final deletedFiles = cachedFileIDs.difference(currentFileIDsSet);
if (deletedFiles.isNotEmpty) {
@@ -250,25 +247,21 @@ class SimilarImagesService {
return existingGroups;
}
- final newFileIDsList = Uint64List.fromList(newFileIDs.toList());
- final (keys, vectorKeys, distances) = await MLComputer.instance
- .bulkVectorSearchWithKeys(newFileIDsList, exact);
- final keysList = keys.map((key) => key.toInt()).toList();
+ final newFileMatches = await MLComputer.instance.bulkVectorSearchWithKeys(
+ newFileIDs.toList(),
+ maxDistance: distanceThreshold,
+ exact: exact,
+ );
- final unassignedNewFilesIndices = <int>{};
- final unassignedNewFileIDs = <int>{};
- for (int i = 0; i < keysList.length; i++) {
- final newFileID = keysList[i];
+ final unassignedNewFiles = <int, List<(int, double)>>{};
+ for (final entry in newFileMatches.entries) {
+ final newFileID = entry.key;
final newFile = allFileIdsToFile[newFileID];
if (newFile == null) continue;
- final similarFileIDs = vectorKeys[i];
- final fileDistances = distances[i];
final newFilePersonIDs = fileIDToPersonIDs[newFileID] ?? <String>{};
bool assigned = false;
- for (int j = 0; j < similarFileIDs.length; j++) {
- final otherFileID = similarFileIDs[j].toInt();
+ for (final (otherFileID, distance) in entry.value) {
if (otherFileID == newFileID) continue;
- final distance = fileDistances[j];
if (distance > distanceThreshold) break;
for (final group in existingGroups) {
if (group.fileIds.contains(otherFileID)) {
@@ -296,29 +289,24 @@ class SimilarImagesService {
if (assigned) break;
}
if (!assigned) {
- unassignedNewFilesIndices.add(i);
- unassignedNewFileIDs.add(newFileID);
+ unassignedNewFiles[newFileID] = entry.value;
}
}
- if (unassignedNewFilesIndices.isNotEmpty) {
+ if (unassignedNewFiles.isNotEmpty) {
final alreadyUsedNewFiles = <int>{};
- for (final searchIndex in unassignedNewFilesIndices) {
- final newFileID = keysList[searchIndex];
+ for (final entry in unassignedNewFiles.entries) {
+ final newFileID = entry.key;
if (alreadyUsedNewFiles.contains(newFileID)) continue;
final newFile = allFileIdsToFile[newFileID];
if (newFile == null) continue;
- final similarFileIDs = vectorKeys[searchIndex];
- final fileDistances = distances[searchIndex];
final newFilePersonIDs = fileIDToPersonIDs[newFileID] ?? <String>{};
final similarNewFiles = <EnteFile>[];
double furthestDistance = 0.0;
- for (int j = 0; j < similarFileIDs.length; j++) {
- final otherFileID = similarFileIDs[j].toInt();
+ for (final (otherFileID, distance) in entry.value) {
if (otherFileID == newFileID) continue;
- if (!unassignedNewFileIDs.contains(otherFileID)) continue;
+ if (!unassignedNewFiles.containsKey(otherFileID)) continue;
if (alreadyUsedNewFiles.contains(otherFileID)) continue;
- final distance = fileDistances[j];
if (distance > distanceThreshold) break;
final otherFile = allFileIdsToFile[otherFileID];
if (otherFile == null) continue;
@@ -357,7 +345,7 @@ class SimilarImagesService {
}
Future<List<SimilarFiles>> _performFullSearch(
- Uint64List potentialKeys,
+ List<int> fileIDs,
Map<int, EnteFile> allFileIdsToFile,
Map<int, Set<String>> fileIDToPersonIDs,
double distanceThreshold,
@@ -365,29 +353,28 @@ class SimilarImagesService {
) async {
_logger.info("Performing full search for similar files");
final w = (kDebugMode ? EnteWatch('getSimilarFiles') : null)?..start();
- final (keys, vectorKeys, distances) = await MLComputer.instance
- .bulkVectorSearchWithKeys(potentialKeys, exact);
+ final fileMatches = await MLComputer.instance.bulkVectorSearchWithKeys(
+ fileIDs,
+ maxDistance: distanceThreshold,
+ exact: exact,
+ );
w?.log("bulkSearchVectors");
final alreadyUsedFileIDs = <int>{};
final allSimilarFiles = <SimilarFiles>[];
- for (int i = 0; i < keys.length; i++) {
- final fileID = keys[i].toInt();
+ for (final entry in fileMatches.entries) {
+ final fileID = entry.key;
if (alreadyUsedFileIDs.contains(fileID)) continue;
final firstLoopFile = allFileIdsToFile[fileID];
if (firstLoopFile == null || firstLoopFile.uploadedFileID == null) {
continue;
}
- final otherFileIDs = vectorKeys[i];
- final distancesToFiles = distances[i];
final similarFilesList = <EnteFile>[];
final personIDs = fileIDToPersonIDs[fileID] ?? <String>{};
double furthestDistance = 0.0;
- for (int j = 0; j < otherFileIDs.length; j++) {
- final otherFileID = otherFileIDs[j].toInt();
+ for (final (otherFileID, distance) in entry.value) {
if (otherFileID == fileID) continue;
if (alreadyUsedFileIDs.contains(otherFileID)) continue;
- final distance = distancesToFiles[j];
if (distance > distanceThreshold) break;
final otherFile = allFileIdsToFile[otherFileID];
if (otherFile == null || otherFile.uploadedFileID == null) {
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 67e0ac45e6..8c441ecde5 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
@@ -8,6 +8,7 @@ import "package:photos/core/event_bus.dart";
import "package:photos/db/ml/clip_vector_db.dart";
import "package:photos/db/ml/cluster_centroid_vector_db.dart";
import "package:photos/db/ml/db.dart";
+import "package:photos/db/ml/usearch_clip_vector_db.dart";
import "package:photos/events/people_changed_event.dart";
import "package:photos/models/ml/face/person.dart";
import "package:photos/service_locator.dart";
@@ -404,8 +405,8 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
? ClusterCentroidVectorDB.localGalleryInstance
: ClusterCentroidVectorDB.instance;
final migrationStatus = await Future.wait<bool>([
- clipVectorDB.checkIfMigrationDone(),
- clusterCentroidVectorDB.checkIfMigrationDone(),
+ clipVectorDB.isReady(),
+ clusterCentroidVectorDB.isReady(),
]);
return (
clipDone: migrationStatus[0],
@@ -1036,8 +1037,8 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
firstButtonOnTap: () async {
try {
final vectorDB = isLocalGalleryMode
- ? ClipVectorDB.localGalleryInstance
- : ClipVectorDB.instance;
+ ? UsearchClipVectorDB.localGalleryInstance
+ : UsearchClipVectorDB.instance;
await vectorDB.deleteIndexFile();
if (!context.mounted) return;
showShortToast(context, "Done");
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index 0900106012..f3ffe36d8f 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -1,10 +1,10 @@
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/db/ml/usearch_clip_vector_db.dart";
import "package:photos/models/ml/face/box.dart";
import "package:photos/models/ml/vector.dart";
import "package:photos/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart";
@@ -65,12 +65,14 @@ Future<dynamic> isolateFunction(
switch (function) {
case IsolateOperation.bulkVectorSearchWithKeys:
await _ensureRustLoaded();
- final potentialKeys = args["potentialKeys"] as Uint64List;
+ final fileIDs = args["fileIDs"] as List<int>;
+ final maxDistance = args["maxDistance"] as double;
final exact = args["exact"] as bool;
- return ClipVectorDB.instance.bulkSearchWithKeys(
- potentialKeys,
- BigInt.from(100),
+ return ClipVectorDB.instance.bulkSearchNearestForFiles(
+ fileIDs,
+ count: 100,
+ maxDistance: maxDistance,
exact: exact,
);
@@ -79,7 +81,7 @@ Future<dynamic> isolateFunction(
final clipFloat32 = args["clipFloat32"] as List<Float32List>;
final exact = args["exact"] as bool;
- return ClipVectorDB.instance.bulkSearchVectors(
+ return UsearchClipVectorDB.instance.bulkSearchVectors(
clipFloat32,
BigInt.from(100),
exact: exact,