Skip to content

armgit / facex

Public Imported from GitHub
0

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.

Measure integer gallery search on close neighbors

Baurzhan Atynovb637cf0de553
diff --git a/docs/research/gallery_integer_screen.md b/docs/research/gallery_integer_screen.md
new file mode 100644
index 0000000..a76a393
--- /dev/null
+++ b/docs/research/gallery_integer_screen.md
@@ -0,0 +1,25 @@
+# Integer screening with exact finalist scoring
+
+Run from the repository root on Linux with NumPy and GCC:
+
+ OPENBLAS_NUM_THREADS=1 PYTHONPATH=python python tests/bench_gallery_codes.py
+
+This standalone experiment targets a single nonzero query against finite nonzero 512-dimensional enrollment vectors. The index scans integer codes and then reads selected original float32 rows from a warm memory-mapped file. Original rows are required for exact scoring. Enrollment time, disk latency on a cold cache, total RSS and model inference are outside these measurements.
+
+Let x and q be unit vectors, c the enrollment mean, v=x-c and t=q-c. Then
+q·x = 1 - (||v||² + ||t||²)/2 + v·t.
+Store the row length, row scale, original norm and reconstruction error r=||v-V|| for a quantized approximation V. Quantize t to T and measure d=||t-T||. The error in the integer dot estimate is bounded by r||t|| + (||v||+r)d, by expanding v·t - V·T. The uncentered variant directly estimates x·q. The experiment adds an absolute floating point allowance of 1e-12. It scores five seed candidates exactly, then includes every remaining row whose upper bound reaches the fifth seed score. The final reduction and stable row ordering match CompactGallery. This is an empirical CPU implementation of a real-arithmetic bound, without a formal floating point proof.
+
+AMD EPYC 9V45, one pinned CPU, one BLAS thread, one warmup and 40 measured queries per case. Rotating execution order, elapsed wall time. Every final ID and score matched the baseline, including exact ties. Median finalist counts include the five seeds.
+
+| Gallery | Method | Median ms | p95 ms | Median finalists |
+|---|---|---:|---:|---:|
+| 65536 independent random rows | CompactGallery | 4.00 | 4.56 | — |
+| same | 8 bit | 1.60 | 1.89 | 9 |
+| same | 4 bit | 13.38 | 15.90 | 17975 |
+| 4096 near-identical rows with duplicate pairs | CompactGallery | 2.58 | 2.97 | — |
+| same | 8 bit | 2.53 | 2.86 | 4096 |
+| same | centered 8 bit | 0.174 | 0.246 | 8 |
+| same | centered 4 bit | 0.996 | 1.256 | 1430 |
+
+Uncentered 8-bit index payload is 33.5 MiB at 65536 rows (32 MiB codes plus 1.5 MiB row metadata). The backing file adds 128 MiB of vector payload, which can also occupy the OS page cache. Standalone approximate 8-bit seed recall@5 was 95.5% in the random workload. Exact refinement therefore matters. The clustered case deliberately uses one shared center for both enrollment and query generation. Mixed clusters, queries far from a cluster, realistic face gallery distributions, and cold reads require separate measurements before integrating this into the product.
diff --git a/tests/bench_gallery_codes.c b/tests/bench_gallery_codes.c
new file mode 100644
index 0000000..7fd7845
--- /dev/null
+++ b/tests/bench_gallery_codes.c
@@ -0,0 +1,24 @@
+#include <stdint.h>
+#include <stddef.h>
+
+/* Each sum is bounded by 512 * 127 * 32767 < INT32_MAX. */
+void scan_codes(const uint8_t *rows, const int16_t *query, size_t n,
+ int bits, int32_t *scores) {
+ for (size_t i = 0; i < n; ++i) {
+ int32_t sum = 0;
+ if (bits == 8) {
+ const int8_t *row = (const int8_t *)rows + 512 * i;
+ #pragma omp simd reduction(+:sum)
+ for (int j = 0; j < 512; ++j)
+ sum += row[j] * query[j];
+ } else {
+ const uint8_t *row = rows + 256 * i;
+ #pragma omp simd reduction(+:sum)
+ for (int j = 0; j < 256; ++j) {
+ sum += ((row[j] & 15) - 7) * query[2*j];
+ sum += ((row[j] >> 4) - 7) * query[2*j + 1];
+ }
+ }
+ scores[i] = sum;
+ }
+}
diff --git a/tests/bench_gallery_codes.py b/tests/bench_gallery_codes.py
new file mode 100644
index 0000000..41eb351
--- /dev/null
+++ b/tests/bench_gallery_codes.py
@@ -0,0 +1,127 @@
+"""Research benchmark for bounded integer screening of a warm backing gallery."""
+import ctypes
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+from time import perf_counter_ns
+
+import numpy as np
+
+from facex.gallery import CompactGallery, _rank, _select, _unit_rows
+
+
+class Index:
+ def __init__(self, raw, bits, scan, centered=False):
+ self.bits, self.scan = bits, scan
+ n = len(raw)
+ self.codes = np.empty((n, 512 * bits // 8), np.uint8)
+ self.scale, self.radius, self.norm = np.empty((3, n))
+ self.center = None
+ if centered:
+ self.center = sum(_unit_rows(raw[i:i+512]).sum(axis=0)
+ for i in range(0, n, 512)) / n
+ self.length = np.empty(n)
+ limit = (1 << (bits - 1)) - 1
+ for start in range(0, n, 512):
+ sl = slice(start, start + 512)
+ rows = raw[sl].astype(np.float64)
+ self.norm[sl] = np.linalg.norm(rows, axis=1)
+ rows /= self.norm[sl, None]
+ if centered:
+ rows -= self.center
+ self.length[sl] = np.linalg.norm(rows, axis=1)
+ scale = np.max(np.abs(rows), axis=1) / limit
+ scale[scale == 0] = 1
+ self.scale[sl] = scale
+ code = np.rint(rows / scale[:, None]).astype(np.int8)
+ self.radius[sl] = np.linalg.norm(rows - code * scale[:, None], axis=1)
+ if bits == 4:
+ shifted = (code + 7).astype(np.uint8)
+ self.codes[sl] = shifted[:, ::2] | (shifted[:, 1::2] << 4)
+ else:
+ self.codes[sl] = code.view(np.uint8)
+
+ def search(self, raw, query):
+ q = _unit_rows(query[None])[0]
+ target = q if self.center is None else q - self.center
+ scale = np.max(np.abs(target)) / 32767 or 1.0
+ encoded = np.rint(target / scale).astype(np.int16)
+ delta = np.linalg.norm(target - scale * encoded)
+ accum = np.empty(len(raw), np.int32)
+ self.scan(self.codes.ctypes.data, encoded.ctypes.data, len(raw),
+ self.bits, accum.ctypes.data)
+ approx = accum * self.scale * scale
+ error = self.radius + (1 + self.radius) * delta + 1e-12
+ if self.center is not None:
+ distance = np.linalg.norm(target)
+ approx += 1 - 0.5 * (distance**2 + self.length**2)
+ error = self.radius * distance + (self.length + self.radius) * delta + 1e-12
+ # Exact seed scores give a tighter lower bound than interval endpoints.
+ seeds = np.sort(_select(approx, 5))
+ ids, scores = _rank(raw, q, seeds, 5, self.norm)
+ extra = approx + error >= scores[-1]
+ extra[seeds] = False
+ others = np.flatnonzero(extra)
+ if len(others):
+ candidates = np.sort(np.concatenate((seeds, others)))
+ ids, scores = _rank(raw, q, candidates, 5, self.norm)
+ return ids, scores, len(others) + 5, seeds
+
+
+def run(directory, scan, clustered):
+ rng = np.random.default_rng(811)
+ n = 4096 if clustered else 65536
+ raw = np.lib.format.open_memmap(directory / "rows.npy", mode="w+",
+ dtype=np.float32, shape=(n, 512))
+ raw[:] = rng.standard_normal(raw.shape, dtype=np.float32)
+ queries = rng.standard_normal((41, 512), dtype=np.float32)
+ if clustered:
+ center = queries[0].copy()
+ raw[:] = center + raw * 1e-4
+ raw[1::2] = raw[::2]
+ queries[:] = center + queries * 1e-4
+ raw.flush()
+ baseline = CompactGallery(raw)
+ indexes = [Index(raw, b, scan) for b in (8, 4)]
+ if clustered:
+ indexes.extend(Index(raw, b, scan, centered=True) for b in (8, 4))
+ timings = [[] for _ in range(1 + len(indexes))]
+ counts, recalls = [[] for _ in indexes], [[] for _ in indexes]
+ for i, q in enumerate(queries):
+ results = {}
+ for j in np.roll(np.arange(len(timings)), i % len(timings)):
+ start = perf_counter_ns()
+ result = baseline.search(q[None], 5) if j == 0 else indexes[j-1].search(raw, q)
+ elapsed = (perf_counter_ns() - start) / 1e6
+ results[j] = result
+ if i:
+ timings[j].append(elapsed)
+ for j in range(1, len(timings)):
+ ids, scores, count, seeds = results[j]
+ np.testing.assert_array_equal(ids, results[0][0][0])
+ np.testing.assert_array_equal(scores, results[0][1][0])
+ if i:
+ counts[j-1].append(count)
+ recalls[j-1].append(len(set(ids) & set(seeds)) / 5)
+ print('rows', n, 'clustered', clustered, flush=True)
+ for j, t in enumerate(timings):
+ print(j, 'wall ms p50 p95', np.percentile(t, [50, 95]),
+ 'candidates median/max', (np.median(counts[j-1]), max(counts[j-1])) if j else n,
+ 'rough recall', np.mean(recalls[j-1]) if j else 1, flush=True)
+
+
+if __name__ == '__main__':
+ if hasattr(os, 'sched_setaffinity'):
+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp)
+ lib = path / 'scan.so'
+ subprocess.run(['cc', '-O3', '-march=native', '-fopenmp-simd', '-fPIC',
+ '-shared', Path(__file__).with_suffix('.c'), '-o', lib], check=True)
+ scan = ctypes.CDLL(str(lib)).scan_codes
+ scan.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t,
+ ctypes.c_int, ctypes.c_void_p]
+ scan.restype = None
+ for clustered in (False, True):
+ run(path, scan, clustered)