Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.
C avx-512avx2biometricsc99computer-visioncpu-inferencedeep-learningedge-aiembedded-aiface-embeddingface-recognitionface-verificationlow-latencyonnx-runtimeproduction-readysimdzero-dependencies
Reduce gallery memory and score tied templates consistently
Baurzhan Atynov69b6d52f538d
diff --git a/docs/research/compact_gallery.md b/docs/research/compact_gallery.mdnew file mode 100644index 0000000..8ed4881--- /dev/null+++ b/docs/research/compact_gallery.md@@ -0,0 +1,24 @@+# Single-query CPU gallery search++The float64 Gallery remains available. CompactGallery stores the original float32 enrollment matrix, one float64 norm and a boolean flag per row. These byte counts describe retained array payloads, excluding construction, temporaries, outputs and allocator overhead.++For a finite, nonzero query, both classes normalize in float64. CompactGallery scans with a float32 query and divides each rough dot product by the stored enrollment norm. On an IEEE CPU the absolute dot error divided by that norm is bounded by a multiple of unit roundoff because the sum of the absolute normalized products is at most one (Cauchy-Schwarz). For D=512 we use gamma(2D+4), with gamma(m)=mu/(1-mu) and u the unit roundoff. The shortlist includes scores within twice this bound of the kth approximate score: both the kth score and its competitor can move. Rows with norms outside [1e-20, 1e20] are always refined and do not set a finite cutoff. If fewer than k ordinary rows remain, all rows are refined.++Both gallery classes score finalists with the same contiguous row-wise float64 reduction. This also fixes a tie bug in the previous implementation, where identical enrollment rows could acquire different last bits in different BLAS tiles. Earlier Gallery scores may differ in those last bits. Identical best rows now abstain in identify, including at min_margin=0.++## Measurements++One Linux CPU, one BLAS thread, k=5, one warmup and 40 measured random queries per gallery size. Both versions were warmed and the order alternated. Median CPU milliseconds per search, excluding enrollment.++| Enrollment rows | Gallery ms | CompactGallery ms | Gallery MiB | CompactGallery MiB |+|---:|---:|---:|---:|---:|+| 4096 | 0.806 | 0.568 | 16 | 8.04 |+| 32768 | 6.582 | 5.439 | 128 | 64.28 |+| 65536 | 12.995 | 10.535 | 256 | 128.56 |++IDs and float64 scores matched for all benchmark queries. Fifteen real-model outputs on repository fixture images also matched when queried against each other. Tests separately check a full-score reference with nearly tied candidates, duplicate rows, extreme norms, threshold boundaries and noncontiguous enrollment. One deliberate all-duplicates benchmark on 4096 rows took 2.994 ms for Gallery and 3.578 ms for CompactGallery. This experiment measures gallery lookup in isolation.++```sh+PYTHONPATH=python OPENBLAS_NUM_THREADS=1 python tests/test_compact_gallery.py+PYTHONPATH=python OPENBLAS_NUM_THREADS=1 python tests/bench_compact_gallery.py+```diff --git a/python/README.md b/python/README.mdindex 90813cc..025161d 100644--- a/python/README.md+++ b/python/README.md@@ -211,3 +211,14 @@ consistency. Calibrate decision thresholds on separate data for each checkpoint.The REST compare endpoint accepts a numeric array or the little-endianfloat32 Base64 string returned by the compact detect endpoint for either input.++For single-query CPU search against a large fixed list, use+`from facex import CompactGallery` and construct it with the same enrollment+matrix. Both gallery classes expose the same search and identification methods.+CompactGallery owns a float32 snapshot plus a float64 norm and a flag per row+(2,057 bytes per 512-component row). It shortlists using a conservative+floating-point error bound, then ranks finalists in float64. Many near ties+can require rescoring the entire gallery. Both implementations now use the same+row-wise summation order for final scores and break equal scores by enrollment+order. At a floating-point decision boundary a score can differ in the last+bits from older releases.diff --git a/python/facex/__init__.py b/python/facex/__init__.pyindex ed24873..61d9e48 100644--- a/python/facex/__init__.py+++ b/python/facex/__init__.py@@ -10,7 +10,7 @@ Usage:from facex.core import FaceX, similarity-from facex.gallery import Gallery, enrollment_template+from facex.gallery import CompactGallery, Gallery, enrollment_template__version__ = "0.1.0"-__all__ = ["FaceX", "Gallery", "enrollment_template", "similarity"]+__all__ = ["FaceX", "CompactGallery", "Gallery", "enrollment_template", "similarity"]diff --git a/python/facex/gallery.py b/python/facex/gallery.pyindex 42f6ca3..8c5fe9f 100644--- a/python/facex/gallery.py+++ b/python/facex/gallery.py@@ -11,7 +11,7 @@ def _unit_rows(values):if raw.ndim != 2 or raw.shape[1] != EMBEDDING_DIM or raw.dtype.kind not in "iuf":raise ValueError("Expected a matrix of 512 dimensional real vectors")with np.errstate(over="ignore"):- rows = raw.astype(np.float32, copy=False).astype(np.float64)+ rows = raw.astype(np.float32, copy=False).astype(np.float64, order="C")if not np.isfinite(rows).all():raise ValueError("Nonfinite embedding")norms = np.linalg.norm(rows, axis=1, keepdims=True)@@ -19,6 +19,55 @@ def _unit_rows(values):return rows+def _select(row, k):+ if k == 1:+ return np.array([row.argmax()])+ if k == len(row):+ return np.argsort(-row, kind="stable")+ cutoff = np.partition(row, len(row) - k)[-k]+ above = np.flatnonzero(row > cutoff)+ ties = np.flatnonzero(row == cutoff)[:k - len(above)]+ candidates = np.concatenate((above, ties))+ return candidates[np.lexsort((candidates, -row[candidates]))]+++# Conservative absolute score error for unit vectors on CPU with IEEE arithmetic.+# Factor two at the cutoff covers errors in both the kth and competing scores.+def _cutoff_slack(dtype):+ unit = float(np.finfo(dtype).eps) / 2+ operations = 2 * EMBEDDING_DIM + 4+ return 2 * operations * unit / (1 - operations * unit)+++_FP32_SLACK = _cutoff_slack(np.float32)+_FP64_SLACK = _cutoff_slack(np.float64)+++def _finalists(rough, k, slack, exceptional=None):+ cutoff = rough.max() if k == 1 else np.partition(rough, len(rough) - k)[-k]+ mask = rough >= cutoff - slack+ if exceptional is not None:+ mask |= exceptional+ return np.flatnonzero(mask)+++def _rank(rows, query, candidates, k, norms=None):+ exact = np.empty(len(candidates), dtype=np.float64)+ for start in range(0, len(candidates), 256):+ take = candidates[start:start + 256]+ values = rows[take]+ if norms is not None:+ values = values.astype(np.float64)+ values /= norms[take, None]+ # Identical contiguous rows must have the same reduction order, even at+ # a BLAS tile boundary or when scored alone at the end of a shortlist.+ np.multiply(values, query, out=values)+ exact[start:start + len(take)] = np.sum(values, axis=1)+ np.clip(exact, -1., 1., out=exact)+ selected = _select(exact, k)+ return candidates[selected], exact[selected]++class Gallery:"""Enrollment row number is the stable ID. Equal scores prefer the earlier row."""def __init__(self, embeddings):@@ -42,16 +91,11 @@ class Gallery:values = queries[start:start + block] @ self._rows.Tnp.clip(values, -1., 1., out=values)for i, row in enumerate(values, start):- if k == 1:- selected = [row.argmax()]- else:- cutoff = np.partition(row, len(row) - k)[-k]- above = np.flatnonzero(row > cutoff)- ties = np.flatnonzero(row == cutoff)[:k - len(above)]- candidates = np.concatenate((above, ties))- selected = candidates[np.lexsort((candidates, -row[candidates]))]- ids[i] = selected- scores[i] = row[selected]+ if not queries[i].any():+ ids[i], scores[i] = np.arange(k), 0.+ continue+ candidates = _finalists(row, k, _FP64_SLACK)+ ids[i], scores[i] = _rank(self._rows, queries[i], candidates, k)return ids, scoresdef identify(self, queries, *, min_score, min_margin):@@ -72,6 +116,49 @@ class Gallery:return np.where(accepted, ids[:, 0], -1)+class CompactGallery(Gallery):+ """Single-query oriented gallery. Store original float32 rows and float64 norms."""++ def __init__(self, embeddings):+ raw = np.asarray(embeddings)+ if raw.ndim != 2 or raw.shape[1] != EMBEDDING_DIM or raw.dtype.kind not in "iuf":+ raise ValueError("Expected a matrix of 512 dimensional real vectors")+ if not len(raw):+ raise ValueError("Empty enrollment matrix")+ with np.errstate(over="ignore"):+ self._rows = raw.astype(np.float32, order="C", copy=True)+ self._norms = np.empty(len(raw), dtype=np.float64)+ for start in range(0, len(raw), 256):+ chunk = self._rows[start:start + 256].astype(np.float64)+ self._norms[start:start + len(chunk)] = np.linalg.norm(chunk, axis=1)+ if not np.isfinite(self._norms).all() or np.any(self._norms == 0):+ raise ValueError("Enrollment vectors must be finite and have a direction")+ # A conservative normal range leaves room for dot-product partial sums.+ self._exceptional = (self._norms < 1e-20) | (self._norms > 1e20)++ def search(self, queries, k=1):+ k = operator.index(k)+ if not 1 <= k <= len(self._rows):+ raise ValueError("k must be within the enrollment size")+ queries = _unit_rows(queries)+ ids = np.empty((len(queries), k), dtype=np.intp)+ scores = np.empty((len(queries), k), dtype=np.float64)+ for i, query in enumerate(queries):+ if not query.any():+ ids[i], scores[i] = np.arange(k), 0.+ continue+ # For ordinary rows, sum(abs(a*b)) / norm(a) <= 1 (Cauchy-Schwarz).+ # The FP32 dot error is bounded by gamma(2D), plus query conversion.+ # Exceptional rows always go through the float64 pass.+ with np.errstate(over="ignore", invalid="ignore", under="ignore"):+ rough = (self._rows @ query.astype(np.float32)).astype(np.float64)+ rough /= self._norms+ rough[self._exceptional] = -np.inf+ candidates = _finalists(rough, k, _FP32_SLACK, self._exceptional)+ ids[i], scores[i] = _rank(self._rows, query, candidates, k, self._norms)+ return ids, scores++def enrollment_template(embeddings, weights=None, *, mode="mean"):"""Combine views of one identity. Return a unit vector and directional agreement.diff --git a/tests/bench_compact_gallery.py b/tests/bench_compact_gallery.pynew file mode 100644index 0000000..6384a4f--- /dev/null+++ b/tests/bench_compact_gallery.py@@ -0,0 +1,34 @@+"""Single-query latency, including selection and final cosine scoring."""+import os+from statistics import median+import time++import numpy as np++from facex import CompactGallery, Gallery+++def main():+ if hasattr(os, "sched_setaffinity"):+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})+ rng = np.random.default_rng(811)+ for n in (4096, 32768, 65536):+ data = rng.standard_normal((n, 512), dtype=np.float32)+ galleries = (Gallery(data), CompactGallery(data))+ del data+ timings = [[], []]+ for i, query in enumerate(rng.standard_normal((41, 512), dtype=np.float32)):+ results = [None, None]+ for j in (i % 2, 1 - i % 2):+ start = time.thread_time_ns()+ results[j] = galleries[j].search(query[None, :], 5)+ elapsed = time.thread_time_ns() - start+ if i:+ timings[j].append(elapsed / 1e6)+ for a, b in zip(*results):+ np.testing.assert_array_equal(a, b)+ print(n, "median CPU ms", *(round(median(t), 3) for t in timings), flush=True)+++if __name__ == "__main__":+ main()diff --git a/tests/test_compact_gallery.py b/tests/test_compact_gallery.pynew file mode 100644index 0000000..247ff5d--- /dev/null+++ b/tests/test_compact_gallery.py@@ -0,0 +1,75 @@+"""Verify both gallery representations against exhaustive row-wise float64 cosine."""+import unittest++import numpy as np++from facex import CompactGallery, Gallery+++def reference(rows, queries, k):+ rows = np.array(rows, dtype="d", order="C")+ rows /= np.linalg.norm(rows, axis=1, keepdims=True)+ ids, values = [], []+ for query in np.array(queries, dtype="d", order="C"):+ norm = np.linalg.norm(query[None, :], axis=1)[0]+ if norm:+ query /= norm+ scores = np.clip(np.sum(rows * query, axis=1), -1., 1.)+ chosen = np.argsort(-scores, kind="stable")[:k]+ ids.append(chosen)+ values.append(scores[chosen])+ return np.array(ids), np.array(values)+++class CompactGalleryTest(unittest.TestCase):+ def test_precision_range_and_cutoff(self):+ rng = np.random.default_rng(152)+ rows = rng.standard_normal((517,512)).astype("f")+ rows[:8] *= 1e-40+ rows[8:16] *= 1e32+ rows[16] = np.finfo("f").max+ rows[17] = -np.nextafter(np.float32(0), np.float32(1))+ rows[18:280] = rows[-1]+ rows[18:280,0] += rng.uniform(-2e-5,2e-5,262).astype("f")+ queries = np.vstack((rows[[0,9,16,17,18]], -rows[50], rows[-1]*0))+ for layout in (rows, np.asfortranarray(rows), rows[:, ::-1]):+ for k in (1, 5, 261, len(rows)):+ expected_ids, expected_scores = reference(layout, queries, k)+ for cls in (Gallery, CompactGallery):+ ids, scores = cls(layout).search(queries,k)+ np.testing.assert_array_equal(ids,expected_ids)+ np.testing.assert_array_equal(scores,expected_scores)++ def test_identical_rows_and_boundary(self):+ rng = np.random.default_rng(21)+ row, query = rng.normal(size=(2,512)).astype("f")+ rows = np.tile(row,(1025,1))+ for cls in (Gallery, CompactGallery):+ gallery = cls(rows)+ ids,scores = gallery.search([query],5)+ np.testing.assert_array_equal(ids, [np.arange(5)])+ self.assertTrue((scores == scores[0,0]).all())+ self.assertEqual(gallery.identify([query],min_score=-1,min_margin=0)[0],-1)++ rows = np.vstack((row, query, -query))+ top, scores = reference(rows,[row],2)+ margin = scores[0,0]-scores[0,1]+ for cls in (Gallery, CompactGallery):+ gallery = cls(rows)+ for m, decision in ((margin,top[0,0]),(np.nextafter(margin,2.),-1)):+ self.assertEqual(gallery.identify([row],min_score=scores[0,0],min_margin=m)[0],decision)++ def test_snapshot_and_empty_queries(self):+ rows = np.eye(2,512,dtype="f")+ gallery = CompactGallery(rows)+ query = rows[1:].copy()+ rows[:] = 0+ self.assertEqual(gallery.search(query)[0][0,0],1)+ self.assertEqual(gallery.search(query[:0],2)[1].shape,(0,2))+ for bad in (rows, rows[:0], np.full_like(rows,np.inf), np.ones((1,511))):+ with self.assertRaises(ValueError):+ CompactGallery(bad)+++if __name__ == "__main__":+ unittest.main()