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.

Avoid decoding queued images when inference is busy

Baurzhan Atynov22531ecc71b0
diff --git a/docker/server.py b/docker/server.py
index 39d952a..0b0f16e 100644
--- a/docker/server.py
+++ b/docker/server.py
@@ -11,7 +11,7 @@ Usage:
gunicorn -w 2 -b 0.0.0.0:8080 server:app
"""
-from contextlib import contextmanager
+from contextlib import contextmanager, nullcontext
import base64
import os
import subprocess
@@ -72,6 +72,9 @@ _fx = None
_embed_lock = threading.Lock()
_detector = None
_detector_lock = threading.Lock()
+# One image can be prepared while the preceding image is inside each model.
+_detect_capacity = threading.BoundedSemaphore(2)
+_embed_capacity = threading.BoundedSemaphore(2)
QUEUE_WAIT_MS = int(os.environ.get("FACEX_QUEUE_WAIT_MS", "250"))
@@ -127,6 +130,12 @@ def inference_slot(lock):
lock.release()
+def preparation_slot(capacity):
+ if g.inference_deadline is None:
+ return nullcontext()
+ return inference_slot(capacity)
+
+
def initialize_detector():
"""Load weights before forking or under the detector lock in a worker."""
global _detector
@@ -169,17 +178,18 @@ def embed():
if 'file' not in request.files:
return jsonify({'error': 'No file uploaded'}), 400
- f = request.files['file']
- img = Image.open(f.stream).convert('RGB').resize((112, 112))
- arr = np.array(img, dtype=np.float32) / 127.5 - 1.0 # normalize to [-1, 1]
+ with preparation_slot(_embed_capacity):
+ f = request.files['file']
+ img = Image.open(f.stream).convert('RGB').resize((112, 112))
+ arr = np.array(img, dtype=np.float32) / 127.5 - 1.0 # normalize to [-1, 1]
- t0 = time.time()
- 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
+ t0 = time.time()
+ 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({
'embedding': emb.tolist(),
@@ -227,21 +237,22 @@ def detect():
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:
- rgb = np.asarray(uploaded.convert('RGB'))
- except (OSError, ValueError, Image.DecompressionBombError):
- return jsonify({'error': 'Invalid image'}), 400
-
- start = time.perf_counter()
- with inference_slot(_detector_lock):
+ with preparation_slot(_detect_capacity):
try:
- initialize_detector()
- check_inference_deadline()
- 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
+ with Image.open(request.files['file'].stream) as uploaded:
+ rgb = np.asarray(uploaded.convert('RGB'))
+ except (OSError, ValueError, Image.DecompressionBombError):
+ return jsonify({'error': 'Invalid image'}), 400
+
+ start = time.perf_counter()
+ with inference_slot(_detector_lock):
+ try:
+ initialize_detector()
+ check_inference_deadline()
+ 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
if embeddings:
for face in faces:
vector = face["embedding"]
diff --git a/docs/research/multiface_requests.md b/docs/research/multiface_requests.md
index b49dded..768208b 100644
--- a/docs/research/multiface_requests.md
+++ b/docs/research/multiface_requests.md
@@ -35,3 +35,17 @@ The Flask worker allows 250 ms by default from handler entry to starting inferen
To include time already spent uploading or waiting at a proxy or a synchronous Gunicorn worker, clients can send `X-FaceX-Deadline-Ms` with the absolute Unix time in milliseconds after which processing the frame is no longer useful. This requires synchronized clocks. The earlier deadline applies. The worker checks expiration before accessing the multipart body and again before model execution. Queues outside Flask can still delay delivery of the 503 response.
In a local 64-request burst with 32 clients, one threaded Flask process and eight real JPEGs, unlimited admission returned 64 successful responses with p95 1767 ms. A 250 ms budget admitted 10 (p95 313 ms) and rejected 54 (p95 253 ms). All admitted responses matched their image's sequential result. A subsequent request completed normally. These are WSGI timings for a single burst.
+
+## Limit decoded images during overload
+
+For requests with a deadline, after multipart parsing each process allows up to two requests per inference endpoint to prepare an image or use the engine. This leaves room to decode the next image while the model is busy. Waiting for preparation and waiting for the model share the original deadline. Expiration in the first queue skips image decoding. Requests with unlimited admission keep the original preprocessing path.
+
+We compared against abc177f in six alternating pairs of local bursts on four pinned logical CPUs. Each burst used one warmed threaded Flask process, 32 clients and 64 detection requests drawn from eight fixture JPEGs resized to 1920 by 1080. The local admission budget was 250 ms. CPU includes the in-process test client. Latency includes successful and rejected responses.
+
+| Median per burst | Before | After |
+|---|---:|---:|
+| JPEGs opened for decoding | 64 | 10.5 |
+| Process CPU seconds | 2.135 | 0.764 |
+| p95 response time in ms | 333 | 267 |
+
+Across 384 requests per build, 39 succeeded before and 37 after. All accepted face results matched their sequential references. The measured benefit is less wasted work under overload. A synchronous single-request worker has no competing in-process decodes.
diff --git a/tests/test_inference_deadline.py b/tests/test_inference_deadline.py
index 7e11cd6..f1f6046 100644
--- a/tests/test_inference_deadline.py
+++ b/tests/test_inference_deadline.py
@@ -34,6 +34,16 @@ class AdmissionTest(unittest.TestCase):
self.assertEqual(self.post(endpoint, future).status_code, 200)
self.assertEqual(len(engine.method_calls), 1)
+ def test_full_preparation_capacity_skips_image_decode(self):
+ for endpoint, slots in (("/detect", server._detect_capacity),
+ ("/embed", server._embed_capacity)):
+ with slots, slots, patch.object(server, "QUEUE_WAIT_MS", 20):
+ with patch.object(server.Image, "open") as open_image:
+ response = self.post(endpoint)
+ self.assertEqual(response.status_code, 503)
+ self.assertEqual(response.json["code"], "inference_busy")
+ open_image.assert_not_called()
+
def test_client_deadline_with_no_server_limit(self):
with patch.object(server, "QUEUE_WAIT_MS", 0), server._detector_lock:
deadline = str(time.time_ns() // 1_000_000 + 30)