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
Let YuNet keep smaller face boxes at calibrated confidence thresholds
Baurzhan Atynov92966539f96b
diff --git a/docker/server.py b/docker/server.pyindex 5ea3165..187e196 100644--- a/docker/server.py+++ b/docker/server.py@@ -32,6 +32,9 @@ DETECT_WEIGHTS = os.environ.get('DETECT_WEIGHTS', 'weights/yunet_fp32.bin')DETECT_SIZE = os.environ.get("FACEX_DETECT_SIZE", "640")if DETECT_SIZE not in ("640", "800"):raise ValueError("FACEX_DETECT_SIZE must be 640 or 800")+MIN_BOX_SIDE = int(os.environ.get("FACEX_MIN_BOX_SIDE", "16"))+if MIN_BOX_SIDE not in (8, 12, 16):+ raise ValueError("FACEX_MIN_BOX_SIDE must be 8, 12 or 16")DETECT_POLICY = "rectangle_bgr_800" if DETECT_SIZE == "800" else "rectangle_bgr"@@ -145,7 +148,8 @@ def detect():try:if _detector is None:engine = FaceX(embed_weights=EMBED_WEIGHTS, detect_weights=DETECT_WEIGHTS,- input_policy=DETECT_POLICY, license_key=os.environ.get("LICENSE_KEY"))+ input_policy=DETECT_POLICY, min_box_side=MIN_BOX_SIDE,+ license_key=os.environ.get("LICENSE_KEY"))if engine.backend != "ctypes":raise RuntimeError("Missing native FaceX library")_detector = enginediff --git a/docs/research/yunet_minimum_side.md b/docs/research/yunet_minimum_side.mdnew file mode 100644index 0000000..f6ee007--- /dev/null+++ b/docs/research/yunet_minimum_side.md@@ -0,0 +1,39 @@+# Does lowering the YuNet minimum box side help?++The earlier RGB ablation observed 17 additional small faces, with a paired 95% image bootstrap interval from −4 to +42. That result prompted this separate test of the current BGR detector.++Compare minimum predicted **width and height** of 16, 12 and 8 detector-canvas pixels, before NMS. The primary comparison is 8 versus 16 for the 640 BGR mode with recalibrated confidence. The 12-pixel cutoff and 800 mode are secondary. Count one-to-one matches against valid WIDER FACE validation boxes at IoU ≥0.50. Small faces have geometric mean side below 16 pixels after scaling the original long side to 320 pixels. This common annotation definition is distinct from the predicted-side cutoff.++For each size budget, compare (1) the same confidence threshold for every cutoff and (2) a threshold calibrated for each cutoff under the baseline count of unmatched predictions. Calibration maximizes small matches and then total matches. It uses 256 images from previously sampled sets. Evaluation uses all images outside the five named geometry, bottleneck, color and detail splits. Both modes use the same evaluation images. Calibration caps apply only on calibration data. Unmatched counts include detections on ignored annotations in this local protocol.++All modes keep BGR preprocessing, weights, NMS, landmark suppression and the 32-result cap fixed. One native forward pass supplies raw candidates per image and resolution. The replay is checked against separately compiled native implementations for each cutoff on every 83rd image. Paired percentile intervals use 4000 resamples of images. Intervals for secondary comparisons are descriptive and do not adjust for multiple comparisons.++## Reproduction++From a checkout containing ee217f5, with GCC, NumPy, Pillow, SciPy, YuNet 2023mar native weights and the two WIDER archives:++```sh+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_minimum.py yunet.bin WIDER_val.zip wider_face_split.zip --side 640+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_minimum.py yunet.bin WIDER_val.zip wider_face_split.zip --side 800+```++## Results++The 954 evaluation images contained 12730 valid faces, including 10935 small faces.++| Budget | Minimum side | Score | Total matches | Small matches | Unmatched |+|---|---:|---:|---:|---:|---:|+| 640 | 16 | 0.70 | 3437 | 1895 | 153 |+| 640 | 12 | 0.70 | 3965 | 2425 | 213 |+| 640 | 12 | 0.74 | 3848 | 2326 | 159 |+| 640 | 8 | 0.70 | 4316 | 2776 | 270 |+| 640 | 8 | 0.75 | 4064 | 2547 | 158 |+| 800 | 16 | 0.75 | 3932 | 2422 | 122 |+| 800 | 12 | 0.75 | 4354 | 2844 | 153 |+| 800 | 8 | 0.75 | 4516 | 3007 | 185 |++For the primary 640 comparison, lowering the minimum to 8 with calibrated score 0.75 gained 652 small matches (+34.4%, paired 95% interval +486 to +843). Small recall rose from 17.3% to 23.3%. Unmatched predictions increased by 5 (interval −20 to +33). At the same score 0.70 the size change alone gained 881 small matches but added 117 unmatched predictions. For minimum 12 with recalibration the gain was 431 (interval +317 to +567), with 6 additional unmatched predictions.++For budget 800 the original score 0.75 met the unmatched budget during calibration for both alternative minima. On evaluation, minimum 8 gained 585 small matches (interval +436 to +760) and added 63 unmatched detections (interval +40 to +89). This setting trades more false detections for recall. The earlier 17-face gain used RGB, different images and different thresholds. These results establish a benefit for the tested BGR pipeline and cannot isolate which of those changes explains the difference between studies.++The filter runs on detector predictions before suppression. It adds no network pass. Choose the minimum of 8 or 12 explicitly to enable it. The default remains 16. The native functions accept a minimum in detector pixels; the Python SDK and REST service expose the three evaluated choices. The 640 BGR policy automatically uses scores 0.75, 0.74 and 0.70 for sides 8, 12 and 16 respectively. All three use 0.75 for the 800 BGR policy. An explicit SDK score overrides the calibrated value. Recognition accuracy on the additionally detected tiny crops was not evaluated.diff --git a/include/detect.h b/include/detect.hindex 6d6b99a..5d88047 100644--- a/include/detect.h+++ b/include/detect.h@@ -83,6 +83,9 @@ void detect_set_score_threshold(Detect* det, float threshold);/* NMS IoU threshold (default 0.4). */void detect_set_nms_threshold(Detect* det, float threshold);+/* Minimum predicted width and height in detector pixels (default 16). */+void detect_set_min_box_side(Detect* det, int pixels);+#ifdef __cplusplus}#endifdiff --git a/include/facex.h b/include/facex.hindex e6cfbb4..057819f 100644--- a/include/facex.h+++ b/include/facex.h@@ -97,6 +97,9 @@ void facex_set_score_threshold(FaceX* fx, float threshold);/* Set NMS IoU threshold (default 0.4) */void facex_set_nms_threshold(FaceX* fx, float threshold);+/* Minimum predicted width and height in detector pixels (default 16). */+void facex_set_min_box_side(FaceX* fx, int pixels);+#ifdef __cplusplus}#endifdiff --git a/python/README.md b/python/README.mdindex 4aba421..0581264 100644--- a/python/README.md+++ b/python/README.md@@ -63,6 +63,13 @@ For small faces use `input_policy="rectangle_bgr_800"`. This raises the pixelbudget to 800² and uses a calibrated threshold of 0.75. The REST equivalent is`FACEX_DETECT_SIZE=800`; the default is 640.+For small faces in the 640 BGR mode, use `min_box_side=8` with+`input_policy="rectangle_bgr"`, or `FACEX_MIN_BOX_SIDE=8` in REST. This admits+predicted boxes with both sides at least eight detector pixels and selects a+score threshold of 0.75. The intermediate setting 12 selects 0.74, and the+default 16 selects 0.70. The 800 BGR mode uses 0.75 for all three sizes.+See [the minimum side comparison](../docs/research/yunet_minimum_side.md).+The Docker REST service uses the BGR rectangle policy for `POST /detect` and returnsup to 32 faces. Mount both weights at the paths above under `/app`, or set`EMBED_WEIGHTS` and `DETECT_WEIGHTS` to their paths inside the container.diff --git a/python/facex/core.py b/python/facex/core.pyindex f9a81ad..68312b4 100644--- a/python/facex/core.py+++ b/python/facex/core.py@@ -207,6 +207,7 @@ class FaceX:license_key: License key for encrypted weights (None for plain).score_threshold: Override the score threshold calibrated for the selected input policy.input_policy: Use "native", "rectangle" (RGB), or a YuNet BGR policy ("rectangle_bgr" or "rectangle_bgr_800").+ min_box_side: Minimum detector box side in pixels (8, 12 or 16).nms_threshold: NMS IoU threshold (default 0.4).max_faces: Maximum faces to detect per image (default 20)."""@@ -222,6 +223,7 @@ class FaceX:nms_threshold: float = 0.4,max_faces: int = MAX_FACES_DEFAULT,input_policy: str = "native",+ min_box_side: int = 16,):self._lib = Noneself._handle = None@@ -229,9 +231,15 @@ class FaceX:self._max_faces = max_facesif input_policy not in _POLICY_THRESHOLDS:raise ValueError("Unknown detector input policy")+ if min_box_side not in (8, 12, 16):+ raise ValueError("min_box_side must be 8, 12 or 16")+ self._min_box_side = min_box_sideself._input_policy = input_policyif score_threshold is None:- score_threshold = _POLICY_THRESHOLDS[input_policy]+ if input_policy == "rectangle_bgr":+ score_threshold = {8: 0.75, 12: 0.74, 16: 0.70}[min_box_side]+ else:+ score_threshold = _POLICY_THRESHOLDS[input_policy]self._score_threshold = score_thresholdself._nms_threshold = nms_threshold@@ -322,6 +330,12 @@ class FaceX:]self._lib.facex_detect_prepared.restype = ctypes.c_int+ if self._min_box_side != 16:+ if not hasattr(self._lib, "facex_set_min_box_side"):+ raise RuntimeError("Custom min_box_side requires an updated FaceX library")+ self._lib.facex_set_min_box_side.argtypes = [ctypes.c_void_p, ctypes.c_int]+ self._lib.facex_set_min_box_side.restype = None+# Init engineembed_b = self._embed_weights.encode() if self._embed_weights else Nonedetect_b = self._detect_weights.encode() if self._detect_weights else None@@ -332,6 +346,8 @@ class FaceX:self._lib = Noneraise RuntimeError("facex_init returned NULL — check weight paths")+ if self._min_box_side != 16:+ self._lib.facex_set_min_box_side(self._handle, self._min_box_side)self._lib.facex_set_score_threshold(self._handle, self._score_threshold)self._lib.facex_set_nms_threshold(self._handle, self._nms_threshold)@@ -375,6 +391,8 @@ class FaceX:if self._lib and self._handle:return self._detect_ctypes(image, w, h, mf)elif self._cli_path:+ if self._min_box_side != 16:+ raise RuntimeError("Custom min_box_side requires the native shared library")return self._detect_cli(image, w, h, mf)else:raise RuntimeError(diff --git a/src/detect.c b/src/detect.cindex 2783c97..fe58289 100644--- a/src/detect.c+++ b/src/detect.c@@ -28,6 +28,7 @@struct Detect {float score_threshold;float nms_threshold;+ int min_box_side;uint8_t* raw;size_t raw_len;float* tensors[DETECT_MAX_TENSORS];@@ -55,6 +56,7 @@ Detect* detect_init(const char* weights_path) {if (!weights_path) return NULL;Detect* det = (Detect*)calloc(1, sizeof(Detect));if (!det) return NULL;+ det->min_box_side = 16;det->score_threshold = DETECT_DEFAULT_SCORE_THRESHOLD;det->nms_threshold = DETECT_DEFAULT_NMS_THRESHOLD;@@ -478,7 +480,7 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,/* Filter degenerate boxes */float bw = candidates[nf].x2 - candidates[nf].x1;float bh = candidates[nf].y2 - candidates[nf].y1;- if (bw < 16 || bh < 16) continue; /* too small */+ if (bw < det->min_box_side || bh < det->min_box_side) continue;if (bw > width*0.95f || bh > height*0.95f) continue; /* too large */float aspect = bw / (bh + 1e-6f);if (aspect < 0.3f || aspect > 3.0f) continue; /* bad aspect ratio */@@ -541,3 +543,7 @@ void detect_set_score_threshold(Detect* det, float t) {void detect_set_nms_threshold(Detect* det, float t) {if(det) det->nms_threshold = t < 0 ? 0 : t > 1 ? 1 : t;}++void detect_set_min_box_side(Detect* det, int pixels) {+ if (det && pixels > 0) det->min_box_side = pixels;+}diff --git a/src/facex.c b/src/facex.cindex ebc8993..8253e29 100644--- a/src/facex.c+++ b/src/facex.c@@ -139,3 +139,7 @@ void facex_set_score_threshold(FaceX* fx, float t) {void facex_set_nms_threshold(FaceX* fx, float t) {if (fx && fx->detector) detect_set_nms_threshold(fx->detector, t);}++void facex_set_min_box_side(FaceX* fx, int pixels) {+ if (fx) detect_set_min_box_side(fx->detector, pixels);+}diff --git a/tests/bench_yunet_minimum.py b/tests/bench_yunet_minimum.pynew file mode 100644index 0000000..10d7066--- /dev/null+++ b/tests/bench_yunet_minimum.py@@ -0,0 +1,129 @@+"""Paired minimum-side ablation on images excluded from earlier FaceX quality splits."""+import argparse+import ctypes+import io+from pathlib import Path+import subprocess+import tempfile+from zipfile import ZipFile++import numpy as np+from PIL import Image+from bench_yunet_bottlenecks import ROOT, annotations, match, native_run, prepare_rectangle, replay, source_boxes++MINIMA = (16, 12, 8)+GRID = np.round(np.arange(.55, .971, .01), 2)+++def partition(labels):+ pool = set(labels)+ for seed, n in ((114, 640), (725, 128), (3519, 672), (9101, 384), (60177, 448)):+ group = np.random.default_rng(seed).choice(sorted(pool), n, replace=False)+ pool -= set(group)+ # Reuse previously seen images for calibration only. All remaining images+ # are held out from every previous named development and evaluation split.+ dev = np.random.default_rng(1702).choice(sorted(set(labels)-pool), 256, replace=False)+ return dev, sorted(pool)+++def build(tmp, minimum):+ src = subprocess.check_output(["git", "show", "ee217f5:src/detect.c"], cwd=ROOT, text=True)+ if minimum is None:+ a = src.index(" if (bw < 16")+ b = src.index(" candidates[nf].score", a)+ src = src[:a] + " if (bw <= 0 || bh <= 0) continue;\n" + src[b:]+ a = src.index(" if (nf > 1) nf = nms_sort")+ b = src.index(" if (nf > max_faces)", a)+ src = src[:a] + src[b:]+ else:+ src = src.replace("if (bw < 16 || bh < 16)", f"if (bw < {minimum} || bh < {minimum})")+ file = tmp / f"det{minimum}.c"+ so = file.with_suffix(".so")+ file.write_text(src)+ subprocess.run(["gcc", "-O3", "-march=native", "-fPIC", "-shared", "-I",+ str(ROOT/"include"), str(file), "-lm", "-o", str(so)], check=True)+ lib = ctypes.CDLL(str(so))+ lib.detect_init.restype = ctypes.c_void_p+ return lib+++def collect(engines, names, labels, photos, side):+ records = []+ for i, name in enumerate(names):+ image = np.asarray(Image.open(io.BytesIO(photos.read("WIDER_val/images/"+name))).convert("RGB"))+ h,w = image.shape[:2]+ canvas,rw,rh = prepare_rectangle(image,bgr=True,side=side)+ ch,cw = canvas.shape[:2]+ raw = native_run(*engines[None],canvas,capacity=16000)+ dims = (raw[:,2:4]-raw[:,:2]).min(1)+ boxes = []+ for minimum in MINIMA:+ pred = replay(raw[dims >= minimum], "min8", cw, ch)+ if i % 83 == 0:+ np.testing.assert_array_equal(pred, native_run(*engines[minimum],canvas,capacity=32))+ boxes.append(source_boxes(pred,w,h,rw,rh,cw,ch))+ gt = labels[name].copy()+ small = np.sqrt(gt[:,2:].prod(1))*320/max(w,h) < 16+ gt[:,2:] += gt[:,:2]+ records.append((gt, small, boxes))+ return records+++def evaluate(data, m, thresholds):+ result = np.zeros((len(data),len(thresholds),3), dtype=int)+ for i,(gt,small,boxes) in enumerate(data):+ cached = {}+ for j,threshold in enumerate(thresholds):+ n = int((boxes[m][:,4] >= np.float32(threshold)).sum())+ if n not in cached:+ good = match(boxes[m][:n],gt)+ cached[n] = [len(good),n-len(good),small[good].sum()]+ result[i,j] = cached[n]+ return result+++def main():+ ap = argparse.ArgumentParser(description=__doc__)+ for key in ("weights","images","labels"):+ ap.add_argument(key,type=Path)+ ap.add_argument("--side",type=int,choices=(640,800),required=True)+ args = ap.parse_args()+ score = .70 if args.side == 640 else .75+ with ZipFile(args.labels) as z:+ labels = annotations(z)+ dev, test = partition(labels)+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.images) as photos:+ engines = {}+ try:+ for m in (None, *MINIMA):+ lib = build(Path(tmp),m)+ eng = ctypes.c_void_p(lib.detect_init(bytes(args.weights)))+ if not eng:+ raise RuntimeError("Cannot load YuNet")+ lib.detect_set_score_threshold(eng,ctypes.c_float(.50))+ engines[m] = (lib,eng)+ calibration = collect(engines,dev,labels,photos,args.side)+ budget = evaluate(calibration,0,[score]).sum(0)[0,1]+ locked = [score]+ for m in (1,2):+ totals = evaluate(calibration,m,GRID).sum(0)+ ok = np.flatnonzero(totals[:,1] <= budget)+ best = max(ok,key=lambda j:(totals[j,2],totals[j,0],-abs(GRID[j]-score)))+ locked.append(GRID[best])+ print("side, calibration FP budget, locked thresholds",args.side,budget,locked,flush=True)+ holdout = collect(engines,test,labels,photos,args.side)+ finally:+ for lib,eng in engines.values():+ lib.detect_free(eng)+ print("images, valid GT, small GT",len(test),sum(len(x[0]) for x in holdout),sum(x[1].sum() for x in holdout))+ base = evaluate(holdout,0,[score])[:,0]+ bs = np.random.default_rng(1703).integers(len(test),size=(4000,len(test)))+ for m,minimum in enumerate(MINIMA):+ for t in dict.fromkeys([score, locked[m]]):+ counts = evaluate(holdout,m,[t])[:,0]+ ci = np.percentile((counts-base)[bs].sum(1), [2.5,97.5], axis=0)+ print(minimum, t, counts.sum(0).tolist(), "delta CI", ci.round(1).tolist())+++if __name__ == "__main__":+ main()diff --git a/tests/verify_rectangular_client.py b/tests/verify_rectangular_client.pyindex ce512be..b59d2e4 100644--- a/tests/verify_rectangular_client.py+++ b/tests/verify_rectangular_client.py@@ -21,11 +21,14 @@ def main():det = ctypes.c_void_p(lib.detect_init(os.fsencode(os.environ["DETECT_WEIGHTS"])))assert detside = int(os.environ.get("FACEX_DETECT_SIZE", "640"))- lib.detect_set_score_threshold(det, ctypes.c_float(.75 if side == 800 else .70))+ minimum = int(os.environ.get("FACEX_MIN_BOX_SIDE", "16"))+ lib.detect_set_min_box_side(det, ctypes.c_int(minimum))+ threshold = .75 if side == 800 else {8: .75, 12: .74, 16: .70}[minimum]+ lib.detect_set_score_threshold(det, ctypes.c_float(threshold))lib.align_face.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,ctypes.c_void_p, ctypes.c_void_p]sdk = FaceX(embed_weights=os.environ["EMBED_WEIGHTS"], detect_weights=os.environ["DETECT_WEIGHTS"],- input_policy="rectangle_bgr_800" if side == 800 else "rectangle_bgr")+ min_box_side=minimum, input_policy="rectangle_bgr_800" if side == 800 else "rectangle_bgr")client = app.test_client()patch = Image.open(ROOT / "data/test_face.jpg").convert("RGB").resize((241, 241))try: