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.
C avx-512avx2biometricsc99computer-visioncpu-inferencedeep-learningedge-aiembedded-aiface-embeddingface-recognitionface-verificationlow-latencyonnx-runtimeproduction-readysimdzero-dependencies
Ускорил распознавание и исправил координаты лиц и прогноз движения
Baurzhan Atynov60f0e1ec3681
diff --git a/Makefile b/Makefileindex eb94fd4..d0746be 100644--- a/Makefile+++ b/Makefile@@ -51,9 +51,17 @@ facex-encrypt$(EXT): src/weight_crypto.c$(CC) $(CFLAGS) -DWEIGHT_CRYPTO_MAIN -o $@ $< $(LDFLAGS).PHONY: check-check: kernel-test$(EXT) mfn-depthwise-test$(EXT)+check: kernel-test$(EXT) mfn-depthwise-test$(EXT) geometry-test$(EXT) motion-phase-test$(EXT)./kernel-test$(EXT)./mfn-depthwise-test$(EXT)+ ./geometry-test$(EXT)+ ./motion-phase-test$(EXT)++motion-phase-test$(EXT): tests/motion_phase.c nn2/src/motion_gate.c nn2/src/nn2_internal.h nn2/include/nn2.h+ $(CC) $(CFLAGS) -Inn2/src -Inn2/include -o $@ tests/motion_phase.c nn2/src/motion_gate.c++geometry-test$(EXT): tests/geometry_math.c libfacex.a+ $(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)mfn-depthwise-test$(EXT): tests/mfn_depthwise.c src/facex_mfn.c include/facex_mfn.h$(CC) $(CFLAGS) -Iinclude -o $@ $< $(LDFLAGS)@@ -98,4 +106,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) *.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) geometry-test$(EXT) motion-phase-test$(EXT) *.o $(LIBOBJ:.o=.d)diff --git a/docs/research/math_25.md b/docs/research/math_25.mdnew file mode 100644index 0000000..92afbe1--- /dev/null+++ b/docs/research/math_25.md@@ -0,0 +1,80 @@+# 25 математических задач FaceX++Срез от 25 ноября 2026 года. Первый проход вошёл в b21cc3d, второй проверялся относительно этого коммита. Номера сохранены для сравнения. «В коде» означает изменение рабочего пути. Для опытов с промежуточными тензорами и синтетикой указаны границы вывода.++| № | Задача | Результат опыта и решение |+|---|---|---|+| 1 | Ускорить depthwise 3×3 с шагом 1 | В коде с первого прохода. Повторный замер полного Nano с одинаково исправленной памятью у обеих версий дал снижение CPU-времени на 14,4–14,8%. |+| 2 | Ускорить поиск порога в кросс-валидации | В коде с первого прохода. Сортировка оценок и накопительные счётчики заменяют повторную классификацию пар для каждого порога. Регрессия сравнивает выбор с исходным перебором. |+| 3 | Переиспользовать вход свёртки 1×1 между каналами | В коде. AVX2 считает блок из четырёх выходных каналов и 16 пространственных позиций. Край обрабатывается отдельно. Эффект на полный Nano приведён ниже вместе с № 4–6. |+| 4 | Сократить стоимость выборки при шаге 2 | В коде. Для 56×56 и 48 каналов время ядра depthwise уменьшилось примерно со 154 до 131 мкс. |+| 5 | Ускорить глубинную свёртку 7×7 | В коде. Внутренние позиции обрабатываются векторно, границы сохраняют исходную формулу. Изолированный замер дал 20,33 → 14,07 мкс. |+| 6 | Слить PReLU с записью свёртки | В коде. Активация применяется до записи результата 1×1, что убирает отдельный обход. Итог проверен по эмбеддингу ONNX. |+| 7 | Убрать транспонирование ключей в attention | Прототип проверен совместно с № 8. На реальных весах EdgeFace время выросло с 3,349 до 3,532 мс. Оставлен исходный путь. |+| 8 | Перенести масштабы нормировки из векторов в произведение | Изолированный опыт дал расхождение до 1,19×10⁻⁷, но полный прототип № 7–8 на 24 входах разошёлся с базой до 0,01652 по компоненте эмбеддинга. Без отдельного разбора расхождения внедрять нельзя. |+| 9 | Стабилизировать оценку дисперсии для LayerNorm | Блочный центрированный алгоритм на матрице 200×128 со смещением 100000 и шумом σ=0,02 снизил максимальную ошибку нормированного значения относительно FP64 с 0,32149 до 2,78×10⁻⁷. В NumPy он обходился примерно в 3,5 раза дороже. Оставлен экспериментом. |+| 10 | Стабилизировать косинусное сходство при экстремальных нормах | В коде. Произведение и обе суммы квадратов накапливаются в FP64. Проверены направления с компонентами FLT_MIN и FLT_MAX, включая противоположные. |+| 11 | Подобрать масштаб INT8 по ошибке выходной проекции | 8 изображений для настройки, 7 для проверки. На первой проекции Nano масштаб 0,92 от максимума снизил MSE с 0,000338208 до 0,000322767. Перед переносом на всю модель нужна проверка верификации по парам. |+| 12 | Найти точную границу аккумулятора INT8 | Для произвольных знаковых байтов максимальное положительное произведение равно 16384, поэтому INT32 гарантированно вмещает до 131071 слагаемого с нулевой начальной суммой. На C/VNNI проверены длины 8–131064 против INT64, включая результат 2147352576. |+| 13 | Найти выгодные формы для Winograd 3×3 | Winograd / im2col с тем же GEMM в мкс: 11,38/12,38 при H=7, 36,79/45,33 при 14, 175,51/308,58 при 28, 254,89/465,68 при 56. Входные/выходные каналы соответственно 16/16, 16/32, 32/32, 16/16. Максимальная ошибка 1,67×10⁻⁶. Упаковка весов вне таймера. Универсальный диспетчер по одному CPU не вводили. |+| 14 | Найти выигрыш от блочной разреженности INT8 | При форме 196×128×64, блоках 16×4 и плотности 50% разреженное ядро заняло 17,15 против 23,77 мкс у плотного VNNI. При плотности 9,4% получилось 12,49 против 23,78 мкс. Совпадение с целым эталоном точное. Для использования нужны веса с соответствующей структурой нулей. |+| 15 | Уменьшить ошибку векторной экспоненты | В коде. Полином шестой степени на редуцированном интервале. На 1048576 равноотстоящих входах от −80 до 80 максимальная ошибка уменьшилась с 3 до 1 ULP, время 0,198 → 0,201 мс. Граница относится к испытанной сетке. |+| 16 | Проверить стоимость и ошибку ожидания DFL | Ядро уже переиспользует одну экспоненту для числителя и знаменателя. На 8192 наборах из 16 логитов в диапазоне [−20,20] максимальная ошибка координаты исходного ядра составила 0,000101 пикселя при шаге 32. Сохранён действующий алгоритм. |+| 17 | Устойчиво восстановить преобразование подобия по пяти точкам | В коде. Центрирование и вычисление в FP64. Совпадающие точки дают диагностируемый отказ выравнивания, детекция сохраняется с нулевым эмбеддингом. Проверены тождество, 50 известных преобразований и вырожденные входы. |+| 18 | Убрать повторное деление при обратном отображении пикселей | В коде. Координаты интерполяции обновляются по строке. На испытанном кропе время уменьшилось с 293,49 до 148,09 мкс, максимальная разница нормированного пикселя 6,26×10⁻⁵. |+| 19 | Получать истинные верхние K детекций после подавления дубликатов | В коде. Все масштабы поступают на общую сортировку и NMS до ограничения выдачи. Дополнительно исправлены геометрия рамок YuNet, объединение вероятностей, координаты ключевых точек и размер рабочего буфера. Числа на WIDER ниже. |+| 20 | Масштабировать расстояния слияния по размеру лица | Опыт с относительными порогами носа и глаз. На отдельной проверке 2586 кадров комбинация относительных порогов, минимального размера 4 и порога оценки 0,59 дала 842 совпадения и 71 лишнюю детекцию против 702 и 44 у базового режима. Рост ложных срабатываний на отложенных данных исключает замену по умолчанию. |+| 21 | Измерить зависимость градиента GIoU от размера рамки | Для двух равных квадратов со сдвигом 1,2 стороны модуль производной по сдвигу уменьшился с 0,1033 при стороне 4 до 0,00646 при стороне 64. Это проверка масштабной зависимости. Влияние компенсации на обучение требует отдельного прогона. |+| 22 | Устранить скачок разметки между уровнями FPN | У жёсткого назначения около границ размера 64 и 128 ожидаемое число положительных ячеек скачет примерно с 64 до 16. Взвешивание по логарифму размера в полосе ±⅛ октавы даёт около 40,03 и 39,97 по сторонам границы. На WIDER при приведении к 320 в этих полосах 206 и 59 рамок. Перенос в функцию обучения требует переобучения детектора. |+| 23 | Сравнить жадное и оптимальное назначение треков | Венгерский алгоритм в паре с новой ковариацией дал ещё 5 предотвращённых смен ID ценой 20 потерянных совпадений и роста медианного времени с 3,86 до 5,26 мкс. Сохранено жадное назначение. |+| 24 | Оценивать связь положения и скорости при прогнозе | В коде. Для каждой координаты центра трекер ведёт ковариацию 2×2. При искусственном пропуске 1, 3 и 10 кадров средняя ошибка прогноза центра уменьшилась с 6,664 до 6,270, с 9,869 до 8,353 и с 21,916 до 17,624 пикселя соответственно. Число испытаний 4092, 4024 и 3817. |+| 25 | Устранить постоянные слепые позиции выборки движения | В коде. Смарт-конвейер циклически меняет фазу решётки 4×4 отдельно для камеры, делитель равен фактическому числу выборок. Проверены 16384 сочетания размеров и фаз. При устойчивой межкадровой разнице все 16 позиций попадают в выборку за цикл. Однокадровое изменение по-прежнему может быть пропущено. |++## Измерения полного конвейера++**Nano.** В базовой реализации после первой свёртки выделялся буфер по стороне 55 вместо 56. Для честного сравнения поправка применена к обеим сторонам замера. Повторный замер прошлого ускорения на релизных весах дал 6,2894 → 5,3825, 6,2859 → 5,3587 и 6,3861 → 5,4542 мс. Затем сравнили b21cc3d с новым набором оптимизаций на трёх входах:++| Вход | Предыдущая версия, мс | Новая, мс | Снижение CPU-времени |+|---|---:|---:|---:|+| 1 | 5,4281 | 3,7693 | 30,6% |+| 2 | 5,6697 | 3,8639 | 31,9% |+| 3 | 5,6769 | 4,2115 | 25,8% |++Linux, AMD EPYC 9V74, GCC 14, AVX2/FMA. Один закреплённый поток, CPU-время, прогрев и 9 чередующихся серий по 12 вызовов. Веса facex_nano.onnx релиза facex-nano-1.0, SHA-256 bd0094143bb4c7d04a76dcdad4e332f5985847b921ec4d6678c3fd89aaea3889. Вход 1×3×112×112, выход 1×256. На 15 изображениях проекта максимальная абсолютная разница с ONNX Runtime составила 2,1041×10⁻⁵, минимальный косинус 0,9999999943. Для XS на синтетических весах три времени уменьшились с 45,81–49,56 до 23,47–25,71 мс. На AArch64 выполнен функциональный запуск под QEMU. Замеров на физическом Mac и i5-10400F в этом прогоне нет. Согласованность выходов не измеряет точность идентификации людей.++**YuNet.** Координаты центра равны (ячейка + смещение) × шаг, размеры равны exp(выход) × шаг, оценка равна геометрическому среднему вероятностей cls и obj. На сохранённом входе разница между первой нативной детекцией и декодированными выходами ONNX по 15 числам не превышает 0,00001526. [Реализация OpenCV](https://github.com/opencv/opencv/blob/4.x/modules/objdetect/src/face_detect.cpp)++Пилот WIDER FACE val: 640 из 3226 изображений с фиксированным seed 114, 8909 действительных рамок. RGB и letterbox во всех режимах. Порог оценки 0,5, однозначное сопоставление при IoU ≥ 0,5. «Лишние» означает предсказания без пары среди учтённых рамок. Это локальный протокол, официальный AP easy/medium/hard требует отдельного расчёта.++| Версия и вход | Найдено | Лишние | Пропущено |+|---|---:|---:|---:|+| До исправления, 160 | 1 | 95 | 8908 |+| После, 160 | 174 | 19 | 8735 |+| После, 320 | 533 | 44 | 8376 |+| После, 640 | 1570 | 200 | 7339 |++При 320 из 7903 лиц размером менее 16 пикселей совпали только 13. Из 670 размером 16–32 совпали 248, из 239 размером 32–64 совпали 189, из 97 более крупных совпали 83. Увеличение разрешения повышает полноту и число лишних детекций. Кандидат на следующий опыт — обработка фрагментов высокого разрешения при фиксированном бюджете CPU и сопоставимом числе лишних срабатываний.++**Трекинг.** Семь обучающих последовательностей MOT17 с публичными FRCNN-детекциями. Учитывались детекции с уверенностью ≥0,5, видимые пешеходы с visibility ≥0,5, обновлённые в текущем кадре треки и сопоставление по IoU >0,5. Сброс каждые 120 кадров, max_age=5 и min_hits=2. Смена ID считается внутри окна по процедуре из скрипта. Эти числа нельзя выдавать за официальные IDF1, IDSW или HOTA.++| Назначение и модель движения | Совпадения | Пропуски | Смены ID |+|---|---:|---:|---:|+| Жадное, исходная | 57281 | 9112 | 898 |+| Венгерское, исходная | 57274 | 9119 | 866 |+| Жадное, новая | 57246 | 9147 | 673 |+| Венгерское, новая | 57226 | 9167 | 668 |++## Как повторить основные проверки++Из корня репозитория в Linux. Для Python-прогонов понадобятся NumPy, Pillow, SciPy, ONNX и ONNX Runtime. Для сравнения с базовой версией нужна история git с коммитом b21cc3d. Передайте локальные пути к релизной модели Nano, YuNet 2023mar и архивам соответствующих наборов.++```sh+make check+python tests/test_verification_thresholds.py+python tests/bench_mfn_release.py facex_nano.onnx+python tools/export_yunet_weights.py yunet_2023mar.onnx /tmp/yunet.bin+OPENBLAS_NUM_THREADS=1 python tests/verify_yunet.py /tmp/yunet.bin --wider WIDER_val.zip wider_face_split.zip --sizes 160 320 640+OPENBLAS_NUM_THREADS=1 python tests/bench_mot17.py MOT17Labels.zip+```++Итого 13 задач с рабочими изменениями с учётом первого прохода и 12 исследованных гипотез. Веса моделей в этом проходе не менялись.diff --git a/nn2/src/fast_exp.h b/nn2/src/fast_exp.hindex 0443662..0c683cc 100644--- a/nn2/src/fast_exp.h+++ b/nn2/src/fast_exp.h@@ -2,8 +2,8 @@* fast_exp.h — Vectorized expf() for AVX-512, accurate to float precision.** Based on Cephes approach: exp(x) = 2^n * P(f) where n=round(x/ln2), f=x-n*ln2.- * P(f) is a degree-6 minimax polynomial on [-ln2/2, ln2/2].- * Accuracy: max relative error < 2^-23 (same as hardware expf).+ * P(f) is a degree-6 polynomial on [-ln2/2, ln2/2].+ * Measured error on a 2^20-point grid in [-80, 80]: at most 1 ULP.** ~15 SIMD instructions per call. 3-4x faster than scalar expf loop.*/@@ -23,13 +23,14 @@ static inline __m512 _mm512_exp_fast(__m512 x)const __m512 ln2_lo = _mm512_set1_ps(1.42860682030941723212e-6f);const __m512 half = _mm512_set1_ps(0.5f);- /* Polynomial coefficients (Cephes) */+ /* Degree-six Chebyshev interpolant of exp on the reduced interval,+ * converted to power basis and rounded to float. */const __m512 c1 = _mm512_set1_ps(1.0f);const __m512 c2 = _mm512_set1_ps(0.5f);- const __m512 c3 = _mm512_set1_ps(0.166666666666666019037f);- const __m512 c4 = _mm512_set1_ps(0.0416666666665065678e0f);- const __m512 c5 = _mm512_set1_ps(0.00833333333371142972e0f);- const __m512 c6 = _mm512_set1_ps(0.00138888889039885e0f);+ const __m512 c3 = _mm512_set1_ps(0.16666416f);+ const __m512 c4 = _mm512_set1_ps(0.04166635f);+ const __m512 c5 = _mm512_set1_ps(0.00837513f);+ const __m512 c6 = _mm512_set1_ps(0.00139411f);/* Clamp to prevent overflow/underflow */x = _mm512_max_ps(x, _mm512_set1_ps(-87.3f));@@ -43,7 +44,6 @@ static inline __m512 _mm512_exp_fast(__m512 x)f = _mm512_fnmadd_ps(n, ln2_lo, f);/* P(f) = 1 + f + f²/2 + f³/6 + ... (Horner's method) */- __m512 f2 = _mm512_mul_ps(f, f);__m512 p = c6;p = _mm512_fmadd_ps(p, f, c5);p = _mm512_fmadd_ps(p, f, c4);diff --git a/nn2/src/motion_gate.c b/nn2/src/motion_gate.cindex 2a2f24a..49d4581 100644--- a/nn2/src/motion_gate.c+++ b/nn2/src/motion_gate.c@@ -4,8 +4,7 @@* Compares current frame vs previous frame using Sum of Absolute Differences.* If fewer than threshold pixels changed significantly → no motion → skip inference.*- * AVX-512 SAD: processes 64 bytes (pixels) per cycle.- * For 320×320×3 = 307,200 bytes: ~4800 iterations = ~2μs at 2.7GHz.+ * Each phase samples one pixel per 4x4 cell.** Returns: motion score (0.0 = identical, 1.0 = completely different)* and bounding box of motion region for ROI-crop.@@ -15,70 +14,28 @@#include <string.h>#include <stdlib.h>-#ifdef __AVX512BW__-#include <immintrin.h>-#endif--/* Motion detection result */-typedef struct {- float score; /* 0.0-1.0: fraction of changed pixels */- int has_motion; /* 1 if score > threshold */- int roi_x1, roi_y1, roi_x2, roi_y2; /* bounding box of motion region */-} MotionResult;-/* Compute frame difference score + motion ROI.* prev, curr: RGB HWC uint8, width*height*3 bytes.* pixel_thresh: per-pixel change threshold (e.g., 25 = ~10% of 255)* score_thresh: fraction of changed pixels to trigger motion (e.g., 0.005 = 0.5%)*/-MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,+MotionResult nn2_motion_detect_phase(const uint8_t* prev, const uint8_t* curr,int width, int height,- int pixel_thresh, float score_thresh)+ int pixel_thresh, float score_thresh, unsigned phase){MotionResult r = {0};- int total_pixels = width * height;+ if (width <= 0 || height <= 0) return r;int changed = 0;/* Track motion bounding box */int min_x = width, min_y = height, max_x = 0, max_y = 0;- /* Downsampled check: compare every 4th pixel for speed */- int stride = 4;--#ifdef __AVX512BW__- /* AVX-512 path: process 16 pixels at a time (48 bytes RGB) */- /* Simplified: compare grayscale approximation (R+G+B)/3 per pixel */- for (int y = 0; y < height; y += stride) {- const uint8_t* p = prev + y * width * 3;- const uint8_t* c = curr + y * width * 3;- for (int x = 0; x + 16 <= width; x += 16) {- /* Quick SAD on raw bytes (3 channels interleaved) */- int off = x * 3;- __m512i vp = _mm512_loadu_si512((__m512i*)(p + off));- __m512i vc = _mm512_loadu_si512((__m512i*)(c + off));- /* Absolute difference per byte */- __m512i vd = _mm512_abs_epi8(_mm512_sub_epi8(- _mm512_max_epu8(vp, vc), _mm512_min_epu8(vp, vc)));- /* Actually use SAD: sum of abs diff in groups of 8 bytes */- /* Simpler: check if any byte > threshold using mask */- __mmask64 mask = _mm512_cmpgt_epu8_mask(vd, _mm512_set1_epi8((char)pixel_thresh));- if (mask) {- /* Count changed pixels (each pixel = 3 bytes, any channel > thresh counts) */- int bits = __builtin_popcountll(mask);- changed += bits / 3 + 1; /* approximate */- /* Update ROI */- if (x < min_x) min_x = x;- if (x + 16 > max_x) max_x = x + 16;- if (y < min_y) min_y = y;- if (y + stride > max_y) max_y = y + stride;- }- }- }-#else- /* Scalar fallback */- for (int y = 0; y < height; y += stride) {- for (int x = 0; x < width; x += stride) {- int off = (y * width + x) * 3;+ const int stride = 4;+ int x_start = phase % 4, y_start = (phase / 4) % 4;+ if (x_start >= width || y_start >= height) return r;+ for (int y = y_start; y < height; y += stride) {+ for (int x = x_start; x < width; x += stride) {+ size_t off = ((size_t)y * width + x) * 3;int d = abs((int)prev[off] - (int)curr[off])+ abs((int)prev[off+1] - (int)curr[off+1])+ abs((int)prev[off+2] - (int)curr[off+2]);@@ -91,9 +48,9 @@ MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,}}}-#endif-- int checked = (total_pixels / (stride * stride)) + 1;+ int sampled_w = 1 + (width - 1 - x_start) / stride;+ int sampled_h = 1 + (height - 1 - y_start) / stride;+ size_t checked = (size_t)sampled_w * sampled_h;r.score = (float)changed / (float)checked;r.has_motion = (r.score > score_thresh) ? 1 : 0;@@ -118,6 +75,12 @@ MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,return r;}+MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,+ int width, int height, int pixel_thresh, float score_thresh)+{+ return nn2_motion_detect_phase(prev, curr, width, height, pixel_thresh, score_thresh, 0);+}+/* ============ ROI Crop ============ *//* Crop RGB HWC image to ROI region */diff --git a/nn2/src/nn2_internal.h b/nn2/src/nn2_internal.hindex da421d7..86fbae5 100644--- a/nn2/src/nn2_internal.h+++ b/nn2/src/nn2_internal.h@@ -8,6 +8,18 @@#include "nn2.h"#include <stddef.h>+typedef struct {+ float score;+ int has_motion;+ int roi_x1, roi_y1, roi_x2, roi_y2;+} MotionResult;++MotionResult nn2_motion_detect_phase(const uint8_t* prev, const uint8_t* curr,+ int width, int height, int pixel_thresh,+ float score_thresh, unsigned phase);+MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,+ int width, int height, int pixel_thresh, float score_thresh);+/* ============ GEMM config ============ */#define NN2_MR 6#define NN2_NR 16diff --git a/nn2/src/smart_pipeline.c b/nn2/src/smart_pipeline.cindex d2f565d..fb2b81f 100644--- a/nn2/src/smart_pipeline.c+++ b/nn2/src/smart_pipeline.c@@ -27,18 +27,15 @@ static double sp_now(void) {LARGE_INTEGER t; QueryPerformanceCounter(&t);return (double)t.QuadPart/(double)freq.QuadPart;}+#else+#include <time.h>+static double sp_now(void) {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;+}#endif-/* From motion_gate.c */-typedef struct {- float score;- int has_motion;- int roi_x1, roi_y1, roi_x2, roi_y2;-} MotionResult;--extern MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,- int width, int height,- int pixel_thresh, float score_thresh);extern void nn2_crop_roi(const uint8_t* src, int src_w, int src_h,int x1, int y1, int x2, int y2,uint8_t* dst, int* dst_w, int* dst_h);@@ -109,8 +106,8 @@ static FrameResult smart_process_frame(/* Step 1: Motion gate */if (cam->prev_frame) {double t0 = sp_now();- MotionResult mr = nn2_motion_detect(cam->prev_frame, frame,- width, height, 25, 0.003f);+ MotionResult mr = nn2_motion_detect_phase(cam->prev_frame, frame,+ width, height, 25, 0.003f, (unsigned)cam->frame_count);res.inference_ms = (float)((sp_now() - t0) * 1000.0);if (!mr.has_motion) {diff --git a/nn2/src/track.c b/nn2/src/track.cindex a01a05d..3f6f32e 100644--- a/nn2/src/track.c+++ b/nn2/src/track.c@@ -16,7 +16,8 @@/* Kalman state: [cx, cy, s, r, vx, vy, vs] where s=area, r=aspect ratio */typedef struct {float x[7]; /* state: cx, cy, s, r, vx, vy, vs */- float P[7]; /* diagonal of covariance (simplified) */+ float cross_xy[2]; /* Cov(position, velocity) on each image axis. */+ float P[7]; /* Marginal variances of the state coordinates. */int id;int cls;float score;@@ -63,7 +64,13 @@ static void kf_predict(KalmanTrack* t)t->x[2] += t->x[6]; /* s += vs */if (t->x[2] < 0) t->x[2] = 0;/* Increase uncertainty */- for (int i = 0; i < 7; i++) t->P[i] += 10.0f;+ for (int i = 0; i < 2; i++) {+ t->P[i] += 2 * t->cross_xy[i] + t->P[4+i] + 0.05f;+ t->cross_xy[i] += t->P[4+i];+ t->P[4+i] += 0.01f;+ }+ t->P[2] += 10;+ t->P[3] += 10;t->age++;t->time_since_update++;}@@ -71,17 +78,26 @@ static void kf_predict(KalmanTrack* t)/* Kalman update with measurement z[4] = [cx, cy, s, r] */static void kf_update(KalmanTrack* t, const float z[4]){- /* Simplified Kalman gain: K = P / (P + R) */+ /* Update the center and its velocity from the same innovation. */float R = 10.0f; /* measurement noise */- for (int i = 0; i < 4; i++) {+ for (int i = 0; i < 2; i++) {+ float residual = z[i] - t->x[i];+ float variance = t->P[i] + 1.0f;+ float kp = t->P[i] / variance;+ float kv = t->cross_xy[i] / variance;+ t->x[i] += kp * residual;+ t->x[4+i] += kv * residual;+ t->P[4+i] -= kv * t->cross_xy[i];+ t->cross_xy[i] *= 1 - kp;+ t->P[i] *= 1 - kp;+ }+ for (int i = 2; i < 4; i++) {float K = t->P[i] / (t->P[i] + R);t->x[i] += K * (z[i] - t->x[i]);t->P[i] *= (1.0f - K);}- /* Update velocities: exponential moving average of residuals */+ /* Area retains the existing smoothed velocity estimate. */float alpha = 0.3f;- t->x[4] = (1-alpha) * t->x[4] + alpha * (z[0] - t->x[0]);- t->x[5] = (1-alpha) * t->x[5] + alpha * (z[1] - t->x[1]);t->x[6] = (1-alpha) * t->x[6] + alpha * (z[2] - t->x[2]);t->time_since_update = 0;diff --git a/src/align.c b/src/align.cindex 1dbc7a7..28789e1 100644--- a/src/align.c+++ b/src/align.c@@ -13,7 +13,7 @@*/#include <math.h>-#include <string.h>+#include <float.h>#include <stdint.h>/* Reference 112×112 landmarks (ArcFace order) */@@ -34,80 +34,29 @@ static const float REF_KPS[10] = {** Returns: M[6] = {a, -b, tx, b, a, ty}*/-static void estimate_similarity_transform(const float src[10], const float dst[10], float M[6]) {- /* Solve for [a, b, tx, ty] using normal equations:- * For each point pair (sx,sy) -> (dx,dy):- * dx = a*sx - b*sy + tx- * dy = b*sx + a*sy + ty- */- float sx_sum = 0, sy_sum = 0, dx_sum = 0, dy_sum = 0;- float sxsx = 0, sysy = 0, sxsy = 0;- float sxdx = 0, sydx = 0, sxdy = 0, sydy = 0;- int n = 5;-+static void estimate_similarity_transform(const float src[10], const float dst[10], double M[6]) {+ const int n = 5;+ double sx_m = 0, sy_m = 0, dx_m = 0, dy_m = 0;for (int i = 0; i < n; i++) {- float sx = src[i*2], sy = src[i*2+1];- float dx = dst[i*2], dy = dst[i*2+1];- sx_sum += sx; sy_sum += sy;- dx_sum += dx; dy_sum += dy;- sxsx += sx*sx; sysy += sy*sy; sxsy += sx*sy;- sxdx += sx*dx; sydx += sy*dx;- sxdy += sx*dy; sydy += sy*dy;+ sx_m += src[2*i]; sy_m += src[2*i+1];+ dx_m += dst[2*i]; dy_m += dst[2*i+1];}-- /* Normal equations for similarity transform:- * [sum(sx²+sy²) 0 sum(sx) -sum(sy)] [a ] [sum(sx*dx + sy*dy)]- * [0 sum(sx²+sy²) sum(sy) sum(sx)] [b ] [sum(sx*dy - sy*dx)]- * [sum(sx) sum(sy) n 0 ] [tx] = [sum(dx) ]- * [-sum(sy) sum(sx) 0 n ] [ty] [sum(dy) ]- *- * Simplified: solve 2×2 for (a,b), then get (tx,ty)- */- float ss = sxsx + sysy;- float rhs_a = sxdx + sydy;- float rhs_b = sxdy - sydx;-- /* [ss 0 sx_sum -sy_sum] [a] [rhs_a ]- * [0 ss sy_sum sx_sum] [b] = [rhs_b ]- * [sx sy n 0 ] [tx] [dx_sum]- * [-sy sx 0 n ] [ty] [dy_sum] */-- /* From rows 3,4: tx = (dx_sum - a*sx_sum + b*sy_sum) / n- * ty = (dy_sum - b*sx_sum - a*sy_sum) / n- * Substitute into rows 1,2:- * a*(ss - (sx_sum²+sy_sum²)/n) + 0*b = rhs_a - (sx_sum*dx_sum+sy_sum*dy_sum)/n- * 0*a + b*(ss - (sx_sum²+sy_sum²)/n) = rhs_b - (sy_sum*dx_sum-sx_sum*dy_sum)/n ... actually not quite.- * Easier: just solve directly. */-- float A00 = ss, A02 = sx_sum, A03 = -sy_sum;- float A12 = sy_sum, A13 = sx_sum;- float b0 = rhs_a, b1 = rhs_b;- float b2 = dx_sum, b3 = dy_sum;-- /* Eliminate tx,ty from first two equations using last two */- /* a*ss + tx*sx - ty*sy = rhs_a ... (1)- * b*ss + tx*sy + ty*sx = rhs_b ... (2)- * a*sx + b*sy + tx*n = dx ... (3) → tx = (dx - a*sx - b*sy)/n- * -a*sy + b*sx + ty*n = dy ... (4) → ty = (dy + a*sy - b*sx)/n */- /* Hmm, let me just use the simple form. */-- float sx_m = sx_sum / n, sy_m = sy_sum / n;- float dx_m = dx_sum / n, dy_m = dy_sum / n;+ sx_m /= n; sy_m /= n; dx_m /= n; dy_m /= n;/* Center the points */- float num_a = 0, num_b = 0, denom = 0;+ double num_a = 0, num_b = 0, denom = 0;for (int i = 0; i < n; i++) {- float sx = src[i*2] - sx_m, sy = src[i*2+1] - sy_m;- float dx = dst[i*2] - dx_m, dy = dst[i*2+1] - dy_m;+ double sx = src[i*2] - sx_m, sy = src[i*2+1] - sy_m;+ double dx = dst[i*2] - dx_m, dy = dst[i*2+1] - dy_m;num_a += sx*dx + sy*dy;num_b += sx*dy - sy*dx;denom += sx*sx + sy*sy;}- float a = num_a / denom;- float b = num_b / denom;- float tx = dx_m - a*sx_m + b*sy_m;- float ty = dy_m - b*sx_m - a*sy_m;+ double a = denom > 0 ? num_a / denom : 0;+ double b = denom > 0 ? num_b / denom : 0;+ double tx = dx_m - a*sx_m + b*sy_m;+ double ty = dy_m - b*sx_m - a*sy_m;M[0] = a; M[1] = -b; M[2] = tx;M[3] = b; M[4] = a; M[5] = ty;@@ -121,56 +70,48 @@ static void estimate_similarity_transform(const float src[10], const float dst[1* kps: 5 detected keypoints [x0,y0,x1,y1,...,x4,y4]* out_f32: output 112×112×3 float32 HWC [-1, 1]*/-void align_face(const uint8_t* src_rgb, int src_w, int src_h,+int align_face(const uint8_t* src_rgb, int src_w, int src_h,const float kps[10], float* out_f32) {- float M[6];+ double M[6];/* We want: dst_point = M * src_point* But for warping we need inverse: for each dst pixel, find src pixel.* So compute M: detected_kps → reference_kps, then invert. */estimate_similarity_transform(kps, REF_KPS, M);- /* Invert 2×2 part: [a -b]^-1 = 1/(a²+b²) * [a b]- * [b a] [-b a] */- float a = M[0], b = M[3], tx = M[2], ty = M[5];- float det = a*a + b*b;- float ia = a / det, ib = -b / det;- float itx = -(ia*tx + (-ib)*ty);- float ity = -(ib*tx + ia*ty);- /* Inverse: for dst pixel (dx,dy) → src pixel (sx,sy):- * sx = ia*dx + (-ib)*dy + itx- * sy = ib*dx + ia*dy + ity */-+ double a = M[0], b = M[3], det = a*a + b*b;+ if (!(det > 0) || !isfinite(det)) {+ for (int i = 0; i < 112*112*3; i++) out_f32[i] = -1.0f;+ return 0;+ }+ double u = a / det, v = b / det;+ /* Stabilize integer grid boundaries against roundoff in the inverse. */+ double grid_eps = 64 * DBL_EPSILON * fmax(src_w, src_h);for (int dy = 0; dy < 112; dy++) {- for (int dx = 0; dx < 112; dx++) {- float sx = ia*dx - ib*dy + itx; /* wait, ib = -b/det, so -ib = b/det */- float sy_f = (b/det)*dx + ia*dy + ity;- /* Actually let me redo properly */- /* Forward: [a -b tx] maps src→dst. Inverse maps dst→src.- * inv = [a/(a²+b²) b/(a²+b²) -(a*tx+b*ty)/(a²+b²) ]- * [-b/(a²+b²) a/(a²+b²) (b*tx-a*ty)/(a²+b²) ] */- float inv_a = a/det, inv_b = b/det;- sx = inv_a * dx + inv_b * dy + (-(a*tx + b*ty))/det; /* Hmm getting messy */- /* Start over with clean inverse */- sx = (a*(dx - tx) + b*(dy - ty)) / det;- sy_f = (-b*(dx - tx) + a*(dy - ty)) / det;-+ double sx = -u * M[2] + v * (dy - M[5]) + grid_eps;+ double sy_f = v * M[2] + u * (dy - M[5]) + grid_eps;+ for (int dx = 0; dx < 112; dx++, sx += u, sy_f -= v) {+ if (!(sx >= 0 && sx < src_w && sy_f >= 0 && sy_f < src_h)) {+ for (int c = 0; c < 3; c++) out_f32[(dy*112 + dx)*3 + c] = -1.0f;+ continue;+ }/* Bilinear interpolation */- int ix = (int)floorf(sx), iy = (int)floorf(sy_f);+ int ix = (int)sx, iy = (int)sy_f;float fx = sx - ix, fy = sy_f - iy;for (int c = 0; c < 3; c++) {float v = 0;- if (ix >= 0 && ix < src_w-1 && iy >= 0 && iy < src_h-1) {+ if (ix < src_w-1 && iy < src_h-1) {float v00 = src_rgb[(iy*src_w + ix)*3 + c];float v10 = src_rgb[(iy*src_w + ix+1)*3 + c];float v01 = src_rgb[((iy+1)*src_w + ix)*3 + c];float v11 = src_rgb[((iy+1)*src_w + ix+1)*3 + c];v = v00*(1-fx)*(1-fy) + v10*fx*(1-fy) + v01*(1-fx)*fy + v11*fx*fy;- } else if (ix >= 0 && ix < src_w && iy >= 0 && iy < src_h) {+ } else {v = src_rgb[(iy*src_w + ix)*3 + c];}out_f32[(dy*112 + dx)*3 + c] = v / 127.5f - 1.0f; /* normalize to [-1, 1] */}}}+ return 1;}diff --git a/src/detect.c b/src/detect.cindex fe540c3..8091d0e 100644--- a/src/detect.c+++ b/src/detect.c@@ -7,6 +7,7 @@#include "detect.h"+#include <limits.h>#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -73,9 +74,6 @@ Detect* detect_init(const char* weights_path) {det->tensors[i] = (float*)(det->raw + off); off += sz;}- det->work_size = 4 * 1024 * 1024;- det->work = (float*)calloc(det->work_size, sizeof(float));- if (!det->work) { free(det->raw); free(det); return NULL; }return det;}@@ -234,10 +232,24 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,if (!det || !rgb_hwc || !out || max_faces < 0) return -1;if (width <= 0 || height <= 0) return -1;- int H = height, W = width;+ if (max_faces == 0) return 0;+ /* The feature pyramid halves five times. Pad the bottom and right so+ * both sides of every lateral addition share a spatial shape. */+ if (height > INT_MAX - 31 || width > INT_MAX - 31) return -1;+ int H = (height + 31) / 32 * 32, W = (width + 31) / 32 * 32;+ if (W > INT_MAX / 16 / H) return -1;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+ + (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) {+ float *work = realloc(det->work, needed * sizeof(float));+ if (!work) return -1;+ det->work = work;+ det->work_size = needed;+ }float* wp = det->work;float* inp = wp; wp += 3*H*W;float* a = wp; wp += 64*h2*w2;@@ -249,10 +261,11 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,float* hd = wp; wp += 16*h8*w8; /* head scratch *//* uint8 HWC → float32 CHW [0..255] */- for (int y = 0; y < H; y++)- for (int x = 0; x < W; x++)+ if (W != width || H != height) memset(inp, 0, (size_t)3*H*W*sizeof(*inp));+ for (int y = 0; y < height; y++)+ for (int x = 0; x < width; x++)for (int ch = 0; ch < 3; ch++)- inp[(size_t)ch*H*W + y*W + x] = (float)rgb_hwc[(y*W+x)*3 + ch];+ inp[(size_t)ch*H*W + y*W + x] = (float)rgb_hwc[((size_t)y*width+x)*3 + ch];/* Stem: Conv3×3 s2 (3→16) + ReLU + PW(16→16) */conv2d(inp, 3, H, W, T(0), T(1), 16, 3, 2, 1, a);@@ -341,6 +354,10 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,memcpy(f8, a, 64*h8*w8*sizeof(float));/* === HEADS + DECODE === */+ size_t anchors = (size_t)h8*w8 + (size_t)h16*w16 + (size_t)h32*w32;+ if (anchors == 0) return 0;+ DetectFace *candidates = malloc(anchors * sizeof(*candidates));+ if (!candidates) return -1;int nf = 0;struct { float* feat; int fh, fw, stride; } levels[3] = {{f8, h8, w8, 8}, {f16, h16, w16, 16}, {f32_, h32, w32, 32}@@ -380,63 +397,70 @@ int detect_run(Detect* det, const uint8_t* rgb_hwc, int width, int height,conv1x1(feat, 64, hw, T(kw1[si]), T(kb1[si]), 10, a);conv_dw(a, 10, fh, fw, T(kw2[si]), T(kb2[si]), 3, 1, 1, hd + 4*hw);- for (int gy = 0; gy < fh && nf < max_faces; gy++)- for (int gx = 0; gx < fw && nf < max_faces; gx++) {+ for (int gy = 0; gy < fh; gy++)+ for (int gx = 0; gx < fw; gx++) {int idx = gy * fw + gx;- float sc = sigm(cls[idx]) * sigm(obj[idx]);+ float sc = sqrtf(sigm(cls[idx]) * sigm(obj[idx]));if (sc < det->score_threshold) continue;- float cx = (gx + 0.5f) * st, cy = (gy + 0.5f) * st;- out[nf].x1 = fmaxf(0, cx - hd[0*hw+idx] * st);- out[nf].y1 = fmaxf(0, cy - hd[1*hw+idx] * st);- out[nf].x2 = fminf((float)width, cx + hd[2*hw+idx] * st);- out[nf].y2 = fminf((float)height, cy + hd[3*hw+idx] * st);+ /* YuNet regresses the center offset and log width/height. */+ float cx = (gx + hd[idx]) * st;+ float cy = (gy + hd[hw + idx]) * st;+ float half_w = 0.5f * expf(hd[2*hw + idx]) * st;+ float half_h = 0.5f * expf(hd[3*hw + idx]) * st;+ candidates[nf].x1 = fmaxf(0, cx - half_w);+ candidates[nf].y1 = fmaxf(0, cy - half_h);+ candidates[nf].x2 = fminf((float)width, cx + half_w);+ candidates[nf].y2 = fminf((float)height, cy + half_h);/* Filter degenerate boxes */- float bw = out[nf].x2 - out[nf].x1;- float bh = out[nf].y2 - out[nf].y1;+ float bw = candidates[nf].x2 - candidates[nf].x1;+ float bh = candidates[nf].y2 - candidates[nf].y1;if (bw < 16 || bh < 16) continue; /* too small */if (bw > width*0.95f || bh > height*0.95f) continue; /* too large */float aspect = bw / (bh + 1e-6f);if (aspect < 0.3f || aspect > 3.0f) continue; /* bad aspect ratio */- out[nf].score = sc;+ candidates[nf].score = sc;for (int k = 0; k < 5; k++) {- out[nf].kps[k*2] = fmaxf(0, fminf((float)width, cx + hd[(4+k*2)*hw+idx] * st));- out[nf].kps[k*2+1] = fmaxf(0, fminf((float)height, cy + hd[(4+k*2+1)*hw+idx] * st));+ candidates[nf].kps[k*2] = fmaxf(0, fminf((float)width, (gx + hd[(4+k*2)*hw+idx]) * st));+ candidates[nf].kps[k*2+1] = fmaxf(0, fminf((float)height, (gy + hd[(4+k*2+1)*hw+idx]) * st));}nf++;}}- if (nf > 1) nf = nms_sort(out, nf, det->nms_threshold);+ if (nf > 1) nf = nms_sort(candidates, nf, det->nms_threshold);/* Cross-scale merge: if two faces have nose keypoints within 20px,* keep only the one with better score. This handles multi-scale* detections of the same face at different strides. */if (nf > 1) {for (int i = 0; i < nf; i++) {- if (out[i].score < 0) continue; /* already merged */+ if (candidates[i].score < 0) continue; /* already merged */for (int j = i + 1; j < nf; j++) {- if (out[j].score < 0) continue;+ if (candidates[j].score < 0) continue;/* Compare nose keypoints (index 4,5) */- float dx = out[i].kps[4] - out[j].kps[4];- float dy = out[i].kps[5] - out[j].kps[5];+ float dx = candidates[i].kps[4] - candidates[j].kps[4];+ float dy = candidates[i].kps[5] - candidates[j].kps[5];float dist = sqrtf(dx*dx + dy*dy);/* Also compare eye midpoints */- float ei_x = (out[i].kps[0] + out[i].kps[2]) * 0.5f;- float ei_y = (out[i].kps[1] + out[i].kps[3]) * 0.5f;- float ej_x = (out[j].kps[0] + out[j].kps[2]) * 0.5f;- float ej_y = (out[j].kps[1] + out[j].kps[3]) * 0.5f;+ float ei_x = (candidates[i].kps[0] + candidates[i].kps[2]) * 0.5f;+ float ei_y = (candidates[i].kps[1] + candidates[i].kps[3]) * 0.5f;+ float ej_x = (candidates[j].kps[0] + candidates[j].kps[2]) * 0.5f;+ float ej_y = (candidates[j].kps[1] + candidates[j].kps[3]) * 0.5f;float eye_dist = sqrtf((ei_x-ej_x)*(ei_x-ej_x) + (ei_y-ej_y)*(ei_y-ej_y));if (dist < 25.0f || eye_dist < 20.0f) {- out[j].score = -1; /* suppress */+ candidates[j].score = -1; /* suppress */}}}/* Compact */int k = 0;for (int i = 0; i < nf; i++)- if (out[i].score > 0) { if (k != i) out[k] = out[i]; k++; }+ if (candidates[i].score > 0) { if (k != i) candidates[k] = candidates[i]; k++; }nf = k;}+ if (nf > max_faces) nf = max_faces;+ memcpy(out, candidates, (size_t)nf * sizeof(*out));+ free(candidates);return nf;}diff --git a/src/facex.c b/src/facex.cindex dd80935..cef8baf 100644--- a/src/facex.c+++ b/src/facex.c@@ -18,7 +18,7 @@#include "edgeface_engine.c"/* External: alignment */-extern void align_face(const uint8_t* src_rgb, int src_w, int src_h,+extern int align_face(const uint8_t* src_rgb, int src_w, int src_h,const float kps[10], float* out_f32);struct FaceX {@@ -77,7 +77,10 @@ int facex_detect(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,/* Align face to 112×112 using keypoints */float aligned[112 * 112 * 3];- align_face(rgb_hwc, width, height, det_faces[i].kps, aligned);+ if (!align_face(rgb_hwc, width, height, det_faces[i].kps, aligned)) {+ memset(out[i].embedding, 0, sizeof(out[i].embedding));+ continue;+ }/* Compute embedding */facex_embed(fx, aligned, out[i].embedding);@@ -100,14 +103,14 @@ int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]) {}float facex_similarity(const float emb1[512], const float emb2[512]) {- float dot = 0, n1 = 0, n2 = 0;+ double dot = 0, n1 = 0, n2 = 0;for (int i = 0; i < 512; i++) {- dot += emb1[i] * emb2[i];- n1 += emb1[i] * emb1[i];- n2 += emb2[i] * emb2[i];+ double a = emb1[i], b = emb2[i];+ dot += a * b;+ n1 += a * a;+ n2 += b * b;}- float denom = sqrtf(n1) * sqrtf(n2);- return denom > 1e-8f ? dot / denom : 0.0f;+ return n1 > 0 && n2 > 0 ? (float)(dot / sqrt(n1 * n2)) : 0.0f;}void facex_free(FaceX* fx) {diff --git a/src/facex_mfn.c b/src/facex_mfn.cindex 61461c6..71d1de4 100644--- a/src/facex_mfn.c+++ b/src/facex_mfn.c@@ -203,6 +203,12 @@ static void load_conv(MfnConv *c, int c_in, int c_out, int k, int stride,}+/* ============ Output Hout from Conv spec ============ */+static int conv_hout(const MfnConv *c, int Hin)+{+ return (Hin + 2 * c->padding - c->kernel) / c->stride + 1;+}+/* ============ Public init ============ */int mfn_engine_init(const char *path, MfnEngine *e)@@ -360,8 +366,8 @@ int mfn_engine_init(const char *path, MfnEngine *e)*/int H = MFN_INPUT_HW;int max_floats = 0;- /* After stem: floor((112 - stem_k) / stem_stride) + 1 */- int Hcur = (H - e->arch.stem_kernel) / e->arch.stem_stride + 1;+ /* Include the same padding used by the forward convolution. */+ int Hcur = conv_hout(&e->stem, H);int Ccur = e->arch.stem_channels;int blk_idx = 0;int stage_c_in = e->arch.stem_channels;@@ -431,10 +437,12 @@ static inline float hsum256(__m256 v) {}#endif+static void prelu_nchw(float *x, int C, int HW, const float *slope);+/* 1x1 conv: y[co, hw] = sum_ci w[co, ci] * x[ci, hw] + b[co]* Most of MFN compute is here. We tile over output channels (4 at a* time) and use AVX2 along the spatial dim. */-static void conv2d_1x1_nchw(const float *x, const MfnConv *c,+static void conv2d_1x1_prelu_nchw(const float *x, const MfnConv *c,int H, int W, float *y){int Cin = c->c_in, Cout = c->c_out;@@ -444,8 +452,43 @@ static void conv2d_1x1_nchw(const float *x, const MfnConv *c,const float *bias = c->b;#ifdef __AVX2__+ /* Reuse two spatial vectors across four independent output channels. */+ int co = 0;+ for (; co + 4 <= Cout && HW >= 16; co += 4) {+ for (int tile = 0; tile < HW; tile += 16) {+ /* A partial final tile reuses a few output positions; each is+ * recomputed from bias, so overlap needs no scratch or mask. */+ int pos = tile <= HW - 16 ? tile : HW - 16;+ __m256 lo[4], hi[4];+ for (int j = 0; j < 4; j++)+ lo[j] = hi[j] = _mm256_set1_ps(bias[co + j]);+ for (int ci = 0; ci < Cin; ci++) {+ const float *in = x + (size_t)ci * HW + pos;+ __m256 left = _mm256_loadu_ps(in);+ __m256 right = _mm256_loadu_ps(in + 8);+ for (int j = 0; j < 4; j++) {+ __m256 weight = _mm256_set1_ps(W_[(co + j) * Cin + ci]);+ lo[j] = _mm256_fmadd_ps(weight, left, lo[j]);+ hi[j] = _mm256_fmadd_ps(weight, right, hi[j]);+ }+ }+ for (int j = 0; j < 4; j++) {+ float *out = y + (size_t)(co + j) * HW + pos;+ if (c->prelu) {+ __m256 slope = _mm256_set1_ps(c->prelu[co + j]);+ __m256 zero = _mm256_setzero_ps();+ lo[j] = _mm256_blendv_ps(lo[j], _mm256_mul_ps(lo[j], slope),+ _mm256_cmp_ps(lo[j], zero, _CMP_LT_OQ));+ hi[j] = _mm256_blendv_ps(hi[j], _mm256_mul_ps(hi[j], slope),+ _mm256_cmp_ps(hi[j], zero, _CMP_LT_OQ));+ }+ _mm256_storeu_ps(out, lo[j]);+ _mm256_storeu_ps(out + 8, hi[j]);+ }+ }+ }/* Process 1 Cout at a time, vectorize along HW. */- for (int co = 0; co < Cout; co++) {+ for (; co < Cout; co++) {float bi = bias[co];float *yc = y + (size_t)co * HW;/* init with bias */@@ -466,6 +509,7 @@ static void conv2d_1x1_nchw(const float *x, const MfnConv *c,}for (; i < HW; i++) yc[i] += wv * xc[i];}+ if (c->prelu) prelu_nchw(yc, 1, HW, c->prelu + co);}#elsefor (int co = 0; co < Cout; co++) {@@ -475,6 +519,7 @@ static void conv2d_1x1_nchw(const float *x, const MfnConv *c,float wv = W_[co * Cin + ci];for (int hw = 0; hw < HW; hw++) y[co * HW + hw] += wv * x[ci * HW + hw];}+ if (c->prelu) prelu_nchw(y + (size_t)co * HW, 1, HW, c->prelu + co);}#endif}@@ -530,6 +575,32 @@ static void conv2d_dw3x3_nchw(const float *x, const MfnConv *c,_mm256_storeu_ps(out + ox, acc);}}+ if (S == 2 && oy > 0 && 2 * oy + 1 < Hin && Wout >= 10) {+ const __m256i offsets = _mm256_setr_epi32(0, 2, 4, 6, 8, 10, 12, 14);+ out[0] = dw3x3_pixel(xc, kw, bi, Hin, Win, 2 * oy - 1, -1);+ for (ox = 1; 2 * (ox + 7) + 1 < Win; ox += 8) {+ __m256 acc = _mm256_set1_ps(bi);+ for (int ky = 0; ky < 3; ky++) {+ const float *row = xc + (size_t)(2 * oy + ky - 1) * Win + 2 * ox - 1;+ for (int kx = 0; kx < 3; kx++)+ acc = _mm256_fmadd_ps(_mm256_i32gather_ps(row + kx, offsets, 4),+ _mm256_set1_ps(kw[3 * ky + kx]), acc);+ }+ _mm256_storeu_ps(out + ox, acc);+ }+ }+ if (S == 1 && Win == 7 && oy > 0 && oy + 1 < Hin) {+ out[0] = dw3x3_pixel(xc, kw, bi, Hin, Win, oy - 1, -1);+ __m128 acc = _mm_set1_ps(bi);+ for (int ky = 0; ky < 3; ky++) {+ const float *row = xc + (size_t)(oy + ky - 1) * Win;+ for (int kx = 0; kx < 3; kx++)+ acc = _mm_fmadd_ps(_mm_loadu_ps(row + kx),+ _mm_set1_ps(kw[3 * ky + kx]), acc);+ }+ _mm_storeu_ps(out + 1, acc);+ ox = 5;+ }#endiffor (; ox < Wout; ox++)out[ox] = dw3x3_pixel(xc, kw, bi, Hin, Win, oy * S - 1, ox * S - 1);@@ -576,10 +647,6 @@ static void conv2d_nchw(const float *x, const MfnConv *c,int Hin, int Win, float *y){/* Fast paths */- if (c->kernel == 1 && c->stride == 1 && c->padding == 0 && c->groups == 1) {- conv2d_1x1_nchw(x, c, Hin, Win, y);- return;- }if (c->kernel == 3 && c->padding == 1 && c->groups == c->c_in&& c->c_in == c->c_out) {conv2d_dw3x3_nchw(x, c, Hin, Win, y);@@ -668,16 +735,14 @@ static void add_inplace(float *y, const float *x, size_t n)}-/* ============ Output Hout from Conv spec ============ */-static int conv_hout(const MfnConv *c, int Hin)-{- return (Hin + 2 * c->padding - c->kernel) / c->stride + 1;-}-/* ============ Run one Conv (+ optional PReLU) ============ */static int run_conv(const float *x, const MfnConv *c, int Hin, int Win,float *y){+ if (c->kernel == 1 && c->stride == 1 && c->padding == 0 && c->groups == 1) {+ conv2d_1x1_prelu_nchw(x, c, Hin, Win, y);+ return Hin;+ }conv2d_nchw(x, c, Hin, Win, y);int Hout = conv_hout(c, Hin);int Wout = conv_hout(c, Win);diff --git a/tests/bench_mfn_release.py b/tests/bench_mfn_release.pynew file mode 100644index 0000000..bc0c93c--- /dev/null+++ b/tests/bench_mfn_release.py@@ -0,0 +1,139 @@+"""Compare the release ONNX to two native builds. Run from the repository root.++Requires Linux x86 with AVX2/FMA, GCC, NumPy, Pillow, onnx and onnxruntime.+Pass the local facex_nano.onnx from the facex-nano-1.0 release.+"""+import argparse+import ctypes+import hashlib+import os+from pathlib import Path+import statistics+import struct+import subprocess+import sys+import tempfile+import time++import numpy as np+import onnx+import onnxruntime as ort+from PIL import Image++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "training/scripts"))+from arch import ARCH_NANO+from binformat import _pack_arch++RELEASE_SHA256 = "bd0094143bb4c7d04a76dcdad4e332f5985847b921ec4d6678c3fd89aaea3889"+BASE = "b21cc3d2f292818b23879f988b32dce34b335895"+BUFFER = np.ctypeslib.ndpointer(dtype=np.float32, flags="C_CONTIGUOUS")+++def export_folded_weights(model, path):+ graph = onnx.load(model).graph+ initializers = {item.name: onnx.numpy_helper.to_array(item) for item in graph.initializer}+ tensors = []+ for node in graph.node:+ if node.op_type == "Conv":+ weights, bias = (initializers[name] for name in node.input[1:])+ # ONNX already folded BN. Make the native loader apply unit scale.+ tensors.extend((weights, np.ones_like(bias), bias,+ np.zeros_like(bias), np.full_like(bias, 1 - 1e-5)))+ elif node.op_type == "PRelu":+ tensors.append(initializers[node.input[1]])+ with path.open("wb") as out:+ out.write(b"EFM3" + struct.pack("<I", 3) + _pack_arch(ARCH_NANO))+ out.write(struct.pack("<II", 0, len(tensors)))+ for tensor in tensors:+ data = tensor.astype("<f4").tobytes()+ out.write(struct.pack("<I", len(data)))+ out.write(data)+++def build_engine(directory, name, source, weights):+ source_file = directory / (name + ".c")+ source_file.write_text(source + """+static MfnEngine benchmark_engine;+int setup(const char *path) { return mfn_engine_init(path, &benchmark_engine); }+void evaluate(const float *x, float *y) { mfn_engine_forward(&benchmark_engine, x, y); }+void release(void) { mfn_engine_free(&benchmark_engine); }+""")+ binary = directory / (name + ".so")+ subprocess.run(["gcc", "-O3", "-mavx2", "-mfma", "-fPIC", "-shared",+ "-I", str(ROOT / "src"), str(source_file), "-lm", "-o", str(binary)],+ check=True)+ lib = ctypes.CDLL(str(binary))+ lib.setup.argtypes = [ctypes.c_char_p]+ lib.evaluate.argtypes = [BUFFER, BUFFER]+ lib.evaluate.restype = None+ if lib.setup(os.fsencode(weights)) != 0:+ raise RuntimeError("Native EFM3 initialization failed")+ return lib+++def timed_forward(engine, image, embedding):+ start = time.thread_time_ns()+ for _ in range(12):+ engine.evaluate(image, embedding)+ return (time.thread_time_ns() - start) / 12e6+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("model", type=Path)+ args = parser.parse_args()+ if hashlib.sha256(args.model.read_bytes()).hexdigest() != RELEASE_SHA256:+ parser.error("The file differs from the measured Nano release")+ os.sched_setaffinity(0, {min(os.sched_getaffinity(0))})+ options = ort.SessionOptions()+ options.intra_op_num_threads = 1+ session = ort.InferenceSession(str(args.model), options, providers=["CPUExecutionProvider"])+ baseline = subprocess.check_output(["git", "show", BASE + ":src/facex_mfn.c"],+ cwd=ROOT, text=True)+ # Both sides need the correct workspace dimensions for a valid comparison.+ baseline = baseline.replace("(H - e->arch.stem_kernel) / e->arch.stem_stride + 1",+ "(H + 2 * e->stem.padding - e->stem.kernel) / e->stem.stride + 1")+ current = (ROOT / "src/facex_mfn.c").read_text()+ with tempfile.TemporaryDirectory() as tmp:+ directory = Path(tmp)+ weights = directory / "nano.bin"+ export_folded_weights(args.model, weights)+ engines = [build_engine(directory, name, source, weights)+ for name, source in (("baseline", baseline), ("current", current))]+ outputs = [np.empty(256, "f") for _ in engines]+ files = sorted((ROOT / "tests/golden").glob("*.npz"))+ if not files:+ raise RuntimeError("Missing golden images")+ errors, cosines = [], []+ for file in files:+ with np.load(file) as fixture:+ image = Image.fromarray(fixture["image"]).resize((112, 112))+ x = np.ascontiguousarray((np.asarray(image, dtype="f").transpose(2, 0, 1)+ - 127.5) / 128)+ reference = session.run(None, {"input": x[None]})[0].ravel()+ engines[1].evaluate(x, outputs[1])+ current_out = outputs[1].astype("d")+ errors.append(np.max(abs(current_out - reference)))+ cosines.append(np.dot(current_out, reference) /+ (np.linalg.norm(current_out) * np.linalg.norm(reference.astype("d"))))+ print(f"{len(files)} images, max error {max(errors):.7g}, min cosine {min(cosines):.10f}")+ if not max(errors) < 1e-4 or not min(cosines) > .99999:+ raise AssertionError("ONNX agreement failed")+ rng = np.random.default_rng(20261125)+ for _ in range(3):+ image = rng.uniform(-1, 1, (3, 112, 112)).astype("f")+ times = [[], []]+ for i, engine in enumerate(engines):+ engine.evaluate(image, outputs[i])+ np.testing.assert_allclose(outputs[0], outputs[1], atol=1e-4, rtol=0)+ for pair in range(9):+ for i in ([1, 0] if pair % 2 else [0, 1]):+ times[i].append(timed_forward(engines[i], image, outputs[i]))+ print("CPU ms per image", [round(statistics.median(t), 4) for t in times])+ for engine in engines:+ engine.release()+++if __name__ == "__main__":+ main()diff --git a/tests/bench_mot17.py b/tests/bench_mot17.pynew file mode 100644index 0000000..a59f752--- /dev/null+++ b/tests/bench_mot17.py@@ -0,0 +1,110 @@+"""Replay a local MOT17Labels.zip through the baseline and current C tracker.++Uses the seven training sequences with public FRCNN detections. These local+counts use the matching protocol below; official MOTChallenge scores require+its complete evaluation procedure.+"""+import argparse+import ctypes+from pathlib import Path+import statistics+import subprocess+import tempfile+import time+from zipfile import ZipFile++import numpy as np+from scipy.optimize import linear_sum_assignment++ROOT = Path(__file__).resolve().parents[1]+BASE = "b21cc3d2f292818b23879f988b32dce34b335895"+DET = np.dtype([("box", "f", 4), ("score", "f"), ("cls", "i")])+TRACK = np.dtype([("id", "i"), ("cls", "i"), ("score", "f"), ("box", "f", 4),+ ("age", "i"), ("hits", "i"), ("since", "i")])+++def group_frames(rows):+ rows = rows[np.argsort(rows[:, 0], kind="stable")]+ return {int(frame[0, 0]): frame for frame in+ np.split(rows, np.flatnonzero(np.diff(rows[:, 0])) + 1) if len(frame)}+++def corners(rows):+ boxes = rows[:, 2:6].copy()+ boxes[:, 2:] += boxes[:, :2]+ return boxes+++def matches(a, b):+ inter = (np.minimum(a[:, None, 2:], b[None, :, 2:]) -+ np.maximum(a[:, None, :2], b[None, :, :2])).clip(0).prod(2)+ union = ((a[:, 2:] - a[:, :2]).prod(1)[:, None] ++ (b[:, 2:] - b[:, :2]).prod(1) - inter)+ iou = inter / np.maximum(union, 1e-8)+ rows, cols = linear_sum_assignment(np.where(iou > .5, 1 + iou, 0), maximize=True)+ return [(i, j) for i, j in zip(rows, cols) if iou[i, j] > .5]+++def evaluate(source, archive):+ binary = source.with_suffix(".so")+ subprocess.run(["gcc", "-O3", "-march=native", "-shared", "-fPIC",+ "-I", str(ROOT / "nn2/include"), str(source), "-lm", "-o", str(binary)],+ check=True)+ lib = ctypes.CDLL(str(binary))+ lib.nn2_tracker_create.restype = ctypes.c_void_p+ matched = missing = switches = 0+ times = []+ for gt_name in sorted(n for n in archive.namelist() if "FRCNN/gt/gt.txt" in n):+ gt = np.loadtxt(archive.open(gt_name), delimiter=",")+ det = np.loadtxt(archive.open(gt_name.replace("gt/gt", "det/det")), delimiter=",")+ gt_frames = group_frames(gt[(gt[:, 6] == 1) & (gt[:, 7] == 1) & (gt[:, 8] >= .5)])+ det_frames = group_frames(det[det[:, 6] >= .5])+ engine = None+ try:+ for frame in range(1, max(gt_frames) + 1):+ if frame % 120 == 1:+ if engine:+ lib.nn2_tracker_free(engine)+ engine = ctypes.c_void_p(lib.nn2_tracker_create(5, 2))+ identities = {}+ truth = gt_frames.get(frame, np.empty((0, 9)))+ observed = det_frames.get(frame, np.empty((0, 10)))+ detections = np.zeros(len(observed), DET)+ detections["box"] = corners(observed)+ detections["score"] = observed[:, 6]+ out = np.empty(128, TRACK)+ t = time.thread_time_ns()+ n = lib.nn2_tracker_update(engine, detections.ctypes.data_as(ctypes.c_void_p),+ len(detections), out.ctypes.data_as(ctypes.c_void_p), len(out))+ times.append((time.thread_time_ns() - t) / 1000)+ current = out[:n][out["since"][:n] == 0]+ pairs = matches(current["box"], corners(truth))+ matched += len(pairs)+ missing += len(truth) - len(pairs)+ for i, j in pairs:+ who, track_id = int(truth[j, 1]), int(current["id"][i])+ switches += who in identities and identities[who] != track_id+ identities[who] = track_id+ finally:+ if engine:+ lib.nn2_tracker_free(engine)+ return matched, missing, switches, round(statistics.median(times), 2)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("labels", type=Path)+ args = parser.parse_args()+ with tempfile.TemporaryDirectory() as tmp, ZipFile(args.labels) as archive:+ directory = Path(tmp)+ for name in ("baseline", "current"):+ source = directory / (name + ".c")+ path = "nn2/src/track.c"+ source.write_bytes(subprocess.check_output(["git", "show", BASE + ":" + path], cwd=ROOT)+ if name == "baseline" else (ROOT / path).read_bytes())+ print(name, "matched, missed, ID changes, CPU microseconds",+ evaluate(source, archive))+++if __name__ == "__main__":+ main()diff --git a/tests/geometry_math.c b/tests/geometry_math.cnew file mode 100644index 0000000..a4179aa--- /dev/null+++ b/tests/geometry_math.c@@ -0,0 +1,34 @@+#include "facex.h"+#include <float.h>+#include <math.h>+#include <stdint.h>+#include <stdio.h>++extern int align_face(const uint8_t*, int, int, const float*, float*);++int main(void)+{+ float a[512], b[512];+ const float scales[] = {1.0f, FLT_MIN, FLT_MAX};+ for (int j = 0; j < 3; j++) {+ for (int i = 0; i < 512; i++) {+ a[i] = i % 2 ? scales[j] : -scales[j];+ b[i] = -a[i];+ }+ if (facex_similarity(a, a) != 1 || facex_similarity(a, b) != -1) return 1;+ }+ static uint8_t img[112*112*3];+ static float crop[112*112*3];+ float kps[] = {38.2946f,51.6963f,73.5318f,51.5014f,56.0252f,+ 71.7366f,41.5493f,92.3655f,70.7299f,92.2041f};+ for (int i = 0; i < 112*112*3; i++) img[i] = (uint8_t)(i % 251);+ if (!align_face(img, 112, 112, kps, crop)) return 2;+ for (int i = 0; i < 112*112*3; i++)+ if (!(fabs(crop[i] - (img[i]/127.5f - 1)) < 1e-6)) { fprintf(stderr, "Identity mismatch %d: %g vs %g\n",i,crop[i],img[i]/127.5f - 1); return 2; }++ for (int i = 0; i < 10; i++) kps[i] = 10;+ if (align_face(img, 112, 112, kps, crop)) return 3;+ for (int i = 0; i < 112*112*3; i++) if (crop[i] != -1) return 3;+ puts("Cosine and alignment checks passed");+ return 0;+}diff --git a/tests/motion_phase.c b/tests/motion_phase.cnew file mode 100644index 0000000..eaaca52--- /dev/null+++ b/tests/motion_phase.c@@ -0,0 +1,28 @@+#include "nn2_internal.h"+#include <string.h>++int main(void) {+ uint8_t dark[32 * 32 * 3] = {0}, frame[sizeof(dark)];+ for (int dy = 0; dy < 4; dy++) {+ for (int dx = 0; dx < 4; dx++) {+ memset(frame, 0, sizeof(frame));+ memset(frame + 3 * ((8 + dy) * 32 + 8 + dx), 255, 3);+ int hits = 0;+ for (unsigned phase = 0; phase < 16; phase++) {+ MotionResult r = nn2_motion_detect_phase(dark, frame, 32, 32, 25, .003f, phase);+ hits += r.has_motion;+ if (r.has_motion && r.score != 1.f / 64) return 1;+ }+ if (hits != 1) return 2;+ }+ }+ memset(frame, 255, sizeof(frame));+ for (int h = 1; h <= 32; h++)+ for (int w = 1; w <= 32; w++)+ for (unsigned phase = 0; phase < 16; phase++) {+ MotionResult r = nn2_motion_detect_phase(dark, frame, w, h, 25, .003f, phase);+ int any_sample = (int)(phase % 4) < w && (int)(phase / 4) < h;+ if (r.score != (float)any_sample) return 3;+ }+ return 0;+}diff --git a/tests/verify_yunet.py b/tests/verify_yunet.pynew file mode 100644index 0000000..0967aae--- /dev/null+++ b/tests/verify_yunet.py@@ -0,0 +1,141 @@+"""Check native YuNet against the repository fixture and optional WIDER annotations.++Accepts weights exported by tools/export_yunet_weights.py. The optional WIDER+run reports a fixed operating point, with RGB input and the C engine's default+threshold. It counts unmatched detections and ignores invalid GT boxes.+"""+import argparse+import ctypes+import io+from pathlib import Path+import subprocess+import tempfile+from zipfile import ZipFile++import numpy as np+from PIL import Image+from scipy.optimize import linear_sum_assignment++ROOT = Path(__file__).resolve().parents[1]+++def native_run(lib, engine, image, capacity=525):+ height, width, _ = image.shape+ out = np.empty((capacity, 15), dtype=np.float32)+ count = lib.detect_run(engine, image.ctypes.data_as(ctypes.c_void_p),+ width, height, out.ctypes.data_as(ctypes.c_void_p), capacity)+ if count < 0 or count > capacity:+ raise ValueError("Native detector returned an invalid count")+ return out[:count]+++def check_golden(lib, engine):+ root = ROOT / "tests/golden"+ expected = None+ for stride in (8, 16, 32):+ def head(name):+ return np.load(root / f"onnx_160_{name}_{stride}.npy")[0]+ scores = np.sqrt(head("cls").ravel() * head("obj").ravel())+ idx = np.argmax(scores)+ if expected is not None and scores[idx] <= expected[4]:+ continue+ gy, gx = divmod(int(idx), 160 // stride)+ ox, oy, lw, lh = head("bbox")[idx]+ cx, cy = (gx + ox) * stride, (gy + oy) * stride+ hw, hh = np.exp([lw, lh]) * (stride / 2)+ points = (head("kps")[idx].reshape(5, 2) + [gx, gy]) * stride+ expected = np.r_[cx - hw, cy - hh, cx + hw, cy + hh, scores[idx], points.ravel()]+ image = np.fromfile(ROOT / "tests/test_face_160.raw", dtype="u1").reshape(160, 160, 3)+ out = native_run(lib, engine, image)+ np.testing.assert_allclose(out[0], expected, atol=.002, rtol=0)+ np.testing.assert_array_equal(native_run(lib, engine, image, 1), out[:1])+ lib.detect_set_score_threshold(engine, ctypes.c_float(.005))+ for path in sorted(root.glob("*.npz")):+ with np.load(path) as fixture:+ face = np.asarray(Image.fromarray(fixture["image"]).resize((160, 160)))+ candidates = native_run(lib, engine, face)+ for capacity in (1, 3):+ np.testing.assert_array_equal(native_run(lib, engine, face, capacity),+ candidates[:capacity])+ lib.detect_set_score_threshold(engine, ctypes.c_float(.5))+ # Resize and re-use the same engine, including a non-aligned shape.+ for size in ((161, 165), (320, 320), (640, 640)):+ native_run(lib, engine, np.asarray(Image.fromarray(image).resize(size)))+ np.testing.assert_array_equal(native_run(lib, engine, image), out)+ print("Golden maximum absolute difference", float(np.max(abs(out[0] - expected))))+++def annotations(archive):+ lines = iter(archive.read("wider_face_split/wider_face_val_bbx_gt.txt").decode().splitlines())+ result = {}+ for name in lines:+ if not name.endswith(".jpg"):+ continue+ boxes = []+ for _ in range(int(next(lines))):+ row = list(map(int, next(lines).split()))+ if len(row) >= 10 and row[7] == 0 and min(row[2:4]) > 0:+ boxes.append(row[:4])+ result[name] = np.array(boxes, dtype=float).reshape(-1, 4)+ return result+++def match(detections, gt):+ a = detections[:, :4]+ inter = (np.minimum(a[:, None, 2:], gt[None, :, 2:]) -+ np.maximum(a[:, None, :2], gt[None, :, :2])).clip(0).prod(2)+ union = ((a[:, 2:] - a[:, :2]).prod(1)[:, None] ++ (gt[:, 2:] - gt[:, :2]).prod(1) - inter)+ iou = inter / np.maximum(union, 1e-8)+ rows, cols = linear_sum_assignment(np.where(iou >= .5, 100 + iou, 0), maximize=True)+ return cols[iou[rows, cols] >= .5]+++def evaluate_wider(lib, engine, image_archive, annotation_archive, size):+ labels = annotations(annotation_archive)+ names = np.random.default_rng(114).choice(sorted(labels), 640, replace=False)+ counts = np.zeros(3, int)+ for name in names:+ image = Image.open(io.BytesIO(image_archive.read("WIDER_val/images/" + name))).convert("RGB")+ width, height = image.size+ scale = size / max(width, height)+ w, h = max(1, round(width * scale)), max(1, round(height * scale))+ x, y = (size - w) // 2, (size - h) // 2+ canvas = np.zeros((size, size, 3), "u1")+ canvas[y:y+h, x:x+w] = image.resize((w, h))+ gt = labels[name] * [w / width, h / height, w / width, h / height]+ gt[:, 2:] += gt[:, :2]+ gt += [x, y, x, y]+ det = native_run(lib, engine, canvas)+ found = len(match(det, gt))+ counts += [found, len(det) - found, len(gt) - found]+ print(size, "matched, unmatched detections, missed boxes", counts.tolist())+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("weights", type=Path)+ parser.add_argument("--wider", type=Path, nargs=2, metavar=("IMAGES_ZIP", "LABELS_ZIP"))+ parser.add_argument("--sizes", type=int, nargs="+", default=[160, 320])+ args = parser.parse_args()+ with tempfile.TemporaryDirectory() as tmp:+ binary = Path(tmp) / "detector.so"+ subprocess.run(["gcc", "-O3", "-march=native", "-shared", "-fPIC", "-I", str(ROOT / "include"),+ str(ROOT / "src/detect.c"), "-lm", "-o", str(binary)], check=True)+ lib = ctypes.CDLL(str(binary))+ lib.detect_init.restype = ctypes.c_void_p+ engine = ctypes.c_void_p(lib.detect_init(bytes(args.weights)))+ if not engine:+ raise RuntimeError("Unable to load YNET weights")+ try:+ check_golden(lib, engine)+ if args.wider:+ with ZipFile(args.wider[0]) as images, ZipFile(args.wider[1]) as labels:+ for size in args.sizes:+ evaluate_wider(lib, engine, images, labels, size)+ finally:+ lib.detect_free(engine)+++if __name__ == "__main__":+ main()diff --git a/tools/yunet_golden.py b/tools/yunet_golden.pyindex 6c5b1ee..9c7b877 100644--- a/tools/yunet_golden.py+++ b/tools/yunet_golden.py@@ -72,35 +72,22 @@ def decode_anchor_free(outputs, strides=(8, 16, 32), input_size=160,for s in strides:feat_h = input_size // sfeat_w = input_size // s- # Skip levels where the input doesn't map cleanly (e.g. 160/32 = 5)- # YuNet outputs are sized for 640x640; for 160x160 we get 20/10/5 cells- # per side. We slice the first feat_h*feat_w rows.n_cells = feat_h * feat_w- cls_s = cls[s][:n_cells]- obj_s = obj[s][:n_cells]- bbox_s = bbox[s][:n_cells]- kps_s = kps[s][:n_cells]- # Sigmoid both: classification * objectness- # ONNX outputs are pre-sigmoid for cls and obj per opencv_zoo's YuNet- score_s = 1.0 / (1.0 + np.exp(-cls_s)) * 1.0 / (1.0 + np.exp(-obj_s))- for idx in range(n_cells):- sc = float(score_s[idx, 0])- if sc < score_thresh:- continue- cy_idx = idx // feat_w- cx_idx = idx % feat_w- cx = (cx_idx + 0.5) * s- cy = (cy_idx + 0.5) * s- # bbox = [l, t, r, b] offsets to grid center- l, t, r, b = bbox_s[idx]- x1 = cx - l * s- y1 = cy - t * s- x2 = cx + r * s- y2 = cy + b * s- kp = kps_s[idx].copy()- for k in range(kps_count):- kp[k * 2] = cx + kp[k * 2] * s- kp[k * 2 + 1] = cy + kp[k * 2 + 1] * s+ if len(cls[s]) != n_cells:+ raise ValueError(f"stride {s} output does not match input size {input_size}")+ # ONNX emits probabilities. The native head applies its sigmoid in C.+ scores = np.sqrt(np.clip(cls[s] * obj[s], 0, 1)).ravel()+ for idx in np.flatnonzero(scores >= score_thresh):+ sc = float(scores[idx])+ gy, gx = divmod(int(idx), feat_w)+ offset_x, offset_y, log_w, log_h = bbox[s][idx]+ cx, cy = (gx + offset_x) * s, (gy + offset_y) * s+ w, h = np.exp(log_w) * s, np.exp(log_h) * s+ x1, y1 = cx - w/2, cy - h/2+ x2, y2 = cx + w/2, cy + h/2+ kp = kps[s][idx].copy()+ kp[0::2] = (gx + kp[0::2]) * s+ kp[1::2] = (gy + kp[1::2]) * sfaces.append((x1, y1, x2, y2, sc, kp.tolist()))return faces@@ -141,7 +128,19 @@ def main():out_dir = Path(args.out_dir)out_dir.mkdir(parents=True, exist_ok=True)- sess = ort.InferenceSession(args.onnx_path, providers=["CPUExecutionProvider"])+ if args.input_size <= 0 or args.input_size % 32:+ ap.error("--input-size must be a positive multiple of 32")+ # Public YuNet declares fixed spatial dimensions despite using convolutions+ # throughout. Set the reference graph to the same resolution as the C run.+ import onnx+ model = onnx.load(args.onnx_path)+ dims = model.graph.input[0].type.tensor_type.shape.dim+ for dim in dims[2:4]:+ dim.dim_value = args.input_size+ for output in model.graph.output:+ stride = int(output.name.rsplit("_", 1)[1])+ output.type.tensor_type.shape.dim[1].dim_value = (args.input_size // stride) ** 2+ sess = ort.InferenceSession(model.SerializeToString(), providers=["CPUExecutionProvider"])out_names = [o.name for o in sess.get_outputs()]print(f"Loaded {args.onnx_path}")print(f"Outputs: {out_names}")