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.

Add a full precision engine for consistent gallery decisions

Baurzhan Atynov5f10ce0b4ec2
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.yml
index bf08643..3c99204 100644
--- a/.github/workflows/go-gallery.yml
+++ b/.github/workflows/go-gallery.yml
@@ -3,6 +3,14 @@ on:
push:
paths:
- 'go/facex/**'
+ - 'Makefile'
+ - 'src/**'
+ - 'include/**'
+ - 'tests/golden/**'
+ - 'tests/bench_gallery_codes.py'
+ - 'tests/bench_gallery_groups.py'
+ - 'tests/check_gallery_profiles.py'
+ - 'python/facex/gallery.py'
- '.github/workflows/go-gallery.yml'
workflow_dispatch:
@@ -42,30 +50,26 @@ jobs:
FACEX_GALLERY_SCALE: '1'
FACEX_GALLERY_FIXTURE: ${{ runner.temp }}/gallery
run: |
- make cli
+ make cli cli-fp32
+ mv facex-cli-fp32 "$RUNNER_TEMP/facex-native-fp32"
+ make cli-fp32 CFLAGS="-O3 -march=x86-64 -funroll-loops"
+ cc --version | head -1
+ cc -march=native -Q --help=target | awk '$1 == "-march=" || $1 == "-mavx2" || $1 == "-mavx512f" || $1 == "-mavx512vnni"'
weights="$RUNNER_TEMP/edgeface_xs_fp32.bin"
curl --fail --silent --show-error --location --retry 2 https://github.com/facex-engine/facex/releases/download/v1.0.0/edgeface_xs_fp32.bin -o "$weights"
echo "d23f7b3cf8bcda5e451b48cf012e7dc6c4963d5703fafb8893f956d0203691d8 $weights" | sha256sum --check
python -m pip install numpy==2.3.5 Pillow==12.0.0
- PYTHONPATH=tests:python python - "$weights" <<'PY'
- import os
- import sys
- from pathlib import Path
- import numpy as np
- from bench_gallery_groups import fixture_views, prepare
-
- output = Path(os.environ["FACEX_GALLERY_FIXTURE"])
- output.mkdir()
- prepare(output, fixture_views(Path(sys.argv[1])), scaled=True)
- near_and_boundary = np.load(output / "queries.npy")
- random = np.random.default_rng(77).standard_normal((15, 512))
- np.vstack((near_and_boundary, random)).astype("<f4").tofile(output / "queries")
- PY
+ PYTHONPATH=python python tests/check_gallery_profiles.py "$weights" ./facex-cli ./facex-cli-fp32 "$RUNNER_TEMP/facex-native-fp32" "$FACEX_GALLERY_FIXTURE"
cd go/facex
- go test -v -run '^Test(IdentityGalleryScale|LiveGalleryScale|MathModelFixture|MathWorkloads|DecisionModelReplay|DecisionWorkloads)$' -count=1 ./...
+ gallery="$FACEX_GALLERY_FIXTURE"
+ sha256sum "$gallery"/{production,fp32}/{rows,queries}
+ FACEX_GALLERY_FIXTURE="$gallery/production" go test -v -run '^Test(IdentityGalleryScale|LiveGalleryScale|MathModelFixture|MathWorkloads|DecisionModelReplay|DecisionWorkloads)$' -count=1 ./...
+ FACEX_GALLERY_FIXTURE="$gallery/fp32" FACEX_GALLERY_PROFILE=fp32 go test -v -run '^TestDecisionModelReplay$' -count=1 ./...
- name: Verify concurrent engine replies against serial inference
working-directory: go/facex
env:
FACEX_POOL_TEST_EXE: ${{ github.workspace }}/facex-cli
FACEX_POOL_TEST_WEIGHTS: ${{ runner.temp }}/edgeface_xs_fp32.bin
- run: go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...
+ run: |
+ go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...
+ FACEX_POOL_TEST_EXE="$RUNNER_TEMP/facex-native-fp32" go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...
diff --git a/Makefile b/Makefile
index d0746be..8d2d110 100644
--- a/Makefile
+++ b/Makefile
@@ -14,7 +14,7 @@ ifeq ($(OS),Windows_NT)
endif
-.PHONY: all clean example lib cli encrypt test detect-lib v2-cli
+.PHONY: all clean example lib cli cli-fp32 encrypt test detect-lib v2-cli
all: lib cli detect-lib v2-cli
@@ -34,10 +34,18 @@ libfacex.a: $(LIBOBJ)
# Standalone CLI (for Go subprocess / testing)
cli: facex-cli$(EXT)
-facex-cli$(EXT): src/edgeface_engine.c src/transformer_ops.c src/gemm_int8_4x8c8.c src/threadpool.c src/weight_crypto.c
+CLI_SRC = src/edgeface_engine.c src/transformer_ops.c src/threadpool.c src/weight_crypto.c
+
+facex-cli$(EXT): $(CLI_SRC) src/gemm_int8_4x8c8.c
$(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)
@echo "Built facex-cli$(EXT)"
+# FP32 reference for comparing embeddings across CPU profiles.
+cli-fp32: facex-cli-fp32$(EXT)
+
+facex-cli-fp32$(EXT): $(CLI_SRC)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -DFACEX_FP32_ONLY -Iinclude -o $@ $^ $(LDFLAGS)
+
# Example program
example: facex-example$(EXT)
@@ -106,4 +114,4 @@ libdetect.a: detect.o
$(AR) rcs $@ $^
clean:
- rm -f libfacex.a libdetect.a facex-cli$(EXT) facex-example$(EXT) facex-encrypt$(EXT) golden-test$(EXT) facex-v2$(EXT) facex-mfn$(EXT) kernel-test$(EXT) mfn-depthwise-test$(EXT) geometry-test$(EXT) motion-phase-test$(EXT) *.o $(LIBOBJ:.o=.d)
+ rm -f libfacex.a libdetect.a facex-cli$(EXT) facex-cli-fp32$(EXT) facex-example$(EXT) facex-encrypt$(EXT) golden-test$(EXT) facex-v2$(EXT) facex-mfn$(EXT) kernel-test$(EXT) mfn-depthwise-test$(EXT) geometry-test$(EXT) motion-phase-test$(EXT) *.o $(LIBOBJ:.o=.d)
diff --git a/README.md b/README.md
index b14d0f2..c55aacb 100644
--- a/README.md
+++ b/README.md
@@ -262,6 +262,14 @@ embedding, _ := ff.Embed(rgbImage)
sim := facex.CosSim(embA, embB)
```
+For EdgeFace XS deployments that need close agreement across x86 CPU profiles,
+build the FP32 engine with `make cli-fp32` and set `Config.Exe` to
+`"./facex-cli-fp32"` for either `New` or `NewEmbedPool`. It uses the same
+weights and wire protocol and runs the matrix products without dynamic INT8
+quantization. Use the same engine for enrollment and queries. When switching
+an existing gallery, recompute its templates and validate decision thresholds
+on representative visits. Measure latency on the deployment CPU.
+
### CLI (any language via stdin/stdout)
```bash
diff --git a/go/facex/decision_math_test.go b/go/facex/decision_math_test.go
index 4a2f3df..09059b4 100644
--- a/go/facex/decision_math_test.go
+++ b/go/facex/decision_math_test.go
@@ -481,6 +481,9 @@ func TestDecisionModelReplay(t *testing.T) {
oldPolicy.WriteString("visit_id,decision\n")
newPolicy.WriteString("visit_id,decision\n")
fixed, withheld, remaining := 0, 0, 0
+ // Expected gaps for the five held out FP32 probes in fixture order.
+ fp32Gaps := [...]float64{0.017933, 0.036219, 0.170846, 0.082843, 0.084267}
+ fp32 := os.Getenv("FACEX_GALLERY_PROFILE") == "fp32"
for truth := 0; truth < 15; truth++ {
q := make([]float32, OutputSize)
if e = binary.Read(qf, binary.LittleEndian, q); e != nil {
@@ -511,6 +514,12 @@ func TestDecisionModelReplay(t *testing.T) {
candidate = "review"
}
fmt.Fprintf(&newPolicy, "%d,%s\n", truth, candidate)
+ if truth >= len(axes) {
+ t.Logf("probe=%d top_id=%d best=%.8f next=%.8f gap=%.8f decision=%s", truth, id, best, next, gap, candidate)
+ if fp32 && math.Abs(gap-fp32Gaps[truth-len(axes)]) > 2e-5 {
+ t.Errorf("FP32 gap changed for probe %d: %.8f", truth, gap)
+ }
+ }
wrong := id != truth
visits = append(visits, ReviewVisit{-gap, wrong})
if gap <= .1 {
@@ -532,6 +541,9 @@ func TestDecisionModelReplay(t *testing.T) {
t.Fatal(comparison, err)
}
t.Logf("paired report visits=%d known=%d unknown=%d wrong_removed=%d introduced=%d correct_to_review=%d remaining=%d", comparison.Visits, comparison.Known, comparison.Unknown, comparison.WrongRemoved, comparison.WrongIntroduced, comparison.CorrectIDToReview, remaining)
+ if fp32 && (fixed != 4 || withheld != 0 || remaining != 1) {
+ t.Error("FP32 review decisions changed on the model fixture")
+ }
before := a.Curve[0].RemainingWrong
if before != fixed+remaining {
t.Fatal("replay mismatch")
diff --git a/src/edgeface_engine.c b/src/edgeface_engine.c
index 02944ff..9463dca 100644
--- a/src/edgeface_engine.c
+++ b/src/edgeface_engine.c
@@ -116,8 +116,6 @@ static int load_weights(const char* path, Weights* w, const char* license_key) {
#define W(idx) (weights->tensors[idx])
/* Forward declarations */
-static void matmul_w(const float* A, const float* B, float* C,
- int M, int K, int N, const PackedMM* mm);
static void matmul_wp(const float* A, float* C,
int M, int K, int N, const PackedFP32* fp);
static void matmul_wpb(const float* A, float* C, const float* bias,
@@ -513,20 +511,6 @@ static void matmul_auto(const float* A, int M, int K, int N,
/* Use matmul that checks for pre-packed FP32 or INT8 weights */
extern void matmul_fp32_packed(const float*, const float*, float*, int, int, int);
-extern void matmul_dynamic_int8(const float*, int, int, int,
- const void*, const int32_t*, const float*, float*);
-
-static void matmul_w(const float* A, const float* B, float* C,
- int M, int K, int N, const PackedMM* mm)
-{
- /* Use INT8 when pre-packed weights available (2× faster) */
- if (mm && mm->packed && mm->w_scales && N >= 8) {
- matmul_dynamic_int8(A, M, K, N, mm->packed, mm->col_sums, mm->w_scales, C);
- return;
- }
- matmul_fp32(A, B, C, M, K, N);
-}
-
/* Packed FP32 matmul — uses pre-packed weights for cache-friendly access.
* Optional bias: added to each output row during store (avoids separate pass). */
extern void matmul_fp32_packed_bias(const float*, const float*, const float*, float*, int, int, int);
@@ -540,6 +524,7 @@ static Weights* _g_weights = NULL; /* set in forward pass for INT8 lookup */
static inline void matmul_wp(const float* A, float* C,
int M, int K, int N, const PackedFP32* fp)
{
+#ifndef FACEX_FP32_ONLY
/* Use INT8 VNNI for large matmuls where VNNI throughput > quant overhead.
* For small K*N (<4096), FP32 packed is faster due to zero quant overhead. */
if (_g_weights && _g_weights->mm) {
@@ -554,6 +539,7 @@ static inline void matmul_wp(const float* A, float* C,
}
}
}
+#endif
matmul_fp32_packed(A, fp->data, C, M, fp->K, fp->N);
}
static void matmul_wpb(const float* A, float* C, const float* bias,
@@ -962,12 +948,12 @@ static int engine_init(const char* weights_path, Weights* weights, const char* l
fprintf(stderr, "Failed to load %s\n", weights_path);
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->fp) goto fail;
-
- if (!weights->mm || !weights->fp) goto fail;
+#ifndef FACEX_FP32_ONLY
+ weights->mm = (PackedMM*)calloc(weights->n_tensors, sizeof(PackedMM));
+ if (!weights->mm) goto fail;
/* Pre-pack MatMul weights to INT8 c8 format */
{
@@ -1067,6 +1053,8 @@ static int engine_init(const char* weights_path, Weights* weights, const char* l
}
}
+#endif
+
/* Pre-pack FP32 MatMul weights into column-panel format [ceil(N/8), K, 8] */
{
extern void pack_b_fp32(const float*, int, int, float*);
diff --git a/src/transformer_ops.c b/src/transformer_ops.c
index c26d62a..4fd326d 100644
--- a/src/transformer_ops.c
+++ b/src/transformer_ops.c
@@ -251,6 +251,7 @@ void softmax_fp32(float* x, int N, int C) {
/* ============ Dynamic INT8 MatMul ============ */
/* C[M,N] = A_fp32[M,K] @ W_int8_packed[K,N], with dynamic A quantization.
* W is pre-packed in c8 format. A is quantized per-tensor at runtime. */
+#ifndef FACEX_FP32_ONLY
void matmul_dynamic_int8(const float* A_fp32, int M, int K, int N,
const void* W_packed, const int32_t* col_sums,
const float* w_scales, float* C_fp32)
@@ -441,7 +442,7 @@ void matmul_dynamic_int8(const float* A_fp32, int M, int K, int N,
#endif
}
-/* matmul_dynamic_int8_gelu not needed — GELU already vectorized and fast */
+#endif
/* ============ MatMul FP32 (AVX2 register-tiled, auto-INT8 for large K) ============ */
/* C[M,N] = A[M,K] @ B[K,N]
diff --git a/tests/bench_gallery_groups.py b/tests/bench_gallery_groups.py
index b72d770..ff2b088 100644
--- a/tests/bench_gallery_groups.py
+++ b/tests/bench_gallery_groups.py
@@ -20,7 +20,7 @@ HERE = Path(__file__).resolve().parent
GROUPS = 15
-def fixture_views(weights):
+def fixture_patches():
patches = []
items = json.loads((HERE / "golden/summary.json").read_text())["items"]
for item in items:
@@ -34,11 +34,19 @@ def fixture_views(weights):
box = tuple(np.rint(xy + [dx, dy, dx, dy]).astype(int))
patch = image.crop(box).resize((112, 112), Image.Resampling.BILINEAR)
patches.append((np.asarray(patch, dtype='f') / 127.5 - 1).transpose(2, 0, 1))
- result = subprocess.run([HERE.parent / 'facex-cli', weights, '--batch'],
- input=np.asarray(patches).tobytes(), capture_output=True, check=True)
+ return np.asarray(patches).tobytes()
+
+
+def embed_patches(weights, patches, executable):
+ result = subprocess.run([executable, weights, '--batch'], input=patches,
+ capture_output=True, check=True)
return np.frombuffer(result.stdout, dtype='f').reshape(GROUPS, 9, 512)
+def fixture_views(weights):
+ return embed_patches(weights, fixture_patches(), HERE.parent / 'facex-cli')
+
+
def kernel(path):
scan = ctypes.CDLL(str(path / 'scan.so')).scan_codes
scan.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t,
diff --git a/tests/check_gallery_profiles.py b/tests/check_gallery_profiles.py
new file mode 100644
index 0000000..d9d904f
--- /dev/null
+++ b/tests/check_gallery_profiles.py
@@ -0,0 +1,55 @@
+"""Exercise the production and FP32 gallery paths on the same input bytes."""
+import argparse
+import hashlib
+from pathlib import Path
+
+import numpy as np
+
+from bench_gallery_groups import embed_patches, fixture_patches, prepare
+
+
+def run_engine(weights, patches, executable):
+ views = embed_patches(weights, patches, executable.resolve())
+ if not np.isfinite(views).all():
+ raise ValueError(f"{executable} produced a nonfinite embedding")
+ print(f"{executable.name} embeddings_sha256={hashlib.sha256(views.tobytes()).hexdigest()}", flush=True)
+ return views
+
+
+def directions(views):
+ vectors = views.reshape(-1, 512).astype(np.float64)
+ norms = np.linalg.norm(vectors, axis=1, keepdims=True)
+ if np.any(norms == 0):
+ raise ValueError("zero fixture embedding")
+ return vectors / norms
+
+
+def check_fp32(reference, native):
+ left, right = directions(reference), directions(native)
+ coordinate_drift = np.max(np.abs(left - right))
+ cosine_drift = np.max(np.abs(left @ left.T - right @ right.T))
+ print(f"FP32 max coordinate drift={coordinate_drift:.8g} max pairwise cosine drift={cosine_drift:.8g}", flush=True)
+ if coordinate_drift > 1e-5 or cosine_drift > 1e-5:
+ raise AssertionError("FP32 build profiles diverged")
+
+
+def write_gallery(path, views):
+ path.mkdir(parents=True, exist_ok=True)
+ prepare(path, views, scaled=True)
+ near_and_boundary = np.load(path / "queries.npy")
+ random = np.random.default_rng(77).standard_normal((15, 512))
+ np.vstack((near_and_boundary, random)).astype("<f4").tofile(path / "queries")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ for arg in ("weights", "production", "reference", "native", "output"):
+ parser.add_argument(arg, type=Path)
+ args = parser.parse_args()
+ patches = fixture_patches()
+ print(f"crops_sha256={hashlib.sha256(patches).hexdigest()}", flush=True)
+ reference = run_engine(args.weights, patches, args.reference)
+ native = run_engine(args.weights, patches, args.native)
+ check_fp32(reference, native)
+ write_gallery(args.output / "fp32", native)
+ write_gallery(args.output / "production", run_engine(args.weights, patches, args.production))