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
Improve template search and isolate recognition weights between models
Baurzhan Atynovb0284d68326c
diff --git a/docker/server.py b/docker/server.pyindex 2adf0bf..3809460 100644--- a/docker/server.py+++ b/docker/server.py@@ -13,6 +13,7 @@ Usage:from contextlib import contextmanager, nullcontextimport base64+import binasciiimport osimport subprocessimport threading@@ -21,7 +22,7 @@ import timeimport numpy as npfrom flask import Flask, g, request, jsonifyfrom PIL import Image-from facex import FaceX+from facex import FaceX, similarityapp = Flask(__name__)@@ -204,14 +205,27 @@ def compare():Input: JSON {"emb1": [512], "emb2": [512]}Output: {"similarity": float, "match": bool}"""- data = request.get_json()- if not data or 'emb1' not in data or 'emb2' not in data:+ data = request.get_json(silent=True)+ if not isinstance(data, dict) or 'emb1' not in data or 'emb2' not in data:return jsonify({'error': 'Need emb1 and emb2'}), 400- emb1 = np.array(data['emb1'], dtype=np.float32)- emb2 = np.array(data['emb2'], dtype=np.float32)+ def decode(value):+ if isinstance(value, str):+ if len(value) != 2732:+ raise ValueError("Expected 512 base64 encoded float32 components")+ raw = base64.b64decode(value, validate=True)+ if len(raw) != 2048:+ raise ValueError("Expected 2048 embedding bytes")+ return np.frombuffer(raw, dtype="<f4")+ if not isinstance(value, list) or len(value) != 512 or any(+ type(v) not in (int, float) for v in value):+ raise ValueError("Expected an array of 512 real components")+ return value- sim = float(np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2) + 1e-8))+ try:+ sim = similarity(decode(data["emb1"]), decode(data["emb2"]))+ except (ValueError, OverflowError, binascii.Error):+ return jsonify(error="Invalid embedding"), 400return jsonify({'similarity': round(sim, 6),diff --git a/docs/research/math_54.md b/docs/research/math_54.mdnew file mode 100644index 0000000..6009686--- /dev/null+++ b/docs/research/math_54.md@@ -0,0 +1,92 @@+# 54 mathematical and engineering tasks for FaceX++Baseline a8d0332. These are engineering tasks with shared implementations. Timings below measure specific operations. The release does not establish a new biometric accuracy or an end-to-end throughput improvement.++| ID | Problem | Implemented solution and verification |+|---:|---|---|+| 1 | Cosine overflows for large finite float32 templates | Promote products and reductions to float64. Maximum finite parallel and antiparallel vectors score +1 and -1. |+| 2 | Tiny nonzero vectors lose their direction | Remove the absolute norm cutoff. The smallest positive float32 survives the cosine calculation. |+| 3 | Define the score for an absent direction | Handle zero norm explicitly as zero; identification abstains for a zero query. |+| 4 | Keep cosine in its mathematical domain | Clamp the final result to [-1,1] after accumulation. |+| 5 | Prevent undefined scores entering decisions | Reject nonfinite or incompatible inputs. REST returns 400; the SDK raises ValueError. |+| 6 | Keep SDK and REST decisions numerically consistent | Use the same cosine routine. REST applies its existing strict 0.3 decision rule before rounding the displayed score. |+| 7 | Compare compact output directly | Decode each operand independently as little-endian float32. Array, compact and mixed pairs agree. |+| 8 | Avoid accepting truncated or ambiguous vector representations | Check encoded length, Base64 alphabet, decoded byte count, flat array arity and numeric types. Tested malformed payloads. |+| 9 | Eliminate repeated enrollment normalization | Normalize enrollment rows once, retain an owned matrix and reuse it for subsequent queries. |+| 10 | Search multiple queries together | Score query blocks by matrix multiplication. Tested against a normalized exhaustive reference. |+| 11 | Bound a batch's temporary score matrix | Choose the query block size from a 1 MiB target, with a minimum of one gallery row of scores. Tested across the block boundary. |+| 12 | Find one nearest neighbor without sorting | Use argmax directly for k=1. Tested self matches and duplicate rows. |+| 13 | Find exact top k without sorting the whole gallery | Partition at the kth score and sort only selected candidates. Verified k=4 and k equal to gallery size. |+| 14 | Resolve ties at the kth boundary deterministically | Fill cutoff ties by enrollment order, then rank by score and row ID. Tested duplicate and all-zero scores. |+| 15 | Reject an insufficient best match | Identify applies a user-supplied minimum cosine and returns -1 when insufficient. |+| 16 | Abstain on ambiguous nearest identities | Require separation from the runner-up and reject exact ties. Tested equidistant and duplicate templates. |+| 17 | Avoid inventing a margin for a singleton gallery | A positive required margin yields abstention when no runner-up exists. |+| 18 | Build one enrollment template from several views | Compute a spherical mean over normalized embedding directions. The resulting template has unit length. |+| 19 | Include quality without numerical dependence on weight units | Rescale nonnegative quality weights before accumulation; tested scaling by 1e200 and 1e-200. |+| 20 | Exclude missing or explicitly ignored views | Omit zero vectors and zero-weight views; reject a group with no usable direction. |+| 21 | Select a representative observed view efficiently | The weighted cosine medoid maximizes the dot product with the resultant; O(nD) instead of materializing n squared similarities. Compared to exhaustive pairwise scoring. |+| 22 | Detect contradictory enrollment directions | Reject a numerically vanishing resultant. Antipodal enrollment is a regression fixture. |+| 23 | Quantify within-enrollment consistency | Return normalized resultant length along with the template. Checked against a direct weighted average. |+| 24 | Evaluate all empirical thresholds without a pair-by-threshold matrix | Sort scores once and accumulate true and false accepts. |+| 25 | Treat tied scores as indivisible ROC steps | Evaluate only ends of equal-score runs, including reject-all. Tested discrete tied inputs. |+| 26 | Compute tie-aware AUC | Integrate the empirical ROC and compare to independent positive-negative pair counting with half credit for ties. |+| 27 | Estimate the equal-error crossing | Interpolate between neighboring ROC points. Perfect, reversed and fully tied fixtures give 0, 1 and 0.5. |+| 28 | Select an operating point at a maximum empirical FAR | Maximize true accepts under the budget, minimizing false accepts on a tie. Checked by exhaustive enumeration. |+| 29 | Represent an unattainable nontrivial operating point | Use an explicit reject-all threshold (JSON null) instead of a fabricated numeric cutoff. |+| 30 | Show when the sample cannot resolve a small FAR | Report impostor denominator and its one-count resolution alongside the measured FAR. |+| 31 | Separate threshold selection and evaluation | Accept a separate holdout NPZ and apply the frozen rule; report false accepts and false rejects independently. Caller supplies the independent split. |+| 32 | Quantify uncertainty after zero false accepts | On a frozen independent holdout, report the one-sided exact 95% binomial upper bound via expm1. Tested by inverting the zero-event probability. |+| 33 | Avoid dominance by the majority verification class | Report balanced accuracy on the holdout. Missing classes produce an explicit error. |+| 34 | Eliminate per-record binary parsing overhead | Read the training image index through a structured little-endian memory map. Reject partial records. |+| 35 | Replace Python lists of image indices per identity | Stable-sort the label column and represent each class by its offsets into one order array. |+| 36 | Avoid repeated conversion of the entire class list for impostor sampling | Sample eligible group IDs directly from a NumPy array. The original eligible population is preserved. |+| 37 | Preserve the historical training comparison when changing sampling | Restore first-seen class order and within-class source order. Seeded ordered pairs, including their final shuffle, match the old sampler. |+| 38 | Avoid materializing all cross-validation fold indices | Use contiguous slice boundaries with divmod, preserving remainder distribution, threshold tie handling and held-out results. |+| 39 | Detect undefined cross-validation setups | Validate fold count, vector shapes and finite nondecreasing threshold grids before counting. |+| 40 | Optimize detector aspect-ratio budget exactly | Binary-search the crossing between increasing width and decreasing height capacity and evaluate the boundary neighbors. Compared to the original exhaustive optimizer. |+| 41 | Reuse the geometry of a fixed camera feed | Bound the size/shape result cache to 256 entries; repeated dimensions and pixel budgets avoid the search. |+| 42 | Preserve extreme aspect and padding constraints | Keep the original long-side cap, rounding and 32-pixel padding. Verified 9,012 shape/budget combinations against exhaustive search. |+| 43 | Avoid an allocation-heavy vote for one crop center | Use the sole eligible center directly and scalar clipping for the output coordinates. |+| 44 | Bound the memory of center-density estimation | Vote in blocks of 64 candidate centers using separate x and y comparisons instead of a full n by n by 2 displacement tensor. |+| 45 | Resolve tied crop centers across blocks consistently | Retain the first maximum and reject degenerate boxes. Compared to exhaustive voting including a 513-point case. |+| 46 | Speed up exact overlap suppression | Reject disjoint boxes before arithmetic and cache accepted box areas. Greedy score order, strict IoU threshold and output cap are preserved. |+| 47 | Make repeated guided merges geometrically idempotent | Translate extra boxes and landmarks into fresh records. Repeated merges leave inputs untouched and reproduce the same detections. |+| 48 | Prevent checkpoint A from supplying checkpoint B's first convolution | Store the packed stem inside each checkpoint's own tensor storage. Alternating two distinct stems matches isolated CLI processes bitwise. |+| 49 | Move first-frame weight permutation off the inference path | Transpose the stem at initialization using the existing checked packer. Single-model output matches the baseline on 15 fixture inputs. |+| 50 | Isolate decryption state between native handles | Pass the license key down the initialization call chain; opening with a key no longer authorizes a subsequent keyless open. Checked valid, wrong and absent keys. |+| 51 | Keep model initialization transactional after stem packing | A failed stem allocation follows existing rollback; the allocation harness covers 453 injected failure points and 100 successful cycles. |+| 52 | Eliminate the ConvNeXt skip-connection copy | Read each original activation until its final output element is written. Verified native embedding bytes. |+| 53 | Bound shared forward scratch from tensor lifetimes | Size for the maximum of the ConvNeXt and XCA layouts instead of reserving 2,097,152 floats. Largest ConvNeXt block needs 140,336 floats. |+| 54 | Bound the main activation buffer by actual stage products | The largest HW times C is 784 times 32 rather than 784 times 192. Both static arrays together fall from 8,990,720 to 661,696 bytes; these are reserved bytes, not measured RSS. |++## Local paired timings++One pinned x86 Linux CPU, one BLAS thread, seven alternating pairs, median CPU time in ms. Gallery input is synthetic and repeated enrollment is fixed. The vectorized reference performs fresh normalization and stable full sorting for each batch. Enrollment setup is excluded from the reusable gallery measurement. The sampler comparison includes reading the same generated index and checking identical ordered output.++| Operation | Reference | New |+|---|---:|---:|+| Top 5 for 16 queries against 4,096 rows | 15.513 | 5.019 |+| Sample 2,000 pairs from 60,000 index records | 378.457 | 34.348 |+| Merge 32 sparse scored boxes | 0.477 | 0.029 |+| Guided crop, 32 eligible centers | 0.068 | 0.038 |+| Guided crop, one eligible center | 0.0132 | 0.00151 |+| Repeated rectangle geometry, 1920 by 1080 | 0.00683 | 0.00010 |++Native CLI comparison on 15 repository fixture images resized to 112 by 112 used identical GCC x86-64-v3 flags. Original and updated outputs, including the encrypted-load variant, matched byte for byte. Nine warmed paired runs measured 3.177 and 3.158 ms per embedding including local pipe transfer, too close to claim a meaningful forward-pass speedup. AddressSanitizer and UndefinedBehaviorSanitizer completed the input set. LeakSanitizer cannot enumerate threads under ptrace here; the allocation rollback test was run separately.++An ordinary pair of float32 vectors took 4.57 versus 4.44 microseconds for scalar SDK cosine, seven alternating runs of 5,000 calls. The important change is the wider numerical domain. The normalized gallery costs eight bytes per enrolled component (16 MiB for 4,096 rows of 512) and needs rebuilding after enrollment changes.++## Run the checks++Use matching compiler flags for the library and CLI when comparing float bytes.++```sh+make check+PYTHONPATH=python OPENBLAS_NUM_THREADS=1 python tests/test_math_pipeline.py+PYTHONPATH=python:docker python tests/test_compare_formats.py+python tests/test_verification_thresholds.py+python tests/verify_checkpoint_isolation.py /path/to/libfacex.so /path/to/facex-cli /path/to/edgeface.bin+python training/scripts/verification_curve.py calibration.npz --far 0.001 --holdout evaluation.npz+```++Both NPZ inputs to the verification tool contain equal-length arrays named scores and same. The independent-pair model is required for the binomial confidence bound. No population FAR, calibrated access threshold or production latency is claimed from the synthetic or fixture tests.diff --git a/python/README.md b/python/README.mdindex 0a3db14..90813cc 100644--- a/python/README.md+++ b/python/README.md@@ -188,3 +188,26 @@ master. Example inside the REST container:```shgunicorn --preload --worker-class sync --workers 4 --bind 0.0.0.0:8080 preloaded:app```++### Exact gallery search and enrollment++Use a row per identity and keep the row to identity mapping with the matrix.+The gallery owns a normalized float64 copy. Rebuild it when enrollment changes.++```python+from facex import Gallery, enrollment_template++template, agreement = enrollment_template(views, weights=qualities)+gallery = Gallery(enrollment_rows)+indices, scores = gallery.search(query_rows, k=5)+decisions = gallery.identify(query_rows, min_score=calibrated_score,+ min_margin=calibrated_margin)+```++A decision of -1 means abstention. A margin requires two enrollment rows.+Equal best scores always abstain. The optional medoid mode selects an actual+enrolled view. Agreement ranges from zero to one and measures directional+consistency. Calibrate decision thresholds on separate data for each checkpoint.++The REST compare endpoint accepts a numeric array or the little-endian+float32 Base64 string returned by the compact detect endpoint for either input.diff --git a/python/facex/__init__.py b/python/facex/__init__.pyindex 35a20bf..ed24873 100644--- a/python/facex/__init__.py+++ b/python/facex/__init__.py@@ -10,5 +10,7 @@ Usage:from facex.core import FaceX, similarity+from facex.gallery import Gallery, enrollment_template+__version__ = "0.1.0"-__all__ = ["FaceX", "similarity"]+__all__ = ["FaceX", "Gallery", "enrollment_template", "similarity"]diff --git a/python/facex/core.py b/python/facex/core.pyindex 203589b..0f6ae2e 100644--- a/python/facex/core.py+++ b/python/facex/core.py@@ -4,6 +4,7 @@ FaceX core module — ctypes binding with subprocess fallback.import ctypesimport ctypes.util+import mathimport osimport platformimport struct@@ -179,17 +180,21 @@ def similarity(emb1: np.ndarray, emb2: np.ndarray) -> float:Returns:Cosine similarity in [-1, 1]. Values > 0.3 indicate same person."""- emb1 = np.asarray(emb1, dtype=np.float32).ravel()- emb2 = np.asarray(emb2, dtype=np.float32).ravel()- if emb1.shape[0] != EMBEDDING_DIM or emb2.shape[0] != EMBEDDING_DIM:- raise ValueError(f"Embeddings must be {EMBEDDING_DIM}-dim, "- f"got {emb1.shape[0]} and {emb2.shape[0]}")- dot = np.dot(emb1, emb2)- norm1 = np.linalg.norm(emb1)- norm2 = np.linalg.norm(emb2)- if norm1 < 1e-9 or norm2 < 1e-9:- return 0.0- return float(dot / (norm1 * norm2))+ vectors = []+ for embedding in (emb1, emb2):+ raw = np.asarray(embedding)+ if raw.size != EMBEDDING_DIM or raw.dtype.kind not in "iuf":+ raise ValueError("Expected 512 real embedding components")+ if raw.dtype != np.float32:+ with np.errstate(over="ignore"):+ raw = raw.astype(np.float32)+ vectors.append(raw.ravel().astype(np.float64))+ a, b = vectors+ aa, bb = float(np.dot(a, a)), float(np.dot(b, b))+ if not (math.isfinite(aa) and math.isfinite(bb)):+ raise ValueError("Embedding contains a nonfinite float32 value")+ norm = math.sqrt(aa * bb)+ return min(1., max(-1., float(np.dot(a, b)) / norm)) if norm else 0.# ---------------------------------------------------------------------------diff --git a/python/facex/gallery.py b/python/facex/gallery.pynew file mode 100644index 0000000..42f6ca3--- /dev/null+++ b/python/facex/gallery.py@@ -0,0 +1,97 @@+"""Exact cosine search against a fixed enrollment matrix."""+import operator++import numpy as np++from .core import EMBEDDING_DIM+++def _unit_rows(values):+ raw = np.asarray(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)+ if not np.isfinite(rows).all():+ raise ValueError("Nonfinite embedding")+ norms = np.linalg.norm(rows, axis=1, keepdims=True)+ np.divide(rows, norms, out=rows, where=norms != 0)+ return rows+++class Gallery:+ """Enrollment row number is the stable ID. Equal scores prefer the earlier row."""+ def __init__(self, embeddings):+ self._rows = _unit_rows(embeddings)+ if not len(self._rows):+ raise ValueError("Empty enrollment matrix")+ if not np.all(np.any(self._rows, axis=1)):+ raise ValueError("Enrollment vectors must have a direction")++ def search(self, queries, k=1):+ """Return ID and cosine matrices of shape (query count, k)."""+ 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)+ # Bound temporary score rows independently of the submitted batch size.+ block = max(1, (1 << 20) // (8 * len(self._rows)))+ for start in range(0, len(queries), block):+ values = queries[start:start + block] @ self._rows.T+ np.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]+ return ids, scores++ def identify(self, queries, *, min_score, min_margin):+ """Return enrollment row IDs, or -1 when score or separation is insufficient.++ Thresholds here are inclusive. Equal best scores always require abstention.+ Use one row per identity when interpreting margins as identity separation.+ """+ if not -1 <= min_score <= 1 or not 0 <= min_margin <= 2:+ raise ValueError("Invalid cosine score or margin threshold")+ ids, values = self.search(queries, min(2, len(self._rows)))+ accepted = (values[:, 0] >= min_score) & np.any(np.asarray(queries, dtype=np.float32), axis=1)+ if values.shape[1] == 2:+ gap = values[:, 0] - values[:, 1]+ accepted &= (gap > 0) & (gap >= min_margin)+ elif min_margin > 0:+ accepted[:] = False+ return np.where(accepted, ids[:, 0], -1)+++def enrollment_template(embeddings, weights=None, *, mode="mean"):+ """Combine views of one identity. Return a unit vector and directional agreement.++ The medoid maximizes weighted cosine similarity to all included views.+ Agreement is the resultant length on the unit sphere and is not a probability.+ """+ rows = _unit_rows(embeddings)+ if not len(rows) or mode not in ("mean", "medoid"):+ raise ValueError("Expected at least one view and mean or medoid mode")+ weight = np.ones(len(rows)) if weights is None else np.asarray(weights, dtype=np.float64)+ if weight.shape != (len(rows),) or not np.isfinite(weight).all() or np.any(weight < 0):+ raise ValueError("Expected one finite nonnegative weight per view")+ usable = np.any(rows, axis=1) & (weight > 0)+ if not usable.any():+ raise ValueError("No usable enrollment view")+ rows, weight = rows[usable], weight[usable]+ weight = weight / weight.max()+ resultant = (weight / weight.sum()) @ rows+ length = np.linalg.norm(resultant)+ if length <= 8 * np.finfo(np.float64).eps:+ raise ValueError("Views have no consistent direction")+ vector = resultant / length if mode == "mean" else rows[np.argmax(rows @ resultant)]+ return vector.astype(np.float32), float(min(length, 1.))diff --git a/python/facex/yunet.py b/python/facex/yunet.pyindex a4d119f..5ec8424 100644--- a/python/facex/yunet.py+++ b/python/facex/yunet.py@@ -1,16 +1,30 @@"""Prepare the rectangular input used by the native YuNet detector."""+from functools import lru_cache+import math+import numpy as npfrom PIL import Image+@lru_cache(maxsize=256)def rectangle_shape(w, h, *, side=640):if min(w, h) <= 0:raise ValueError("Image dimensions must be positive")if side not in (448, 640, 800):raise ValueError("Unsupported detector pixel budget")cells = (side // 32) ** 2- scale = min(2 * side / max(w, h), max(- min(32 * cols / w, 32 * (cells // cols) / h) for cols in range(1, 2 * side // 32 + 1)))+ # Width capacity increases with cols and height capacity decreases.+ limit = 2 * side // 32+ lo, hi = 1, limit+ while lo < hi:+ mid = (lo + hi) // 2+ if mid * h < (cells // mid) * w:+ lo = mid + 1+ else:+ hi = mid+ def capacity(cols):+ return min(32 * cols / w, 32 * (cells // cols) / h)+ scale = min(2 * side / max(w, h), max(capacity(lo), capacity(max(1, lo - 1))))rw, rh = max(1, round(w * scale)), max(1, round(h * scale))return rw, rh, (rw + 31) // 32 * 32, (rh + 31) // 32 * 32@@ -38,33 +52,49 @@ def guided_crop(faces, w, h):centers = []for f in faces:l, t, r, b = f["bbox"]- if np.sqrt((r-l)*(b-t))*320/max(w,h) < 20 and f["score"] < .85:+ if f["score"] < .85 and math.sqrt(max(0., (r-l)*(b-t)))*320/max(w,h) < 20 and r > l and b > t:centers.append(((l+r)/2, (t+b)/2))if not centers:return None- centers = np.asarray(centers)- delta = np.abs(centers[:, None] - centers)- counts = ((delta[:,:,0] <= w/4) & (delta[:,:,1] <= h/4)).sum(1)- cx, cy = centers[np.argmax(counts)]+ if len(centers) > 1:+ points = np.asarray(centers)+ xs, ys = points.T+ best = 0+ # Bounded scratch even for a large caller supplied candidate list.+ for start in range(0, len(points), 64):+ rows = points[start:start + 64]+ counts = ((np.abs(rows[:, :1] - xs) <= w/4) &+ (np.abs(rows[:, 1:] - ys) <= h/4)).sum(axis=1)+ i = int(np.argmax(counts))+ if counts[i] > best:+ best = counts[i]+ center = centers[start + i]+ else:+ center = centers[0]+ cx, cy = centercw, ch = max(1,w//2), max(1,h//2)- return int(np.clip(cx-cw/2,0,w-cw)), int(np.clip(cy-ch/2,0,h-ch)), cw, ch+ return int(min(max(cx-cw/2,0),w-cw)), int(min(max(cy-ch/2,0),h-ch)), cw, chdef merge_faces(base, extra, x, y):+ translated = []for f in extra:l,t,r,b = f["bbox"]- f["bbox"] = (x+l,y+t,x+r,y+b)- f["keypoints"] = [(x+kx,y+ky) for kx,ky in f["keypoints"]]- kept = []- for f in sorted(base + extra, key=lambda face: -face["score"]):+ translated.append(dict(f, bbox=(x+l,y+t,x+r,y+b),+ keypoints=[(x+kx,y+ky) for kx,ky in f["keypoints"]]))+ kept, regions = [], []+ for f in sorted(base + translated, key=lambda face: -face["score"]):l,t,r,b = f["bbox"]- for prior in kept:- pl,pt,pr,pb = prior["bbox"]- inter = max(0,min(r,pr)-max(l,pl))*max(0,min(b,pb)-max(t,pt))- if inter > .4*((r-l)*(b-t)+(pr-pl)*(pb-pt)-inter):+ area = (r-l)*(b-t)+ for pl,pt,pr,pb,previous_area in regions:+ if r <= pl or pr <= l or b <= pt or pb <= t:+ continue+ inter = (min(r,pr)-max(l,pl))*(min(b,pb)-max(t,pt))+ if inter > .4*(area + previous_area - inter):breakelse:kept.append(f)+ regions.append((l,t,r,b,area))if len(kept) == 32:breakreturn keptdiff --git a/src/edgeface_engine.c b/src/edgeface_engine.cindex e9b58f4..02944ff 100644--- a/src/edgeface_engine.c+++ b/src/edgeface_engine.c@@ -68,9 +68,7 @@ typedef struct {PackedFP32* fp; /* array, indexed same as tensors */} Weights;-static const char* g_license_key = NULL;--static int load_weights(const char* path, Weights* w) {+static int load_weights(const char* path, Weights* w, const char* license_key) {FILE* f = fopen(path, "rb");if (!f) return -1;@@ -88,8 +86,8 @@ static int load_weights(const char* path, Weights* w) {size_t size = w->raw_size;#ifndef NO_CRYPTOif (size >= 20 && memcmp(payload, "EFXE", 4) == 0) {- if (!g_license_key || !*g_license_key) return -3;- int rc = weight_decrypt_inplace(payload, size, g_license_key);+ if (!license_key || !*license_key) return -3;+ int rc = weight_decrypt_inplace(payload, size, license_key);if (rc) return rc;payload += 20;size -= 20;@@ -612,13 +610,12 @@ void convnext_block(float* x_hwc, int H, int W, int C,const PackedFP32* fp2, const PackedFP32* fp3){int HW = H * W;- float* residual = tmp;- float* dw_out = residual + HW * C;+ /* The skip input stays intact until its own final output element is written. */+ const float* residual = x_hwc;+ float* dw_out = tmp;float* t1 = dw_out + HW * C;float* t2 = t1 + HW * rank;- memcpy(residual, x_hwc, (size_t)HW * C * sizeof(float));-/* DW Conv: output to dw_out, then use dw_out for LN+MLP (avoids memcpy!) */depthwise_conv_nxn_hwc_fp32(x_hwc, H, W, C, dw_w, dw_b, K, dw_out);/* No memcpy — use dw_out directly for subsequent ops */@@ -678,28 +675,17 @@ static void edgeface_forward(const float* input_chw, /* [3, 112, 112] */{_g_weights = weights; /* enable INT8 lookup in matmul_wp *//* Static workspace — avoids malloc overhead on every call */- static float work[2 * 1024 * 1024]; /* 8MB workspace */- static float x_buf[28 * 28 * 192]; /* largest: 784 positions × 192 channels */+ /* Stage zero has the largest ConvNeXt scratch: HW * (C + rank + hidden).+ * The largest XCA attention layout at stage one needs 111960 floats. */+ static float work[784 * (32 + 19 + 128)];+ static float x_buf[784 * 32];float* x = x_buf;/* === STEM: Conv 3→32 4×4 s4 → output directly in HWC === */{- const float* sw = W(0); /* [32, 3, 4, 4] OIHW */- const float* sb = W(1); /* [32] */-- /* Pre-rearrange weights from [co, ci, ky, kx] to [ci, ky, kx, co] (contiguous per co).- * This converts strided gather (stride=48) to contiguous load (1 AVX2 op). */- static float sw_rearr[3 * 4 * 4 * 32]; /* 6KB — fits in L1 */- static int sw_done = 0;- if (!sw_done) {- for (int ci = 0; ci < 3; ci++)- for (int ky = 0; ky < 4; ky++)- for (int kx = 0; kx < 4; kx++)- for (int co = 0; co < 32; co++)- sw_rearr[((ci*16 + ky*4 + kx)*32) + co] = sw[(co*3+ci)*16 + ky*4+kx];- sw_done = 1;- }+ const float* sw_rearr = W(0);+ const float* sb = W(1);for (int oy = 0; oy < 28; oy++)for (int ox = 0; ox < 28; ox++) {@@ -970,9 +956,9 @@ static void release_weights(Weights* w) {memset(w, 0, sizeof(*w));}-static int engine_init(const char* weights_path, Weights* weights) {+static int engine_init(const char* weights_path, Weights* weights, const char* license_key) {memset(weights, 0, sizeof(*weights));- if (load_weights(weights_path, weights) != 0) {+ if (load_weights(weights_path, weights, license_key) != 0) {fprintf(stderr, "Failed to load %s\n", weights_path);goto fail;}@@ -1199,7 +1185,8 @@ static int engine_init(const char* weights_path, Weights* weights) {}/* Reorder downsample conv weights: OIHW [Cout,Cin,K,K] → [Cin*KK, Cout] for AVX2 */- if (reorder_conv_weights(weights->tensors[42], 64, 32, 4) ||+ if (reorder_conv_weights(weights->tensors[0], 32, 3, 16) ||+ reorder_conv_weights(weights->tensors[42], 64, 32, 4) ||reorder_conv_weights(weights->tensors[103], 100, 64, 4) ||reorder_conv_weights(weights->tensors[223], 192, 100, 4)) goto fail;@@ -1247,20 +1234,21 @@ fail:/* ============ Main ============ */#ifndef FACEX_LIBint main(int argc, char** argv) {+ const char* license_key = NULL;const char* weights_path = "data/edgeface_xs_fp32.bin";if (argc > 1) weights_path = argv[1];/* Parse --license KEY from args or LICENSE_KEY env */for (int i = 1; i < argc - 1; i++) {if (strcmp(argv[i], "--license") == 0) {- g_license_key = argv[i + 1];+ license_key = argv[i + 1];break;}}- if (!g_license_key) g_license_key = getenv("LICENSE_KEY");+ if (!license_key) license_key = getenv("LICENSE_KEY");Weights weights;- if (engine_init(weights_path, &weights) != 0) {+ if (engine_init(weights_path, &weights, license_key) != 0) {fprintf(stderr, "Failed to load %s\n", weights_path);return 1;}diff --git a/src/facex.c b/src/facex.cindex d9c07ed..eecd940 100644--- a/src/facex.c+++ b/src/facex.c@@ -28,8 +28,6 @@ struct FaceX {};FaceX* facex_init(const char* embed_weights, const char* detect_weights, const char* license_key) {- if (license_key) g_license_key = license_key;-FaceX* fx = (FaceX*)calloc(1, sizeof(FaceX));if (!fx) return NULL;@@ -40,7 +38,7 @@ FaceX* facex_init(const char* embed_weights, const char* detect_weights, const creturn NULL;}}- if (embed_weights && engine_init(embed_weights, &fx->embed_weights) != 0) {+ if (embed_weights && engine_init(embed_weights, &fx->embed_weights, license_key) != 0) {if (fx->detector) detect_free(fx->detector);free(fx);return NULL;diff --git a/tests/test_compare_formats.py b/tests/test_compare_formats.pynew file mode 100644index 0000000..6d0eb61--- /dev/null+++ b/tests/test_compare_formats.py@@ -0,0 +1,25 @@+import base64+import unittest++import numpy as np+import server+++class CompareTest(unittest.TestCase):+ def test_round_trip(self):+ client = server.app.test_client()+ rng = np.random.default_rng(91)+ a,b = rng.normal(size=(2,512)).astype("<f4")+ def enc(v):+ return base64.b64encode(v).decode("ascii")+ expected = client.post("/compare",json=dict(emb1=a.tolist(),emb2=b.tolist()))+ self.assertEqual(expected.status_code,200)+ for x in (enc(a), a.tolist()):+ for y in (enc(b), b.tolist()):+ self.assertEqual(client.post("/compare",json=dict(emb1=x,emb2=y)).json,expected.json)+ for value in ("!" * 2732, "A" * 2732, [0]*511, [False]*512, [float("nan")]*512):+ self.assertEqual(client.post("/compare",json=dict(emb1=value,emb2=enc(a))).status_code,400)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_math_pipeline.py b/tests/test_math_pipeline.pynew file mode 100644index 0000000..57da2ff--- /dev/null+++ b/tests/test_math_pipeline.py@@ -0,0 +1,183 @@+"""Independent numerical references for search, verification and guided geometry."""+import copy+from pathlib import Path+import sys+import tempfile+import unittest++import numpy as np++from facex import Gallery, enrollment_template, similarity+from facex.yunet import rectangle_shape, guided_crop, merge_faces++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "training/scripts"))+from pair_sampling import INDEX_RECORD, sample_index_pairs+from verification_curve import evaluate_threshold, verification_curve+++class MathPipelineTest(unittest.TestCase):+ def test_scalar(self):+ z = np.zeros(512, dtype="f")+ for v in (np.finfo("f").max, np.finfo("f").tiny, np.nextafter(np.float32(0), np.float32(1))):+ a = np.full_like(z, v)+ self.assertEqual(similarity(a, a), 1)+ self.assertEqual(similarity(a, -a), -1)+ self.assertEqual(similarity(a, z), 0)+ for invalid in ([float("nan")]*512, [float("inf")]*512, [1]*511, ["1"]*512):+ with self.assertRaises(ValueError):+ similarity(z, invalid)++ def test_gallery(self):+ rng = np.random.default_rng(51)+ rows = rng.normal(size=(513, 512)).astype("f")+ rows[1:8] = rows[0]+ queries = rows[:257].copy()+ queries[1] = 0+ gallery = Gallery(rows)+ base = rows.astype("d")+ base /= np.linalg.norm(base, axis=1)[:, None]+ for k in (1, 4, 513):+ ids, values = gallery.search(queries, k)+ for q, found, scores in zip(queries, ids, values):+ q = q.astype("d")+ ref = np.clip(base @ (q / np.linalg.norm(q) if q.any() else q), -1, 1)+ np.testing.assert_array_equal(found, np.argsort(-ref, kind="stable")[:k])+ np.testing.assert_allclose(scores, ref[found], atol=2e-14)+ self.assertEqual(gallery.search(queries[:0])[0].shape, (0, 1))+ rows[:] = 0+ self.assertEqual(gallery.search(queries[:1])[0][0, 0], 0)+ with self.assertRaises(ValueError):+ gallery.search(queries, 514)+ with self.assertRaises(ValueError):+ Gallery(np.zeros((1,512)))++ def test_identify(self):+ a,b = np.eye(2,512)+ gallery = Gallery([a,b])+ ids = gallery.identify([a,b,a+b,-a,a*0], min_score=.3, min_margin=.1)+ np.testing.assert_array_equal(ids,[0,1,-1,-1,-1])+ self.assertEqual(Gallery([a,a]).identify([a], min_score=0, min_margin=0)[0],-1)+ self.assertEqual(Gallery([a]).identify([a], min_score=1, min_margin=.1)[0],-1)++ def test_enrollment(self):+ rng = np.random.default_rng(82)+ rows = rng.normal(size=(17,512)).astype("f")+ units = rows.astype("d")+ units /= np.linalg.norm(units,axis=1)[:,None]+ weights = rng.uniform(0,1,17)+ medoid = np.argmax((units @ units.T) @ weights)+ for scale in (1.,1e200,1e-200):+ result, coherence = enrollment_template(rows,weights*scale,mode="medoid")+ np.testing.assert_array_equal(result,units[medoid].astype("f"))+ self.assertAlmostEqual(coherence,np.linalg.norm(np.average(units,axis=0,weights=weights)))+ pooled, _ = enrollment_template([rows[0],rows[1],rows[2]*0],[1,0,1])+ np.testing.assert_array_equal(pooled,units[0].astype("f"))+ with self.assertRaises(ValueError):+ enrollment_template([rows[0],-rows[0]])++ def test_verification(self):+ rng = np.random.default_rng(126)+ for _ in range(100):+ a = rng.integers(-4, 5, 23)+ b = rng.integers(-4, 5, 29)+ d = a[:, None] - b+ expected = (np.mean(d > 0) + .5*np.mean(d == 0))+ for target in (0, .1, 1):+ out = verification_curve(np.r_[a,b], np.r_[np.ones(len(a)),np.zeros(len(b))], target)+ self.assertAlmostEqual(out["auc"], expected)+ self.assertLessEqual(out["far"], target)+ candidates = [(sum(a >= t), -sum(b >= t)) for t in range(-4, 6)+ if np.mean(b >= t) <= target]+ self.assertEqual((out["true_accepts"], -out["false_accepts"]), max(candidates))+ self.assertAlmostEqual(out["far_resolution"], 1/len(b))+ for pos, neg, eer in (([1], [0], 0), ([0], [1], 1), ([1], [1], .5)):+ out = verification_curve(pos+neg, [1,0], 0)+ self.assertAlmostEqual(out["interpolated_eer"], eer)+ for s, labels in (([1,2],[0,0]), ([np.nan,1],[0,1]), ([1,2],[1,2])):+ with self.assertRaises(ValueError):+ verification_curve(s, labels, 0)++ def test_frozen_threshold(self):+ for t, fp, fn in ((None,0,2), (.5,1,1), (1.,0,1)):+ out = evaluate_threshold([1,.25,.5,0], [1,1,0,0], t)+ self.assertEqual((out["false_accepts"], out["false_rejects"]), (fp,fn))+ self.assertEqual(out["balanced_accuracy"], 1-(fp+fn)/4)+ if not fp:+ self.assertAlmostEqual((1-out["zero_false_accept_upper95"])**2,.05)++ def test_canvas(self):+ rng = np.random.default_rng(427)+ sizes = [(1, 100000), (100000, 1), (640, 640), (1,1)]+ sizes.extend(map(tuple,rng.integers(1, 12000, (3000,2)).tolist()))+ for side in (448,640,800):+ for w,h in sizes:+ cells = (side // 32)**2+ scale = min(2*side/max(w,h), max(min(32*c/w, 32*(cells//c)/h)+ for c in range(1,2*side//32+1)))+ rw,rh = max(1,round(w*scale)), max(1,round(h*scale))+ self.assertEqual(rectangle_shape(w,h,side=side),+ (rw,rh,(rw+31)//32*32,(rh+31)//32*32))++ def test_crop(self):+ rng = np.random.default_rng(425)+ for n in (0,1,2,32,64,65,513):+ xy = rng.integers(0, 1000, (n,2))+ faces = [dict(score=.5, bbox=(x-2,y-2,x+2,y+2)) for x,y in xy]+ expected = None+ if n:+ votes = (np.abs(xy[:,None]-xy) <= 250).all(axis=2).sum(axis=1)+ expected = tuple(np.clip(xy[votes.argmax()] - 250,0,500)) + (500,500)+ self.assertEqual(guided_crop(faces,1000,1000),expected)+ self.assertIsNone(guided_crop([dict(score=.1,bbox=(3,5,2,1))],640,640))++ def test_merge(self):+ rng = np.random.default_rng(582)+ for spacing in (12, 1200):+ boxes = rng.integers(0,spacing,(80,2)).tolist()+ faces = [dict(bbox=(x,y,x+12,y+18),score=i%5, keypoints=[(x,y)])+ for i,(x,y) in enumerate(boxes)]+ base, extra = faces[:40], faces[40:]+ original = copy.deepcopy(extra)+ expected = []+ for i, f in sorted(enumerate(faces),key=lambda p:-p[1]["score"]):+ x,y,r,b = f["bbox"]+ if i >= 40:+ x,y,r,b = x+3,y+2,r+3,b+2+ if all((lambda area: area <= .4*(432-area))(+ max(0,min(r,pr)-max(x,px))*max(0,min(b,pb)-max(y,py)))+ for px,py,pr,pb in expected):+ expected.append((x,y,r,b))+ if len(expected) == 32:+ break+ for _ in range(2):+ result = merge_faces(base,extra,3,2)+ self.assertEqual([f["bbox"] for f in result],expected)+ self.assertEqual(extra,original)+ self.assertTrue(all(f["keypoints"][0] == f["bbox"][:2] for f in result))++ def test_sampling(self):+ labels = np.random.default_rng(98).integers(0,120,3000)+ data = np.zeros(len(labels),dtype=INDEX_RECORD)+ data["label"] = labels+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory)/"index.bin"+ data.tofile(path)+ pairs = sample_index_pairs(path,87,123)+ rng = np.random.default_rng(87)+ groups = {}+ for i, label in enumerate(labels):+ groups.setdefault(label,[]).append(i)+ multi = [c for c in groups if len(groups[c]) >= 2]+ ref = [(*rng.choice(groups[c],2,replace=False),True) for c in rng.choice(multi,123)]+ for _ in range(123):+ c,d = rng.choice(multi,2,replace=False)+ ref.append((rng.choice(groups[c]),rng.choice(groups[d]),False))+ rng.shuffle(ref)+ self.assertEqual(pairs,ref)+ path.write_bytes(b"partial")+ with self.assertRaises(ValueError):+ sample_index_pairs(path,87,123)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_verification_thresholds.py b/tests/test_verification_thresholds.pyindex c78ca32..3f4d139 100644--- a/tests/test_verification_thresholds.py+++ b/tests/test_verification_thresholds.py@@ -26,6 +26,11 @@ def exhaustive(scores, same, grid, n_folds):class TestThresholds(unittest.TestCase):+ def test_invalid_grid_and_folds(self):+ for grid, count in (([], 2), ([1, 0], 2), ([float("nan")], 2), ([0], 1), ([0], 3)):+ with self.assertRaises(ValueError):+ fold_metrics([0, 1], [False, True], grid, count)+def test_reference(self):rng = np.random.default_rng(275)for grid in (np.linspace(0, 1, 401), np.linspace(-0.5, 1, 601)):diff --git a/tests/verify_checkpoint_isolation.py b/tests/verify_checkpoint_isolation.pynew file mode 100644index 0000000..5aa025f--- /dev/null+++ b/tests/verify_checkpoint_isolation.py@@ -0,0 +1,49 @@+"""Compare alternating native handles to freshly started single-checkpoint CLI processes."""+import argparse+import ctypes+from pathlib import Path+import subprocess+import tempfile++import numpy as np+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ for name in ("library", "cli", "weights"):+ parser.add_argument(name, type=Path)+ args = parser.parse_args()+ lib = ctypes.CDLL(str(args.library.resolve()))+ lib.facex_init.argtypes = [ctypes.c_char_p] * 3+ lib.facex_init.restype = ctypes.c_void_p+ lib.facex_free.argtypes = [ctypes.c_void_p]+ floats = ctypes.POINTER(ctypes.c_float)+ lib.facex_embed.argtypes = [ctypes.c_void_p, floats, floats]+ source = args.weights.read_bytes()+ assert source[:4] == b"EFXS" and int.from_bytes(source[8:12], "little") == 6144+ images = np.random.default_rng(518).uniform(-1,1,(4,112,112,3)).astype("f")+ with tempfile.TemporaryDirectory() as directory:+ variant = bytearray(source)+ np.frombuffer(variant, "<f4", 1536, 12)[:] *= -1+ alternate = Path(directory) / "alternate.bin"+ alternate.write_bytes(variant)+ paths = (args.weights, alternate)+ refs = [subprocess.check_output([str(args.cli.resolve()), str(p), "--server"],+ input=images.tobytes()) for p in paths]+ assert refs[0] != refs[1]+ handles = [lib.facex_init(bytes(p), None, None) for p in paths]+ assert all(handles)+ try:+ for i, image in enumerate(images):+ for j in (0, 1, 1, 0):+ out = np.empty(512, dtype="f")+ assert lib.facex_embed(handles[j], image.ctypes.data_as(floats),+ out.ctypes.data_as(floats)) == 0+ assert out.tobytes() == refs[j][i*2048:(i+1)*2048]+ finally:+ for handle in handles:+ lib.facex_free(handle)+++if __name__ == "__main__":+ main()diff --git a/training/scripts/eval_pairs.py b/training/scripts/eval_pairs.pyindex c6d2d6f..a1c691d 100644--- a/training/scripts/eval_pairs.py+++ b/training/scripts/eval_pairs.py@@ -16,8 +16,6 @@ Usage:"""import argparse-import io-import structimport timefrom pathlib import Path@@ -26,13 +24,14 @@ import torchfrom PIL import Imagefrom verification_thresholds import fold_metrics+from verification_curve import verification_curve+from pair_sampling import sample_index_pairsimport arch as arch_modulefrom model import MobileFaceNetfrom dataset import MS1MDatasetDATA_ROOT = Path("D:/apps/facex/training/data/ms1m")-INDEX = struct.Struct("<QII")SEED = 1337N_PAIRS_PER_TYPE = 3000 # 3000 same + 3000 diff = 6000 pairs totalN_FOLDS = 10@@ -40,41 +39,7 @@ N_FOLDS = 10def build_pairs(seed: int = SEED, n_per: int = N_PAIRS_PER_TYPE):"""Build a balanced list of (img_idx_a, img_idx_b, same_label) pairs."""- rng = np.random.default_rng(seed)- # We need quick lookup of all images per label. Walk the index once.- print("Building label -> images map...")- blob_path = DATA_ROOT / "blob.jpg.bin"- idx_path = DATA_ROOT / "index.bin"- idx_mm = np.memmap(idx_path, dtype=np.uint8, mode="r")- n = idx_mm.size // 16- labels = np.empty(n, dtype=np.int64)- for i in range(n):- _, _, lbl = INDEX.unpack(idx_mm[i * 16:(i + 1) * 16].tobytes())- labels[i] = lbl-- # Bucket images by label- by_label = {}- for i, lb in enumerate(labels.tolist()):- by_label.setdefault(lb, []).append(i)- multi = [lb for lb, ix in by_label.items() if len(ix) >= 2]- print(f"{n:,} images, {len(by_label):,} classes, {len(multi):,} with >=2 imgs")-- pairs = []- # same-pairs- same_classes = rng.choice(multi, size=n_per, replace=True)- for cls in same_classes:- ids = by_label[int(cls)]- i, j = rng.choice(ids, size=2, replace=False)- pairs.append((int(i), int(j), True))- # diff-pairs- for _ in range(n_per):- c1, c2 = rng.choice(multi, size=2, replace=False)- i = int(rng.choice(by_label[int(c1)]))- j = int(rng.choice(by_label[int(c2)]))- pairs.append((i, j, False))- rng.shuffle(pairs)- print(f"Built {len(pairs):,} pairs ({n_per:,} same / {n_per:,} diff)")- return pairs+ return sample_index_pairs(DATA_ROOT / "index.bin", seed, n_per)def load_image_chw(ds, idx, size: int = 112):@@ -136,6 +101,9 @@ def eval_one(arch_name: str, ckpt_path: str, pairs, ds, device: str):print(f" same: mean={same_sims.mean():.4f} std={same_sims.std():.4f}")print(f" diff: mean={diff_sims.mean():.4f} std={diff_sims.std():.4f}")print(f" separation gap: {same_sims.mean() - diff_sims.mean():.4f}")+ curve = verification_curve(sims, issame, target_far=0.001)+ print(f" empirical AUC {curve['auc']:.6f}, interpolated EER {curve['interpolated_eer']:.6f}, "+ f"TAR {curve['tar']:.6f} at {curve['false_accepts']}/{curve['negatives']} false accepts")stats = kfold_threshold(sims, issame)print(f" verification accuracy: {stats['acc_mean']*100:.2f}% "f"+/- {stats['acc_std']*100:.2f}% (thr={stats['thr_mean']:.3f})")diff --git a/training/scripts/pair_sampling.py b/training/scripts/pair_sampling.pynew file mode 100644index 0000000..f030f3b--- /dev/null+++ b/training/scripts/pair_sampling.py@@ -0,0 +1,34 @@+"""Seed-compatible balanced verification pairs from a mapped image index."""+from pathlib import Path++import numpy as np++INDEX_RECORD = np.dtype([("offset", "<u8"), ("size", "<u4"), ("label", "<u4")])+++def sample_index_pairs(path, seed, n_per):+ size = Path(path).stat().st_size+ if not size or size % INDEX_RECORD.itemsize:+ raise ValueError("Expected complete image index records")+ labels = np.memmap(path, dtype=INDEX_RECORD, mode="r")["label"]+ # Stable sorting preserves source order inside each class.+ order = np.argsort(labels, kind="stable")+ ordered = labels[order]+ starts = np.r_[0, 1 + np.flatnonzero(ordered[:-1] != ordered[1:])]+ ends = np.r_[starts[1:], len(order)]+ groups = np.flatnonzero(ends - starts >= 2)+ groups = groups[np.argsort(order[starts[groups]])]+ if len(groups) < 2 or n_per < 1:+ raise ValueError("Need two classes with two images each and a positive pair count")+ rng = np.random.default_rng(seed)+ pairs = []+ for g in rng.choice(groups, n_per):+ a, b = rng.choice(order[starts[g]:ends[g]], size=2, replace=False)+ pairs.append((int(a), int(b), True))+ for _ in range(n_per):+ g, h = rng.choice(groups, size=2, replace=False)+ a = rng.choice(order[starts[g]:ends[g]])+ b = rng.choice(order[starts[h]:ends[h]])+ pairs.append((int(a), int(b), False))+ rng.shuffle(pairs)+ return pairsdiff --git a/training/scripts/verification_curve.py b/training/scripts/verification_curve.pynew file mode 100644index 0000000..7b015c4--- /dev/null+++ b/training/scripts/verification_curve.py@@ -0,0 +1,71 @@+"""Empirical verification metrics from held-out, labeled pair scores."""+import argparse+import json+import math++import numpy as np+++def _pairs(scores, same):+ scores, same = np.asarray(scores), np.asarray(same)+ if scores.ndim != 1 or scores.shape != same.shape or scores.dtype.kind not in "iuf":+ raise ValueError("Expected equal length vectors of real scores and binary labels")+ if not np.isfinite(scores).all() or not np.isin(same, [0, 1]).all():+ raise ValueError("Invalid score or label")+ positives = int(np.count_nonzero(same))+ negatives = len(same) - positives+ if not positives or not negatives:+ raise ValueError("Need genuine and impostor pairs")+ return scores, same.astype(bool), positives, negatives+++def evaluate_threshold(scores, same, threshold):+ """Evaluate a frozen threshold on a separate set with independent pairs."""+ scores, same, positives, negatives = _pairs(scores, same)+ if threshold is not None and not math.isfinite(threshold):+ raise ValueError("Expected a finite threshold or None for reject all")+ accepted = scores >= threshold if threshold is not None else np.zeros_like(same)+ fp = int(np.count_nonzero(accepted & ~same))+ fn = int(np.count_nonzero(~accepted & same))+ return dict(false_accepts=fp, false_rejects=fn, far=fp/negatives, frr=fn/positives,+ balanced_accuracy=1 - .5 * (fp/negatives + fn/positives),+ negatives=negatives, positives=positives,+ zero_false_accept_upper95=-math.expm1(math.log(.05)/negatives) if fp == 0 else None)+++def verification_curve(scores, same, target_far):+ scores, same, positives, negatives = _pairs(scores, same)+ if not 0 <= target_far <= 1:+ raise ValueError("Expected target FAR between zero and one")+ order = np.argsort(scores, kind="stable")[::-1]+ ranked = scores[order]+ ends = np.r_[np.flatnonzero(ranked[1:] != ranked[:-1]), len(ranked)-1]+ tp = np.r_[0, np.cumsum(same[order], dtype=np.int64)[ends]]+ fp = np.r_[0, ends + 1 - tp[1:]]+ tar, far = tp / positives, fp / negatives+ auc = np.sum(np.diff(far) * (tar[1:] + tar[:-1]) * .5)+ valid = np.flatnonzero(far <= target_far)+ best = valid[np.argmax(tp[valid])]+ gap = far + tar - 1+ right = int(np.searchsorted(gap, 0))+ left = right - 1+ eer = far[left] + (far[right]-far[left]) * (-gap[left]) / (gap[right]-gap[left])+ return dict(auc=float(auc), interpolated_eer=float(eer),+ threshold=float(ranked[ends[best-1]]) if best else None,+ false_accepts=int(fp[best]), true_accepts=int(tp[best]),+ negatives=negatives, positives=positives, tar=float(tar[best]),+ far=float(far[best]), far_resolution=1 / negatives)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("pairs", help="NPZ file with scores and same arrays")+ parser.add_argument("--far", required=True, type=float)+ parser.add_argument("--holdout", help="Independent NPZ to evaluate at the frozen threshold")+ args = parser.parse_args()+ with np.load(args.pairs) as data:+ result = verification_curve(data["scores"], data["same"], args.far)+ if args.holdout:+ with np.load(args.holdout) as data:+ result["holdout"] = evaluate_threshold(data["scores"], data["same"], result["threshold"])+ print(json.dumps(result))diff --git a/training/scripts/verification_thresholds.py b/training/scripts/verification_thresholds.pyindex e03f302..bd57da0 100644--- a/training/scripts/verification_thresholds.py+++ b/training/scripts/verification_thresholds.py@@ -1,18 +1,28 @@"""Select thresholds on training folds using exact counts on a fixed grid."""+import operator+import numpy as npdef fold_metrics(scores, same, grid, n_folds):+ n_folds = operator.index(n_folds)scores = np.asarray(scores)same = np.asarray(same, dtype=bool)+ grid = np.asarray(grid)+ if scores.ndim != 1 or same.shape != scores.shape or not 2 <= n_folds <= len(scores):+ raise ValueError("Need equally sized score and label vectors and nonempty folds")+ if grid.ndim != 1 or not grid.size or not np.isfinite(grid).all() or np.any(grid[1:] < grid[:-1]):+ raise ValueError("Threshold grid must be finite, nonempty and nondecreasing")# Each score passes exactly the first 'passed' thresholds, including ties.# Use the same promotion as comparing a score array to one grid scalar.dtype = np.result_type(scores, grid[0])passed = np.searchsorted(grid.astype(dtype), scores.astype(dtype), side="right")passed[np.isnan(scores)] = 0counts = []- folds = np.array_split(np.arange(len(scores)), n_folds)+ width, extra = divmod(len(scores), n_folds)+ boundaries = [i * width + min(i, extra) for i in range(n_folds + 1)]+ folds = [slice(start, end) for start, end in zip(boundaries, boundaries[1:])]for indices in folds:labels = same[indices]bins = passed[indices]@@ -29,7 +39,7 @@ def fold_metrics(scores, same, grid, n_folds):threshold = grid[best] if training[best] > 0 else 0.0thresholds.append(threshold)if training[best] > 0:- accuracies.append(held_out[best] / len(indices))+ accuracies.append(held_out[best] / (indices.stop - indices.start))else:accuracies.append(((scores[indices] >= threshold) == same[indices]).mean())return accuracies, thresholds