Skip to content

armgit / facex

Public Imported from GitHub
0

Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.

Release packed weights and make detection and crop refinement cheaper

Baurzhan Atynov6192e8e6748b
diff --git a/docker/server.py b/docker/server.py
index 187e196..852d893 100644
--- a/docker/server.py
+++ b/docker/server.py
@@ -136,6 +136,11 @@ def detect():
if 'file' not in request.files:
return jsonify({'error': 'No file uploaded'}), 400
+ flag = request.args.get("embeddings", "true").lower()
+ if flag not in ("true", "false"):
+ return jsonify({"error": "embeddings must be true or false"}), 400
+ embeddings = flag == "true"
+
try:
with Image.open(request.files['file'].stream) as uploaded:
rgb = np.asarray(uploaded.convert('RGB'))
@@ -153,12 +158,13 @@ def detect():
if engine.backend != "ctypes":
raise RuntimeError("Missing native FaceX library")
_detector = engine
- faces = _detector.detect(rgb, max_faces=32)
+ faces = _detector.detect(rgb, max_faces=32, embeddings=embeddings)
except (RuntimeError, OSError):
app.logger.exception("Face detection failed")
return jsonify({'error': 'Face detection unavailable'}), 503
- for face in faces:
- face['embedding'] = face['embedding'].tolist()
+ if embeddings:
+ for face in faces:
+ face['embedding'] = face['embedding'].tolist()
return jsonify({'faces': faces, 'ms': round((time.perf_counter() - start) * 1000, 2)})
diff --git a/docs/research/facex_runtime_costs.md b/docs/research/facex_runtime_costs.md
new file mode 100644
index 0000000..a0d5e06
--- /dev/null
+++ b/docs/research/facex_runtime_costs.md
@@ -0,0 +1,51 @@
+# Engine lifetime, working memory and optional recognition
+
+Reference commit 9296653. Measurements are local Linux x86 experiments. The reported workspace totals, process RSS and API latency describe different resources.
+
+## Engine lifetime
+
+EdgeFace retained both sets of packed matrices and a cached position tensor. It also started three extra idle workers at every initialization, although the threaded GEMM branch is disabled. The loader now releases owned allocations on success and on partial initialization failure, and this engine no longer creates an unused pool. The standalone CLI and library use the same cleanup.
+
+After warmup, process RSS was 10084 KiB after 10, 50 and 100 open/close cycles. A separate native test wraps allocation functions at link time: 100 successful cycles balanced every owned allocation. Injecting a failure at each of the 452 allocation sites reached in the measured initialization also left zero outstanding allocations. LeakSanitizer cannot enumerate threads in this sandbox under ptrace.
+
+## YuNet workspace
+
+The largest activation for each alternating buffer fits 16 channels at stride two or 64 at stride four. The objectness map needs a single channel at stride eight. The revised arena sizes follow those bounds. On a 640-square input, 1, 4 and 8 independent detector handles gave the following process-memory deltas after a forward pass on each:
+
+| Handles | Virtual MiB before / after | Resident MiB before / after |
+|---:|---:|---:|
+| 1 | 82.3 / 19.9 | 19.9 / 19.9 |
+| 4 | 329.8 / 79.9 | 79.6 / 79.5 |
+| 8 | 659.1 / 159.3 | 158.8 / 158.8 |
+
+Untouched virtual pages did not occupy physical memory in this environment. Full output comparisons against the reference cover 20 WIDER images at three shapes including odd sizes.
+
+## REST without embeddings
+
+Sequential Flask client posts with JPEGs containing 1, 8 and 32 repeated face fixtures; six timed requests per mode following warmup, alternating order. Times include request parsing, decoding and JSON serialization. The same engine and weights served both modes. Sizes below refer to representative JSON responses and include the timing field.
+
+| Faces returned | Full median ms | Geometry median ms | Full bytes | Geometry bytes |
+|---:|---:|---:|---:|---:|
+| 1 | 50.44 | 45.70 | 11340 | 328 |
+| 8 | 71.58 | 43.64 | 90681 | 2562 |
+| 32 | 154.49 | 41.66 | 362085 | 9977 |
+
+All returned boxes, scores and landmarks matched across modes. These are local service measurements, excluding external network and concurrent load.
+
+## Guided refinement with the current small-face filter
+
+BGR, minimum side eight. Reuse the 128 development and 320 evaluation images from the previous detail experiment for a paired retrospective comparison. Calibrate the guided score against the development baseline's unmatched count. The one-pass threshold is 0.75 and the chosen guided threshold is 0.78. The experiment admitted all suggested crops.
+
+| Mode | Total matches | Small matches | Unmatched | Mean detector CPU ms |
+|---|---:|---:|---:|---:|
+| 640 single pass | 1022 | 563 | 33 | 49.38 |
+| 640 plus conditional 448 crop | 1084 | 627 | 29 | 60.38 |
+
+148 of 320 images triggered a crop. The net small-face gain was 64 (+11.4%), paired image bootstrap 95% interval +32 to +101. Unmatched delta −4, interval −13 to +5. Mean detector CPU rose 22%. These timings exclude recognition. The public SDK was compared to the reference refinement on a further 40 images, including 26 crop triggers; zero extra CPU budget reproduced the single-pass geometry.
+
+```sh
+OPENBLAS_NUM_THREADS=1 python tests/bench_yunet_guided_min8.py yunet.bin WIDER_val.zip wider_face_split.zip
+make lib
+gcc -Iinclude tests/weights_lifetime.c libfacex.a -Wl,--wrap=malloc,--wrap=calloc,--wrap=aligned_alloc,--wrap=free -lm -lpthread -o /tmp/weights_lifetime
+/tmp/weights_lifetime edgeface_xs_fp32.bin
+```
diff --git a/include/detect.h b/include/detect.h
index 5d88047..43c923b 100644
--- a/include/detect.h
+++ b/include/detect.h
@@ -83,6 +83,10 @@ void detect_set_score_threshold(Detect* det, float threshold);
/* NMS IoU threshold (default 0.4). */
void detect_set_nms_threshold(Detect* det, float threshold);
+/* Per-call confidence threshold. */
+int detect_run_threshold(Detect* det, const uint8_t* rgb_hwc, int width, int height,
+ DetectFace* out, int max_faces, float threshold);
+
/* Minimum predicted width and height in detector pixels (default 16). */
void detect_set_min_box_side(Detect* det, int pixels);
diff --git a/include/facex.h b/include/facex.h
index 057819f..a0ee2c3 100644
--- a/include/facex.h
+++ b/include/facex.h
@@ -70,6 +70,15 @@ int facex_detect_prepared(FaceX* fx, const uint8_t* rgb_hwc, int width, int heig
const uint8_t* canvas, int canvas_w, int canvas_h,
int resized_w, int resized_h, FaceXResult* out, int max_faces);
+/* Set embeddings to zero to skip recognition. A negative threshold uses the configured default. */
+int facex_detect_prepared_ex(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,
+ const uint8_t* canvas, int canvas_w, int canvas_h,
+ int resized_w, int resized_h, FaceXResult* out, int max_faces, int embeddings, float threshold);
+
+int facex_embed_landmarks(FaceX* fx, const uint8_t* rgb, int w, int h,
+ const float kps[10], float embedding[512]);
+
+
/*
* Compute embedding only (no detection). Input must be pre-aligned 112×112.
* rgb_hwc: 112*112*3 float32 array, HWC layout, values in [-1, 1]
diff --git a/python/README.md b/python/README.md
index 0581264..7311eb0 100644
--- a/python/README.md
+++ b/python/README.md
@@ -138,3 +138,24 @@ sim = similarity(emb1, emb2)
| none | nothing | No | No |
Similarity always works (pure numpy).
+
+### Geometry only and guided refinement
+
+Use `fx.detect(image, embeddings=False)` or `POST /detect?embeddings=false` to
+get original-coordinate boxes, scores and five landmarks. The embedding field
+is omitted. The default response includes embeddings.
+
+For a crowded still image, initialize the native SDK with
+`input_policy="rectangle_bgr", min_box_side=8` and call:
+
+```python
+faces = fx.detect_guided(image, extra_cpu_ms=30, embeddings=False, max_faces=32)
+```
+
+The first pass selects a small-face neighborhood. The SDK runs at most one
+448-budget crop, estimates its CPU cost from the first pass and skips it when
+the estimate exceeds the extra budget. This is an admission estimate, not a
+hard deadline. A zero budget selects the one-pass result. The guided operating
+point uses confidence 0.78, and crops use original-frame coordinates. If
+requested, embeddings are computed only for the retained faces on the source
+RGB image.
diff --git a/python/facex/core.py b/python/facex/core.py
index 68312b4..8372062 100644
--- a/python/facex/core.py
+++ b/python/facex/core.py
@@ -9,6 +9,7 @@ import platform
import struct
import subprocess
import sys
+import time
from pathlib import Path
from typing import Dict, List, Optional, Tuple
@@ -43,16 +44,18 @@ class FaceXResult(ctypes.Structure):
]
-def _result_to_dict(r: FaceXResult) -> dict:
+def _result_to_dict(r: FaceXResult, embeddings=True) -> dict:
"""Convert a FaceXResult struct to a Python dict."""
kps_raw = list(r.kps)
keypoints = [(kps_raw[i], kps_raw[i + 1]) for i in range(0, 10, 2)]
- return {
+ face = {
"bbox": (r.x1, r.y1, r.x2, r.y2),
"score": r.score,
"keypoints": keypoints,
- "embedding": np.array(list(r.embedding), dtype=np.float32),
}
+ if embeddings:
+ face["embedding"] = np.ctypeslib.as_array(r.embedding).copy()
+ return face
# ---------------------------------------------------------------------------
@@ -336,6 +339,16 @@ class FaceX:
self._lib.facex_set_min_box_side.argtypes = [ctypes.c_void_p, ctypes.c_int]
self._lib.facex_set_min_box_side.restype = None
+ if hasattr(self._lib, "facex_detect_prepared_ex"):
+ pixel = ctypes.POINTER(ctypes.c_uint8)
+ scalar = ctypes.POINTER(ctypes.c_float)
+ self._lib.facex_detect_prepared_ex.argtypes = [
+ ctypes.c_void_p, pixel, ctypes.c_int, ctypes.c_int, pixel,
+ ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,
+ ctypes.POINTER(FaceXResult), ctypes.c_int, ctypes.c_int, ctypes.c_float]
+ self._lib.facex_embed_landmarks.argtypes = [
+ ctypes.c_void_p, pixel, ctypes.c_int, ctypes.c_int, scalar, scalar]
+
# Init engine
embed_b = self._embed_weights.encode() if self._embed_weights else None
detect_b = self._detect_weights.encode() if self._detect_weights else None
@@ -364,6 +377,7 @@ class FaceX:
self,
image: np.ndarray,
max_faces: Optional[int] = None,
+ *, embeddings: bool = True,
) -> List[dict]:
"""
Detect faces and compute embeddings.
@@ -371,6 +385,7 @@ class FaceX:
Args:
image: RGB uint8 numpy array, shape (H, W, 3).
max_faces: Override max faces for this call.
+ embeddings: Pass False to omit alignment, embedding inference and vectors.
Returns:
List of dicts, each with keys:
@@ -389,33 +404,76 @@ class FaceX:
if self._input_policy != "native" and self.backend != "ctypes":
raise RuntimeError("Rectangle input requires the native FaceX shared library")
if self._lib and self._handle:
- return self._detect_ctypes(image, w, h, mf)
+ return self._detect_ctypes(image, w, h, mf, embeddings)
elif self._cli_path:
- if self._min_box_side != 16:
- raise RuntimeError("Custom min_box_side requires the native shared library")
+ if not embeddings or self._min_box_side != 16:
+ raise RuntimeError("This detection option requires the native shared library")
return self._detect_cli(image, w, h, mf)
else:
raise RuntimeError(
"No backend available. Install the shared library or set FACEX_CLI."
)
- def _detect_ctypes(self, image: np.ndarray, w: int, h: int, max_faces: int) -> List[dict]:
+ def _detect_ctypes(self, image, w, h, max_faces, embeddings=True, side=None, threshold=-1):
results = (FaceXResult * max_faces)()
- ptr = image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
+ pixels = ctypes.POINTER(ctypes.c_uint8)
+ ptr = image.ctypes.data_as(pixels)
+ canvas, rw, rh = image, w, h
if self._input_policy != "native":
from .yunet import prepare_rectangle
- side = 800 if self._input_policy == "rectangle_bgr_800" else 640
+ side = side or (800 if self._input_policy == "rectangle_bgr_800" else 640)
canvas, rw, rh = prepare_rectangle(image, bgr=self._input_policy != "rectangle", side=side)
- ch, cw = canvas.shape[:2]
- n = self._lib.facex_detect_prepared(
- self._handle, ptr, w, h,
- canvas.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), cw, ch,
+ ch, cw = canvas.shape[:2]
+ args = (self._handle, ptr, w, h, canvas.ctypes.data_as(pixels), cw, ch,
rw, rh, results, max_faces)
- else:
+ if hasattr(self._lib, "facex_detect_prepared_ex"):
+ n = self._lib.facex_detect_prepared_ex(*args, int(embeddings), threshold)
+ elif not embeddings or threshold >= 0:
+ raise RuntimeError("This option requires an updated native library")
+ elif self._input_policy == "native":
n = self._lib.facex_detect(self._handle, ptr, w, h, results, max_faces)
+ else:
+ n = self._lib.facex_detect_prepared(*args)
if n < 0:
raise RuntimeError(f"facex_detect returned error code {n}")
- return [_result_to_dict(results[i]) for i in range(n)]
+ return [_result_to_dict(results[i], embeddings) for i in range(n)]
+
+ def detect_guided(self, image, *, extra_cpu_ms, embeddings=True, max_faces=None):
+ """Refine at most one crop when its estimated CPU cost fits the extra budget."""
+ from .yunet import guided_crop, merge_faces
+ if self._input_policy != "rectangle_bgr" or self._min_box_side != 8 or self.backend != "ctypes":
+ raise ValueError("Guided detection requires native rectangle_bgr with min_box_side=8")
+ if not np.isfinite(extra_cpu_ms) or extra_cpu_ms < 0:
+ raise ValueError("extra_cpu_ms must be finite and nonnegative")
+ image = np.ascontiguousarray(image, dtype=np.uint8)
+ if image.ndim != 3 or image.shape[2] != 3 or min(image.shape[:2]) == 0:
+ raise ValueError("Expected a nonempty RGB image")
+ h, w = image.shape[:2]
+ start = time.thread_time_ns()
+ faces = self._detect_ctypes(image, w, h, 32, False, 640, .35)
+ estimate = (time.thread_time_ns() - start) / 1e6 * (448/640)**2
+ crop = guided_crop(faces, w, h) if estimate <= extra_cpu_ms else None
+ if crop:
+ x, y, cw, ch = crop
+ patch = np.ascontiguousarray(image[y:y+ch, x:x+cw])
+ extra = self._detect_ctypes(patch, cw, ch, 32, False, 448, .35)
+ faces = merge_faces(faces, extra, x, y)
+ threshold = .78 if estimate <= extra_cpu_ms else self._score_threshold
+ limit = self._max_faces if max_faces is None else max_faces
+ if limit < 0:
+ 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
+ return faces
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."""
diff --git a/python/facex/yunet.py b/python/facex/yunet.py
index 51f9471..d9ce1e4 100644
--- a/python/facex/yunet.py
+++ b/python/facex/yunet.py
@@ -24,3 +24,39 @@ def prepare_rectangle(image, *, bgr=False, side=640):
pixels = np.asarray(Image.fromarray(image).resize((rw, rh), bicubic))
canvas[y:y + rh, x:x + rw] = pixels[:, :, ::-1] if bgr else pixels
return canvas, rw, rh
+
+
+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:
+ 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)]
+ cw, 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
+
+
+def merge_faces(base, extra, x, y):
+ 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"]):
+ 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):
+ break
+ else:
+ kept.append(f)
+ if len(kept) == 32:
+ break
+ return kept
diff --git a/src/detect.c b/src/detect.c
index fe58289..58a5caf 100644
--- a/src/detect.c
+++ b/src/detect.c
@@ -295,6 +295,12 @@ static int nms_sort(DetectFace* f, int n, float iou_t) {
int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,
DetectFace* out, int max_faces) {
+ return detect_run_threshold(det, rgb_hwc, width, height, out, max_faces,
+ det ? det->score_threshold : 0);
+}
+
+int detect_run_threshold(Detect* det, const uint8_t* rgb_hwc, int width, int height,
+ DetectFace* out, int max_faces, float threshold) {
if (!det || !rgb_hwc || !out || max_faces < 0) return -1;
if (width <= 0 || height <= 0) return -1;
@@ -307,7 +313,10 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,
int h2=H/2, w2=W/2, h4=h2/2, w4=w2/2, h8=h4/2, w8=w4/2, h16=h8/2, w16=w8/2, h32=h16/2, w32=w16/2;
/* Workspace layout: dedicated buffers */
- uint64_t needed = (uint64_t)3*H*W + (uint64_t)3*64*h2*w2
+ /* Peaks: stem 16 channels at stride two, backbone 64 at stride four. */
+ size_t feature_slots = (size_t)16*h2*w2;
+ size_t object_slots = (size_t)h8*w8;
+ uint64_t needed = (uint64_t)3*H*W + 2 * (uint64_t)feature_slots + object_slots
+ (size_t)80*h8*w8 + (size_t)64*h16*w16 + (size_t)64*h32*w32;
if (needed > SIZE_MAX / sizeof(float)) return -1;
if (needed > det->work_size) {
@@ -318,9 +327,9 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,
}
float* wp = det->work;
float* inp = wp; wp += 3*H*W;
- float* a = wp; wp += 64*h2*w2;
- float* b = wp; wp += 64*h2*w2;
- float* c = wp; wp += 64*h2*w2;
+ float* a = wp; wp += feature_slots;
+ float* b = wp; wp += feature_slots;
+ float* c = wp; wp += object_slots;
float* f8 = wp; wp += 64*h8*w8; /* saved stride-8 */
float* f16 = wp; wp += 64*h16*w16; /* saved stride-16 */
float* f32_ = wp; wp += 64*h32*w32; /* saved stride-32 */
@@ -467,7 +476,7 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,
for (int gx = 0; gx < fw; gx++) {
int idx = gy * fw + gx;
float sc = sqrtf(sigm(cls[idx]) * sigm(obj[idx]));
- if (sc < det->score_threshold) continue;
+ if (sc < threshold) continue;
/* YuNet regresses the center offset and log width/height. */
float cx = (gx + hd[idx]) * st;
float cy = (gy + hd[hw + idx]) * st;
diff --git a/src/edgeface_engine.c b/src/edgeface_engine.c
index 2f7be96..e9b58f4 100644
--- a/src/edgeface_engine.c
+++ b/src/edgeface_engine.c
@@ -12,6 +12,7 @@
*/
#include <stdio.h>
+#include <limits.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
@@ -63,6 +64,7 @@ typedef struct {
/* INT8 pre-packed MatMul weights */
PackedMM* mm; /* array, indexed same as tensors */
/* FP32 pre-packed MatMul weights */
+ float* cached_position;
PackedFP32* fp; /* array, indexed same as tensors */
} Weights;
@@ -72,72 +74,44 @@ static int load_weights(const char* path, Weights* w) {
FILE* f = fopen(path, "rb");
if (!f) return -1;
- fseek(f, 0, SEEK_END);
- w->raw_size = ftell(f);
- fseek(f, 0, SEEK_SET);
-
- w->raw = (uint8_t*)malloc(w->raw_size);
- fread(w->raw, 1, w->raw_size, f);
+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return -1; }
+ long length = ftell(f);
+ if (length < 8) { fclose(f); return -1; }
+ rewind(f);
+ w->raw_size = (size_t)length;
+ w->raw = malloc(w->raw_size);
+ int ok = w->raw && fread(w->raw, 1, w->raw_size, f) == w->raw_size;
fclose(f);
+ if (!ok) return -1;
- /* Handle encrypted weights (EFXE magic) */
+ uint8_t* payload = w->raw;
+ size_t size = w->raw_size;
#ifndef NO_CRYPTO
- if (w->raw_size >= 20 && memcmp(w->raw, "EFXE", 4) == 0) {
- if (!g_license_key || !g_license_key[0]) {
- fprintf(stderr, "ERROR: Encrypted weights require LICENSE_KEY\n");
- fprintf(stderr, "Set LICENSE_KEY environment variable or pass --license KEY\n");
- free(w->raw);
- return -3;
- }
- int r = weight_decrypt_inplace(w->raw, w->raw_size, g_license_key);
- if (r == -2) {
- fprintf(stderr, "ERROR: Invalid license key for this machine\n");
- free(w->raw);
- return -2;
- } else if (r != 0) {
- fprintf(stderr, "ERROR: Decryption failed (%d)\n", r);
- free(w->raw);
- return r;
- }
- /* After decryption, EFXS payload starts at offset 20 */
- uint8_t* payload = w->raw + 20;
- size_t payload_size = w->raw_size - 20;
-
- if (memcmp(payload, "EFXS", 4) != 0) {
- free(w->raw);
- return -1;
- }
-
- uint32_t n = *(uint32_t*)(payload + 4);
- w->n_tensors = n;
- w->tensors = (float**)malloc(n * sizeof(float*));
-
- size_t off = 8;
- for (uint32_t i = 0; i < n; i++) {
- uint32_t sz = *(uint32_t*)(payload + off);
- off += 4;
- w->tensors[i] = (float*)(payload + off);
- off += sz;
- }
- return 0;
+ if (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 (rc) return rc;
+ payload += 20;
+ size -= 20;
}
#endif
-
- /* Unencrypted weights (EFXS magic) */
- if (memcmp(w->raw, "EFXS", 4) != 0) return -1;
-
- uint32_t n = *(uint32_t*)(w->raw + 4);
- w->n_tensors = n;
- w->tensors = (float**)malloc(n * sizeof(float*));
-
+ if (size < 8 || memcmp(payload, "EFXS", 4) != 0) return -1;
+ uint32_t n;
+ memcpy(&n, payload + 4, sizeof(n));
+ if (n < 286 || n > (size-8)/4 || n > INT_MAX) return -1;
+ w->n_tensors = (int)n;
+ w->tensors = calloc(n, sizeof(*w->tensors));
+ if (!w->tensors) return -1;
size_t off = 8;
for (uint32_t i = 0; i < n; i++) {
- uint32_t sz = *(uint32_t*)(w->raw + off);
- off += 4;
- w->tensors[i] = (float*)(w->raw + off);
- off += sz;
+ uint32_t bytes;
+ if (size-off < sizeof(bytes)) return -1;
+ memcpy(&bytes, payload+off, sizeof(bytes));
+ off += sizeof(bytes);
+ if (bytes > size-off || bytes % sizeof(float)) return -1;
+ w->tensors[i] = (float*)(payload+off);
+ off += bytes;
}
-
return 0;
}
@@ -451,14 +425,20 @@ void xca_block(float* x_hwc, int H, int W, int C,
* AVX2 optimized: vectorize across output channels (Cout). */
/* conv2d_hwc with pre-transposed weights in [Cin*KK, Cout] layout.
* At load time, call conv2d_hwc_reorder_weights() to transpose OIHW → [Cin*KK, Cout]. */
-void conv2d_hwc_reorder_weights(float* w, int Cout, int Cin, int KK) {
+static int reorder_conv_weights(float* w, int Cout, int Cin, int KK) {
/* In-place transpose from [Cout, Cin*KK] to [Cin*KK, Cout] */
float* tmp = (float*)malloc((size_t)Cout * Cin * KK * sizeof(float));
+ if (!tmp) return -1;
memcpy(tmp, w, (size_t)Cout * Cin * KK * sizeof(float));
for (int co = 0; co < Cout; co++)
for (int ci_ki = 0; ci_ki < Cin * KK; ci_ki++)
w[ci_ki * Cout + co] = tmp[co * Cin * KK + ci_ki];
free(tmp);
+ return 0;
+}
+
+void conv2d_hwc_reorder_weights(float* w, int Cout, int Cin, int KK) {
+ (void)reorder_conv_weights(w, Cout, Cin, KK);
}
void conv2d_hwc(const float* in_hwc, int Cin, int H, int W,
@@ -966,22 +946,43 @@ static void edgeface_forward(const float* input_chw, /* [3, 112, 112] */
}
/* ============ Engine Init (used by both main and library API) ============ */
-static int engine_init(const char* weights_path, Weights* weights) {
- /* Init thread pool for parallel GEMM */
- {
- extern void tp_init(int);
- tp_init(4);
+static void release_weights(Weights* w) {
+ if (_g_weights == w) _g_weights = NULL;
+ for (int i = 0; i < w->n_tensors; i++) {
+ if (w->mm) {
+ free(w->mm[i].packed);
+ free(w->mm[i].w_scales);
+ free(w->mm[i].col_sums);
+ }
+ if (w->fp) {
+#ifdef _WIN32
+ _aligned_free(w->fp[i].data);
+#else
+ free(w->fp[i].data);
+#endif
+ }
}
+ free(w->mm);
+ free(w->fp);
+ free(w->cached_position);
+ free(w->tensors);
+ free(w->raw);
+ memset(w, 0, sizeof(*w));
+}
+static int engine_init(const char* weights_path, Weights* weights) {
+ memset(weights, 0, sizeof(*weights));
if (load_weights(weights_path, weights) != 0) {
fprintf(stderr, "Failed to load %s\n", weights_path);
- return -1;
+ goto fail;
}
/* Allocate packed MatMul weight arrays */
weights->mm = (PackedMM*)calloc(weights->n_tensors, sizeof(PackedMM));
weights->fp = (PackedFP32*)calloc(weights->n_tensors, sizeof(PackedFP32));
+ if (!weights->mm || !weights->fp) goto fail;
+
/* Pre-pack MatMul weights to INT8 c8 format */
{
extern void pack_weights_4x8c8(const int8_t*, const float*, int, int, void*, int32_t*);
@@ -1045,6 +1046,8 @@ static int engine_init(const char* weights_path, Weights* weights) {
int8_t* w_int8 = (int8_t*)malloc((size_t)N * K);
float* w_scales = (float*)malloc(N * sizeof(float));
+ weights->mm[idx].w_scales = w_scales;
+ if (!w_int8 || !w_scales) { free(w_int8); goto fail; }
for (int n = 0; n < N; n++) {
float mx = 0;
for (int k = 0; k < K; k++) {
@@ -1064,11 +1067,12 @@ static int engine_init(const char* weights_path, Weights* weights) {
int pw_size = packed_weights_size_4x8c8(K, N);
void* packed = malloc(pw_size);
int32_t* col_sums = (int32_t*)calloc(((N+7)&~7), sizeof(int32_t));
- pack_weights_4x8c8(w_int8, NULL, K, N, packed, col_sums);
+
weights->mm[idx].packed = packed;
weights->mm[idx].col_sums = col_sums;
- weights->mm[idx].w_scales = w_scales;
+ if (!packed || !col_sums) { free(w_int8); goto fail; }
+ pack_weights_4x8c8(w_int8, NULL, K, N, packed, col_sums);
weights->mm[idx].K = K;
weights->mm[idx].N = N;
packed_count++;
@@ -1115,16 +1119,12 @@ static int engine_init(const char* weights_path, Weights* weights) {
int K_ = fp_shapes[i][0], N_ = fp_shapes[i][1];
int sz = packed_b_fp32_size(K_, N_);
float* packed;
-#ifdef _WIN32
#ifdef _WIN32
packed = (float*)_aligned_malloc((size_t)sz * sizeof(float), 64);
-#else
- if (posix_memalign((void**)&packed, 64, (size_t)sz * sizeof(float)) != 0) packed = NULL;
-#endif
#else
packed = (float*)aligned_alloc(32, (size_t)sz * sizeof(float));
#endif
- if (!packed) packed = (float*)malloc((size_t)sz * sizeof(float));
+ if (!packed) goto fail;
pack_b_fp32(weights->tensors[idx], K_, N_, packed);
weights->fp[idx].data = packed;
weights->fp[idx].K = K_;
@@ -1154,6 +1154,7 @@ static int engine_init(const char* weights_path, Weights* weights) {
for (int j = 0; j < 3; j++) {
int idx = stage0_dw[j]; int C = 32, KK = 9;
float* tmp = (float*)malloc(C * KK * sizeof(float));
+ if (!tmp) goto fail;
memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
for (int c = 0; c < C; c++)
for (int ki = 0; ki < KK; ki++)
@@ -1165,6 +1166,7 @@ static int engine_init(const char* weights_path, Weights* weights) {
for (int j = 0; j < 2; j++) {
int idx = stage1_dw[j]; int C = 64, KK = 25;
float* tmp = (float*)malloc(C * KK * sizeof(float));
+ if (!tmp) goto fail;
memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
for (int c = 0; c < C; c++)
for (int ki = 0; ki < KK; ki++)
@@ -1175,6 +1177,7 @@ static int engine_init(const char* weights_path, Weights* weights) {
for (int b = 0; b < 8; b++) {
int idx = 105 + b * 11; int C = 100, KK = 49;
float* tmp = (float*)malloc(C * KK * sizeof(float));
+ if (!tmp) goto fail;
memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
for (int c = 0; c < C; c++)
for (int ki = 0; ki < KK; ki++)
@@ -1186,6 +1189,7 @@ static int engine_init(const char* weights_path, Weights* weights) {
for (int j = 0; j < 2; j++) {
int idx = stage3_dw[j]; int C = 192, KK = 81;
float* tmp = (float*)malloc(C * KK * sizeof(float));
+ if (!tmp) goto fail;
memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
for (int c = 0; c < C; c++)
for (int ki = 0; ki < KK; ki++)
@@ -1195,9 +1199,9 @@ static int engine_init(const char* weights_path, Weights* weights) {
}
/* Reorder downsample conv weights: OIHW [Cout,Cin,K,K] → [Cin*KK, Cout] for AVX2 */
- conv2d_hwc_reorder_weights(weights->tensors[42], 64, 32, 4); /* ds 0→1: 32→64 2×2 */
- conv2d_hwc_reorder_weights(weights->tensors[103], 100, 64, 4); /* ds 1→2: 64→100 2×2 */
- conv2d_hwc_reorder_weights(weights->tensors[223], 192, 100, 4);/* ds 2→3: 100→192 2×2 */
+ if (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;
/* Register JIT kernels for small-K matmuls (optional — link jit_gemm.c) */
#ifdef USE_JIT
@@ -1219,6 +1223,8 @@ static int engine_init(const char* weights_path, Weights* weights) {
{
int HW = 196, C = 64;
float* pos_cached = (float*)malloc((size_t)HW * C * sizeof(float));
+ if (!pos_cached) goto fail;
+ weights->cached_position = pos_cached;
const float* pos_const = weights->tensors[69]; /* [1, 64, 14, 14] NCHW */
const float* pos_w = weights->tensors[70]; /* [64, 64, 1, 1] = [Cout, Cin] */
const float* pos_b = weights->tensors[71]; /* [64] */
@@ -1233,6 +1239,9 @@ static int engine_init(const char* weights_path, Weights* weights) {
}
return 0;
+fail:
+ release_weights(weights);
+ return -1;
}
/* ============ Main ============ */
@@ -1265,6 +1274,7 @@ int main(int argc, char** argv) {
size_t rd = fread(input, sizeof(float), 3*112*112, stdin);
if (rd != 3*112*112) {
fprintf(stderr, "Expected %d floats, got %zu\n", 3*112*112, rd);
+ release_weights(&weights);
return 1;
}
} else {
@@ -1324,8 +1334,7 @@ int main(int argc, char** argv) {
fflush(stdout);
}
- free(weights.tensors);
- free(weights.raw);
+ release_weights(&weights);
return 0;
}
#endif /* FACEX_LIB */
diff --git a/src/facex.c b/src/facex.c
index 8253e29..d9c07ed 100644
--- a/src/facex.c
+++ b/src/facex.c
@@ -64,6 +64,13 @@ static float source_coordinate(float value, int padding, int resized, int origin
int facex_detect_prepared(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,
const uint8_t* canvas, int canvas_w, int canvas_h,
int resized_w, int resized_h, FaceXResult* out, int max_faces) {
+ return facex_detect_prepared_ex(fx, rgb_hwc, width, height, canvas, canvas_w, canvas_h,
+ resized_w, resized_h, out, max_faces, 1, -1);
+}
+
+int facex_detect_prepared_ex(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,
+ const uint8_t* canvas, int canvas_w, int canvas_h,
+ int resized_w, int resized_h, FaceXResult* out, int max_faces, int embeddings, float threshold) {
if (!fx || !fx->ready || !fx->detector || !rgb_hwc || !canvas || !out ||
width <= 0 || height <= 0 || max_faces <= 0 ||
resized_w <= 0 || resized_w > canvas_w ||
@@ -71,7 +78,8 @@ int facex_detect_prepared(FaceX* fx, const uint8_t* rgb_hwc, int width, int heig
DetectFace det_faces[32];
int n_det = max_faces < 32 ? max_faces : 32;
- int n = detect_run(fx->detector, canvas, canvas_w, canvas_h, det_faces, n_det);
+ int n = threshold < 0 ? detect_run(fx->detector, canvas, canvas_w, canvas_h, det_faces, n_det)
+ : detect_run_threshold(fx->detector, canvas, canvas_w, canvas_h, det_faces, n_det, threshold);
int dx = (canvas_w - resized_w) / 2, dy = (canvas_h - resized_h) / 2;
for (int i = 0; i < n; i++) {
DetectFace* face = &det_faces[i];
@@ -84,20 +92,26 @@ int facex_detect_prepared(FaceX* fx, const uint8_t* rgb_hwc, int width, int heig
out[i].kps[k] = source_coordinate(face->kps[k], dx, resized_w, width);
out[i].kps[k+1] = source_coordinate(face->kps[k+1], dy, resized_h, height);
}
- /* Align face to 112×112 using keypoints */
- float aligned[112 * 112 * 3];
- if (!fx->embed_weights.raw || !align_face(rgb_hwc, width, height, out[i].kps, aligned)) {
+ if (embeddings)
+ facex_embed_landmarks(fx, rgb_hwc, width, height, out[i].kps, out[i].embedding);
+ else
memset(out[i].embedding, 0, sizeof(out[i].embedding));
- continue;
- }
-
- /* Compute embedding */
- facex_embed(fx, aligned, out[i].embedding);
}
return n;
}
+int facex_embed_landmarks(FaceX* fx, const uint8_t* rgb, int w, int h,
+ const float kps[10], float embedding[512]) {
+ if (!fx || !rgb || !kps || !embedding || w <= 0 || h <= 0) return -1;
+ float aligned[112*112*3];
+ if (!fx->embed_weights.raw || !align_face(rgb, w, h, kps, aligned)) {
+ memset(embedding, 0, 512 * sizeof(float));
+ return 0;
+ }
+ return facex_embed(fx, aligned, embedding);
+}
+
int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]) {
if (!fx || !fx->ready) return -1;
@@ -125,8 +139,7 @@ float facex_similarity(const float emb1[512], const float emb2[512]) {
void facex_free(FaceX* fx) {
if (!fx) return;
if (fx->detector) detect_free(fx->detector);
- if (fx->embed_weights.raw) free(fx->embed_weights.raw);
- if (fx->embed_weights.tensors) free(fx->embed_weights.tensors);
+ release_weights(&fx->embed_weights);
free(fx);
}
diff --git a/tests/bench_yunet_guided_min8.py b/tests/bench_yunet_guided_min8.py
new file mode 100644
index 0000000..ab5c634
--- /dev/null
+++ b/tests/bench_yunet_guided_min8.py
@@ -0,0 +1,69 @@
+"""Recheck guided refinement with the eight pixel minimum and the optimized detector."""
+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_detail import annotations, detect, refine, score
+from verify_yunet import ROOT
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ for key in ("weights", "images", "labels"):
+ parser.add_argument(key, type=Path)
+ args = parser.parse_args()
+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})
+ with ZipFile(args.labels) as z:
+ labels = annotations(z)
+ pool = set(labels)
+ for seed, n in ((114,640),(725,128),(3519,672),(9101,384)):
+ pool -= set(np.random.default_rng(seed).choice(sorted(pool),n,replace=False))
+ names = np.random.default_rng(60177).choice(sorted(pool),448,replace=False)
+ data = []
+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.images) as photos:
+ so = Path(tmp)/"native.so"
+ subprocess.run(["gcc","-O3","-march=native","-fPIC","-shared","-I",str(ROOT/"include"),
+ str(ROOT/"src/detect.c"),"-lm","-o",str(so)],check=True)
+ lib = ctypes.CDLL(str(so))
+ lib.detect_init.restype = ctypes.c_void_p
+ e = ctypes.c_void_p(lib.detect_init(bytes(args.weights)))
+ if not e:
+ raise RuntimeError("Cannot load detector")
+ lib.detect_set_min_box_side(e,ctypes.c_int(8))
+ lib.detect_set_score_threshold(e,ctypes.c_float(.35))
+ try:
+ for name in names:
+ rgb = np.asarray(Image.open(io.BytesIO(photos.read("WIDER_val/images/"+name))).convert("RGB"))
+ gt = labels[name].copy()
+ small = np.sqrt(gt[:,2:].prod(1))*320/max(rgb.shape[:2]) < 16
+ gt[:,2:] += gt[:,:2]
+ t0 = time.thread_time_ns()
+ base = detect(lib,e,rgb,640)
+ t1 = time.thread_time_ns()
+ guided,used = refine(lib,e,rgb,base)
+ t2 = time.thread_time_ns()
+ data.append((gt,small,[base,guided],[(t1-t0)/1e6,(t2-t0)/1e6],used))
+ finally:
+ lib.detect_free(e)
+ dev,test = data[:128],data[128:]
+ budget = score(dev,0,.75)[0].sum(0)[1]
+ options = [(t,score(dev,1,t)[0].sum(0)) for t in np.round(np.arange(.50,.981,.01),2)]
+ threshold,_ = max((o for o in options if o[1][1]<=budget),key=lambda o:(o[1][2],o[1][0]))
+ baseline = score(test,0,.75)[0]
+ guided = score(test,1,threshold)[0]
+ bs = np.random.default_rng(315).integers(len(test),size=(2000,len(test)))
+ print("threshold",threshold,"baseline vs guided TP FP small",baseline.sum(0),guided.sum(0))
+ print("mean CPU ms",np.mean([x[3] for x in test],axis=0),"cropped",sum(x[4] for x in test))
+ print("paired delta CI",np.percentile((guided-baseline)[bs].sum(1),[2.5,97.5],axis=0))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/verify_rectangular_client.py b/tests/verify_rectangular_client.py
index b59d2e4..f77bce7 100644
--- a/tests/verify_rectangular_client.py
+++ b/tests/verify_rectangular_client.py
@@ -57,6 +57,14 @@ def main():
buf.seek(0)
response = client.post("/detect", data={"file": (buf, "image.png")})
assert response.status_code == 200, response.data
+ buf = io.BytesIO()
+ image.save(buf, format="PNG")
+ buf.seek(0)
+ geometry = client.post("/detect?embeddings=false", data={"file": (buf, "image.png")})
+ assert geometry.status_code == 200
+ expected_geometry = [{k: v for k, v in face.items() if k != "embedding"}
+ for face in response.get_json()["faces"]]
+ assert geometry.get_json()["faces"] == expected_geometry
returned = response.get_json()["faces"]
assert len(returned) == len(faces)
for api, face in zip(returned, faces):
diff --git a/tests/weights_lifetime.c b/tests/weights_lifetime.c
new file mode 100644
index 0000000..7f13916
--- /dev/null
+++ b/tests/weights_lifetime.c
@@ -0,0 +1,48 @@
+/* Link the native objects with GNU ld --wrap for each allocation below. */
+#include "facex.h"
+#include <assert.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+static int live, calls, fail_at;
+void *__real_malloc(size_t);
+void *__real_calloc(size_t, size_t);
+void *__real_aligned_alloc(size_t, size_t);
+void __real_free(void *);
+
+static void *record(void *p) {
+ if (p) live++;
+ return p;
+}
+void *__wrap_malloc(size_t n) {
+ return ++calls == fail_at ? NULL : record(__real_malloc(n));
+}
+void *__wrap_calloc(size_t n, size_t size) {
+ return ++calls == fail_at ? NULL : record(__real_calloc(n, size));
+}
+void *__wrap_aligned_alloc(size_t alignment, size_t size) {
+ return ++calls == fail_at ? NULL : record(__real_aligned_alloc(alignment, size));
+}
+void __wrap_free(void *p) {
+ if (p) live--;
+ __real_free(p);
+}
+int main(int argc, char **argv) {
+ if (argc != 2) return 2;
+ int allocations = 0;
+ for (int i = 0; i < 100; i++) {
+ calls = 0;
+ FaceX *fx = facex_init(argv[1], NULL, NULL);
+ assert(fx);
+ facex_free(fx);
+ assert(live == 0);
+ allocations = calls;
+ }
+ for (fail_at = 1; fail_at <= allocations; fail_at++) {
+ calls = 0;
+ FaceX *fx = facex_init(argv[1], NULL, NULL);
+ assert(!fx && live == 0);
+ }
+ printf("100 cycles and %d allocation failure paths balanced\n", allocations);
+}