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
Stream detector pooling and reuse video embeddings across stable tracks
Baurzhan Atynov16603e3e4ea2
diff --git a/Dockerfile b/Dockerfileindex 9e789d7..3ef1b4e 100644--- a/Dockerfile+++ b/Dockerfile@@ -28,7 +28,7 @@ WORKDIR /appCOPY --from=builder /build/facex-cli /app/facex-serverCOPY --from=builder /build/libfacex.so /app/libfacex.soCOPY python/facex /app/facex-COPY docker/server.py /app/+COPY docker/server.py docker/preloaded.py /app/ENV FACEX_LIB=/app/libfacex.so# Weights must be mounted or baked indiff --git a/docker/preloaded.py b/docker/preloaded.pynew file mode 100644index 0000000..8d6b65e--- /dev/null+++ b/docker/preloaded.py@@ -0,0 +1,4 @@+"""Gunicorn entry point for sharing initialized weights through fork."""+from server import app, initialize_detector++initialize_detector()diff --git a/docker/server.py b/docker/server.pyindex 852d893..8f480fd 100644--- a/docker/server.py+++ b/docker/server.py@@ -67,6 +67,18 @@ _detector = None_detector_lock = threading.Lock()+def initialize_detector():+ """Load weights before forking or under the detector lock in a worker."""+ global _detector+ if _detector is None:+ engine = FaceX(embed_weights=EMBED_WEIGHTS, detect_weights=DETECT_WEIGHTS,+ 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 = engine++def get_fx():global _fxif _fx is None:@@ -148,16 +160,9 @@ def detect():return jsonify({'error': 'Invalid image'}), 400start = time.perf_counter()- global _detectorwith _detector_lock:try:- if _detector is None:- engine = FaceX(embed_weights=EMBED_WEIGHTS, detect_weights=DETECT_WEIGHTS,- 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 = engine+ initialize_detector()faces = _detector.detect(rgb, max_faces=32, embeddings=embeddings)except (RuntimeError, OSError):app.logger.exception("Face detection failed")diff --git a/docs/research/facex_remaining_four.md b/docs/research/facex_remaining_four.mdnew file mode 100644index 0000000..c3fb849--- /dev/null+++ b/docs/research/facex_remaining_four.md@@ -0,0 +1,56 @@+# Remaining detector, video and concurrency experiments++Reference: 6192e8e. All CPU results describe this Linux AMD EPYC 9V74 host.++## 4. Sparse detector geometry++YuNet calculates confidence first. Empty pyramid levels skip geometry. On levels with at most one accepted cell per 128 cells the detector computes the pointwise projection and subsequent 3×3 depthwise regression only around surviving centers. Regression of landmarks can also skip boxes rejected by geometry filters. Dense levels retain the dense path. The FMA implementation explicitly preserves dot-product accumulation order.++## 5. Stream the first depthwise convolution into pooling++Two scratch rows in the destination arena hold depthwise outputs. Pooling and ReLU consume the rows immediately. The next layer reads the pooled map without a pass over a full-size intermediate. Scalar borders and the vectorized row path are shared with the normal depthwise convolution.++On 193 WIDER validation images (one warmup, 96 measured per resolution) all output counts, coordinates, scores and landmarks matched bitwise across three builds. Work was interleaved on one pinned CPU thread, with 0.35 and 0.75 thresholds; GCC used x86-64-v3. Times cover native inference, not resizing, JPEG decoding or embedding.++| Budget | Original mean / median ms | Streamed pool mean / median | Pool and sparse heads mean / median |+|---|---:|---:|---:|+| 640 | 38.98 / 38.30 | 38.47 / 37.50 | 37.25 / 36.97 |+| 800 | 60.41 / 58.10 | 58.95 / 55.96 | 58.03 / 55.66 |++## 7. Refresh video embeddings on stable tracks++The optional Python cache consumes externally assigned track IDs. Its default refresh interval is at most 12 frames. Loss, a frame gap, overlapping or ambiguous tracks, poor detection confidence, small boxes and substantial changes in appearance or quality trigger a fresh embedding. A passing track ID alone does not establish identity.++We compared against fresh embeddings on the same matched detections from three annotated clips. For each 160-frame window we enrolled the first matched frame of each subject and classified the other 477 faces by nearest template. The David annotations start at source frame 300. Each window uses a fresh gallery and cache.++| Annotated frames per clip | Faces | Fresh embeddings with cache | Gallery disagreements | Wrong subject, fresh / cached |+|---|---:|---:|---:|---:|+| 1 through 160 | 480 | 102 | 0 / 477 | 1 / 1 |+| 161 through 320 | 480 | 126 | 13 / 477 | 13 / 14 |++Across these windows the cache avoided 732 of 960 embedding calls. All 13 changed decisions were on David. The test associates detections with ground truth and does not measure a production tracker's ID switch rate. A separate controlled crossing with two faces and a deliberate ID swap refreshed both tracks at the swap and produced zero gallery disagreements in 18 comparisons. Use fresh embeddings when every frame needs an independent recognition decision.++## 8. Concurrent inference++Use `preloaded:app` with Gunicorn preload and synchronous process workers. Packing is done in the parent; immutable weight pages can be shared using copy-on-write. The existing detector lock and native mutable scratch remain process-local. Thread-parallel use of a shared native handle was not enabled.++The harness executed 64 full-embedding Flask WSGI requests per configuration, in closed batches of 1, 2 or 4 concurrent requests, using eight distinct JPEG inputs. Each worker had one warmup request. Linux CPU affinity was restricted to the same four logical CPUs for all configurations. PSS sums the master and workers after warmup and accounts for shared physical pages. All six configurations produced the same per-image output hashes. The test uses pipes for request dispatch; external sockets, Gunicorn HTTP transport and network latency are outside the measurement.++| Workers | Lazy req/s | Preloaded req/s | Lazy / preloaded p95 ms | Lazy / preloaded PSS MiB |+|---:|---:|---:|---:|---:|+| 1 | 19.21 | 17.08 | 57.79 / 69.17 | 87.4 / 84.7 |+| 2 | 33.03 | 35.47 | 80.21 / 78.59 | 136.6 / 116.6 |+| 4 | 66.48 | 63.84 | 74.44 / 80.06 | 234.7 / 180.6 |++The primary benefit of preloading here is memory. Parallel processes account for the throughput gain. Each latency or throughput cell is a single local run.++## Reproduction++Set FACEX_LIB, EMBED_WEIGHTS, DETECT_WEIGHTS and the matching FACEX_EMBED_WEIGHTS and FACEX_DETECT_WEIGHTS before running. For the video test obtain the WebM and gt.txt files under david, dudek and faceocc2 from [OpenCV extra tracking data](https://github.com/opencv/opencv_extra/tree/5.x/testdata/cv/tracking). Place each clip and its annotation in its own named directory. Requires FFmpeg and ffprobe. The project does not distribute the clips.++```sh+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_heads.py yunet.bin WIDER_val.zip+PYTHONPATH=python python tests/bench_video_embeddings.py /path/to/sequences --start 0+PYTHONPATH=python python tests/bench_video_embeddings.py /path/to/sequences --start 160+PYTHONPATH=python:docker python tests/bench_prefork_detection.py 4 --preload+```diff --git a/python/README.md b/python/README.mdindex 7311eb0..0a3db14 100644--- a/python/README.md+++ b/python/README.md@@ -159,3 +159,32 @@ hard deadline. A zero budget selects the one-pass result. The guided operatingpoint uses confidence 0.78, and crops use original-frame coordinates. Ifrequested, embeddings are computed only for the retained faces on the sourceRGB image.++### Video and concurrent REST requests++For a camera with upstream tracking, call detection with `embeddings=False`,+associate the resulting geometry with tracker IDs and pass it to a per-camera+cache. This optional SDK policy refreshes on first sight, loss, overlap, a+large change in appearance or position, improved crop quality, low confidence,+small boxes and at most every 12 frames. Supply every frame, including empty+frames, and call `reset()` when seeking or reconnecting. Mark uncertain+associations with `ambiguous=True`. ID switches that the tracker does not+report can still carry an outdated embedding until the next refresh.++```python+from facex.video import VideoEmbeddings++cache = VideoEmbeddings(fx, max_age=12)+# Each entry contains track_id, bbox, score and the five source keypoints.+results = cache.update(rgb, frame_number, tracked_faces)+```++On Linux with Gunicorn, start synchronous workers from the preloaded entry+point to share packed model pages by fork. The model files must be present+when the master starts. Each process allocates its own inference buffers;+keep one active inference call per process. To replace weights restart the+master. Example inside the REST container:++```sh+gunicorn --preload --worker-class sync --workers 4 --bind 0.0.0.0:8080 preloaded:app+```diff --git a/python/facex/core.py b/python/facex/core.pyindex 8372062..203589b 100644--- a/python/facex/core.py+++ b/python/facex/core.py@@ -464,17 +464,28 @@ class FaceX:raise ValueError("max_faces must be nonnegative")faces = [f for f in faces if f["score"] >= threshold][:min(32, limit)]if embeddings:- scalar = ctypes.POINTER(ctypes.c_float)for face in faces:- kps = np.asarray(face["keypoints"], dtype=np.float32)- vec = np.empty(512, dtype=np.float32)- rc = self._lib.facex_embed_landmarks(self._handle, image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)),- w, h, kps.ctypes.data_as(scalar), vec.ctypes.data_as(scalar))- if rc < 0:- raise RuntimeError("Failed to embed guided detection")- face["embedding"] = vec+ face["embedding"] = self.embed_landmarks(image, face["keypoints"])return faces+ def embed_landmarks(self, image, keypoints):+ """Align five source landmarks and embed the original RGB crop."""+ if self.backend != "ctypes" or not hasattr(self._lib, "facex_embed_landmarks"):+ raise RuntimeError("Landmark embedding requires an updated native library")+ image = np.ascontiguousarray(image, dtype=np.uint8)+ points = np.ascontiguousarray(keypoints, dtype=np.float32)+ if image.ndim != 3 or image.shape[2] != 3 or points.shape != (5, 2) or not np.isfinite(points).all():+ raise ValueError("Expected an RGB image and five finite landmark pairs")+ h, w = image.shape[:2]+ scalar = ctypes.POINTER(ctypes.c_float)+ vec = np.empty(512, dtype=np.float32)+ rc = self._lib.facex_embed_landmarks(+ self._handle, image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), w, h,+ points.ctypes.data_as(scalar), vec.ctypes.data_as(scalar))+ if rc < 0:+ raise RuntimeError("Landmark embedding failed")+ return vec+def _detect_cli(self, image: np.ndarray, w: int, h: int, max_faces: int) -> List[dict]:"""Subprocess fallback: pipe image data to CLI and parse output."""# Build command — the CLI protocol:diff --git a/python/facex/video.py b/python/facex/video.pynew file mode 100644index 0000000..a64489e--- /dev/null+++ b/python/facex/video.py@@ -0,0 +1,79 @@+"""Embedding refresh for one camera with externally assigned track IDs."""+import math++import numpy as np+from PIL import Image+++def _iou(a, b):+ w = max(0, min(a[2], b[2]) - max(a[0], b[0]))+ h = max(0, min(a[3], b[3]) - max(a[1], b[1]))+ intersection = w*h+ union = (a[2]-a[0])*(a[3]-a[1]) + (b[2]-b[0])*(b[3]-b[1]) - intersection+ return intersection / union if union > 0 else 0.+++def _appearance(rgb, box):+ h, w = rgb.shape[:2]+ x1, y1, x2, y2 = box+ patch = rgb[max(0, math.floor(y1)):min(h, math.ceil(y2)),+ max(0, math.floor(x1)):min(w, math.ceil(x2))]+ if x2 <= 0 or y2 <= 0 or x1 >= w or y1 >= h or not patch.size:+ raise ValueError("Track box lies outside the image")+ thumb = np.asarray(Image.fromarray(patch).convert("L").resize((16, 16)), dtype=np.float32)+ sharpness = np.abs(np.diff(thumb, axis=0)).mean() + np.abs(np.diff(thumb, axis=1)).mean()+ centered = thumb - thumb.mean()+ signature = centered / max(1., np.linalg.norm(centered))+ quality = math.sqrt((x2-x1)*(y2-y1)) * (1 + min(64., sharpness)/64)+ return signature, quality+++class VideoEmbeddings:+ """One instance per stream. Omitted or ambiguous tracks must reacquire."""+ def __init__(self, engine, max_age=12):+ if int(max_age) != max_age or max_age < 1:+ raise ValueError("max_age must be a positive frame count")+ self.engine = engine+ self.max_age = max_age+ self.reset()++ def reset(self):+ self._tracks = {}+ self._last_frame = None++ def update(self, rgb, frame_number, tracks):+ """Return geometry, embedding and refresh flag for each supplied track."""+ if self._last_frame is not None and frame_number <= self._last_frame:+ raise ValueError("Frame numbers must increase. Call reset() when seeking.")+ rgb = np.ascontiguousarray(rgb, dtype=np.uint8)+ if rgb.ndim != 3 or rgb.shape[2] != 3:+ raise ValueError("Expected an RGB image")+ tracks = list(tracks)+ ids = [f["track_id"] for f in tracks]+ if len(ids) != len(set(ids)):+ raise ValueError("Duplicate track ID in one frame")+ next_tracks, results = {}, []+ for i, face in enumerate(tracks):+ key, box = ids[i], tuple(face["bbox"])+ if len(box) != 4 or not all(map(math.isfinite, box)) or box[2] <= box[0] or box[3] <= box[1]:+ raise ValueError("Invalid track box")+ signature, quality = _appearance(rgb, box)+ ambiguous = bool(face.get("ambiguous")) or any(+ j != i and _iou(box, other["bbox"]) > .15 for j, other in enumerate(tracks))+ prev = self._tracks.get(key)+ uncertain = face["score"] < .90 or min(box[2]-box[0], box[3]-box[1]) < 40+ refresh = (uncertain or prev is None or self._last_frame != frame_number-1 or ambiguous or+ prev["ambiguous"] or prev["uncertain"] or frame_number-prev["at"] >= self.max_age or+ _iou(box, prev["box"]) < .35 or quality > 1.25*prev["quality"] or+ float(np.linalg.norm(signature-prev["signature"])) > .55)+ if refresh:+ vec = self.engine.embed_landmarks(rgb, face["keypoints"])+ state = dict(at=frame_number, quality=quality, signature=signature, vector=vec)+ else:+ state = prev.copy()+ state.update(box=box, ambiguous=ambiguous, uncertain=uncertain)+ next_tracks[key] = state+ results.append(dict(face, embedding=state["vector"].copy(), refreshed=refresh))+ self._tracks = next_tracks+ self._last_frame = frame_number+ return resultsdiff --git a/src/detect.c b/src/detect.cindex 58a5caf..fe5f9c0 100644--- a/src/detect.c+++ b/src/detect.c@@ -119,54 +119,57 @@ static void conv2d(const float* in, int Ci, int Hi, int Wi,}}+static inline void dw_row(const float* inp_c, int Hi, int Wi, const float* wc,+ float bc, int oy, float* output) {+ float w00=wc[0],w01=wc[1],w02=wc[2];+ float w10=wc[3],w11=wc[4],w12=wc[5];+ float w20=wc[6],w21=wc[7],w22=wc[8];+ for (int ox = 0; ox < Wi; ox++) {+#if defined(__AVX2__) && defined(__FMA__)+ if (oy > 0 && oy + 1 < Hi && ox > 0 && ox + 8 < Wi) {+ __m256 acc = _mm256_set1_ps(bc);+ for (int ky = 0; ky < 3; ky++) {+ const float* row = inp_c + (oy + ky - 1) * Wi + ox - 1;+ for (int kx = 0; kx < 3; kx++) {+ acc = _mm256_fmadd_ps(_mm256_loadu_ps(row + kx),+ _mm256_set1_ps(wc[3*ky + kx]), acc);+ }+ }+ _mm256_storeu_ps(output + ox, acc);+ ox += 7;+ continue;+ }+#endif+ float sum = bc;+ int iy = oy - 1, ix = ox - 1;+ /* Unrolled 3×3 with boundary checks */+ if(iy>=0) {+ if(ix>=0) sum += inp_c[iy*Wi+ix]*w00;+ sum += inp_c[iy*Wi+ox]*w01;+ if(ox+1<Wi) sum += inp_c[iy*Wi+ox+1]*w02;+ }+ if(ix>=0) sum += inp_c[oy*Wi+ix]*w10;+ sum += inp_c[oy*Wi+ox]*w11;+ if(ox+1<Wi) sum += inp_c[oy*Wi+ox+1]*w12;+ if(oy+1<Hi) {+ if(ix>=0) sum += inp_c[(oy+1)*Wi+ix]*w20;+ sum += inp_c[(oy+1)*Wi+ox]*w21;+ if(ox+1<Wi) sum += inp_c[(oy+1)*Wi+ox+1]*w22;+ }+ output[ox] = sum;+ }+}+static void conv_dw(const float* in, int C, int Hi, int Wi,const float* w, const float* b, int K, int s, int pad, float* out) {int Ho = (Hi + 2*pad - K) / s + 1, Wo = (Wi + 2*pad - K) / s + 1;/* Fast path: K=3, s=1, pad=1 — most common in YuNet */if (K == 3 && s == 1 && pad == 1) {for (int c = 0; c < C; c++) {- const float* inp_c = in + (size_t)c*Hi*Wi;- const float* wc = w + (size_t)c*9;- float bc = b ? b[c] : 0;- float w00=wc[0],w01=wc[1],w02=wc[2];- float w10=wc[3],w11=wc[4],w12=wc[5];- float w20=wc[6],w21=wc[7],w22=wc[8];- for (int oy = 0; oy < Ho; oy++) {- for (int ox = 0; ox < Wo; ox++) {-#if defined(__AVX2__) && defined(__FMA__)- if (oy > 0 && oy + 1 < Hi && ox > 0 && ox + 8 < Wi) {- __m256 acc = _mm256_set1_ps(bc);- for (int ky = 0; ky < 3; ky++) {- const float* row = inp_c + (oy + ky - 1) * Wi + ox - 1;- for (int kx = 0; kx < 3; kx++) {- acc = _mm256_fmadd_ps(_mm256_loadu_ps(row + kx),- _mm256_set1_ps(wc[3*ky + kx]), acc);- }- }- _mm256_storeu_ps(out + (size_t)c*Ho*Wo + oy*Wo + ox, acc);- ox += 7;- continue;- }-#endif- float sum = bc;- int iy = oy - 1, ix = ox - 1;- /* Unrolled 3×3 with boundary checks */- if(iy>=0) {- if(ix>=0) sum += inp_c[iy*Wi+ix]*w00;- sum += inp_c[iy*Wi+ox]*w01;- if(ox+1<Wi) sum += inp_c[iy*Wi+ox+1]*w02;- }- if(ix>=0) sum += inp_c[oy*Wi+ix]*w10;- sum += inp_c[oy*Wi+ox]*w11;- if(ox+1<Wi) sum += inp_c[oy*Wi+ox+1]*w12;- if(oy+1<Hi) {- if(ix>=0) sum += inp_c[(oy+1)*Wi+ix]*w20;- sum += inp_c[(oy+1)*Wi+ox]*w21;- if(ox+1<Wi) sum += inp_c[(oy+1)*Wi+ox+1]*w22;- }- out[(size_t)c*Ho*Wo + oy*Wo + ox] = sum;- }- }+ const float* input = in + (size_t)c*Hi*Wi;+ for (int y = 0; y < Hi; y++)+ dw_row(input, Hi, Wi, w + c*9, b ? b[c] : 0,+ y, out + ((size_t)c*Hi + y)*Wi);}return;}@@ -185,6 +188,29 @@ static void conv_dw(const float* in, int C, int Hi, int Wi,}}+/* The destination arena has room for pooled output and two full scratch rows. */+static void dw_relu_pool(const float* in, int C, int H, int W, const float* weights,+ const float* bias, float* out) {+ int ph = H/2, pw = W/2;+ float* first = out + (size_t)C*ph*pw;+ float* second = first + W;+ for (int c = 0; c < C; c++) {+ const float* src = in + (size_t)c*H*W;+ for (int y = 0; y < ph; y++) {+ dw_row(src,H,W,weights+c*9,bias[c],2*y,first);+ dw_row(src,H,W,weights+c*9,bias[c],2*y+1,second);+ float* dst = out + ((size_t)c*ph+y)*pw;+ for (int x = 0; x < pw; x++) {+ float m = first[2*x];+ if (first[2*x+1] > m) m = first[2*x+1];+ if (second[2*x] > m) m = second[2*x];+ if (second[2*x+1] > m) m = second[2*x+1];+ dst[x] = m < 0 ? 0 : m;+ }+ }+ }+}+static void conv1x1(const float* in, int Ci, int HW, const float* w, const float* b, int Co, float* out) {#if defined(__AVX2__) && defined(__FMA__)/* Reuse two input vectors across four output channels. Keep partial@@ -242,6 +268,34 @@ static void conv1x1(const float* in, int Ci, int HW, const float* w, const float}}+/* Evaluate the pointwise projection only in the 3x3 neighborhood used+ * by an accepted location's depthwise output. */+static void sparse_head(const float* feat, int H, int W, int y, int x,+ int channels, const float* pw, const float* pb,+ const float* dw, const float* db, float* out) {+ int hw = H*W;+ for (int co = 0; co < channels; co++) {+ float sum = db[co];+ for (int ky = 0; ky < 3; ky++) {+ int iy = y+ky-1;+ if (iy < 0 || iy >= H) continue;+ for (int kx = 0; kx < 3; kx++) {+ int ix = x+kx-1;+ if (ix < 0 || ix >= W) continue;+ float projected = pb[co];+ for (int ci = 0; ci < 64; ci++)+#if defined(__FMA__)+ projected = fmaf(feat[(size_t)ci*hw + iy*W + ix], pw[co*64+ci], projected);+#else+ projected += feat[(size_t)ci*hw + iy*W + ix] * pw[co*64+ci];+#endif+ sum += projected * dw[co*9+ky*3+kx];+ }+ }+ out[(size_t)co*hw + y*W+x] = sum;+ }+}+static void relu_(float* x, int n) { for (int i = 0; i < n; i++) if (x[i] < 0) x[i] = 0; }static void maxpool2x2(const float* in, int C, int H, int W, float* out) {@@ -348,9 +402,10 @@ int detect_run_threshold(Detect* det, const uint8_t* rgb_hwc, int width, int heiconv1x1(a, 16, h2*w2, T(33), T(32), 16, b);/* model0: DW3×3 + ReLU + MaxPool */- conv_dw(b, 16, h2, w2, T(2), T(3), 3, 1, 1, a);- relu_(a, 16*h2*w2);- maxpool2x2(a, 16, h2, w2, b); /* → [16, h4, w4] */+ dw_relu_pool(b, 16, h2, w2, T(2), T(3), a);+ float* swap = a;+ a = b;+ b = swap;/* model1: PW(16→16) + DW+ReLU + PW(16→32) */conv1x1(b, 16, h4*w4, T(35), T(34), 16, a);@@ -464,19 +519,31 @@ int detect_run_threshold(Detect* det, const uint8_t* rgb_hwc, int width, int heiconv_dw(a, 1, fh, fw, T(ow2[si]), T(ob2[si]), 3, 1, 1, c);float* obj = c;- /* bbox: PW(64→4) + DW3×3(4) */- conv1x1(feat, 64, hw, T(bw1[si]), T(bb1[si]), 4, a);- conv_dw(a, 4, fh, fw, T(bw2[si]), T(bb2[si]), 3, 1, 1, hd);-- /* kps: PW(64→10) + DW3×3(10) */- conv1x1(feat, 64, hw, T(kw1[si]), T(kb1[si]), 10, a);- conv_dw(a, 10, fh, fw, T(kw2[si]), T(kb2[si]), 3, 1, 1, hd + 4*hw);+ int active = 0;+ for (int i = 0; i < hw; i++) {+ cls[i] = sqrtf(sigm(cls[i]) * sigm(obj[i]));+ if (cls[i] >= threshold) active++;+ }+ if (!active) continue;+ int sparse = active <= hw/128;+ if (!sparse) {+ /* bbox: PW(64→4) + DW3×3(4) */+ conv1x1(feat, 64, hw, T(bw1[si]), T(bb1[si]), 4, a);+ conv_dw(a, 4, fh, fw, T(bw2[si]), T(bb2[si]), 3, 1, 1, hd);++ /* kps: PW(64→10) + DW3×3(10) */+ conv1x1(feat, 64, hw, T(kw1[si]), T(kb1[si]), 10, a);+ conv_dw(a, 10, fh, fw, T(kw2[si]), T(kb2[si]), 3, 1, 1, hd + 4*hw);+ }for (int gy = 0; gy < fh; gy++)for (int gx = 0; gx < fw; gx++) {int idx = gy * fw + gx;- float sc = sqrtf(sigm(cls[idx]) * sigm(obj[idx]));+ float sc = cls[idx];if (sc < threshold) continue;+ if (sparse)+ sparse_head(feat, fh, fw, gy, gx, 4, T(bw1[si]), T(bb1[si]),+ T(bw2[si]), T(bb2[si]), hd);/* YuNet regresses the center offset and log width/height. */float cx = (gx + hd[idx]) * st;float cy = (gy + hd[hw + idx]) * st;@@ -494,6 +561,9 @@ int detect_run_threshold(Detect* det, const uint8_t* rgb_hwc, int width, int heifloat aspect = bw / (bh + 1e-6f);if (aspect < 0.3f || aspect > 3.0f) continue; /* bad aspect ratio */candidates[nf].score = sc;+ if (sparse)+ sparse_head(feat, fh, fw, gy, gx, 10, T(kw1[si]), T(kb1[si]),+ T(kw2[si]), T(kb2[si]), hd + 4*hw);for (int k = 0; k < 5; k++) {candidates[nf].kps[k*2] = fmaxf(0, fminf((float)width, (gx + hd[(4+k*2)*hw+idx]) * st));candidates[nf].kps[k*2+1] = fmaxf(0, fminf((float)height, (gy + hd[(4+k*2+1)*hw+idx]) * st));diff --git a/tests/bench_prefork_detection.py b/tests/bench_prefork_detection.pynew file mode 100644index 0000000..f3c0db0--- /dev/null+++ b/tests/bench_prefork_detection.py@@ -0,0 +1,98 @@+"""Measure process-isolated WSGI inference using Gunicorn's lazy and prefork layouts."""+import argparse+import hashlib+import io+import json+import os+from pathlib import Path+import select+import time++import numpy as np+from PIL import Image++from server import app, initialize_detector+++def memory(pid):+ with open(f"/proc/{pid}/smaps_rollup") as src:+ return next(int(line.split()[1]) for line in src if line.startswith("Pss:"))+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("workers", type=int, choices=(1,2,4))+ parser.add_argument("--preload", action="store_true")+ args = parser.parse_args()+ cpus = sorted(os.sched_getaffinity(0))[:4]+ os.sched_setaffinity(0,set(cpus))+ if args.preload:+ initialize_detector()+ root = Path(__file__).resolve().parents[1]+ images = []+ for path in sorted((root/"tests/golden").glob("*.npz"))[:8]:+ with np.load(path) as f:+ buf=io.BytesIO()+ Image.fromarray(f["image"]).save(buf,format="JPEG")+ images.append(buf.getvalue())+ workers=[]+ for i in range(args.workers):+ rd,wr=os.pipe()+ rd2,wr2=os.pipe()+ pid=os.fork()+ if pid == 0:+ os.close(wr);os.close(rd2)+ try:+ c=app.test_client()+ def run(j):+ res=c.post("/detect",data={"file":(io.BytesIO(images[j]),"input.jpg")})+ if res.status_code != 200:+ raise RuntimeError(res.data)+ return hashlib.sha256(json.dumps(res.json["faces"],sort_keys=True).encode()).hexdigest()+ run(i%len(images))+ os.write(wr2,b"R")+ while True:+ msg=os.read(rd,1)+ if msg==b"Q" or not msg:+ break+ os.write(wr2,run(msg[0]).encode())+ os._exit(0)+ except BaseException:+ import traceback+ traceback.print_exc()+ os._exit(1)+ os.close(rd);os.close(wr2)+ workers.append((pid,wr,rd2))+ try:+ for _,_,r in workers:+ assert os.read(r,1)==b"R"+ pss=sum(memory(pid) for pid,_,_ in workers)+memory(os.getpid())+ answers={};elapsed=[]+ start=time.monotonic()+ for k in range(0,64,args.workers):+ tick=time.monotonic()+ waiting={}+ for j,(_,w,r) in enumerate(workers):+ idx=(k+j)%len(images)+ os.write(w,bytes([idx]));waiting[r]=idx+ while waiting:+ readable,_,_=select.select(list(waiting),[],[],30)+ if not readable: raise RuntimeError("Timed out")+ for r in readable:+ val=os.read(r,64)+ assert len(val)==64+ i=waiting.pop(r)+ assert answers.setdefault(i,val)==val+ elapsed.append((time.monotonic()-tick)*1000)+ total=time.monotonic()-start+ print(args.workers,args.preload,"req/s",round(64/total,2),"p95 ms",round(np.percentile(elapsed,95),2),+ "PSS MiB",round(pss/1024,1),"checksum",hashlib.sha256(b"".join(answers[i] for i in sorted(answers))).hexdigest())+ finally:+ for pid,w,r in workers:+ try: os.write(w,b"Q")+ except BrokenPipeError: pass+ os.close(w);os.close(r);os.waitpid(pid,0)+++if __name__ == "__main__":+ main()diff --git a/tests/bench_video_embeddings.py b/tests/bench_video_embeddings.pynew file mode 100644index 0000000..8ef4517--- /dev/null+++ b/tests/bench_video_embeddings.py@@ -0,0 +1,122 @@+"""Evaluate refresh on annotated OpenCV tracking clips and controlled ID reuse."""+import argparse+import json+import subprocess+from pathlib import Path++import numpy as np+from PIL import Image+from facex import FaceX+from facex.video import VideoEmbeddings, _iou+++def unit(x):+ return x / max(1e-12, np.linalg.norm(x))+++def crossing_check(engine, examples):+ # Replay two annotated source crops on converging paths with a known ID swap.+ patches = []+ for rgb, face in examples[:2]:+ x1, y1, x2, y2 = np.rint(face["bbox"]).astype(int)+ patch = Image.fromarray(rgb[y1:y2, x1:x2]).resize((96,96))+ pts = (np.asarray(face["keypoints"]) - [x1,y1]) * [96/(x2-x1),96/(y2-y1)]+ patches.append((patch,pts))+ cache = VideoEmbeddings(engine)+ wrong = 0+ refs = []+ for frame, (left,right) in enumerate(((8,184),(14,178),(36,156),(62,130),+ (82,110),(110,82),(130,62),(156,36),(178,14))):+ canvas = Image.new("RGB",(288,120))+ tracks = []+ for person, x in enumerate((left,right)):+ patch, pts = patches[person]+ canvas.paste(patch,(x,10))+ tracks.append(dict(track_id=person if frame<5 else 1-person,+ bbox=(x,10,x+96,106),score=.99,+ keypoints=(pts+[x,10]).tolist()))+ rgb = np.asarray(canvas)+ out = cache.update(rgb,frame,tracks)+ if not refs:+ refs = [unit(engine.embed_landmarks(rgb,f["keypoints"])) for f in tracks]+ for f,t in zip(out,tracks):+ oracle = engine.embed_landmarks(rgb,t["keypoints"])+ if frame == 5:+ assert f["refreshed"]+ np.testing.assert_allclose(oracle,f["embedding"],atol=1e-5)+ wrong += int(np.argmax(refs @ unit(oracle)) != np.argmax(refs @ unit(f["embedding"])))+ print("controlled crossing, gallery disagreements over 18 comparisons:",wrong)+++def main():+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument("directory", type=Path)+ p.add_argument("--frames",type=int,default=160)+ p.add_argument("--start", type=int, default=0)+ args = p.parse_args()+ engine = FaceX(input_policy="rectangle_bgr")+ examples, galleries, samples = [], [], []+ for name in ("david", "dudek", "faceocc2"):+ folder = args.directory/name+ vid = folder/(name+".webm")+ gt = np.loadtxt(folder/"gt.txt",delimiter=",",ndmin=2)+ info = json.loads(subprocess.check_output(["ffprobe","-v","quiet","-show_streams",+ "-of","json",str(vid)]))["streams"][0]+ w,h = info["width"],info["height"]+ cache = VideoEmbeddings(engine)+ first, record = None, []+ # The David annotations begin at source frame 300 (one-based).+ offset = 299 if name == "david" else 0+ with subprocess.Popen(["ffmpeg","-loglevel","error","-threads","1","-i",str(vid),+ "-frames:v",str(offset+args.start+args.frames),"-f","rawvideo","-pix_fmt","rgb24","-threads","1","-"],+ stdout=subprocess.PIPE) as proc:+ for source_frame in range(offset+min(args.start+args.frames,len(gt))):+ t = source_frame-offset+ raw = proc.stdout.read(w*h*3)+ if not raw:+ break+ if t < args.start:+ continue+ rgb = np.frombuffer(raw,dtype="u1").reshape(h,w,3)+ faces = engine.detect(rgb,embeddings=False)+ x,y,bw,bh = gt[t,:4]+ box = (x,y,x+bw,y+bh)+ face = max(faces,key=lambda f:_iou(box,f["bbox"]),default=None)+ tracks = [dict(face,track_id=1)] if face and _iou(box,face["bbox"])>=.20 else []+ out = cache.update(rgb,t,tracks)+ if out:+ ref = engine.embed_landmarks(rgb,face["keypoints"])+ if first is None:+ first = unit(ref)+ examples.append((rgb.copy(),tracks[0]))+ record.append((t,out[0]["refreshed"],unit(ref),unit(out[0]["embedding"])))+ if proc.wait() != 0:+ raise RuntimeError("Video decoding failed")+ if first is None:+ raise RuntimeError("No target face matched in "+name)+ galleries.append(first)+ samples.append(record)+ gallery = np.stack(galleries)+ for idx,rec in enumerate(samples):+ # Exclude the enrollment frame from the nearest-template comparison.+ ids = [(np.argmax(gallery@r),np.argmax(gallery@c)) for _,_,r,c in rec[1:]]+ print(idx,"matched frames, refreshes, first frame",len(rec),sum(r[1] for r in rec),rec[0][0],+ "reference/cached wrong",sum(a!=idx for a,b in ids),sum(b!=idx for a,b in ids),+ "label disagreements",sum(a!=b for a,b in ids),flush=True)+ cache = VideoEmbeddings(engine)+ img,one = examples[0]+ cache.update(img,0,[one])+ cache.update(img,1,[one])+ assert all(f["refreshed"] for f in cache.update(img,2,[one,dict(one,track_id=2)]))+ assert cache.update(img,3,[one])[0]["refreshed"]+ cache.update(img,4,[])+ img,two = examples[1]+ after = cache.update(img,5,[two])[0]+ assert after["refreshed"]+ np.testing.assert_allclose(after["embedding"],engine.embed_landmarks(img,two["keypoints"]),atol=1e-5)+ print("ambiguity, separation and ID reuse after loss refreshed correctly")+ crossing_check(engine,examples)+++if __name__ == "__main__":+ main()diff --git a/tests/bench_yunet_heads.py b/tests/bench_yunet_heads.pynew file mode 100644index 0000000..b107a13--- /dev/null+++ b/tests/bench_yunet_heads.py@@ -0,0 +1,67 @@+"""Paired end-to-end timings and exact geometry checks for the pooling and head changes."""+import argparse+import ctypes+import io+import os+from pathlib import Path+import subprocess+import tempfile+import time+from zipfile import ZipFile++import numpy as np+from PIL import Image++from bench_yunet_bottlenecks import ROOT, native_run, prepare_rectangle+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("weights", type=Path)+ parser.add_argument("images", type=Path)+ args = parser.parse_args()+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})+ base = subprocess.check_output(["git","show","6192e8e:src/detect.c"],cwd=ROOT,text=True)+ current = (ROOT/"src/detect.c").read_text()+ marker = " /* === HEADS + DECODE === */"+ pool_only = current.split(marker)[0] + marker + base.split(marker)[1]+ engines = []+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.images) as photos:+ try:+ for i, src in enumerate((base,pool_only,current)):+ path = Path(tmp)/f"v{i}.c"+ path.write_text(src)+ libpath = path.with_suffix(".so")+ subprocess.run(["gcc","-O3","-march=x86-64-v3","-shared","-fPIC","-I",+ str(ROOT/"include"),str(path),"-lm","-o",str(libpath)],check=True)+ lib = ctypes.CDLL(str(libpath))+ lib.detect_init.restype=ctypes.c_void_p+ eng = ctypes.c_void_p(lib.detect_init(bytes(args.weights)))+ if not eng:+ raise RuntimeError("Failed to load weights")+ engines.append((lib,eng))+ names=np.random.default_rng(597).choice(sorted(n for n in photos.namelist() if n.endswith(".jpg")),193,replace=False)+ ts=np.zeros((192,3))+ for i,name in enumerate(names):+ rgb=np.asarray(Image.open(io.BytesIO(photos.read(name))).convert("RGB"))+ canvas,*_=prepare_rectangle(rgb,bgr=True,side=640 if i%2 else 800)+ pred={}+ for k in np.roll(np.arange(3),i%3):+ lib,eng=engines[k]+ lib.detect_set_score_threshold(eng,ctypes.c_float(.35 if i%3==0 else .75))+ start=time.thread_time_ns()+ pred[k]=native_run(lib,eng,canvas,capacity=10000)+ if i:+ ts[i-1,k]=(time.thread_time_ns()-start)/1e6+ for k in (1,2):+ np.testing.assert_array_equal(pred[k],pred[0])+ for j,side in enumerate((640,800)):+ t=ts[j::2]+ print(side,"mean, median CPU ms",np.round(t.mean(0),2),np.round(np.median(t,0),2))+ finally:+ for lib,eng in engines:+ lib.detect_free(eng)+++if __name__ == "__main__":+ main()