Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] Add method for safe cosine distance

laurenspriem3c24345b68be
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 7ba4c582b9..0611a1d838 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
@@ -1,9 +1,9 @@
import 'dart:math' show sqrt;
-import "package:ml_linalg/vector.dart";
+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!
double cosineDistanceSIMD(Vector vector1, Vector vector2) {
if (vector1.length != vector2.length) {
@@ -13,6 +13,17 @@ double cosineDistanceSIMD(Vector vector1, Vector vector2) {
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.
+double cosineDistanceSIMDSafe(Vector vector1, Vector vector2) {
+ if (vector1.length != vector2.length) {
+ throw ArgumentError('Vectors must be the same length');
+ }
+
+ return vector1.distanceTo(vector2, distance: Distance.cosine);
+}
+
/// Calculates the cosine distance between two embeddings/vectors.
///
/// Throws an ArgumentError if the vectors are of different lengths or