π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use F32 variant everywhere
Manav Rathi041aaea0b9d7
diff --git a/web/packages/new/photos/services/ml/clip.ts b/web/packages/new/photos/services/ml/clip.tsindex b4c70bdd59..4981a25906 100644--- a/web/packages/new/photos/services/ml/clip.ts+++ b/web/packages/new/photos/services/ml/clip.ts@@ -2,7 +2,7 @@ import type { ElectronMLWorker } from "@/base/types/ipc";import type { ImageBitmapAndData } from "./blob";import { clipIndexes } from "./db";import { pixelRGBBilinear } from "./image";-import { dotProductF32, norm } from "./math";+import { dotProduct, norm } from "./math";import type { CLIPMatches } from "./worker-types";/**@@ -178,12 +178,8 @@ export const clipMatches = async (const textEmbedding = normalized(t);const items = (await cachedOrReadCLIPIndexes()).map(({ fileID, embedding }) =>- // What we want to do is `cosineSimilarity`, but since both the- // embeddings involved are already normalized, we can save the norm- // calculations and directly do their `dotProduct`.- //- // This code is on the hot path, so these optimizations help.- [fileID, dotProductF32(embedding, textEmbedding)] as const,++ [fileID, dotProduct(embedding, textEmbedding)] as const,);// This score threshold was obtain heuristically. 0.2 generally gives solid// results, and around 0.15 we start getting many false positives (all thisdiff --git a/web/packages/new/photos/services/ml/cluster.ts b/web/packages/new/photos/services/ml/cluster.tsindex 57e9101498..ab29c88dd1 100644--- a/web/packages/new/photos/services/ml/cluster.ts+++ b/web/packages/new/photos/services/ml/cluster.ts@@ -5,7 +5,7 @@ import { ensure } from "@/utils/ensure";import type { EnteFile } from "../../types/file";import { type EmbeddingCluster, clusterHdbscan } from "./cluster-hdb";import type { Face, FaceIndex } from "./face";-import { dotProduct, dotProductF32 } from "./math";+import { dotProduct } from "./math";/*** A face cluster is an set of faces.@@ -138,7 +138,7 @@ export interface ClusterPreview {}export interface ClusterPreviewFace {- face: Face;+ face: Omit<Face, "embedding">;cosineSimilarity: number;wasMerged: boolean;}@@ -217,7 +217,8 @@ export const clusterFaces = (]),);- const fileForFace = ({ faceID }: Face) => ensure(fileForFaceID.get(faceID));+ const fileForFace = ({ faceID }: { faceID: string }) =>+ ensure(fileForFaceID.get(faceID));// Sort faces so that photos taken temporally close together are close.//@@ -231,11 +232,10 @@ export const clusterFaces = (// For fast reverse lookup - map from face ids to the face.const faceForFaceID = new Map(faces.map((f) => [f.faceID, f]));- const faceEmbeddingsN = faces.map(({ embedding }) => embedding);-- const faceEmbeddings = faces.map(- ({ embedding }) => new Float32Array(embedding),- );+ const faceEmbeddings = faces.map(({ embedding }) => embedding);+ // For the old hbdscan. This is not performant but we might be discarding+ // that code anyway, so no point in optimizing.+ const faceEmbeddingsN = faces.map(({ embedding }) => [...embedding]);// Map from face index to the corresponding cluster ID (if any).const clusterIndexForFaceIndex = new Map<number, number>();@@ -450,11 +450,14 @@ export const clusterFaces = (/*** A generator function that returns a stream of {faceID, embedding} values,* flattening all the the faces present in the given {@link faceIndices}.+ *+ * It also converts the embeddings to Float32Arrays to speed up the dot product+ * calculations that will happen during clustering.*/function* enumerateFaces(faceIndices: FaceIndex[]) {for (const fi of faceIndices) {for (const f of fi.faces) {- yield f;+ yield { ...f, embedding: new Float32Array(f.embedding) };}}}@@ -509,7 +512,7 @@ const clusterLinear = (// The vectors are already normalized, so we can directly use their// dot product as their cosine similarity.- const csim = dotProductF32(ei, ej);+ const csim = dotProduct(ei, ej);if (csim > joinThreshold) {if (csim > nnCosineSimilarity) {nnIndex = j;diff --git a/web/packages/new/photos/services/ml/index.ts b/web/packages/new/photos/services/ml/index.tsindex 97ed45c7ea..a99342bedc 100644--- a/web/packages/new/photos/services/ml/index.ts+++ b/web/packages/new/photos/services/ml/index.ts@@ -366,7 +366,7 @@ export interface ClusterDebugPageContents {clusters: FaceCluster[];clusterPreviewsWithFile: ClusterPreviewWithFile[];unclusteredFacesWithFile: {- face: Face;+ face: Omit<Face, "embedding">;enteFile: EnteFile;}[];}@@ -391,7 +391,7 @@ export const wipClusterDebugPageContents = async (...rest} = await worker().then((w) => w.clusterFaces(opts, proxy(onProgress)));- const fileForFace = ({ faceID }: Face) =>+ const fileForFace = ({ faceID }: { faceID: string }) =>ensure(localFileByID.get(ensure(fileIDFromFaceID(faceID))));const clusterPreviewsWithFile = clusterPreviews.map(diff --git a/web/packages/new/photos/services/ml/math.ts b/web/packages/new/photos/services/ml/math.tsindex 65c191456d..ca965da0a5 100644--- a/web/packages/new/photos/services/ml/math.ts+++ b/web/packages/new/photos/services/ml/math.ts@@ -12,6 +12,8 @@ export const clamp = (value: number, min: number, max: number) =>** Precondition: The two vectors must be of the same length.*+ * ---+ ** [Note: Dot product is cosine similarity for normalized vectors]** The cosine similarity of two vectors is defined as@@ -22,6 +24,14 @@ export const clamp = (value: number, min: number, max: number) =>* product. When we're computing dot products in a hot loop, skipping over that* unnecessary renormalization matters.*+ * When comparing embeddings we usually want is the cosine similarity, but when+ * both the embeddings involved are already normalized, we can save the norm+ * calculations and directly do their `dotProduct`.+ *+ * Such code is often on the hot path, so these optimizations help.+ *+ * ---+ ** [Note: Cosine similarity and cosine distance]** The cosine similarity of two vectors is [-1, 1] (inclusive), indicating how@@ -32,6 +42,8 @@ export const clamp = (value: number, min: number, max: number) =>** in an attempt to convert it into a (pseudo) distance metric.*+ * ---+ ** [Note: Dot product performance]** In theory, WASM SIMD instructions should give us a huge boost for computing@@ -45,21 +57,7 @@ export const clamp = (value: number, min: number, max: number) =>* itself to WASM's set. But that'll require bundling native code, so as a* tradeoff to avoid complexity we currently leave that 1x on the table.*/-export const dotProduct = (v1: number[], v2: number[]) => {- if (v1.length != v2.length)- throw new Error(`Length mismatch ${v1.length} ${v2.length}`);- let d = 0;- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion- for (let i = 0; i < v1.length; i++) d += v1[i]! * v2[i]!;- return d;-};--/**- * Float32Array variant of {@link dotProduct}.- *- * See: [Note: Dot product performance].- */-export const dotProductF32 = (v1: Float32Array, v2: Float32Array) => {+export const dotProduct = (v1: Float32Array, v2: Float32Array) => {if (v1.length != v2.length)throw new Error(`Length mismatch ${v1.length} ${v2.length}`);let d = 0;