Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] Calculate cosine distance inline

laurenspriem9a8c4d9cfd99
diff --git a/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart b/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart
index 0611a1d838..c081ef4520 100644
--- a/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart
+++ b/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart
@@ -5,17 +5,15 @@ import "package:ml_linalg/linalg.dart";
/// Calculates the cosine distance between two embeddings/vectors using SIMD from ml_linalg
///
/// WARNING: This assumes both vectors are already normalized!
+/// WARNING: For even more performance, consider calculating the logic below inline!
+@pragma("vm:prefer-inline")
double cosineDistanceSIMD(Vector vector1, Vector vector2) {
- if (vector1.length != vector2.length) {
- throw ArgumentError('Vectors must be the same length');
- }
-
return 1 - vector1.dot(vector2);
}
/// Calculates the cosine distance between two embeddings/vectors using SIMD from ml_linalg
///
-/// WARNING: Only use when you're not sure if vectors are normalized. If you're sure they are, use [cosineDistanceSIMD] instead for better performance.
+/// WARNING: Only use when you're not sure if vectors are normalized. If you're sure they are, use [cosineDistanceSIMD] instead for better performance, or inline for best performance.
double cosineDistanceSIMDSafe(Vector vector1, Vector vector2) {
if (vector1.length != vector2.length) {
throw ArgumentError('Vectors must be the same length');
diff --git a/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart b/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
index 1a635b0f07..8407698640 100644
--- a/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
+++ b/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
@@ -565,10 +565,10 @@ class FaceClusteringService {
for (int j = i - 1; j >= 0; j--) {
late double distance;
if (sortedFaceInfos[i].vEmbedding != null) {
- distance = cosineDistanceSIMD(
- sortedFaceInfos[i].vEmbedding!,
- sortedFaceInfos[j].vEmbedding!,
- );
+ distance = 1 -
+ sortedFaceInfos[i]
+ .vEmbedding!
+ .dot(sortedFaceInfos[j].vEmbedding!);
} else {
distance = cosineDistForNormVectors(
sortedFaceInfos[i].embedding!,
@@ -814,10 +814,8 @@ class FaceClusteringService {
double closestDistance = double.infinity;
for (int j = 0; j < totalFaces; j++) {
if (i == j) continue;
- final double distance = cosineDistanceSIMD(
- faceInfos[i].vEmbedding!,
- faceInfos[j].vEmbedding!,
- );
+ final double distance =
+ 1 - faceInfos[i].vEmbedding!.dot(faceInfos[j].vEmbedding!);
if (distance < closestDistance) {
closestDistance = distance;
closestIdx = j;
@@ -870,10 +868,10 @@ class FaceClusteringService {
for (int i = 0; i < clusterIds.length; i++) {
for (int j = 0; j < clusterIds.length; j++) {
if (i == j) continue;
- final double newDistance = cosineDistanceSIMD(
- clusterIdToMeanEmbeddingAndWeight[clusterIds[i]]!.$1,
- clusterIdToMeanEmbeddingAndWeight[clusterIds[j]]!.$1,
- );
+ final double newDistance = 1 -
+ clusterIdToMeanEmbeddingAndWeight[clusterIds[i]]!
+ .$1
+ .dot(clusterIdToMeanEmbeddingAndWeight[clusterIds[j]]!.$1);
if (newDistance < distance) {
distance = newDistance;
clusterIDsToMerge = (clusterIds[i], clusterIds[j]);
diff --git a/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart b/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
index 8567e88685..b354719f9a 100644
--- a/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
+++ b/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
@@ -13,7 +13,6 @@ import "package:photos/face/db.dart";
import "package:photos/face/model/person.dart";
import "package:photos/generated/protos/ente/common/vector.pb.dart";
import "package:photos/models/file/file.dart";
-import "package:photos/services/machine_learning/face_ml/face_clustering/cosine_distance.dart";
import "package:photos/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart";
import "package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart";
import "package:photos/services/machine_learning/face_ml/face_ml_result.dart";
@@ -434,7 +433,9 @@ class ClusterFeedbackService {
distanceThreshold: 0.22,
);
- if (clusterResult == null || clusterResult.newClusterIdToFaceIds == null || clusterResult.isEmpty) {
+ if (clusterResult == null ||
+ clusterResult.newClusterIdToFaceIds == null ||
+ clusterResult.isEmpty) {
_logger.warning('No clusters found or something went wrong');
return ClusteringResult(newFaceIdToCluster: {});
}
@@ -537,8 +538,7 @@ class ClusterFeedbackService {
EVector.fromBuffer(clusterSummary.$1).values,
dtype: DType.float32,
);
- final bigClustersMeanDistance =
- cosineDistanceSIMD(biggestMean, currentMean);
+ final bigClustersMeanDistance = 1 - biggestMean.dot(currentMean);
_logger.info(
"Mean distance between biggest cluster and current cluster: $bigClustersMeanDistance",
);
@@ -595,8 +595,7 @@ class ClusterFeedbackService {
final List<double> trueDistances = [];
for (final biggestEmbedding in biggestSampledEmbeddings) {
for (final currentEmbedding in currentSampledEmbeddings) {
- distances
- .add(cosineDistanceSIMD(biggestEmbedding, currentEmbedding));
+ distances.add(1 - biggestEmbedding.dot(currentEmbedding));
trueDistances.add(
biggestEmbedding.distanceTo(
currentEmbedding,
@@ -789,7 +788,7 @@ class ClusterFeedbackService {
final List<double> distances = [];
for (final otherEmbedding in sampledOtherEmbeddings) {
for (final embedding in sampledEmbeddings) {
- distances.add(cosineDistanceSIMD(embedding, otherEmbedding));
+ distances.add(1 - embedding.dot(otherEmbedding));
}
}
distances.sort();
@@ -1086,7 +1085,7 @@ class ClusterFeedbackService {
final fileIdToDistanceMap = {};
for (final entry in faceIdToVectorMap.entries) {
fileIdToDistanceMap[getFileIdFromFaceId(entry.key)] =
- cosineDistanceSIMD(personAvg, entry.value);
+ 1 - personAvg.dot(entry.value);
}
w?.log('calculated distances for cluster $clusterID');
suggestion.filesInCluster.sort((b, a) {
@@ -1141,7 +1140,7 @@ List<(int, double)> _calcSuggestionsMean(Map<String, dynamic> args) {
continue;
}
final Vector avg = clusterAvg[personCluster]!;
- final distance = cosineDistanceSIMD(avg, otherAvg);
+ final distance = 1 - avg.dot(otherAvg);
comparisons++;
if (distance < maxClusterDistance) {
if (minDistance == null || distance < minDistance) {
diff --git a/mobile/lib/ui/viewer/people/cluster_app_bar.dart b/mobile/lib/ui/viewer/people/cluster_app_bar.dart
index 83ebe54284..8b95d4247e 100644
--- a/mobile/lib/ui/viewer/people/cluster_app_bar.dart
+++ b/mobile/lib/ui/viewer/people/cluster_app_bar.dart
@@ -3,7 +3,6 @@ import 'dart:async';
import "package:flutter/foundation.dart";
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
-import "package:ml_linalg/linalg.dart";
import 'package:photos/core/configuration.dart';
import 'package:photos/core/event_bus.dart';
import "package:photos/db/files_db.dart";
@@ -11,12 +10,10 @@ import "package:photos/events/people_changed_event.dart";
import 'package:photos/events/subscription_purchased_event.dart';
import "package:photos/face/db.dart";
import "package:photos/face/model/person.dart";
-import "package:photos/generated/protos/ente/common/vector.pb.dart";
import "package:photos/models/file/file.dart";
import 'package:photos/models/gallery_type.dart';
import 'package:photos/models/selected_files.dart';
import 'package:photos/services/collections_service.dart';
-import "package:photos/services/machine_learning/face_ml/face_clustering/cosine_distance.dart";
import "package:photos/services/machine_learning/face_ml/face_ml_result.dart";
import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedback.dart";
import 'package:photos/ui/actions/collection/collection_sharing_actions.dart';
@@ -160,58 +157,6 @@ class _AppBarWidgetState extends State<ClusterAppBar> {
return actions;
}
- @Deprecated(
- 'Used for debugging an issue with conflicts on cluster IDs, resolved now',
- )
- Future<void> _validateCluster(BuildContext context) async {
- _logger.info('_validateCluster called');
- final faceMlDb = FaceMLDataDB.instance;
-
- final faceIDs = await faceMlDb.getFaceIDsForCluster(widget.clusterID);
- final fileIDs = faceIDs.map((e) => getFileIdFromFaceId(e)).toList();
-
- final embeddingsBlobs = await faceMlDb.getFaceEmbeddingMapForFile(fileIDs);
- embeddingsBlobs.removeWhere((key, value) => !faceIDs.contains(key));
- final embeddings = embeddingsBlobs
- .map((key, value) => MapEntry(key, EVector.fromBuffer(value).values));
-
- for (final MapEntry<String, List<double>> embedding in embeddings.entries) {
- double closestDistance = double.infinity;
- double closestDistance32 = double.infinity;
- double closestDistance64 = double.infinity;
- String? closestFaceID;
- for (final MapEntry<String, List<double>> otherEmbedding
- in embeddings.entries) {
- if (embedding.key == otherEmbedding.key) {
- continue;
- }
- final distance64 = cosineDistanceSIMD(
- Vector.fromList(embedding.value, dtype: DType.float64),
- Vector.fromList(otherEmbedding.value, dtype: DType.float64),
- );
- final distance32 = cosineDistanceSIMD(
- Vector.fromList(embedding.value, dtype: DType.float32),
- Vector.fromList(otherEmbedding.value, dtype: DType.float32),
- );
- final distance = cosineDistForNormVectors(
- embedding.value,
- otherEmbedding.value,
- );
- if (distance < closestDistance) {
- closestDistance = distance;
- closestDistance32 = distance32;
- closestDistance64 = distance64;
- closestFaceID = otherEmbedding.key;
- }
- }
- if (closestDistance > 0.3) {
- _logger.severe(
- "Face ${embedding.key} is similar to $closestFaceID with distance $closestDistance, and float32 distance $closestDistance32, and float64 distance $closestDistance64",
- );
- }
- }
- }
-
Future<void> _onIgnoredClusterClicked(BuildContext context) async {
await showChoiceDialog(
context,