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.

Keep concurrent embedding responses paired with their requests

Baurzhan Atynovb2cfb378c58b
diff --git a/docker/server.py b/docker/server.py
index 8f480fd..5182bf9 100644
--- a/docker/server.py
+++ b/docker/server.py
@@ -11,6 +11,7 @@ Usage:
gunicorn -w 2 -b 0.0.0.0:8080 server:app
"""
+import base64
import os
import subprocess
import threading
@@ -46,7 +47,6 @@ class FaceXProcess:
[FACEX_CLI, EMBED_WEIGHTS, '--server'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
)
def embed(self, face_112x112_hwc):
@@ -55,14 +55,20 @@ class FaceXProcess:
self.proc.stdin.write(data)
self.proc.stdin.flush()
out = self.proc.stdout.read(512 * 4)
+ if len(out) != 512 * 4:
+ raise OSError("Incomplete embedding from worker")
return np.frombuffer(out, dtype=np.float32).copy()
def close(self):
self.proc.terminate()
+ self.proc.wait()
+ self.proc.stdin.close()
+ self.proc.stdout.close()
# Global process (per worker)
_fx = None
+_embed_lock = threading.Lock()
_detector = None
_detector_lock = threading.Lock()
@@ -79,11 +85,18 @@ def initialize_detector():
_detector = engine
-def get_fx():
+def embed_in_worker(arr):
global _fx
- if _fx is None:
- _fx = FaceXProcess()
- return _fx
+ # The binary protocol has no request IDs. Keep each write and read together.
+ with _embed_lock:
+ if _fx is None:
+ _fx = FaceXProcess()
+ try:
+ return _fx.embed(arr)
+ except OSError:
+ failed, _fx = _fx, None
+ failed.close()
+ raise
@app.route('/health', methods=['GET'])
@@ -106,8 +119,11 @@ def embed():
arr = np.array(img, dtype=np.float32) / 127.5 - 1.0 # normalize to [-1, 1]
t0 = time.time()
- fx = get_fx()
- emb = fx.embed(arr)
+ try:
+ emb = embed_in_worker(arr)
+ except OSError:
+ app.logger.exception("Embedding worker failed")
+ return jsonify({"error": "Face embedding unavailable"}), 503
ms = (time.time() - t0) * 1000
return jsonify({
@@ -152,6 +168,9 @@ def detect():
if flag not in ("true", "false"):
return jsonify({"error": "embeddings must be true or false"}), 400
embeddings = flag == "true"
+ encoding = request.args.get("embedding_format", "array")
+ if encoding not in ("array", "base64_f32le"):
+ return jsonify({"error": "embedding_format must be array or base64_f32le"}), 400
try:
with Image.open(request.files['file'].stream) as uploaded:
@@ -169,7 +188,11 @@ def detect():
return jsonify({'error': 'Face detection unavailable'}), 503
if embeddings:
for face in faces:
- face['embedding'] = face['embedding'].tolist()
+ vector = face["embedding"]
+ if encoding == "base64_f32le":
+ face["embedding"] = base64.b64encode(vector.astype("<f4", copy=False)).decode("ascii")
+ else:
+ face["embedding"] = vector.tolist()
return jsonify({'faces': faces, 'ms': round((time.perf_counter() - start) * 1000, 2)})
diff --git a/docs/research/multiface_requests.md b/docs/research/multiface_requests.md
new file mode 100644
index 0000000..3811abd
--- /dev/null
+++ b/docs/research/multiface_requests.md
@@ -0,0 +1,29 @@
+# Fresh embeddings and simultaneous requests
+
+The Flask endpoint accepts `POST /detect?embedding_format=base64_f32le`. The usual numeric array is the default. In compact mode each face's embedding is one standard Base64 string containing 512 little-endian float32 values. Decode with `np.frombuffer(base64.b64decode(face["embedding"]), dtype="<f4")`.
+
+On Linux x86-64-v3, a tiled 32-face JPEG took a median 157.29 ms per complete default request and 152.75 ms compact, versus 39.39 ms for geometry only. Response size fell from about 362,085 to 97,882 bytes. All coordinates and all 16,384 float bit patterns matched. The warmed Flask client ran 12 timed requests per mode on one pinned CPU, rotating the order. Separate replay timings for 32 faces were 5.16 ms for alignment, 116.25 ms for the embedding model and SDK calls, and 7.31 ms for conversion and JSON serialization of the vectors. Independent medians do not add up to endpoint latency.
+
+A separate process-group experiment on the same JPEG and unconstrained CPU affinity split the 32 faces over four persistent processes. Alignment and fresh embedding took 61.83 ms versus 132.10 ms sequentially, including dispatch, copying the RGB image to each process and returning the results. All vectors matched bitwise. This experiment has no competing clients and does not enable a process pool inside the service.
+
+## Burst measurements
+
+Each cell below used 64 requests to 8 different JPEGs. The client checked every response payload against the same image's sequential reference, excluding timing. Two isolated processes ran the Flask endpoints. Client timing includes queueing, process dispatch, response parsing and checksum computation. HTTP sockets, proxies, authentication and a downstream identity database are outside the WSGI measurement.
+
+| Concurrent clients | Detect requests/s | Detect p95 ms | Embed requests/s | Embed p95 ms |
+|---:|---:|---:|---:|---:|
+| 1 | 19.4 | 59 | 92.8 | 13 |
+| 8 | 36.1 | 268 | 207.1 | 39 |
+| 32 | 39.1 | 816 | 206.9 | 155 |
+
+A separate single-process threaded run also matched all sequential references, including 32 concurrent clients. The embedding CLI's binary request and response now share one lock per parent process. A terminated child yields a 503 and a later request creates a fresh worker.
+
+With the native library, CLI and mounted weights configured, run from the repository root:
+
+~~~sh
+PYTHONPATH=python:docker python tests/bench_multiface_response.py --batch-workers 4
+PYTHONPATH=python:docker python tests/bench_http_burst.py --wsgi-processes 2
+PYTHONPATH=python:docker python tests/bench_http_burst.py --wsgi-threads
+~~~
+
+For a running Gunicorn instance listening on a Unix socket, pass `--socket /path/to/socket` instead.
diff --git a/tests/bench_http_burst.py b/tests/bench_http_burst.py
new file mode 100644
index 0000000..df81178
--- /dev/null
+++ b/tests/bench_http_burst.py
@@ -0,0 +1,94 @@
+"""Send overlapping requests to a local Gunicorn Unix socket and verify response ownership."""
+import argparse
+from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
+from hashlib import sha256
+from http.client import HTTPConnection
+import io
+import json
+from pathlib import Path
+import socket
+import threading
+from time import perf_counter
+
+import numpy as np
+from PIL import Image
+
+
+class LocalHTTP(HTTPConnection):
+ def __init__(self, path):
+ super().__init__("localhost", timeout=30)
+ self.path = path
+
+ def connect(self):
+ self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ self.sock.settimeout(self.timeout)
+ self.sock.connect(self.path)
+
+
+_clients = threading.local()
+
+
+def wsgi_digest(endpoint, field, jpeg):
+ from server import app
+ if not hasattr(_clients, "client"):
+ _clients.client = app.test_client()
+ response = _clients.client.post(endpoint, data={"file": (io.BytesIO(jpeg), "face.jpg")})
+ assert response.status_code == 200, response.data
+ return sha256(json.dumps(response.json[field], sort_keys=True).encode()).digest()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ mode = parser.add_mutually_exclusive_group(required=True)
+ mode.add_argument("--socket")
+ mode.add_argument("--wsgi-processes", type=int)
+ mode.add_argument("--wsgi-threads", action="store_true")
+ args = parser.parse_args()
+ jpegs = []
+ payloads = []
+ for path in sorted((Path(__file__).parent / "golden").glob("*.npz"))[:8]:
+ with np.load(path) as fixture:
+ buf = io.BytesIO()
+ Image.fromarray(fixture["image"]).save(buf, "JPEG")
+ jpegs.append(buf.getvalue())
+ payloads.append(b'--face\r\nContent-Disposition: form-data; name="file"; filename="f.jpg"\r\n'
+ b'Content-Type: image/jpeg\r\n\r\n' + buf.getvalue() + b'\r\n--face--\r\n')
+ assert len(payloads) == 8
+ workers = ProcessPoolExecutor(args.wsgi_processes) if args.wsgi_processes else None
+ for endpoint, field in (("/detect", "faces"), ("/embed", "embedding")):
+ def send(i):
+ start = perf_counter()
+ if not args.socket:
+ params = (endpoint, field, jpegs[i % 8])
+ digest = workers.submit(wsgi_digest, *params).result() if workers else wsgi_digest(*params)
+ return perf_counter() - start, digest
+ conn = LocalHTTP(args.socket)
+ try:
+ conn.request("POST", endpoint, payloads[i % 8],
+ {"Content-Type": "multipart/form-data; boundary=face"})
+ response = conn.getresponse()
+ raw = response.read()
+ elapsed = perf_counter() - start
+ assert response.status == 200, raw
+ result = json.loads(raw)[field]
+ return elapsed, sha256(json.dumps(result, sort_keys=True).encode()).digest()
+ finally:
+ conn.close()
+ expected = [send(i)[1] for i in range(8)]
+ assert len(set(expected)) == 8
+ for concurrency in (1, 8, 32):
+ with ThreadPoolExecutor(concurrency) as pool:
+ start = perf_counter()
+ samples = list(pool.map(send, range(64)))
+ elapsed = perf_counter() - start
+ assert all(digest == expected[i % 8] for i, (_, digest) in enumerate(samples))
+ lat = [s * 1000 for s, _ in samples]
+ print(endpoint, concurrency, "clients", round(64/elapsed, 1), "req/s",
+ "p50/p95 ms", np.round(np.percentile(lat, [50, 95]), 1), flush=True)
+
+ if workers:
+ workers.shutdown()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/bench_multiface_response.py b/tests/bench_multiface_response.py
new file mode 100644
index 0000000..5844a80
--- /dev/null
+++ b/tests/bench_multiface_response.py
@@ -0,0 +1,109 @@
+"""Profile 32 fresh face embeddings through the Flask endpoint and native API."""
+import argparse
+import base64
+from concurrent.futures import ProcessPoolExecutor
+import ctypes
+import io
+import statistics
+import time
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+import server
+
+
+def embed_group(image, landmarks):
+ server.initialize_detector()
+ return [server._detector.embed_landmarks(image, points) for points in landmarks]
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--batch-workers", type=int, choices=(2, 4))
+ args = parser.parse_args()
+ root = Path(__file__).resolve().parents[1]
+ with Image.open(root / "data/test_face.jpg") as source:
+ tile = source.convert("RGB").resize((112, 112))
+ image = Image.new("RGB", (896, 448))
+ for i in range(32):
+ image.paste(tile, (i % 8 * 112, i // 8 * 112))
+ buf = io.BytesIO()
+ image.save(buf, format="JPEG")
+ payload = buf.getvalue()
+ rgb = np.asarray(Image.open(io.BytesIO(payload)).convert("RGB"))
+ client = server.app.test_client()
+
+ def request(query):
+ return client.post("/detect" + query, data={"file": (io.BytesIO(payload), "faces.jpg")})
+
+ queries = ("", "?embedding_format=base64_f32le", "?embeddings=false")
+ samples = [[] for _ in queries]
+ for rep in range(13):
+ results = {}
+ for j in (np.arange(3) + rep) % 3:
+ start = time.perf_counter_ns()
+ response = request(queries[j])
+ elapsed = time.perf_counter_ns() - start
+ assert response.status_code == 200
+ faces = response.json["faces"]
+ assert len(faces) == 32
+ if rep:
+ samples[j].append(elapsed / 1e6)
+ results[j] = faces
+ if rep == 0:
+ print(queries[j] or "array", len(response.data), "bytes")
+ for a, b, geom in zip(results[0], results[1], results[2]):
+ expected = np.asarray(a.pop("embedding"), dtype="<f4").tobytes()
+ assert base64.b64decode(b.pop("embedding"), validate=True) == expected
+ assert a == b == geom
+ assert request("?embedding_format=bad").status_code == 400
+ print("Full request median ms (array, compact, geometry)", list(map(statistics.median, samples)))
+
+ engine = server._detector
+ float_ptr = ctypes.POINTER(ctypes.c_float)
+ byte_ptr = ctypes.POINTER(ctypes.c_uint8)
+ align = engine._lib.align_face
+ align.argtypes = [byte_ptr, ctypes.c_int, ctypes.c_int, float_ptr, float_ptr]
+ pts = [np.array(face["keypoints"], dtype="f").ctypes.data_as(float_ptr) for face in results[2]]
+ aligned = [np.empty((112, 112, 3), dtype="f") for _ in pts]
+ src = rgb.ctypes.data_as(byte_ptr)
+ stages = [[], [], []]
+ for rep in range(9):
+ start = time.perf_counter_ns()
+ for point, dest in zip(pts, aligned):
+ assert align(src, rgb.shape[1], rgb.shape[0], point, dest.ctypes.data_as(float_ptr))
+ mid = time.perf_counter_ns()
+ vectors = [engine.embed(face) for face in aligned]
+ end = time.perf_counter_ns()
+ with server.app.app_context():
+ server.app.json.dumps([v.tolist() for v in vectors])
+ done = time.perf_counter_ns()
+ if rep:
+ for arr, dt in zip(stages, (mid-start, end-mid, done-end)):
+ arr.append(dt / 1e6)
+ print("Stage median ms (align, embed, array JSON)", list(map(statistics.median, stages)))
+
+ if args.batch_workers:
+ landmarks = [face["keypoints"] for face in results[2]]
+ groups = np.array_split(landmarks, args.batch_workers)
+ timings = [[], []]
+ with ProcessPoolExecutor(args.batch_workers) as pool:
+ for rep in range(13):
+ for parallel in (rep % 2, 1 - rep % 2):
+ start = time.perf_counter_ns()
+ if parallel:
+ jobs = [pool.submit(embed_group, rgb, group) for group in groups]
+ batch = [v for job in jobs for v in job.result()]
+ else:
+ batch = embed_group(rgb, landmarks)
+ elapsed = (time.perf_counter_ns() - start) / 1e6
+ assert np.stack(batch).tobytes() == np.stack(vectors).tobytes()
+ if rep:
+ timings[parallel].append(elapsed)
+ print("Fresh landmark embeddings median ms (serial, process groups)",
+ list(map(statistics.median, timings)))
+
+
+if __name__ == "__main__":
+ main()