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.

Ускорил свертку в MobileFaceNet и подбор порога распознавания

Baurzhan Atynovb21cc3d2f292
diff --git a/Makefile b/Makefile
index 1c1b536..eb94fd4 100644
--- a/Makefile
+++ b/Makefile
@@ -51,8 +51,12 @@ facex-encrypt$(EXT): src/weight_crypto.c
$(CC) $(CFLAGS) -DWEIGHT_CRYPTO_MAIN -o $@ $< $(LDFLAGS)
.PHONY: check
-check: kernel-test$(EXT)
+check: kernel-test$(EXT) mfn-depthwise-test$(EXT)
./kernel-test$(EXT)
+ ./mfn-depthwise-test$(EXT)
+
+mfn-depthwise-test$(EXT): tests/mfn_depthwise.c src/facex_mfn.c include/facex_mfn.h
+ $(CC) $(CFLAGS) -Iinclude -o $@ $< $(LDFLAGS)
kernel-test$(EXT): tests/packed_math.c libfacex.a
$(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)
@@ -94,4 +98,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) *.o $(LIBOBJ:.o=.d)
+ 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) *.o $(LIBOBJ:.o=.d)
diff --git a/src/facex_mfn.c b/src/facex_mfn.c
index f067f53..61461c6 100644
--- a/src/facex_mfn.c
+++ b/src/facex_mfn.c
@@ -480,6 +480,22 @@ static void conv2d_1x1_nchw(const float *x, const MfnConv *c,
}
+static inline float dw3x3_pixel(const float *xc, const float *kw, float bi,
+ int Hin, int Win, int iy_base, int ix_base)
+{
+ float sum = bi;
+ for (int ky = 0; ky < 3; ky++) {
+ int iy = iy_base + ky;
+ if (iy < 0 || iy >= Hin) continue;
+ for (int kx = 0; kx < 3; kx++) {
+ int ix = ix_base + kx;
+ if (ix < 0 || ix >= Win) continue;
+ sum += xc[iy * Win + ix] * kw[ky * 3 + kx];
+ }
+ }
+ return sum;
+}
+
/* Depthwise 3x3 conv stride={1,2}, padding=1. Per-channel SIMD over spatial. */
static void conv2d_dw3x3_nchw(const float *x, const MfnConv *c,
int Hin, int Win, float *y)
@@ -497,21 +513,26 @@ static void conv2d_dw3x3_nchw(const float *x, const MfnConv *c,
float bi = bias[cc];
for (int oy = 0; oy < Hout; oy++) {
- for (int ox = 0; ox < Wout; ox++) {
- float sum = bi;
- int iy_base = oy * S - 1;
- int ix_base = ox * S - 1;
- for (int ky = 0; ky < 3; ky++) {
- int iy = iy_base + ky;
- if (iy < 0 || iy >= Hin) continue;
- for (int kx = 0; kx < 3; kx++) {
- int ix = ix_base + kx;
- if (ix < 0 || ix >= Win) continue;
- sum += xc[iy * Win + ix] * kw[ky * 3 + kx];
+ float *out = yc + oy * Wout;
+ int ox = 0;
+#ifdef __AVX2__
+ /* Eight adjacent interior pixels share the same nine coefficients. */
+ if (S == 1 && Win >= 10 && oy > 0 && oy + 1 < Hin) {
+ out[0] = dw3x3_pixel(xc, kw, bi, Hin, Win, oy - 1, -1);
+ for (ox = 1; ox + 8 < Win; ox += 8) {
+ __m256 acc = _mm256_set1_ps(bi);
+ for (int ky = 0; ky < 3; ky++) {
+ const float *row = xc + (size_t)(oy + ky - 1) * Win + ox - 1;
+ for (int kx = 0; kx < 3; kx++)
+ acc = _mm256_fmadd_ps(_mm256_loadu_ps(row + kx),
+ _mm256_set1_ps(kw[3 * ky + kx]), acc);
}
+ _mm256_storeu_ps(out + ox, acc);
}
- yc[oy * Wout + ox] = sum;
}
+#endif
+ for (; ox < Wout; ox++)
+ out[ox] = dw3x3_pixel(xc, kw, bi, Hin, Win, oy * S - 1, ox * S - 1);
}
}
}
diff --git a/tests/mfn_depthwise.c b/tests/mfn_depthwise.c
new file mode 100644
index 0000000..5532201
--- /dev/null
+++ b/tests/mfn_depthwise.c
@@ -0,0 +1,40 @@
+/* Check padding, SIMD tails and stride against direct spatial convolution. */
+#include "../src/facex_mfn.c"
+
+int main(void)
+{
+ enum { channels = 3, max_width = 57, height = 17 };
+ float x[channels * height * max_width], y[channels * height * max_width];
+ float w[channels * 9], bias[] = {0.17f, -0.25f, 0.33f};
+ for (size_t i = 0; i < sizeof(x) / sizeof(x[0]); i++)
+ x[i] = ((int)(i % 91) - 54) * 0.0181f;
+ for (int i = 0; i < channels * 9; i++)
+ w[i] = (i % 7 - 3) * 0.137f;
+
+ for (int width = 1; width <= max_width; width++) {
+ for (int stride = 1; stride <= 2; stride++) {
+ MfnConv conv = {.w = w, .b = bias, .c_in = channels, .stride = stride};
+ conv2d_dw3x3_nchw(x, &conv, height, width, y);
+ int ow = (width - 1) / stride + 1, oh = (height - 1) / stride + 1;
+ for (int c = 0; c < channels; c++) {
+ for (int row = 0; row < oh; row++) {
+ for (int col = 0; col < ow; col++) {
+ double ref = bias[c];
+ for (int tap = 0; tap < 9; tap++) {
+ int iy = row * stride + tap / 3 - 1;
+ int ix = col * stride + tap % 3 - 1;
+ if (iy >= 0 && iy < height && ix >= 0 && ix < width)
+ ref += (double)x[(c * height + iy) * width + ix] * w[c * 9 + tap];
+ }
+ if (!(fabs(y[(c * oh + row) * ow + col] - ref) < 1e-6)) {
+ fprintf(stderr, "Mismatch at width %d stride %d channel %d row %d col %d\n",
+ width, stride, c, row, col);
+ return 1;
+ }
+ }
+ }
+ }
+ }
+ }
+ return 0;
+}
diff --git a/tests/test_verification_thresholds.py b/tests/test_verification_thresholds.py
new file mode 100644
index 0000000..c78ca32
--- /dev/null
+++ b/tests/test_verification_thresholds.py
@@ -0,0 +1,46 @@
+"""Regression test for exact threshold selection, including ties on the grid."""
+
+import sys
+import unittest
+from pathlib import Path
+
+import numpy as np
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "training/scripts"))
+from verification_thresholds import fold_metrics
+
+
+def exhaustive(scores, same, grid, n_folds):
+ accuracies, thresholds = [], []
+ for test in np.array_split(np.arange(len(scores)), n_folds):
+ train = np.ones(len(scores), dtype=bool)
+ train[test] = False
+ best, threshold = 0, 0.0
+ for t in grid:
+ correct = np.count_nonzero((scores[train] >= t) == same[train])
+ if correct > best:
+ best, threshold = correct, t
+ thresholds.append(threshold)
+ accuracies.append(np.mean((scores[test] >= threshold) == same[test]))
+ return accuracies, thresholds
+
+
+class TestThresholds(unittest.TestCase):
+ def test_reference(self):
+ rng = np.random.default_rng(275)
+ for grid in (np.linspace(0, 1, 401), np.linspace(-0.5, 1, 601)):
+ for dtype in (np.float32, np.float64):
+ ties = grid[::5].astype(dtype)
+ scores = np.concatenate((ties, np.nextafter(ties, dtype(-np.inf)),
+ np.nextafter(ties, dtype(np.inf)),
+ rng.uniform(-1, 1, 79).astype(dtype),
+ np.array([np.nan, np.inf, -np.inf], dtype=dtype)))
+ labels = rng.random(len(scores)) < 0.5
+ for values, same in ((scores, labels), (scores, ~labels),
+ (np.full_like(scores, -1), np.ones_like(labels))):
+ np.testing.assert_array_equal(fold_metrics(values, same, grid, 10),
+ exhaustive(values, same, grid, 10))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/training/scripts/eval_pairs.py b/training/scripts/eval_pairs.py
index fc561f7..c6d2d6f 100644
--- a/training/scripts/eval_pairs.py
+++ b/training/scripts/eval_pairs.py
@@ -25,6 +25,8 @@ import numpy as np
import torch
from PIL import Image
+from verification_thresholds import fold_metrics
+
import arch as arch_module
from model import MobileFaceNet
from dataset import MS1MDataset
@@ -113,22 +115,7 @@ def compute_embeddings_for_pairs(model, pairs, ds, device="cuda",
def kfold_threshold(sims: np.ndarray, issame: np.ndarray, n_folds: int = N_FOLDS):
"""10-fold CV: find best threshold on train folds, evaluate on held-out."""
- n = len(sims)
- folds = np.array_split(np.arange(n), n_folds)
- thrs = np.linspace(-0.5, 1.0, 601)
- accs, best_thrs = [], []
- for i in range(n_folds):
- test_idx = folds[i]
- train_idx = np.concatenate([folds[j] for j in range(n_folds) if j != i])
- best_acc, best_thr = 0.0, 0.0
- for thr in thrs:
- pred = sims[train_idx] >= thr
- a = (pred == issame[train_idx]).mean()
- if a > best_acc:
- best_acc, best_thr = a, thr
- pred = sims[test_idx] >= best_thr
- accs.append((pred == issame[test_idx]).mean())
- best_thrs.append(best_thr)
+ accs, best_thrs = fold_metrics(sims, issame, np.linspace(-0.5, 1.0, 601), n_folds)
return {
"acc_mean": float(np.mean(accs)),
"acc_std": float(np.std(accs)),
diff --git a/training/scripts/lfw_eval.py b/training/scripts/lfw_eval.py
index 53663cb..11f39fc 100644
--- a/training/scripts/lfw_eval.py
+++ b/training/scripts/lfw_eval.py
@@ -18,6 +18,11 @@ import torch
import torch.nn.functional as F
from PIL import Image
+if __package__:
+ from .verification_thresholds import fold_metrics
+else:
+ from verification_thresholds import fold_metrics
+
def load_lfw(bin_path: str):
with open(bin_path, "rb") as f:
@@ -64,24 +69,7 @@ def evaluate(model, lfw_bin_path: str, device: str = "cuda",
sims = (a * b).sum(dim=-1).numpy() # cosine, [n_pairs]
issame = np.asarray(issame, dtype=bool)
- # 10-fold CV for best threshold
- folds = np.array_split(np.arange(n_pairs), 10)
- best_thresholds = []
- accs = []
- for i in range(10):
- test_idx = folds[i]
- train_idx = np.concatenate([folds[j] for j in range(10) if j != i])
- thr_grid = np.linspace(0.0, 1.0, 401)
- best_thr, best_acc = 0.0, 0.0
- for thr in thr_grid:
- pred = sims[train_idx] >= thr
- acc = (pred == issame[train_idx]).mean()
- if acc > best_acc:
- best_acc, best_thr = acc, thr
- # apply on test
- pred = sims[test_idx] >= best_thr
- accs.append((pred == issame[test_idx]).mean())
- best_thresholds.append(best_thr)
+ accs, best_thresholds = fold_metrics(sims, issame, np.linspace(0.0, 1.0, 401), 10)
return {
"accuracy_mean": float(np.mean(accs)),
"accuracy_std": float(np.std(accs)),
diff --git a/training/scripts/verification_thresholds.py b/training/scripts/verification_thresholds.py
new file mode 100644
index 0000000..e03f302
--- /dev/null
+++ b/training/scripts/verification_thresholds.py
@@ -0,0 +1,35 @@
+"""Select thresholds on training folds using exact counts on a fixed grid."""
+
+import numpy as np
+
+
+def fold_metrics(scores, same, grid, n_folds):
+ scores = np.asarray(scores)
+ same = np.asarray(same, dtype=bool)
+ # Each score passes exactly the first 'passed' thresholds, including ties.
+ # Use the same promotion as comparing a score array to one grid scalar.
+ dtype = np.result_type(scores, grid[0])
+ passed = np.searchsorted(grid.astype(dtype), scores.astype(dtype), side="right")
+ passed[np.isnan(scores)] = 0
+ counts = []
+ folds = np.array_split(np.arange(len(scores)), n_folds)
+ for indices in folds:
+ labels = same[indices]
+ bins = passed[indices]
+ positives = np.bincount(bins[labels], minlength=len(grid) + 1)
+ negatives = np.bincount(bins[~labels], minlength=len(grid) + 1)
+ # At threshold j: positives in bins > j and negatives in bins <= j.
+ counts.append(labels.sum() + np.cumsum(negatives - positives)[:-1])
+
+ total = np.sum(counts, axis=0)
+ accuracies, thresholds = [], []
+ for indices, held_out in zip(folds, counts):
+ training = total - held_out
+ best = np.argmax(training) # first maximum, as in the original loop
+ threshold = grid[best] if training[best] > 0 else 0.0
+ thresholds.append(threshold)
+ if training[best] > 0:
+ accuracies.append(held_out[best] / len(indices))
+ else:
+ accuracies.append(((scores[indices] >= threshold) == same[indices]).mean())
+ return accuracies, thresholds