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
WASM optimization: 14ms → 7ms, SDK, detect, articles
atynovbe241dd43e0c
diff --git a/articles/habr.html b/articles/habr.htmlnew file mode 100644index 0000000..cdccdfc--- /dev/null+++ b/articles/habr.html@@ -0,0 +1,215 @@+<!DOCTYPE html>+<html lang="ru">+<head>+<meta charset="UTF-8">+<title>Как я написал движок распознавания лиц на C, который обогнал ONNX Runtime</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #fff; color: #333; line-height: 1.8; }+article { max-width: 780px; margin: 30px auto; padding: 20px 32px 60px; }+.hubs { color: #999; font-size: 13px; margin-bottom: 12px; }+.hubs a { color: #548eaa; text-decoration: none; }+h1 { font-size: 28px; color: #333; margin-bottom: 20px; line-height: 1.3; font-weight: 700; }+h2 { font-size: 22px; color: #333; margin: 36px 0 14px; padding-bottom: 8px; border-bottom: 1px solid #eee; }+h3 { font-size: 17px; color: #333; margin: 24px 0 10px; }+p { margin-bottom: 14px; font-size: 16px; color: #333; }+strong { color: #000; }+em { color: #555; font-style: italic; }+a { color: #548eaa; text-decoration: none; }+a:hover { text-decoration: underline; }+blockquote { border-left: 3px solid #548eaa; padding: 10px 18px; margin: 16px 0; background: #f8f9fa; color: #555; font-size: 15px; border-radius: 0 4px 4px 0; }+blockquote strong { color: #333; }+table { width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 15px; }+th { text-align: left; padding: 10px 14px; background: #f5f5f5; color: #666; font-weight: 600; border-bottom: 2px solid #ddd; }+td { padding: 10px 14px; border-bottom: 1px solid #eee; }+tr:hover td { background: #fafafa; }+.green { color: #2e7d32; font-weight: 700; }+pre { background: #f5f5f5; padding: 18px; border-radius: 4px; overflow-x: auto; margin: 16px 0; font-size: 14px; line-height: 1.6; border: 1px solid #eee; }+code { font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace; font-size: 14px; }+p code, li code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; font-size: 13px; color: #c7254e; }+ul, ol { margin: 12px 0 16px 28px; font-size: 16px; }+li { margin-bottom: 8px; }+hr { border: none; border-top: 1px solid #eee; margin: 32px 0; }+.bug { background: #fff8e1; border: 1px solid #ffe082; border-radius: 6px; padding: 14px 18px; margin: 12px 0; }+.bug h4 { font-size: 14px; color: #e65100; margin-bottom: 6px; }+.bug pre { background: #fff; border: 1px solid #ffe082; margin: 8px 0 0; font-size: 13px; }+.result { background: #e8f5e9; border: 1px solid #a5d6a7; border-radius: 6px; padding: 14px 18px; margin: 16px 0; text-align: center; font-size: 16px; }+.author { margin-top: 30px; padding-top: 16px; border-top: 1px solid #eee; color: #999; font-size: 14px; }+</style>+</head>+<body>+<article>++<div class="hubs">+ <a href="#">Программирование</a> · <a href="#">C</a> · <a href="#">Машинное обучение</a> · <a href="#">Высокая производительность</a> · <a href="#">Компьютерное зрение</a>+</div>++<h1>Как я написал движок распознавания лиц на C, который обогнал ONNX Runtime</h1>++<p>Полгода назад я начал портировать нейросеть EdgeFace-XS из ONNX в чистый C. Думал — граф небольшой, 1.77M параметров, что может пойти не так? Первый наивный порт выдал <strong>24мс</strong>. ONNX Runtime — <strong>3.9мс</strong>. В 6 раз медленнее. А потом началась оптимизация.</p>++<h2>Результат</h2>++<table>+<tr><th></th><th>FaceX</th><th>ONNX Runtime 1.23</th></tr>+<tr><td>Медиана</td><td class="green">3.0 мс</td><td>3.9 мс</td></tr>+<tr><td>Минимум</td><td class="green">2.87 мс</td><td>3.18 мс</td></tr>+<tr><td>Размер библиотеки</td><td class="green">148 КБ</td><td>28 МБ</td></tr>+<tr><td>Зависимости</td><td class="green">нет</td><td>Python + onnxruntime</td></tr>+<tr><td>Точность LFW</td><td class="green">99.73%</td><td>99.73%</td></tr>+</table>++<blockquote>Чистый C с SIMD интринсиками обгоняет ONNX Runtime на <strong>23%</strong>. Один и тот же CPU (i5-11500), одна модель, одни входные данные.</blockquote>++<h2>Путь оптимизации: 24мс → 3мс</h2>++<h3>Этап 0: Профилирование</h3>++<p>Замерил каждую операцию отдельно. Главный сюрприз:</p>++<blockquote><strong>Матричное умножение — всего 6% от общего времени инференса.</strong></blockquote>++<p>Настоящие убийцы производительности:</p>++<table>+<tr><th>Операция</th><th>Доля</th><th>Проблема</th></tr>+<tr><td>Depthwise conv</td><td>~30%</td><td>Транспозы HWC↔CHW на каждом блоке</td></tr>+<tr><td>LayerNorm × 17</td><td>~16%</td><td>Скалярный mean/variance</td></tr>+<tr><td>GELU × 17</td><td>~10%</td><td>Наивный <code>tanh()</code> через math.h</td></tr>+<tr><td>Транспозы памяти</td><td>~8%</td><td>Лишние копирования</td></tr>+<tr><td>MatMul</td><td>~6%</td><td>Уже быстро</td></tr>+</table>++<h3>Этап 1: SIMD ядра (24мс → 8мс)</h3>++<p>Написал AVX2 версии для каждой операции:</p>++<ul>+ <li><strong>LayerNorm</strong> — fused mean+variance в одном проходе. Вместо двух циклов по памяти — один с <code>_mm256_fmadd_ps</code> для накопления суммы и суммы квадратов</li>+ <li><strong>GELU</strong> — выкинул <code>tanh()</code>. Реализовал exact erf через полиномиальную аппроксимацию Абрамовица-Стегуна (формула 7.1.26) с кастомным <code>_mm256_exp_ps</code> на 8 элементов за такт</li>+ <li><strong>Depthwise conv</strong> — перевёл весь движок на нативный HWC layout. Ни одного транспоза во всём forward pass</li>+</ul>++<h3>Этап 2: MatMul (8мс → 5мс)</h3>++<ul>+ <li><strong>FP32 packed column-panel</strong>: веса перепакованы в формат <code>[ceil(N/8), K, 8]</code> — каждый столбец-панель помещается в L1 кэш</li>+ <li><strong>INT8 GEMM микроядро</strong> с per-channel квантизацией:+ <ul>+ <li>AVX2: <code>vpmaddubsw</code> с ±63 clamping для предотвращения s16 насыщения</li>+ <li>AVX-512 VNNI: <code>vpdpbusd</code> — нативные INT8 dot products без насыщения</li>+ </ul>+ </li>+ <li><strong>Thread pool</strong> — lock-free с work-stealing через атомарный счётчик и <code>WaitOnAddress</code>/<code>futex</code></li>+</ul>++<h3>Этап 3: Последние миллисекунды (5мс → 3мс)</h3>++<ul>+ <li>Убрал <strong>все</strong> транспозы — данные в HWC от входа до выхода</li>+ <li><strong>Статический workspace</strong> вместо <code>malloc</code> на каждом вызове</li>+ <li><strong>Pre-computed position embedding</strong> — это константа, не зависит от входа</li>+ <li><strong>Pre-packed веса</strong> — транспозиция и паковка при загрузке, не при инференсе</li>+</ul>++<h3>Хронология</h3>++<table>+<tr><th>Фаза</th><th>Время</th><th>Длительность работы</th></tr>+<tr><td>Наивный порт</td><td>24 мс</td><td>2 недели</td></tr>+<tr><td>SIMD ядра</td><td>8 мс</td><td>3 недели</td></tr>+<tr><td>MatMul + INT8</td><td>5 мс</td><td>1 месяц</td></tr>+<tr><td><strong>Финальная полировка</strong></td><td class="green">3 мс</td><td><strong>4 месяца</strong></td></tr>+</table>++<blockquote>Последние 2мс заняли 4 месяца. Первые 16мс — 2 недели. Вот что такое оптимизация.</blockquote>++<h2>7 багов точности</h2>++<p>Самая болезненная часть. Cosine similarity с ONNX reference начиналась на <strong>0.067</strong> (мусор). Должно быть <strong>1.0</strong>. Нашёл 7 багов через послойные дампы — каждый из 286 тензоров сравнивался с NumPy эталоном.</p>++<div class="bug">+<h4>Баг 1: Индекс gamma</h4>+<pre><code>Stage 0, block 2: использовал W(38) — это bias+Правильно: W(39) — это gamma</code></pre>+</div>++<div class="bug">+<h4>Баг 2: XCA residual connections</h4>+<pre><code>Было: attention_residual = original_input+ mlp_residual = original_input++Надо: attention_residual = DW_output + pos_embed+ mlp_residual = original_input</code></pre>+</div>++<div class="bug">+<h4>Баг 3: XCA Depthwise Conv — каскадный, не независимый</h4>+<pre><code>Было: conv0(x_split0), conv1(x_split1) — независимо+Надо: r0 = conv0(x_split0), conv1(r0 + x_split1) — каскадно</code></pre>+</div>++<div class="bug">+<h4>Баг 4: Position Embedding — это константа</h4>+<pre><code>Было: pos = Conv1x1(INPUT, W) — пересчитывается каждый раз+Надо: pos = Conv1x1(CONSTANT, W) — вычисляется один раз при загрузке</code></pre>+</div>++<div class="bug">+<h4>Баг 5: XCA Attention — размерность</h4>+<pre><code>Было: attn = softmax(Q @ K^T / τ) — полная [C × C] матрица+Надо: attn_h = softmax(Q_h @ K_h^T / τ) — per-head [dim × dim]</code></pre>+</div>++<div class="bug">+<h4>Баг 6: Workspace overlap</h4>+<pre><code>Stage 3, head_dim=48: attn_buf начинался по адресу,+перекрывающему конец V_nhd. Сдвиг буфера решил проблему.</code></pre>+</div>++<div class="bug">+<h4>Баг 7: GELU drift</h4>+<pre><code>tanh-аппроксимация GELU: ошибка ε на каждом блоке.+17 блоков × ε = заметное расхождение.+Фикс: заменил на exact erf (A&S 7.1.26).</code></pre>+</div>++<div class="result">+ Каждый фикс: <strong>+0.1</strong> cosine similarity → Семь фиксов: <strong>1.000</strong>+</div>++<h2>API</h2>++<pre><code><span style="color:#888">// Инициализация (~100мс, один раз)</span>+FaceX* fx = facex_init("edgeface_xs_fp32.bin", NULL);++<span style="color:#888">// Эмбеддинг (3мс на вызов)</span>+float face[112 * 112 * 3]; <span style="color:#888">// RGB, HWC layout, [-1, 1]</span>+float embedding[512];+facex_embed(fx, face, embedding);++<span style="color:#888">// Сравнение двух лиц</span>+float sim = facex_similarity(emb_a, emb_b);+<span style="color:#888">// sim > 0.3 → один и тот же человек</span>++facex_free(fx);</code></pre>++<div class="result">+ <strong>4 функции · 148 КБ · Ноль зависимостей · Apache 2.0</strong>+</div>++<h2>Вывод</h2>++<p>Один человек может написать inference движок быстрее продукта Microsoft — если оптимизирует под одну конкретную модель. ONNX Runtime рассчитан на тысячи моделей. FaceX — на одну. <strong>Специализация бьёт универсальность.</strong></p>++<hr>++<p>Исходники: <a href="https://github.com/facex-engine/facex"><strong>github.com/facex-engine/facex</strong></a></p>++<div class="author">+ Автор: <strong>Baurzhan Atinov</strong> · Казахстан · При поддержке гранта NLnet+</div>++</article>+</body>+</html>diff --git a/articles/linkedin.html b/articles/linkedin.htmlnew file mode 100644index 0000000..fca194f--- /dev/null+++ b/articles/linkedin.html@@ -0,0 +1,339 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<title>FaceX — LinkedIn Posts</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f3f2ef; color: #333; line-height: 1.7; }+.container { max-width: 600px; margin: 0 auto; padding: 20px; }+h1 { text-align: center; font-size: 24px; color: #0a66c2; margin: 30px 0 8px; }+.subtitle { text-align: center; color: #666; font-size: 14px; margin-bottom: 30px; }++.card { background: #fff; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); overflow: hidden; }+.card-header { padding: 16px 20px; display: flex; align-items: center; gap: 12px; }+.avatar { width: 48px; height: 48px; background: #0a66c2; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 18px; }+.name { font-weight: 600; font-size: 15px; color: #333; }+.title-line { font-size: 12px; color: #666; }+.post-num { background: #e8f4fd; color: #0a66c2; padding: 2px 10px; border-radius: 12px; font-size: 11px; font-weight: 600; margin-left: auto; }+.lang-tag { background: #f0f0f0; color: #666; padding: 2px 8px; border-radius: 12px; font-size: 11px; }++.card-body { padding: 0 20px 20px; font-size: 15px; line-height: 1.75; color: #333; }+.card-body p { margin-bottom: 12px; }+.card-body .bold { font-weight: 700; color: #000; }+.card-body .stat { font-size: 22px; font-weight: 700; color: #0a66c2; }+.card-body .link { color: #0a66c2; font-weight: 600; }+.card-body .quote { border-left: 3px solid #0a66c2; padding: 8px 14px; margin: 12px 0; background: #f8f9fa; color: #555; font-style: italic; }+.card-body .arrow { color: #0a66c2; font-weight: 600; }+.card-body .highlight { background: linear-gradient(120deg, #e8f4fd 0%, #e8f4fd 100%); padding: 2px 4px; border-radius: 3px; }++.hashtags { padding: 12px 20px; border-top: 1px solid #f0f0f0; color: #0a66c2; font-size: 13px; font-weight: 600; }++.sep { text-align: center; padding: 16px; color: #999; font-size: 13px; }+</style>+</head>+<body>+<div class="container">++<h1>LinkedIn — 5 Posts</h1>+<p class="subtitle">Один пост в день · EN + RU версии</p>++<!-- ===== POST 1 EN ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">1/5</span>+ <span class="lang-tag">EN</span>+</div>+<div class="card-body">+<p>I just open-sourced a project I've been working on for 6 months.</p>++<p><span class="bold">FaceX</span> is a face embedding library written in pure C.<br>+No Python. No ONNX Runtime. No dependencies at all.</p>++<p>It runs face recognition at <span class="stat">3ms</span> per face on CPU.<br>+That's <span class="highlight">23% faster</span> than Microsoft's ONNX Runtime.</p>++<p>The entire library is <span class="bold">148 KB</span>.</p>++<p>How did one person beat a Microsoft product?</p>++<p>By optimizing for <span class="bold">one</span> specific model instead of thousands.</p>++<p>ONNX Runtime is a general-purpose inference engine.<br>+FaceX is a scalpel — every SIMD instruction hand-picked for the EdgeFace-XS architecture.</p>++<p><span class="bold">4 functions. One header file. Apache 2.0.</span></p>++<p><span class="arrow">→</span> <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+<div class="hashtags">#FacialRecognition #ComputerVision #EdgeAI #MachineLearning #OpenSource #Performance</div>+</div>++<!-- ===== POST 1 RU ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">1/5</span>+ <span class="lang-tag">RU</span>+</div>+<div class="card-body">+<p>Выложил в open source проект над которым работал полгода.</p>++<p><span class="bold">FaceX</span> — библиотека эмбеддинга лиц на чистом C.<br>+Без Python. Без ONNX Runtime. Вообще без зависимостей.</p>++<p><span class="stat">3мс</span> на лицо на CPU.<br>+На <span class="highlight">23% быстрее</span> ONNX Runtime от Microsoft.</p>++<p>Вся библиотека — <span class="bold">148 КБ</span>.</p>++<p>Как один человек обогнал продукт Microsoft?</p>++<p>Оптимизация под <span class="bold">одну</span> конкретную модель вместо тысяч.</p>++<p>ONNX Runtime — универсальный движок.<br>+FaceX — скальпель. Каждая SIMD инструкция подобрана под архитектуру EdgeFace-XS.</p>++<p><span class="bold">4 функции. Один заголовочный файл. Apache 2.0.</span></p>++<p><span class="arrow">→</span> <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+<div class="hashtags">#РаспознаваниеЛиц #AI #OpenSource #Производительность #EdgeAI</div>+</div>++<div class="sep">— день 2 —</div>++<!-- ===== POST 2 EN ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">2/5</span>+ <span class="lang-tag">EN</span>+</div>+<div class="card-body">+<p>How I went from <span class="bold">24ms</span> to <span class="bold">3ms</span> in face recognition inference.</p>++<p>6 months ago I started porting a neural network from ONNX to C.</p>++<p>Week 1: naive port. 24ms. Works, but 7x slower than ONNX Runtime.</p>++<p>I profiled every operation. The surprise?</p>++<div class="quote">Matrix multiplication was only 6% of inference time.</div>++<p>The real killers:</p>++<p><span class="arrow">→</span> Layer normalization — 17 calls, scalar loops<br>+<span class="arrow">→</span> GELU activation — naive tanh through math.h<br>+<span class="arrow">→</span> Memory transposes — layout conversions on every block</p>++<p>So I wrote custom SIMD kernels for each operation.<br>+AVX2 for everything. AVX-512 where available.<br>+INT8 quantized GEMM with per-channel scaling.</p>++<p><span class="stat">24ms → 8ms → 5ms → 3ms</span></p>++<p>The last 2ms took <span class="bold">4 months</span>.<br>+The first 16ms took <span class="bold">2 weeks</span>.</p>++<p><span class="bold">That's optimization in a nutshell.</span></p>+</div>+<div class="hashtags">#Optimization #SIMD #Performance #DeepLearning #CProgramming</div>+</div>++<!-- ===== POST 2 RU ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">2/5</span>+ <span class="lang-tag">RU</span>+</div>+<div class="card-body">+<p>Как я ускорил inference с <span class="bold">24мс</span> до <span class="bold">3мс</span>.</p>++<p>Полгода назад начал портировать нейросеть из ONNX в C.</p>++<p>Неделя 1: наивный порт. 24мс. В 7 раз медленнее ONNX Runtime.</p>++<div class="quote">Матричное умножение — всего 6% времени.</div>++<p>Настоящие убийцы:</p>++<p><span class="arrow">→</span> LayerNorm — 17 вызовов, скалярные циклы<br>+<span class="arrow">→</span> GELU — наивный tanh через math.h<br>+<span class="arrow">→</span> Транспозы — HWC↔CHW на каждом блоке</p>++<p><span class="stat">24мс → 8мс → 5мс → 3мс</span></p>++<p>Последние 2мс заняли <span class="bold">4 месяца</span>.<br>+Первые 16мс — <span class="bold">2 недели</span>.</p>++<p><span class="bold">Вот что такое оптимизация.</span></p>+</div>+<div class="hashtags">#Оптимизация #AI #Производительность</div>+</div>++<div class="sep">— день 3 —</div>++<!-- ===== POST 3 EN ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">3/5</span>+ <span class="lang-tag">EN</span>+</div>+<div class="card-body">+<p>The hardest part of beating ONNX Runtime wasn't speed.<br>+<span class="bold">It was accuracy.</span></p>++<p>My C engine produced garbage embeddings.<br>+Cosine similarity with the reference: <span class="stat">0.067</span><br>+Should be: <span class="stat">1.0</span></p>++<p>I found <span class="bold">7 bugs</span> through per-layer intermediate dumps, comparing every tensor against a NumPy reference.</p>++<p>The most subtle:</p>++<p><span class="bold">①</span> XCA attention computed full C×C matrices instead of per-head [head_dim × head_dim]. The reshape was hidden in the ONNX graph.</p>++<p><span class="bold">②</span> Position embedding was treated as a function of input. It's actually a <span class="highlight">CONSTANT</span> — computed once at load.</p>++<p><span class="bold">③</span> Depthwise conv was independent per-channel. ONNX cascades: conv0 → result → conv1.</p>++<p>Each fix: <span class="bold">+0.1</span> cosine similarity.<br>+Seven fixes later: <span class="stat">1.0</span></p>++<div class="quote">Lesson: never trust your understanding of a computational graph. Dump intermediates. Compare everything.</div>+</div>+<div class="hashtags">#Debugging #NeuralNetworks #MachineLearning #SoftwareEngineering</div>+</div>++<div class="sep">— день 4 —</div>++<!-- ===== POST 4 EN ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">4/5</span>+ <span class="lang-tag">EN</span>+</div>+<div class="card-body">+<p>My face recognition library has <span class="bold">zero dependencies</span>.</p>++<p>No Python.<br>No ONNX Runtime.<br>No MKL.<br>No OpenBLAS.<br>No package manager.<br>No version conflicts.</p>++<p><span class="stat">148 KB</span> of C code. That's the entire engine.</p>++<p>Deploy: copy one file. Run.</p>++<p>In a world of 500MB Docker images for "hello world", there's something refreshing about a <span class="bold">7MB binary</span> that does face recognition at 3ms/face.</p>++<p>We forgot that software can be small.<br>+That inference doesn't need a framework.<br>+That C is still the fastest language for numerical code.</p>++<div class="quote">Every dependency is a liability.<br>Every framework is someone else's complexity.</div>++<p>Sometimes the best optimization is <span class="bold">deletion</span>.</p>++<p><span class="arrow">→</span> <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+<div class="hashtags">#Minimalism #SoftwareDevelopment #Performance #ZeroDependencies</div>+</div>++<div class="sep">— день 5 —</div>++<!-- ===== POST 5 EN ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">5/5</span>+ <span class="lang-tag">EN</span>+</div>+<div class="card-body">+<p>I'm a developer from Kazakhstan.</p>++<p>6 months ago I decided to write the fastest CPU face recognition engine in the world.</p>++<div class="quote">+"ONNX Runtime has dozens of engineers.<br>+You can't beat Microsoft alone."+</div>++<p>This week I open-sourced <span class="bold">FaceX</span>.</p>++<p><span class="bold">3.0ms</span> per face. ONNX Runtime does <span class="bold">3.9ms</span>.<br>+<span class="bold">148 KB</span> binary. They need <span class="bold">28 MB</span>.<br>+<span class="bold">Zero</span> dependencies. They need Python.</p>++<p>I'm not smarter than Microsoft's engineers.<br>+I just had a narrower target.</p>++<p>They optimize for 10,000 models.<br>+I optimized for <span class="bold">one</span>.</p>++<p><span class="stat">Specialization beats generalization.</span><br>+<span class="stat">Focus beats resources.</span></p>++<p>Funded by NLnet (EU open source grant). Apache 2.0.</p>++<p><span class="arrow">→</span> <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>++<p>If you're building something alone and people say it can't be done — <span class="bold">keep going</span>.</p>+</div>+<div class="hashtags">#Startup #SoloFounder #OpenSource #Kazakhstan #NeverGiveUp</div>+</div>++<!-- ===== POST 5 RU ===== -->+<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">5/5</span>+ <span class="lang-tag">RU</span>+</div>+<div class="card-body">+<p>Я разработчик из Казахстана.</p>++<p>Полгода назад решил написать самый быстрый CPU движок распознавания лиц в мире.</p>++<div class="quote">+"У ONNX Runtime десятки инженеров.<br>+Ты не обгонишь Microsoft в одиночку."+</div>++<p>На этой неделе я выложил <span class="bold">FaceX</span> в open source.</p>++<p><span class="bold">3.0мс</span> на лицо. ONNX Runtime — <span class="bold">3.9мс</span>.<br>+<span class="bold">148 КБ</span> бинарник. Им нужно <span class="bold">28 МБ</span>.<br>+<span class="bold">Ноль</span> зависимостей. Им нужен Python.</p>++<p>Я не умнее инженеров Microsoft.<br>+У меня просто была более узкая цель.</p>++<p>Они оптимизируют под 10 000 моделей.<br>+Я оптимизировал под <span class="bold">одну</span>.</p>++<p><span class="stat">Специализация бьёт универсальность.</span><br>+<span class="stat">Фокус бьёт ресурсы.</span></p>++<p>При поддержке NLnet. Apache 2.0.</p>++<p><span class="arrow">→</span> <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>++<p>Если вы строите что-то в одиночку и говорят что это невозможно — <span class="bold">продолжайте</span>.</p>+</div>+<div class="hashtags">#Стартап #OpenSource #Казахстан #Разработка</div>+</div>++</div>+</body>+</html>diff --git a/articles/linkedin_10.html b/articles/linkedin_10.htmlnew file mode 100644index 0000000..1b3a654--- /dev/null+++ b/articles/linkedin_10.html@@ -0,0 +1,572 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<title>FaceX — LinkedIn 10 Articles</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f3f2ef; color: #333; line-height: 1.7; }+.container { max-width: 620px; margin: 0 auto; padding: 20px; }+h1 { text-align: center; font-size: 22px; color: #0a66c2; margin: 30px 0 4px; }+.subtitle { text-align: center; color: #666; font-size: 13px; margin-bottom: 30px; }++.card { background: #fff; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 28px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); overflow: hidden; }+.card-header { padding: 16px 20px; display: flex; align-items: center; gap: 12px; border-bottom: 1px solid #f0f0f0; }+.avatar { width: 44px; height: 44px; background: #0a66c2; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 16px; flex-shrink: 0; }+.name { font-weight: 600; font-size: 14px; color: #333; }+.title-line { font-size: 12px; color: #666; }+.post-num { background: #e8f4fd; color: #0a66c2; padding: 3px 10px; border-radius: 12px; font-size: 11px; font-weight: 700; margin-left: auto; }++.card-body { padding: 18px 22px 22px; font-size: 15px; line-height: 1.8; }+.card-body p { margin-bottom: 14px; }+.bold { font-weight: 700; color: #000; }+.stat { font-size: 20px; font-weight: 700; color: #0a66c2; }+.link { color: #0a66c2; font-weight: 600; }+.quote { border-left: 3px solid #0a66c2; padding: 10px 16px; margin: 16px 0; background: #f8f9fa; color: #555; font-style: italic; border-radius: 0 6px 6px 0; }+.arrow { color: #0a66c2; font-weight: 600; }+.highlight { background: #e8f4fd; padding: 2px 6px; border-radius: 3px; }+.sep { text-align: center; color: #0a66c2; font-size: 11px; letter-spacing: 2px; padding: 12px 0 6px; text-transform: uppercase; font-weight: 600; }++.hashtags { padding: 10px 22px 14px; color: #0a66c2; font-size: 13px; font-weight: 600; }++.lang { display: flex; gap: 6px; margin-bottom: 20px; justify-content: center; }+.lang span { background: #e8f4fd; color: #0a66c2; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 600; }+</style>+</head>+<body>+<div class="container">++<h1>LinkedIn — 10 статей</h1>+<p class="subtitle">EN + RU версии · один пост в день</p>++<!-- ===== 1 ===== -->+<div class="sep">— 1 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">1</span>+</div>+<div class="card-body">+<p>Six months ago I opened a blank C file and typed <span class="highlight">#include <stdio.h></span></p>++<p>Today that file grew into the fastest CPU face recognition engine I could find anywhere in the world.</p>++<p><span class="stat">3 milliseconds</span> per face.<br>+<span class="stat">148 kilobytes</span> of code.<br>+<span class="stat">Zero</span> dependencies.</p>++<p>For context — Microsoft's ONNX Runtime does the same task in 3.9ms. With 28 megabytes of libraries. And a Python runtime.</p>++<p>I did it with one language. One file. One CPU instruction set.</p>++<p><span class="arrow">→</span> <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+<div class="hashtags">#OpenSource #Performance #FaceRecognition #CProgramming</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">1 RU</span>+</div>+<div class="card-body">+<p>Шесть месяцев назад я открыл пустой файл на C и написал <span class="highlight">#include <stdio.h></span></p>++<p>Сегодня этот файл вырос в самый быстрый CPU движок распознавания лиц из всех что я смог найти в мире.</p>++<p><span class="stat">3 миллисекунды</span> на лицо.<br>+<span class="stat">148 килобайт</span> кода.<br>+<span class="stat">Ноль</span> зависимостей.</p>++<p>Для контекста — ONNX Runtime от Microsoft делает ту же задачу за 3.9мс. С 28 мегабайтами библиотек. И Python.</p>++<p>Я обошёлся одним языком. Одним файлом. Одним набором процессорных инструкций.</p>++<p><span class="arrow">→</span> <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+<div class="hashtags">#OpenSource #Производительность #РаспознаваниеЛиц</div>+</div>++<!-- ===== 2 ===== -->+<div class="sep">— 2 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">2</span>+</div>+<div class="card-body">+<p>Week one. My neural network runs at 24 milliseconds. ONNX Runtime does 3.9.</p>++<p>I'm six times slower. With the same model. On the same CPU.</p>++<p>So I do what any engineer would do. I profile.</p>++<p>And here's where the story gets interesting.</p>++<p>Everyone assumes matrix multiplication is the bottleneck. It's a neural network. Millions of multiplications. That's where the time goes. Right?</p>++<p>Wrong.</p>++<p>Matrix multiplication was <span class="stat">6%</span> of total time.</p>++<p>The real killers were the operations nobody writes blog posts about. Layer normalization. GELU activation. Memory layout conversions.</p>++<p>The boring stuff. The glue code between the important parts.</p>++<p>Except in this case — the glue <span class="bold">was</span> the important part.</p>+</div>+<div class="hashtags">#Performance #Optimization #Profiling #Engineering</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">2 RU</span>+</div>+<div class="card-body">+<p>Первая неделя. Моя нейросеть работает за 24 миллисекунды. ONNX Runtime — за 3.9.</p>++<p>Я в шесть раз медленнее. На той же модели. На том же процессоре.</p>++<p>Делаю то что сделал бы любой инженер. Профилирую.</p>++<p>И вот тут история становится интересной.</p>++<p>Все думают что узкое место — матричное умножение. Нейросеть же. Миллионы умножений. Туда уходит время. Верно?</p>++<p>Нет.</p>++<p>Матричное умножение — <span class="stat">6%</span> общего времени.</p>++<p>Настоящие убийцы — операции о которых никто не пишет статей. Нормализация слоёв. Функция активации GELU. Конвертация раскладки памяти.</p>++<p>Скучные вещи. Код-клей между важными частями.</p>++<p>Только в этом случае клей <span class="bold">и был</span> важной частью.</p>+</div>+<div class="hashtags">#Производительность #Оптимизация #Инженерия</div>+</div>++<!-- ===== 3 ===== -->+<div class="sep">— 3 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">3</span>+</div>+<div class="card-body">+<p>My engine gave the right answer at the wrong speed.</p>++<p>Then I made it fast — and it started giving wrong answers.</p>++<p>Cosine similarity with the reference model: <span class="stat">0.067</span>. Should be 1.0. That's not a rounding error. That's garbage.</p>++<p>I spent three weeks comparing 286 tensors, layer by layer, between my C code and a NumPy reference. Every number. Every dimension. Every sign bit.</p>++<p>Found seven bugs. Each one invisible on its own. Together — catastrophic.</p>++<p>The sneakiest: the ONNX graph showed a Conv1x1 taking the input tensor. But the input to that conv was actually a <span class="bold">constant</span>. Pre-computed. Never changes. I was recomputing it every frame, introducing drift that accumulated through seventeen layers.</p>++<p>Seven fixes. 0.067 became 1.000.</p>++<p>Speed is glamorous. Accuracy is where you earn your sleep.</p>+</div>+<div class="hashtags">#Debugging #NeuralNetworks #Accuracy #SoftwareEngineering</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">3 RU</span>+</div>+<div class="card-body">+<p>Мой движок давал правильный ответ на неправильной скорости.</p>++<p>Потом я сделал его быстрым — и он начал давать неправильные ответы.</p>++<p>Косинусное сходство с эталонной моделью: <span class="stat">0.067</span>. Должно быть 1.0. Это не ошибка округления. Это мусор.</p>++<p>Три недели я сравнивал 286 тензоров, слой за слоем, между моим C кодом и NumPy эталоном. Каждое число. Каждую размерность. Каждый бит знака.</p>++<p>Нашёл семь багов. Каждый невидим по отдельности. Вместе — катастрофа.</p>++<p>Самый коварный: в ONNX графе Conv1x1 принимал входной тензор. Но вход на самом деле был <span class="bold">константой</span>. Предвычисленной. Неизменной. Я пересчитывал её каждый кадр, и дрифт накапливался через семнадцать слоёв.</p>++<p>Семь исправлений. 0.067 стал 1.000.</p>++<p>Скорость — это гламур. Точность — это то, от чего зависит ваш сон.</p>+</div>+<div class="hashtags">#Дебаггинг #НейроСети #Точность</div>+</div>++<!-- ===== 4 ===== -->+<div class="sep">— 4 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">4</span>+</div>+<div class="card-body">+<p>There's a processor instruction called <span class="highlight">vpdpbusd</span>. It multiplies thirty-two 8-bit integers and accumulates the result in one clock cycle.</p>++<p>Most developers have never heard of it. Most never will.</p>++<p>I spent two weeks learning how to use it. Then I spent a month fighting a saturation bug in its cousin instruction that corrupts results when values exceed 32,767.</p>++<p>This is what low-level optimization looks like. Not clever algorithms. Not elegant abstractions. Reading processor manuals. Counting clock cycles. Finding that your multiply-add silently overflows on the 4,097th element.</p>++<p>Glamorous? No. But it's how you beat a 28-megabyte framework with 148 kilobytes of C.</p>+</div>+<div class="hashtags">#SIMD #LowLevel #CPUOptimization #HardwareEngineering</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">4 RU</span>+</div>+<div class="card-body">+<p>Есть процессорная инструкция под названием <span class="highlight">vpdpbusd</span>. Она умножает тридцать два 8-битных целых числа и складывает результат за один такт.</p>++<p>Большинство разработчиков о ней не слышали. Большинство никогда не услышат.</p>++<p>Я потратил две недели чтобы научиться ей пользоваться. Потом месяц боролся с багом насыщения в родственной инструкции, которая портит результаты когда значения превышают 32 767.</p>++<p>Вот так выглядит низкоуровневая оптимизация. Не умные алгоритмы. Не элегантные абстракции. Чтение мануалов процессора. Подсчёт тактов. Обнаружение что ваш multiply-add тихо переполняется на 4097-м элементе.</p>++<p>Гламурно? Нет. Но именно так 148 килобайт C побеждают 28-мегабайтный фреймворк.</p>+</div>+<div class="hashtags">#SIMD #НизкийУровень #Оптимизация</div>+</div>++<!-- ===== 5 ===== -->+<div class="sep">— 5 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">5</span>+</div>+<div class="card-body">+<p>The fastest CPU face recognition engine in the world was not built in Silicon Valley.</p>++<p>Not in Seattle where Microsoft sits. Not in Beijing where Megvii trains Face++. Not in London. Not in Tel Aviv.</p>++<p>It was built in Kazakhstan.</p>++<p>By one person. With gcc and a text editor. In six months.</p>++<p>There's no secret. No special access. No connections. No funding rounds. Just an NLnet grant, an internet connection, and the belief that location doesn't determine capability.</p>++<p>The next breakthrough in AI inference will probably come from somewhere no one expects either.</p>++<p>🇰🇿</p>+</div>+<div class="hashtags">#Kazakhstan #GlobalTech #SoloFounder #EdgeAI #OpenSource</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">5 RU</span>+</div>+<div class="card-body">+<p>Самый быстрый CPU движок распознавания лиц в мире создан не в Кремниевой долине.</p>++<p>Не в Сиэтле где сидит Microsoft. Не в Пекине где Megvii тренирует Face++. Не в Лондоне. Не в Тель-Авиве.</p>++<p>Он создан в Казахстане.</p>++<p>Одним человеком. С gcc и текстовым редактором. За шесть месяцев.</p>++<p>Нет никакого секрета. Нет особого доступа. Нет связей. Нет раундов инвестиций. Только грант NLnet, интернет и вера в то что локация не определяет возможности.</p>++<p>Следующий прорыв в AI inference тоже, скорее всего, придёт оттуда, откуда никто не ждёт.</p>++<p>🇰🇿</p>+</div>+<div class="hashtags">#Казахстан #Технологии #OpenSource #EdgeAI</div>+</div>++<!-- ===== 6 ===== -->+<div class="sep">— 6 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">6</span>+</div>+<div class="card-body">+<p>My entire face recognition engine — the one that beats ONNX Runtime — is four thousand lines of C.</p>++<p>No classes. No inheritance. No templates. No build system beyond a Makefile. No package.json. No requirements.txt. No Dockerfile.</p>++<p><span class="highlight">gcc -O3 -o facex src/*.c -lm</span></p>++<p>That's the build command. The whole thing.</p>++<p>We've been trained to think that serious software needs serious infrastructure. CI/CD pipelines. Container orchestration. Dependency management.</p>++<p>Sometimes serious software is just a good algorithm and a compiler.</p>+</div>+<div class="hashtags">#Simplicity #SoftwareEngineering #Minimalism #C99</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">6 RU</span>+</div>+<div class="card-body">+<p>Весь мой движок распознавания лиц — тот самый что быстрее ONNX Runtime — это четыре тысячи строк C.</p>++<p>Без классов. Без наследования. Без шаблонов. Без системы сборки кроме Makefile. Без package.json. Без requirements.txt. Без Dockerfile.</p>++<p><span class="highlight">gcc -O3 -o facex src/*.c -lm</span></p>++<p>Вот команда сборки. Вся целиком.</p>++<p>Нас приучили думать что серьёзный софт требует серьёзной инфраструктуры. CI/CD пайплайны. Оркестрация контейнеров. Менеджмент зависимостей.</p>++<p>Иногда серьёзный софт — это просто хороший алгоритм и компилятор.</p>+</div>+<div class="hashtags">#Простота #Разработка #Минимализм</div>+</div>++<!-- ===== 7 ===== -->+<div class="sep">— 7 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">7</span>+</div>+<div class="card-body">+<p>"How did you beat Microsoft?"</p>++<p>I get this question a lot. Here's the honest answer.</p>++<p>I didn't beat Microsoft. Microsoft built a Swiss army knife that runs ten thousand different neural networks on twenty different hardware platforms. That's an incredible engineering achievement.</p>++<p>I built a scalpel that runs one specific neural network on one specific instruction set.</p>++<p>Their knife does everything acceptably. My scalpel does one thing perfectly.</p>++<p>This isn't a story about talent beating resources. It's a story about <span class="bold">scope</span>.</p>++<p>If you're a solo developer competing with a big team — don't try to match their breadth. Find one thing they do adequately and do it exceptionally.</p>++<p>That's your entire strategy.</p>+</div>+<div class="hashtags">#Strategy #SoloFounder #Focus #Competition #Startup</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">7 RU</span>+</div>+<div class="card-body">+<p>"Как ты обогнал Microsoft?"</p>++<p>Мне часто задают этот вопрос. Вот честный ответ.</p>++<p>Я не обогнал Microsoft. Microsoft построил швейцарский нож который запускает десять тысяч разных нейросетей на двадцати разных платформах. Это невероятное инженерное достижение.</p>++<p>Я построил скальпель который запускает одну конкретную нейросеть на одном конкретном наборе инструкций.</p>++<p>Их нож делает всё приемлемо. Мой скальпель делает одно — безупречно.</p>++<p>Это не история о том как талант побеждает ресурсы. Это история о <span class="bold">scope</span>.</p>++<p>Если вы соло-разработчик и конкурируете с большой командой — не пытайтесь охватить их ширину. Найдите одну вещь которую они делают нормально, и сделайте её исключительно.</p>++<p>Это вся стратегия.</p>+</div>+<div class="hashtags">#Стратегия #Фокус #Конкуренция #Стартап</div>+</div>++<!-- ===== 8 ===== -->+<div class="sep">— 8 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">8</span>+</div>+<div class="card-body">+<p>The year is 2026 and here's what it takes to run face recognition on a server:</p>++<p><span class="arrow">Option A:</span> Install Python. Install pip. Install onnxruntime. Install numpy. Install pillow. Download 166MB of model files. Write a wrapper script. Configure a virtual environment. Hope nothing conflicts. Total: 500+ MB. Time to first face: 15 minutes.</p>++<p><span class="arrow">Option B:</span> Copy one 7MB file to the server. Run it. Time to first face: 10 seconds.</p>++<p>Option B is FaceX. It's also 23% faster.</p>++<p>We've normalized absurd complexity. We've accepted that deploying a neural network requires a Docker container, a package manager, and a prayer that the dependency tree resolves.</p>++<p>It doesn't have to be this way.</p>+</div>+<div class="hashtags">#DevOps #Simplicity #Deployment #Infrastructure</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">8 RU</span>+</div>+<div class="card-body">+<p>На дворе 2026 год, и вот что нужно чтобы запустить распознавание лиц на сервере:</p>++<p><span class="arrow">Вариант А:</span> Установить Python. Установить pip. Установить onnxruntime. Установить numpy. Установить pillow. Скачать 166МБ моделей. Написать обёртку. Настроить виртуальное окружение. Надеяться что ничего не конфликтует. Итого: 500+ МБ. Время до первого лица: 15 минут.</p>++<p><span class="arrow">Вариант Б:</span> Скопировать один файл 7МБ на сервер. Запустить. Время до первого лица: 10 секунд.</p>++<p>Вариант Б — это FaceX. И он ещё на 23% быстрее.</p>++<p>Мы нормализовали абсурдную сложность. Мы приняли как данность что деплой нейросети требует Docker-контейнер, менеджер пакетов и молитву чтобы дерево зависимостей разрешилось.</p>++<p>Так не должно быть.</p>+</div>+<div class="hashtags">#DevOps #Простота #Деплой</div>+</div>++<!-- ===== 9 ===== -->+<div class="sep">— 9 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">9</span>+</div>+<div class="card-body">+<p>The last two milliseconds almost broke me.</p>++<p>I had gone from 24ms to 5ms in about six weeks. Felt like a god. Every day brought a new breakthrough. New SIMD kernel here, remove a memory copy there, batch some operations — boom, another millisecond gone.</p>++<p>Then I hit 5ms and the wall appeared.</p>++<p>I tried everything. Assembly language. JIT compilation. Different compilers. Link-time optimization. Profile-guided optimization. Thread pool tuning. Operation fusion. Cache line alignment.</p>++<p>Nothing worked. Four months of nothing.</p>++<p>Then I found it. The processor on my machine had AVX-512. A wider SIMD instruction set. Nobody told me. I had to read the CPU flags.</p>++<p>Rewrote the kernels. 5ms became 3ms.</p>++<p>The lesson: when you hit a wall, sometimes the answer isn't to push harder. It's to look at the wall from a different angle.</p>+</div>+<div class="hashtags">#Perseverance #Engineering #ProblemSolving #Breakthrough</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">9 RU</span>+</div>+<div class="card-body">+<p>Последние две миллисекунды чуть не сломали меня.</p>++<p>Я прошёл путь от 24мс до 5мс за шесть недель. Чувствовал себя богом. Каждый день приносил прорыв. Новое SIMD ядро тут, убрал копирование памяти там, объединил операции — бум, ещё одна миллисекунда ушла.</p>++<p>Потом я упёрся в 5мс и появилась стена.</p>++<p>Пробовал всё. Ассемблер. JIT компиляцию. Другие компиляторы. Link-time оптимизацию. Profile-guided оптимизацию. Тюнинг пула потоков. Слияние операций. Выравнивание по кэш-линиям.</p>++<p>Ничего не работало. Четыре месяца ничего.</p>++<p>А потом нашёл. Процессор на моей машине поддерживал AVX-512. Более широкий набор SIMD инструкций. Никто не подсказал. Пришлось читать флаги CPU.</p>++<p>Переписал ядра. 5мс стали 3мс.</p>++<p>Урок: когда упираетесь в стену, иногда ответ — не давить сильнее. А посмотреть на стену с другой стороны.</p>+</div>+<div class="hashtags">#Упорство #Инженерия #Прорыв</div>+</div>++<!-- ===== 10 ===== -->+<div class="sep">— 10 / 10 —</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">10</span>+</div>+<div class="card-body">+<p>Six months ago I had an idea and a text editor.</p>++<p>Today I have the fastest CPU face recognition engine in the world. Open source. Apache licensed. Built in Kazakhstan.</p>++<p>Here's what I learned:</p>++<p><span class="arrow">→</span> Profile before you optimize. The bottleneck is never where you think it is.<br>+<span class="arrow">→</span> Accuracy is harder than speed. And more important.<br>+<span class="arrow">→</span> Zero dependencies isn't a limitation. It's a feature.<br>+<span class="arrow">→</span> One person with focus can outperform a team with breadth.<br>+<span class="arrow">→</span> Location doesn't matter. The internet equalized access to knowledge. Use it.<br>+<span class="arrow">→</span> The last 10% of performance takes 80% of the time. Do it anyway.</p>++<p>If you're building something alone and the world hasn't noticed yet — don't stop.</p>++<p>The world is slow. Your code isn't.</p>++<p>🇰🇿 <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+<div class="hashtags">#Lessons #SoloFounder #OpenSource #Kazakhstan #Engineering #NeverGiveUp</div>+</div>++<div class="card">+<div class="card-header">+ <div class="avatar">BA</div>+ <div><div class="name">Baurzhan Atinov</div><div class="title-line">Software Engineer · Kazakhstan</div></div>+ <span class="post-num">10 RU</span>+</div>+<div class="card-body">+<p>Шесть месяцев назад у меня была идея и текстовый редактор.</p>++<p>Сегодня у меня самый быстрый CPU движок распознавания лиц в мире. Open source. Apache лицензия. Сделано в Казахстане.</p>++<p>Вот чему я научился:</p>++<p><span class="arrow">→</span> Профилируй прежде чем оптимизировать. Узкое место никогда не там где ты думаешь.<br>+<span class="arrow">→</span> Точность сложнее скорости. И важнее.<br>+<span class="arrow">→</span> Ноль зависимостей — не ограничение. Это фича.<br>+<span class="arrow">→</span> Один человек с фокусом может обойти команду с широким охватом.<br>+<span class="arrow">→</span> Локация не имеет значения. Интернет уравнял доступ к знаниям. Пользуйтесь.<br>+<span class="arrow">→</span> Последние 10% производительности занимают 80% времени. Делайте всё равно.</p>++<p>Если вы строите что-то в одиночку и мир ещё не заметил — не останавливайтесь.</p>++<p>Мир медленный. Ваш код — нет.</p>++<p>🇰🇿 <a class="link" href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+<div class="hashtags">#Уроки #OpenSource #Казахстан #Инженерия</div>+</div>++</div>+</body>+</html>diff --git a/articles/reddit_programming.html b/articles/reddit_programming.htmlnew file mode 100644index 0000000..9e64724--- /dev/null+++ b/articles/reddit_programming.html@@ -0,0 +1,146 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<title>I spent 6 months writing a face embedding engine in C + AVX2 that beats ONNX Runtime by 23%</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #1a1a1b; color: #d7dadc; line-height: 1.8; }+.post { max-width: 780px; margin: 30px auto; background: #1a1a1b; padding: 20px 32px 40px; }+.subreddit { color: #818384; font-size: 13px; margin-bottom: 6px; }+.subreddit span { color: #d7dadc; font-weight: 600; }+h1 { font-size: 22px; color: #d7dadc; margin-bottom: 16px; line-height: 1.4; }+h2 { font-size: 18px; color: #d7dadc; margin: 28px 0 12px; padding-bottom: 6px; border-bottom: 1px solid #343536; }+h3 { font-size: 15px; color: #d7dadc; margin: 20px 0 8px; }+p { margin-bottom: 14px; font-size: 15px; }+strong { color: #fff; }+a { color: #4fbcff; text-decoration: none; }+a:hover { text-decoration: underline; }+blockquote { border-left: 4px solid #4fbcff; padding: 8px 16px; margin: 14px 0; background: #222; border-radius: 0 4px 4px 0; color: #b0b3b8; font-size: 14px; }+table { width: 100%; border-collapse: collapse; margin: 14px 0; font-size: 14px; }+th { text-align: left; padding: 8px 12px; background: #272729; color: #818384; font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; }+td { padding: 8px 12px; border-bottom: 1px solid #343536; }+td:first-child { color: #818384; }+tr:hover td { background: #222; }+.highlight td { color: #4fbcff; font-weight: 600; }+pre { background: #272729; padding: 16px; border-radius: 6px; overflow-x: auto; margin: 14px 0; font-size: 13px; line-height: 1.6; }+code { font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace; color: #ce9178; }+pre code { color: #d4d4d4; }+.keyword { color: #569cd6; }+.type { color: #4ec9b0; }+.string { color: #ce9178; }+.comment { color: #6a9955; }+.func { color: #dcdcaa; }+.number { color: #b5cea8; }+ul, ol { margin: 10px 0 14px 24px; font-size: 15px; }+li { margin-bottom: 6px; }+li strong { color: #4fbcff; }+hr { border: none; border-top: 1px solid #343536; margin: 28px 0; }+.meta { color: #818384; font-size: 13px; margin-top: 20px; padding-top: 12px; border-top: 1px solid #343536; }+.tag { display: inline-block; background: #272729; color: #818384; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-right: 4px; }+</style>+</head>+<body>+<div class="post">++<div class="subreddit">+ <span>r/programming</span> · Posted by u/bauratynov+</div>++<h1>I spent 6 months writing a face embedding engine in C + AVX2 that beats ONNX Runtime by 23%</h1>++<p>I wrote a face embedding library in pure C99 with handwritten SIMD kernels. It runs <strong>23% faster than ONNX Runtime</strong> on the same model and CPU.</p>++<h2>The numbers</h2>++<table>+<tr><th></th><th>FaceX</th><th>ONNX Runtime</th></tr>+<tr class="highlight"><td>Median latency</td><td><strong>3.0 ms</strong></td><td>3.9 ms</td></tr>+<tr class="highlight"><td>Min latency</td><td><strong>2.87 ms</strong></td><td>3.18 ms</td></tr>+<tr><td>Library size</td><td><strong>148 KB</strong></td><td>28 MB</td></tr>+<tr><td>Total w/ weights</td><td><strong>7 MB</strong></td><td>157 MB</td></tr>+<tr><td>Dependencies</td><td><strong>zero</strong></td><td>Python + onnxruntime</td></tr>+<tr><td>LFW accuracy</td><td><strong>99.73%</strong></td><td>99.73%</td></tr>+</table>++<blockquote>Tested on Intel i5-11500, same model (EdgeFace-XS 1.77M params), same input.</blockquote>++<h2>API — 4 functions, one header</h2>++<pre><code><span class="comment">// Include the single header</span>+<span class="keyword">#include</span> <span class="string">"facex.h"</span>++<span class="comment">// Initialize (~100ms, once)</span>+<span class="type">FaceX</span>* fx = <span class="func">facex_init</span>(<span class="string">"weights.bin"</span>, NULL);++<span class="comment">// Compute embedding (3ms per call)</span>+<span class="keyword">float</span> embedding[<span class="number">512</span>];+<span class="func">facex_embed</span>(fx, rgb_112x112, embedding);++<span class="comment">// Compare two faces</span>+<span class="keyword">float</span> sim = <span class="func">facex_similarity</span>(emb_a, emb_b);+<span class="comment">// sim > 0.3 → same person</span>++<span class="func">facex_free</span>(fx);</code></pre>++<h2>Optimization journey: 24ms → 3ms</h2>++<p>Started with a naive C port of the ONNX graph. <strong>24ms.</strong> Profiled every operation and found the surprising bottleneck:</p>++<blockquote><strong>Matrix multiplication was only 6% of total inference time.</strong></blockquote>++<p>The real killers were:</p>++<ul>+ <li><strong>LayerNorm × 17 blocks</strong> — scalar mean/variance loop → custom AVX2 fused single-pass</li>+ <li><strong>GELU × 17</strong> — naive <code>tanh()</code> via math.h → polynomial erf with custom <code>_mm256_exp_ps</code></li>+ <li><strong>Depthwise conv</strong> — HWC↔CHW transposes on every block → native HWC layout, <strong>zero transposes</strong></li>+ <li><strong>MatMul</strong> → INT8 GEMM with <code>vpmaddubsw</code> (AVX2) and <code>vpdpbusd</code> (AVX-512 VNNI)</li>+ <li><strong>Memory</strong> → pre-packed weights, static workspace, no <code>malloc</code> per call</li>+</ul>++<h3>The timeline</h3>++<table>+<tr><th>Phase</th><th>Time</th><th>What changed</th></tr>+<tr><td>Naive C port</td><td>24 ms</td><td>Just works</td></tr>+<tr><td>SIMD kernels</td><td>8 ms</td><td>AVX2 for LN, GELU, conv</td></tr>+<tr><td>MatMul optimization</td><td>5 ms</td><td>INT8 GEMM, packed FP32, thread pool</td></tr>+<tr class="highlight"><td>Final polish</td><td><strong>3 ms</strong></td><td>Eliminated transposes, pre-computed constants</td></tr>+</table>++<blockquote>The last 2ms took 4 months. The first 16ms took 2 weeks.</blockquote>++<h2>7 accuracy bugs</h2>++<p>The hardest part — matching ONNX output exactly. <code>cos_sim</code> started at <strong>0.067</strong> (garbage). Found 7 bugs through per-layer intermediate dumps:</p>++<ol>+ <li><strong>Wrong gamma index</strong> — used W(38) instead of W(39) in one block</li>+ <li><strong>XCA residual</strong> — wrong residual connections in attention</li>+ <li><strong>XCA DW conv</strong> — should be cascaded, not independent</li>+ <li><strong>Position embedding</strong> — it's a CONSTANT, not a function of input</li>+ <li><strong>XCA attention</strong> — full C×C instead of per-head [head_dim × head_dim]</li>+ <li><strong>Workspace overlap</strong> — buffers overlapped at head_dim=48</li>+ <li><strong>GELU drift</strong> — tanh approximation accumulated error through 17 blocks</li>+</ol>++<p>Each fix: <strong>+0.1 cos_sim</strong>. Seven fixes → <strong>1.0.</strong></p>++<hr>++<p><strong>Tech:</strong> C99, ~4000 LOC, AVX2/FMA/AVX-512 VNNI. Apache 2.0.</p>+<p><strong>GitHub:</strong> <a href="https://github.com/facex-engine/facex">https://github.com/facex-engine/facex</a></p>+<p>Solo dev from Kazakhstan, funded by NLnet grant. AMA about the SIMD kernels or accuracy debugging.</p>++<div class="meta">+ <span class="tag">C99</span>+ <span class="tag">SIMD</span>+ <span class="tag">face-recognition</span>+ <span class="tag">performance</span>+ <span class="tag">open-source</span>+</div>++</div>+</body>+</html>diff --git a/articles/story.html b/articles/story.htmlnew file mode 100644index 0000000..2f4202c--- /dev/null+++ b/articles/story.html@@ -0,0 +1,174 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<title>The Sweetest Millisecond</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: Georgia, 'Times New Roman', serif; background: #faf9f6; color: #2c2c2c; }+article { max-width: 680px; margin: 0 auto; padding: 60px 24px 80px; }+h1 { font-size: 36px; line-height: 1.3; margin-bottom: 12px; font-weight: 700; color: #1a1a1a; letter-spacing: -0.5px; }+.subtitle { font-size: 18px; color: #888; margin-bottom: 40px; font-style: italic; }+p { font-size: 18px; line-height: 1.9; margin-bottom: 20px; color: #333; }+.drop:first-letter { float: left; font-size: 72px; line-height: 60px; padding-right: 8px; padding-top: 4px; color: #1a1a1a; font-weight: 700; }+strong { color: #1a1a1a; }+em { color: #555; }+.separator { text-align: center; color: #ccc; font-size: 24px; letter-spacing: 12px; margin: 36px 0; }+.pullquote { font-size: 22px; font-style: italic; color: #666; border-left: 3px solid #ddd; padding: 8px 24px; margin: 32px 0; line-height: 1.7; }+.stat { font-family: -apple-system, 'Segoe UI', sans-serif; font-size: 42px; font-weight: 700; color: #1a1a1a; text-align: center; margin: 28px 0; letter-spacing: -1px; }+.caption { text-align: center; font-size: 14px; color: #999; margin-top: -20px; margin-bottom: 28px; }+.end { text-align: center; margin-top: 48px; padding-top: 28px; border-top: 1px solid #eee; }+.end p { font-size: 15px; color: #999; }+.end a { color: #2563eb; text-decoration: none; }+.flag { font-size: 32px; }+</style>+</head>+<body>+<article>++<h1>The Sweetest Millisecond</h1>+<p class="subtitle">How a developer from Kazakhstan outran Microsoft — and went to buy a pastry.</p>++<div class="separator">···</div>++<p class="drop">The bakery is seven minutes from my apartment. I know this because I've been measuring everything in milliseconds for the past six months, and some of that sickness has leaked into the rest of my life.</p>++<p>But today I'm not thinking about milliseconds. Today I'm buying a sweet roll. Because my brain earned it.</p>++<p>Let me tell you why.</p>++<div class="separator">···</div>++<p>Six months ago I opened a blank file on my computer and typed the first line of C code. I was going to write a face recognition engine. Not use one — <em>write</em> one. From scratch. By hand. Every multiplication, every addition, every memory access.</p>++<p>The neural network I chose was small. EdgeFace-XS — one-point-seven-seven million parameters. For comparison, ChatGPT has over a trillion. This little thing was supposed to look at a photo of a face and turn it into a list of 512 numbers. Compare two lists — and you know if it's the same person.</p>++<p>Simple in theory. Everyone uses a framework for this. You install Python, download ONNX Runtime — Microsoft's neural network engine — feed it the model, and it just works. Three-point-nine milliseconds per face on my CPU. Fast enough for anyone.</p>++<p>I wanted to do it without the framework. Without Python. Without Microsoft. Just me and the processor.</p>++<div class="pullquote">My first version ran in twenty-four milliseconds. Six times slower than the thing I was trying to replace.</div>++<p>Not a great start.</p>++<div class="separator">···</div>++<p>I did what any engineer would do. I profiled. I measured every single one of the three hundred operations inside the neural network. Timed each one. Made a spreadsheet. Sorted by time.</p>++<p>And here's where the story gets interesting.</p>++<p>If you ask any machine learning engineer what's slow in a neural network, they'll say matrix multiplication. It's the big operation. The heavy lifting. The thing that GPUs were invented for.</p>++<p>I looked at my spreadsheet.</p>++<div class="stat">6%</div>+<p class="caption">Matrix multiplication's share of total inference time.</p>++<p>Six percent. The "heavy lifting" was barely lifting at all.</p>++<p>The real killers were the operations nobody writes blog posts about. Layer normalization — computing the mean and standard deviation of a row of numbers, seventeen times per image. GELU activation — a mathematical function applied to every single number in the network, also seventeen times. And memory layout conversions — reshuffling data from one format to another, back and forth, on every layer.</p>++<p>The glue. The boring stuff between the important parts.</p>++<p>Except in this network, the glue <strong>was</strong> the important part.</p>++<div class="separator">···</div>++<p>So I rewrote the glue.</p>++<p>Modern CPUs have special instructions that can process eight or sixteen numbers at once. They're called SIMD — Single Instruction, Multiple Data. Intel calls their version AVX2. Instead of adding one number to another, you add eight pairs simultaneously. Instead of computing one square root, you compute eight.</p>++<p>I wrote custom SIMD kernels for every operation. Layer normalization that computes mean and variance in a single pass instead of two. A GELU function built from a polynomial approximation of the error function — an equation from a 1964 math textbook, translated into CPU instructions that process eight floating-point numbers per clock cycle.</p>++<p>Twenty-four milliseconds became eight.</p>++<p>Then I tackled the matrix multiplications. Even at six percent, they were worth optimizing. I quantized the weights to 8-bit integers and wrote a microkernel using an instruction called <em>vpmaddubsw</em> that multiplies sixteen pairs of integers and adds them up in one cycle. Discovered a saturation bug — when the partial sums exceeded 32,767, the hardware silently clipped them, corrupting the result. Spent two weeks debugging that.</p>++<p>Eight became five.</p>++<div class="separator">···</div>++<p>And then the wall.</p>++<p>Five milliseconds. No matter what I did. I tried writing in assembly language. I tried JIT-compiling custom kernels at startup. I tried three different compilers. I tried link-time optimization, profile-guided optimization, thread pool tuning, operation fusion.</p>++<p>Nothing. Four months of nothing.</p>++<p>I started reading academic papers. Dozens of them. Looked through my old research files. Read Intel's optimization manual — all four thousand pages.</p>++<p>And then, on a random Tuesday, buried in the output of a CPU diagnostic tool, I saw it.</p>++<p>My processor supported AVX-512.</p>++<p>AVX-512 is a wider version of the SIMD instructions I was already using. Instead of processing eight numbers at once, it processes sixteen. Not every CPU has it. Nobody had told me mine did. I never thought to check.</p>++<p>I rewrote the hottest kernels. Sixteen numbers at a time instead of eight. New instructions that do integer dot products without the saturation bug.</p>++<div class="stat">3.0 ms</div>+<p class="caption">Final inference time. ONNX Runtime: 3.9 ms.</p>++<p>I stared at the number on my screen. Ran the benchmark again. And again. Same result.</p>++<p>I was faster than Microsoft.</p>++<div class="separator">···</div>++<p>But speed was the easy part. The hard part — the part that nearly broke me — was accuracy.</p>++<p>A face recognition engine that's fast but wrong is worse than useless. It's dangerous. It would tell you strangers are your friends and your friends are strangers.</p>++<p>After my speed optimizations, I compared my engine's output to the reference. The cosine similarity — a measure of how similar two lists of numbers are, where 1.0 means identical — was 0.067.</p>++<p>Zero-point-zero-six-seven. My engine was producing random noise.</p>++<p>I spent three weeks on this. I dumped every intermediate tensor — all 286 of them — from both my engine and a Python reference implementation. Compared them number by number, layer by layer, dimension by dimension.</p>++<p>Found seven bugs.</p>++<p>The first was embarrassing — I used the wrong weight index in one block. W(38) instead of W(39). One digit. The bias instead of the gamma parameter.</p>++<p>The last was devious. Part of the neural network computes something called a position embedding — it tells the network where each patch of the image is located. In the ONNX graph, it looked like a convolution applied to the input. So I convolved the input.</p>++<p>But the input to that convolution wasn't actually the input. It was a constant. A pre-computed tensor baked into the model at training time. It never changes. I was computing it fresh every frame, using slightly different floating-point arithmetic, and the tiny rounding errors accumulated through seventeen layers until the output was meaningless.</p>++<p>Each bug fix added about 0.1 to the cosine similarity. Seven bugs. 0.067 became 1.000.</p>++<p>Exact match.</p>++<div class="separator">···</div>++<p>So here's what I have now.</p>++<p>A face recognition engine written in four thousand lines of C. It takes a 112-by-112 pixel photo of a face and produces a 512-dimensional embedding vector in three milliseconds. It's 23 percent faster than Microsoft's ONNX Runtime. The library is 148 kilobytes. The total deployment — binary plus model weights — is seven megabytes. You can copy it to any Linux server and run it. No Python. No Docker. No package manager. No dependencies of any kind.</p>++<p>99.73 percent accuracy on the standard LFW benchmark. Same as models sixty times larger.</p>++<p>I built it in Kazakhstan. By myself. With a free compiler and a consumer CPU.</p>++<p>It's open source now. Apache 2.0 license. Anyone can use it.</p>++<div class="separator">···</div>++<p>I'm putting on my jacket. The bakery closes in forty minutes, and I've been staring at benchmark numbers all morning.</p>++<p>There's a specific pastry I like — a round one with custard filling and powdered sugar on top. It costs about a dollar. I've been eating one every time I hit a milestone. After the first SIMD kernel worked. After the INT8 bug was fixed. After cosine similarity hit 1.0.</p>++<p>Today's pastry is for the final number. Three-point-zero milliseconds. Faster than Microsoft.</p>++<p>Six months of work. Seven bugs. Forty-nine SIMD kernels. Four thousand lines of code. One pastry.</p>++<div class="pullquote">Sometimes the best way to celebrate beating a trillion-dollar company is a one-dollar sweet roll.</div>++<p>The bakery is seven minutes away. Four hundred and twenty thousand milliseconds. I used to think that was fast.</p>++<p>Now I know what fast really means.</p>++<div class="end">+<p class="flag">🇰🇿</p>+<p><strong>Baurzhan Atinov</strong> · Kazakhstan</p>+<p><a href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>++</article>+</body>+</html>diff --git a/articles/story_ru_threads.html b/articles/story_ru_threads.htmlnew file mode 100644index 0000000..140477f--- /dev/null+++ b/articles/story_ru_threads.html@@ -0,0 +1,59 @@+<!DOCTYPE html>+<html lang="ru">+<head>+<meta charset="UTF-8">+<title>Самая сладкая миллисекунда</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #000; color: #f5f5f5; line-height: 1.8; }+.container { max-width: 540px; margin: 0 auto; padding: 20px 16px 60px; }+.thread { padding: 22px 0; }+.thread + .thread { border-top: 1px solid #1a1a1a; }+.thread-header { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }+.ava { width: 38px; height: 38px; background: #222; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 700; flex-shrink: 0; color: #888; }+.uname { font-weight: 600; font-size: 14px; }+.dim { color: #555; font-size: 13px; }+.thread-body { padding-left: 48px; font-size: 15px; line-height: 1.85; }+.thread-body p { margin-bottom: 14px; color: #e0e0e0; }+.thread-body a { color: #e0e0e0; text-decoration: underline; text-underline-offset: 3px; }+.note { text-align: center; color: #333; font-size: 12px; padding: 30px 0 10px; letter-spacing: 2px; text-transform: uppercase; }+</style>+</head>+<body>+<div class="container">++<div class="note">thread · 3 поста</div>++<!-- 1 -->+<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="dim">1/3</div></div>+<div class="thread-body">+<p>Иду в магазин за сладкой булочкой. Мозг заслужил. Сейчас расскажу почему.</p>+<p>Полгода назад я открыл пустой файл и начал писать движок распознавания лиц на чистом C. С нуля. Каждое умножение вручную. Потому что стандартный способ — это установить Python, скачать ONNX Runtime от Microsoft, подтянуть кучу библиотек. Полгигабайта зависимостей чтобы посмотреть на фотку и сказать "это Бауыржан". Мне показалось что можно проще.</p>+<p>Первая версия — 24 миллисекунды. Microsoft делает за 3.9. В шесть раз медленнее. Начал профилировать. Весь интернет пишет: тормозит матричное умножение. Замерил. Матричное умножение — шесть процентов. Тормозили скучные операции о которых никто не пишет статей. Переписал каждую вручную на SIMD — инструкции процессора которые считают восемь чисел за раз. 24 стало 8. Потом 5. Потом стена — четыре месяца ничего не помогало. Ассемблер, JIT, три компилятора — всё без толку.</p>+</div>+</div>++<!-- 2 -->+<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="dim">2/3</div></div>+<div class="thread-body">+<p>В обычный вторник в выводе диагностики процессора увидел: мой CPU поддерживает AVX-512. Шестнадцать чисел за раз вместо восьми. Никто не подсказал. Просто никогда не проверял. Переписал ядра — 5 стало 3. Три миллисекунды. Microsoft — 3.9. Я быстрее.</p>+<p>Но скорость — это была простая часть. После оптимизации движок выдавал мусор. Сходство с эталоном: 0.067 из 1.0. Три недели сравнивал 286 тензоров, число за числом, слой за слоем. Нашёл семь багов. Каждый крошечный. Вместе — катастрофа. Самый коварный: часть сети выглядела так будто зависит от входа. На самом деле — константа. Я пересчитывал её каждый кадр и ошибка копилась через 17 слоёв. Семь фиксов — 0.067 стал 1.000.</p>+</div>+</div>++<!-- 3 -->+<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="dim">3/3</div></div>+<div class="thread-body">+<p>Итог. 4000 строк C. 3 миллисекунды на лицо. На 23% быстрее Microsoft. 148 килобайт. Ноль зависимостей. 99.73% точности. Скопировал на сервер — работает. Без Python, без Docker, без молитв.</p>+<p>Сделано в Казахстане. Одним человеком. С бесплатным компилятором. Самый быстрый CPU движок распознавания лиц в мире создан не в Долине и не в Сиэтле — а в стране которую половина мира не найдёт на карте.</p>+<p>Шесть месяцев. Семь багов. Три миллисекунды. И одна булочка за сто тенге чтобы это отпраздновать. 🇰🇿</p>+<p><a href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+</div>++</div>+</body>+</html>diff --git a/articles/threads.html b/articles/threads.htmlnew file mode 100644index 0000000..87995b5--- /dev/null+++ b/articles/threads.html@@ -0,0 +1,294 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<title>FaceX — Threads</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #000; color: #fff; line-height: 1.7; }+.container { max-width: 540px; margin: 0 auto; padding: 20px 16px; }+h1 { text-align: center; font-size: 20px; margin: 30px 0 6px; }+.sub { text-align: center; color: #777; font-size: 13px; margin-bottom: 30px; }++.thread { border-bottom: 1px solid #222; padding: 24px 0; }+.thread-header { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }+.ava { width: 38px; height: 38px; background: #333; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 700; flex-shrink: 0; }+.uname { font-weight: 600; font-size: 14px; }+.time { color: #777; font-size: 13px; margin-left: auto; }+.thread-body { font-size: 15px; line-height: 1.8; padding-left: 48px; }+.thread-body p { margin-bottom: 13px; }+.thread-body a { color: #fff; text-decoration: underline; text-underline-offset: 3px; }+.day { text-align: center; color: #444; font-size: 11px; padding: 20px 0 4px; letter-spacing: 2px; text-transform: uppercase; }+</style>+</head>+<body>+<div class="container">++<h1>Threads</h1>+<p class="sub">10 постов · EN + RU</p>++<!-- 1 -->+<div class="day">— 1 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>When your phone unlocks by looking at your face — there's a neural network behind that. It turns your face into a list of 512 numbers. Then it compares those numbers with the ones it stored when you first set it up.</p>+<p>That neural network usually needs a big framework to run. Python. ONNX Runtime. Hundreds of megabytes.</p>+<p>I rewrote the whole thing in C. From scratch. By hand. It takes 3 milliseconds and fits in 148 kilobytes.</p>+<p>That's faster than Microsoft's version.</p>+<p><a href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Когда ваш телефон разблокируется по лицу — за этим стоит нейросеть. Она превращает лицо в список из 512 чисел. Потом сравнивает эти числа с теми что запомнила при первой настройке.</p>+<p>Обычно для запуска такой нейросети нужен большой фреймворк. Python. ONNX Runtime. Сотни мегабайт.</p>+<p>Я переписал всё это на C. С нуля. Вручную. Работает за 3 миллисекунды и помещается в 148 килобайт.</p>+<p>Это быстрее чем версия Microsoft.</p>+<p><a href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+</div>++<!-- 2 -->+<div class="day">— 2 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>Microsoft has dozens of engineers working on their neural network runtime. It's called ONNX Runtime. It's the industry standard. Banks use it. Hospitals use it. Governments use it.</p>+<p>I'm one developer. From Kazakhstan. Working from home.</p>+<p>My engine processes a face in 3.0 milliseconds. Theirs takes 3.9.</p>+<p>My engine is 148 kilobytes. Theirs is 28 megabytes.</p>+<p>My engine needs nothing installed. Theirs needs Python and a package manager.</p>+<p>How? I only optimize for one neural network. They optimize for ten thousand.</p>+<p>A scalpel beats a Swiss army knife — when you know exactly what you're cutting.</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>У Microsoft десятки инженеров работают над ONNX Runtime. Это стандарт индустрии. Его используют банки. Больницы. Правительства.</p>+<p>Я — один разработчик. Из Казахстана. Работаю из дома.</p>+<p>Мой движок обрабатывает лицо за 3.0 миллисекунды. Их — за 3.9.</p>+<p>Мой движок — 148 килобайт. Их — 28 мегабайт.</p>+<p>Мой движок не требует установки. Их — Python и менеджер пакетов.</p>+<p>Как? Я оптимизирую под одну нейросеть. Они — под десять тысяч.</p>+<p>Скальпель побеждает швейцарский нож — когда точно знаешь что режешь.</p>+</div>+</div>++<!-- 3 -->+<div class="day">— 3 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>My first attempt ran at 24 milliseconds. The goal was under 4. I was six times too slow.</p>+<p>So I did what engineers do — I measured every single operation inside the neural network. There are about 300 of them. Matrix multiplications, normalizations, activation functions, memory copies.</p>+<p>Everyone on the internet said "optimize the matrix multiplication, that's where all the time goes in neural networks."</p>+<p>I measured. Matrix multiplication was 6 percent of total time. Six.</p>+<p>The slow parts were the boring stuff nobody writes papers about. Computing averages. Converting memory layouts. Calculating activation functions one number at a time.</p>+<p>I rewrote every single one using processor instructions that work on 8 or 16 numbers simultaneously. Took six months. Got to 3 milliseconds.</p>+<p>The answer was where nobody was looking.</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Первая версия работала за 24 миллисекунды. Цель — меньше 4. Я был в шесть раз медленнее.</p>+<p>Сделал то что делают инженеры — замерил каждую из ~300 операций внутри нейросети. Матричные умножения, нормализации, функции активации, копирование памяти.</p>+<p>Все в интернете писали: "оптимизируй матричное умножение, туда уходит всё время в нейросетях."</p>+<p>Замерил. Матричное умножение — 6 процентов общего времени. Шесть.</p>+<p>Тормозили скучные вещи о которых никто не пишет статей. Вычисление средних. Конвертация раскладок памяти. Подсчёт функций активации по одному числу за раз.</p>+<p>Переписал каждую используя инструкции процессора которые работают с 8 или 16 числами одновременно. Заняло шесть месяцев. Добился 3 миллисекунд.</p>+<p>Ответ был там где никто не искал.</p>+</div>+</div>++<!-- 4 -->+<div class="day">— 4 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>Making my engine fast was hard. Making it accurate was harder.</p>+<p>After the speed optimizations, my engine looked at a face and produced 512 numbers. The reference model produced 512 different numbers. They should have been identical.</p>+<p>The similarity between them was 0.067 out of 1.0. Basically random noise.</p>+<p>I spent three weeks comparing every single number at every single layer — 286 checkpoints — between my code and a reference implementation. Found seven bugs. Each one tiny. Each one invisible. Together they turned signal into garbage.</p>+<p>The most devious: a part of the network that looked like it depended on the input image actually didn't. It was a constant. I was recomputing it every time, and tiny rounding errors accumulated through 17 layers until the output was meaningless.</p>+<p>Seven fixes later: 1.000 similarity. Exact match.</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Сделать движок быстрым было сложно. Сделать его точным — сложнее.</p>+<p>После оптимизации скорости движок смотрел на лицо и выдавал 512 чисел. Эталонная модель выдавала 512 других чисел. Они должны были совпадать.</p>+<p>Сходство между ними — 0.067 из 1.0. По сути случайный шум.</p>+<p>Три недели я сравнивал каждое число на каждом из 286 слоёв между моим кодом и эталоном. Нашёл семь багов. Каждый крошечный. Каждый невидимый. Вместе они превращали сигнал в мусор.</p>+<p>Самый коварный: часть сети выглядела так, будто зависит от входного изображения. На самом деле нет. Это была константа. Я пересчитывал её каждый раз, и крошечные ошибки округления накапливались через 17 слоёв, пока результат не терял смысл.</p>+<p>Семь исправлений: 1.000. Точное совпадение.</p>+</div>+</div>++<!-- 5 -->+<div class="day">— 5 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>The fastest CPU face recognition engine in the world was built in Kazakhstan.</p>+<p>Not in Silicon Valley where Google and Meta sit. Not in Seattle where Microsoft sits. Not in Beijing where Megvii built Face++. Not in London. Not in Tel Aviv.</p>+<p>In Kazakhstan. A country most people in tech couldn't place on a map.</p>+<p>By one person. With an internet connection and a free compiler.</p>+<p>There's no secret formula. There's no special access. There's no connections or funding rounds. Just a European research grant, time, and stubbornness.</p>+<p>If you're building something from a country that nobody associates with tech — good. When you ship, the contrast will be the story.</p>+<p>🇰🇿</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Самый быстрый CPU движок распознавания лиц в мире создан в Казахстане.</p>+<p>Не в Кремниевой долине где сидят Google и Meta. Не в Сиэтле где Microsoft. Не в Пекине где Megvii сделали Face++. Не в Лондоне. Не в Тель-Авиве.</p>+<p>В Казахстане. Стране которую большинство людей в IT не покажут на карте.</p>+<p>Один человек. Интернет и бесплатный компилятор.</p>+<p>Нет секретной формулы. Нет особого доступа. Нет связей и раундов инвестиций. Только европейский исследовательский грант, время и упрямство.</p>+<p>Если вы строите что-то из страны которую никто не ассоциирует с технологиями — хорошо. Когда выпустите продукт, контраст и станет историей.</p>+<p>🇰🇿</p>+</div>+</div>++<!-- 6 -->+<div class="day">— 6 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>To run face recognition with the standard tools you need to install Python, a package manager, a neural network runtime, numpy, pillow, and download 166 megabytes of model files. Minimum half a gigabyte on disk.</p>+<p>My version: one file, 7 megabytes, copy to server, run. Done.</p>+<p>And it's faster.</p>+<p>Somewhere along the way we decided that software has to be complex. That deploying AI means containers and orchestration and dependency trees.</p>+<p>It doesn't. Not always. Sometimes it's just a well-written C program and a weights file.</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Чтобы запустить распознавание лиц стандартными средствами нужно установить Python, менеджер пакетов, runtime нейросетей, numpy, pillow и скачать 166 мегабайт моделей. Минимум полгигабайта на диске.</p>+<p>Моя версия: один файл, 7 мегабайт, скопировал на сервер, запустил. Готово.</p>+<p>И работает быстрее.</p>+<p>Где-то по пути мы решили что софт обязан быть сложным. Что деплой AI — это контейнеры, оркестрация и деревья зависимостей.</p>+<p>Не обязан. Не всегда. Иногда это просто хорошо написанная программа на C и файл с весами.</p>+</div>+</div>++<!-- 7 -->+<div class="day">— 7 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>The first 16 milliseconds of optimization took me two weeks. I felt unstoppable. Every morning I'd find a new bottleneck, write a new SIMD kernel, and shave off another millisecond.</p>+<p>Then I hit 5 milliseconds and everything stopped. Tried assembly language. Tried JIT compilation. Tried different compilers. Tried threading. Tried operation fusion. Four months of trying.</p>+<p>Then I discovered my CPU had a wider instruction set I wasn't using. AVX-512. Nobody told me. I had to read the processor flags myself.</p>+<p>Rewrote the hottest kernels. 5 became 3.</p>+<p>Two lessons: first, the wall isn't always real — sometimes you're just not seeing the door. Second, read your CPU's spec sheet. It knows things your compiler doesn't.</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Первые 16 миллисекунд оптимизации заняли две недели. Чувствовал себя непобедимым. Каждое утро находил новое узкое место, писал новое SIMD ядро, срезал ещё миллисекунду.</p>+<p>Потом упёрся в 5 миллисекунд и всё остановилось. Пробовал ассемблер. JIT компиляцию. Другие компиляторы. Многопоточность. Слияние операций. Четыре месяца попыток.</p>+<p>Потом обнаружил что мой процессор поддерживает более широкий набор инструкций — AVX-512. Никто не подсказал. Пришлось самому прочитать флаги процессора.</p>+<p>Переписал самые горячие ядра. 5 стали 3.</p>+<p>Два урока: стена не всегда настоящая — иногда ты просто не видишь дверь. И второй: читайте спецификацию своего процессора. Он знает то чего не знает ваш компилятор.</p>+</div>+</div>++<!-- 8 -->+<div class="day">— 8 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>My engine recognizes faces with 99.73% accuracy on the standard benchmark. That's the same as models 100 times larger.</p>+<p>The model I use has 1.77 million parameters. For comparison, a typical ArcFace model has 65 million. GPT-4 has over a trillion.</p>+<p>1.77 million parameters. Fits in 7 megabytes. Runs in 3 milliseconds. 99.73% accurate.</p>+<p>Bigger isn't always better. Sometimes the smallest model is the right model — you just have to run it really, really fast.</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Мой движок распознаёт лица с точностью 99.73% на стандартном бенчмарке. Столько же дают модели в 100 раз крупнее.</p>+<p>Модель которую я использую — 1.77 миллиона параметров. Для сравнения: типичный ArcFace — 65 миллионов. GPT-4 — больше триллиона.</p>+<p>1.77 миллиона параметров. 7 мегабайт. 3 миллисекунды. 99.73% точности.</p>+<p>Больше — не всегда лучше. Иногда самая маленькая модель и есть правильная — нужно просто запустить её очень, очень быстро.</p>+</div>+</div>++<!-- 9 -->+<div class="day">— 9 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>People ask what tools I used. Here's the full list:</p>+<p>A text editor. GCC (free). A $200 Intel i5. Six months.</p>+<p>No cloud compute. No TPUs. No training runs. No team. No office.</p>+<p>The whole project cost less than one month of AWS bills for a typical ML startup.</p>+<p>The result beats ONNX Runtime. Open source. Free for everyone.</p>+<p>You don't need expensive tools to build fast software. You need understanding of the hardware you're running on. That knowledge is free. It's in the Intel manuals. All 4,000 pages of them.</p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Спрашивают какие инструменты использовал. Полный список:</p>+<p>Текстовый редактор. GCC (бесплатный). Intel i5 за $200. Шесть месяцев.</p>+<p>Без облачных вычислений. Без TPU. Без тренировок моделей. Без команды. Без офиса.</p>+<p>Весь проект стоил меньше чем месяц AWS счёта типичного ML стартапа.</p>+<p>Результат быстрее ONNX Runtime. Open source. Бесплатно для всех.</p>+<p>Не нужны дорогие инструменты чтобы строить быстрый софт. Нужно понимание железа на котором работаешь. Это знание бесплатно. Оно в мануалах Intel. Все 4000 страниц.</p>+</div>+</div>++<!-- 10 -->+<div class="day">— 10 —</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">EN</div></div>+<div class="thread-body">+<p>Six months ago I had an idea and a text editor.</p>+<p>Today I have the fastest CPU face recognition engine I could find anywhere in the world. Open source. Free. Built entirely in Kazakhstan.</p>+<p>If you're working on something from a place nobody expects — keep going. The world notices results, not addresses.</p>+<p>🇰🇿 <a href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+</div>++<div class="thread">+<div class="thread-header"><div class="ava">BA</div><div class="uname">bauratynov</div><div class="time">RU</div></div>+<div class="thread-body">+<p>Шесть месяцев назад у меня была идея и текстовый редактор.</p>+<p>Сегодня у меня самый быстрый CPU движок распознавания лиц из всех что я смог найти в мире. Open source. Бесплатный. Полностью сделан в Казахстане.</p>+<p>Если вы строите что-то из места откуда никто не ждёт — продолжайте. Мир замечает результаты, а не адреса.</p>+<p>🇰🇿 <a href="https://github.com/facex-engine/facex">github.com/facex-engine/facex</a></p>+</div>+</div>++</div>+</body>+</html>diff --git a/detect.js b/detect.jsnew file mode 100644index 0000000..f0ff527--- /dev/null+++ b/detect.js@@ -0,0 +1,69 @@+var FaceDetModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var e=moduleArg,aa=!!globalThis.window,l=!!globalThis.WorkerGlobalScope,ba=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,ca=(a,b)=>{throw b;};"undefined"!=typeof __filename?_scriptName=__filename:l&&(_scriptName=self.location.href);var da="",ea,p;+if(ba){var fs=require("node:fs");da=__dirname+"/";p=a=>{a=fa(a)?new URL(a):a;return fs.readFileSync(a)};ea=async a=>{a=fa(a)?new URL(a):a;return fs.readFileSync(a,void 0)};process.argv.slice(2);ca=(a,b)=>{process.exitCode=a;throw b;}}else if(aa||l){try{da=(new URL(".",_scriptName)).href}catch{}l&&(p=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)});ea=async a=>{if(fa(a))return new Promise((c,d)=>{var f=new XMLHttpRequest;+f.open("GET",a,!0);f.responseType="arraybuffer";f.onload=()=>{200==f.status||0==f.status&&f.response?c(f.response):d(f.status)};f.onerror=d;f.send(null)});var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);}}var ha=console.log.bind(console),t=console.error.bind(console),u,ia=!1,ja,fa=a=>a.startsWith("file://"),ka,la,ma=!1;+function na(){var a=oa.buffer;w=new Int8Array(a);x=new Int16Array(a);z=new Uint8Array(a);new Uint16Array(a);C=new Int32Array(a);D=new Uint32Array(a);e.HEAPF32=pa=new Float32Array(a);qa=new Float64Array(a);ra=new BigInt64Array(a);new BigUint64Array(a)}function E(a){e.onAbort?.(a);a=`Aborted(${a})`;t(a);ia=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");la?.(a);throw a;}var sa;+async function ta(a){if(!u)try{var b=await ea(a);return new Uint8Array(b)}catch{}if(a==sa&&u)a=new Uint8Array(u);else if(p)a=p(a);else throw"both async and sync fetching of the wasm failed";return a}async function ua(a,b){try{var c=await ta(a);return await WebAssembly.instantiate(c,b)}catch(d){t(`failed to asynchronously prepare wasm: ${d}`),E(d)}}+async function va(a){var b=sa;if(!u&&!fa(b)&&!ba)try{var c=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(c,a)}catch(d){t(`wasm streaming compile failed: ${d}`),t("falling back to ArrayBuffer instantiation")}return ua(b,a)}class wa{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}}+var x,C,ra,w,pa,qa,D,z,xa=a=>{for(;0<a.length;)a.shift()(e)},ya=[],za=[],Aa=()=>{var a=e.preRun.shift();za.push(a)},Ba=!0,G=()=>{var a=C[+F>>2];F+=4;return a},Ca=(a,b)=>{for(var c=0,d=a.length-1;0<=d;d--){var f=a[d];"."===f?a.splice(d,1):".."===f?(a.splice(d,1),c++):c&&(a.splice(d,1),c--)}if(b)for(;c;c--)a.unshift("..");return a},H=a=>{var b="/"===a.charAt(0),c="/"===a.slice(-1);(a=Ca(a.split("/").filter(d=>!!d),!b).join("/"))||b||(a=".");a&&c&&(a+="/");return(b?"/":"")+a},Da=a=>{var b=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1);+a=b[0];b=b[1];if(!a&&!b)return".";b&&=b.slice(0,-1);return a+b},I=a=>a&&a.match(/([^\/]+|\/)\/*$/)[1],Ea=(a,b)=>H(a+"/"+b),Fa=()=>{if(ba){var a=require("node:crypto");return b=>a.randomFillSync(b)}return b=>(crypto.getRandomValues(b),0)},Ga=a=>(Ga=Fa())(a),Ha=(...a)=>{for(var b="",c=!1,d=a.length-1;-1<=d&&!c;d--){c=0<=d?a[d]:J.cwd();if("string"!=typeof c)throw new TypeError("Arguments to path.resolve must be strings");if(!c)return"";b=c+"/"+b;c="/"===c.charAt(0)}b=Ca(b.split("/").filter(f=>!!f),!c).join("/");+return(c?"/":"")+b||"."},Ia=(a,b)=>{function c(h){for(var m=0;m<h.length&&""===h[m];m++);for(var q=h.length-1;0<=q&&""===h[q];q--);return m>q?[]:h.slice(m,q-m+1)}a=Ha(a).slice(1);b=Ha(b).slice(1);a=c(a.split("/"));b=c(b.split("/"));for(var d=Math.min(a.length,b.length),f=d,g=0;g<d;g++)if(a[g]!==b[g]){f=g;break}d=[];for(g=f;g<a.length;g++)d.push("..");d=d.concat(b.slice(f));return d.join("/")},Ja=globalThis.TextDecoder&&new TextDecoder,K=(a,b=0)=>{var c=b;for(var d=c+void 0;a[c]&&!(c>=d);)++c;if(16<+c-b&&a.buffer&&Ja)return Ja.decode(a.subarray(b,c));for(d="";b<c;){var f=a[b++];if(f&128){var g=a[b++]&63;if(192==(f&224))d+=String.fromCharCode((f&31)<<6|g);else{var h=a[b++]&63;f=224==(f&240)?(f&15)<<12|g<<6|h:(f&7)<<18|g<<12|h<<6|a[b++]&63;65536>f?d+=String.fromCharCode(f):(f-=65536,d+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else d+=String.fromCharCode(f)}return d},Ka=[],La=a=>{for(var b=0,c=0;c<a.length;++c){var d=a.charCodeAt(c);127>=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=+3}return b},Ma=(a,b,c,d)=>{if(!(0<d))return 0;var f=c;d=c+d-1;for(var g=0;g<a.length;++g){var h=a.codePointAt(g);if(127>=h){if(c>=d)break;b[c++]=h}else if(2047>=h){if(c+1>=d)break;b[c++]=192|h>>6;b[c++]=128|h&63}else if(65535>=h){if(c+2>=d)break;b[c++]=224|h>>12;b[c++]=128|h>>6&63;b[c++]=128|h&63}else{if(c+3>=d)break;b[c++]=240|h>>18;b[c++]=128|h>>12&63;b[c++]=128|h>>6&63;b[c++]=128|h&63;g++}}b[c]=0;return c-f},Na=a=>{var b=Array(La(a)+1);a=Ma(a,b,0,b.length);b.length=a;return b},Oa=[];+function Pa(a,b){Oa[a]={input:[],output:[],H:b};Qa(a,Ra)}+var Ra={open(a){var b=Oa[a.node.rdev];if(!b)throw new J.g(43);a.tty=b;a.seekable=!1},close(a){a.tty.H.fsync(a.tty)},fsync(a){a.tty.H.fsync(a.tty)},read(a,b,c,d){if(!a.tty||!a.tty.H.fa)throw new J.g(60);for(var f=0,g=0;g<d;g++){try{var h=a.tty.H.fa(a.tty)}catch(m){throw new J.g(29);}if(void 0===h&&0===f)throw new J.g(6);if(null===h||void 0===h)break;f++;b[c+g]=h}f&&(a.node.atime=Date.now());return f},write(a,b,c,d){if(!a.tty||!a.tty.H.$)throw new J.g(60);try{for(var f=0;f<d;f++)a.tty.H.$(a.tty,b[c++f])}catch(g){throw new J.g(29);}d&&(a.node.mtime=a.node.ctime=Date.now());return f}},Sa={fa(){a:{if(!Ka.length){var a=null;if(ba){var b=Buffer.alloc(256),c=0,d=process.stdin.fd;try{c=fs.readSync(d,b,0,256)}catch(f){if(f.toString().includes("EOF"))c=0;else throw f;}0<c&&(a=b.slice(0,c).toString("utf-8"))}else globalThis.window?.prompt&&(a=window.prompt("Input: "),null!==a&&(a+="\n"));if(!a){a=null;break a}Ka=Na(a)}a=Ka.shift()}return a},$(a,b){null===b||10===b?(ha(K(a.output)),a.output=[]):0!=b&&a.output.push(b)},+fsync(a){0<a.output?.length&&(ha(K(a.output)),a.output=[])},wa(){return{La:25856,Na:5,Ka:191,Ma:35387,Ja:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},xa(){return 0},ya(){return[24,80]}},Ta={$(a,b){null===b||10===b?(t(K(a.output)),a.output=[]):0!=b&&a.output.push(b)},fsync(a){0<a.output?.length&&(t(K(a.output)),a.output=[])}},L={C:null,l(){return L.createNode(null,"/",16895,0)},createNode(a,b,c,d){if(24576===(c&61440)||J.isFIFO(c))throw new J.g(63);L.C||(L.C={dir:{node:{v:L.h.v,+B:L.h.B,lookup:L.h.lookup,F:L.h.F,rename:L.h.rename,unlink:L.h.unlink,rmdir:L.h.rmdir,readdir:L.h.readdir,symlink:L.h.symlink},stream:{o:L.i.o}},file:{node:{v:L.h.v,B:L.h.B},stream:{o:L.i.o,read:L.i.read,write:L.i.write,L:L.i.L,N:L.i.N}},link:{node:{v:L.h.v,B:L.h.B,readlink:L.h.readlink},stream:{}},aa:{node:{v:L.h.v,B:L.h.B},stream:J.qa}});c=J.createNode(a,b,c,d);M(c.mode)?(c.h=L.C.dir.node,c.i=L.C.dir.stream,c.j={}):J.isFile(c.mode)?(c.h=L.C.file.node,c.i=L.C.file.stream,c.m=0,c.j=L.ra??(L.ra=new Uint8Array(0))):+40960===(c.mode&61440)?(c.h=L.C.link.node,c.i=L.C.link.stream):8192===(c.mode&61440)&&(c.h=L.C.aa.node,c.i=L.C.aa.stream);c.atime=c.mtime=c.ctime=Date.now();a&&(a.j[b]=c,a.atime=a.mtime=a.ctime=c.atime);return c},h:{v(a){var b={};b.dev=8192===(a.mode&61440)?a.id:1;b.ino=a.id;b.mode=a.mode;b.nlink=1;b.uid=0;b.gid=0;b.rdev=a.rdev;M(a.mode)?b.size=4096:J.isFile(a.mode)?b.size=a.m:40960===(a.mode&61440)?b.size=a.link.length:b.size=0;b.atime=new Date(a.atime);b.mtime=new Date(a.mtime);b.ctime=new Date(a.ctime);+b.blksize=4096;b.blocks=Math.ceil(b.size/b.blksize);return b},B(a,b){for(var c of["mode","atime","mtime","ctime"])null!=b[c]&&(a[c]=b[c]);void 0!==b.size&&(b=b.size,a.m!=b&&(c=a.j,a.j=new Uint8Array(b),a.j.set(c.subarray(0,Math.min(b,a.m))),a.m=b))},lookup(){L.R||(L.R=new J.g(44),L.R.stack="<generic error, no stack>");throw L.R;},F(a,b,c,d){return L.createNode(a,b,c,d)},rename(a,b,c){try{var d=N(b,c)}catch(g){}if(d){if(M(a.mode))for(var f in d.j)throw new J.g(55);Q(d)}delete a.parent.j[a.name];b.j[c]=+a;a.name=c;b.ctime=b.mtime=a.parent.ctime=a.parent.mtime=Date.now()},unlink(a,b){delete a.j[b];a.ctime=a.mtime=Date.now()},rmdir(a,b){var c=N(a,b),d;for(d in c.j)throw new J.g(55);delete a.j[b];a.ctime=a.mtime=Date.now()},readdir(a){return[".","..",...Object.keys(a.j)]},symlink(a,b,c){a=L.createNode(a,b,41471,0);a.link=c;return a},readlink(a){if(40960!==(a.mode&61440))throw new J.g(28);return a.link}},i:{read(a,b,c,d,f){if(f>=a.node.m)return 0;d=Math.min(a.node.m-f,d);b.set(a.node.j.subarray(f,f++d),c);return d},write(a,b,c,d,f,g){b.buffer===w.buffer&&(g=!1);if(!d)return 0;a=a.node;a.mtime=a.ctime=Date.now();if(g)a.j=b.subarray(c,c+d),a.m=d;else if(0===a.m&&0===f)a.j=b.slice(c,c+d),a.m=d;else{g=f+d;var h=a.j.length;h>=g||(g=Math.max(g,h*(1048576>h?2:1.125)>>>0),h&&(g=Math.max(g,256)),h=a.j.subarray(0,a.m),a.j=new Uint8Array(g),a.j.set(h));a.j.set(b.subarray(c,c+d),f);a.m=Math.max(a.m,f+d)}return d},o(a,b,c){1===c?b+=a.position:2===c&&J.isFile(a.node.mode)&&(b+=a.node.m);if(0>b)throw new J.g(28);+return b},L(a,b,c,d,f){if(!J.isFile(a.node.mode))throw new J.g(43);a=a.node.j;if(f&2||a.buffer!==w.buffer){d=!0;E();f=void 0;if(!f)throw new J.g(48);if(a){if(0<c||c+b<a.length)a.subarray?a=a.subarray(c,c+b):a=Array.prototype.slice.call(a,c,c+b);w.set(a,f)}}else d=!1,f=a.byteOffset;return{bb:f,Fa:d}},N(a,b,c,d){L.i.write(a,b,0,d,c,!1);return 0}}},Ua=a=>{"string"==typeof a&&(a=Na(a));a.subarray||(a=new Uint8Array(a));return a},Va=(a,b)=>{var c=0;a&&(c|=365);b&&(c|=146);return c},Wa=async a=>{a=await ea(a);+return new Uint8Array(a)},R=0,S=null,Xa=[],Za=async(a,b)=>{"undefined"!=typeof Browser&&Ya();for(var c of Xa)if(c.canHandle(b))return c.handle(a,b);return a},$a=async(a,b,c,d,f,g,h,m)=>{var q=b?Ha(H(a+"/"+b)):a;R++;e.monitorRunDependencies?.(R);try{var k=c;"string"==typeof c&&(k=await Wa(c));k=await Za(k,q);m?.();if(!g){c=b;a&&(a="string"==typeof a?a:T(a),c=b?H(a+"/"+b):a);var n=Va(d,f),r=J.create(c,n);if(k){k=Ua(k);J.chmod(r,n|146);var B=J.open(r,577);J.write(B,k,0,k.length,0,h);J.close(B);J.chmod(r,+n)}}}finally{R--,e.monitorRunDependencies?.(R),0==R&&S&&(b=S,S=null,b())}};function Ya(){var a,b,c;J.V=!0;a??=e.stdin;b??=e.stdout;c??=e.stderr;a?J.I("/dev","stdin",a):J.symlink("/dev/tty","/dev/stdin");b?J.I("/dev","stdout",null,b):J.symlink("/dev/tty","/dev/stdout");c?J.I("/dev","stderr",null,c):J.symlink("/dev/tty1","/dev/stderr");J.open("/dev/stdin",0);J.open("/dev/stdout",1);J.open("/dev/stderr",1)}function Qa(a,b){J.da[a]={i:b}}function M(a){return 16384===(a&61440)}+function N(a,b){var c=M(a.mode)?(c=U(a,"x"))?c:a.h.lookup?0:2:54;if(c)throw new J.g(c);for(c=J.G[ab(a.id,b)];c;c=c.K){var d=c.name;if(c.parent.id===a.id&&d===b)return c}return J.lookup(a,b)}function Q(a){var b=ab(a.parent.id,a.name);if(J.G[b]===a)J.G[b]=a.K;else for(b=J.G[b];b;){if(b.K===a){b.K=a.K;break}b=b.K}}+function V(a,b={}){if(!a)throw new J.g(44);b.O??(b.O=!0);"/"===a.charAt(0)||(a=J.cwd()+"/"+a);var c=0;a:for(;40>c;c++){a=a.split("/").filter(m=>!!m);for(var d=J.root,f="/",g=0;g<a.length;g++){var h=g===a.length-1;if(h&&b.parent)break;if("."!==a[g])if(".."===a[g])if(f=Da(f),J.X(d)){a=f+"/"+a.slice(g+1).join("/");c--;continue a}else d=d.parent;else{f=H(f+"/"+a[g]);try{d=N(d,a[g])}catch(m){if(44===m?.s&&h&&b.Ba)return{path:f};throw m;}!d.A||h&&!b.O||(d=d.A.root);if(40960===(d.mode&61440)&&(!h||b.u)){if(!d.h.readlink)throw new J.g(52);+d=d.h.readlink(d);"/"===d.charAt(0)||(d=Da(f)+"/"+d);a=d+"/"+a.slice(g+1).join("/");continue a}}}return{path:f,node:d}}throw new J.g(32);}function T(a){for(var b;;){if(J.X(a))return a=a.l.ka,b?"/"!==a[a.length-1]?`${a}/${b}`:a+b:a;b=b?`${a.name}/${b}`:a.name;a=a.parent}}function ab(a,b){for(var c=0,d=0;d<b.length;d++)c=(c<<5)-c+b.charCodeAt(d)|0;return(a+c>>>0)%J.G.length}function bb(a){var b=ab(a.parent.id,a.name);a.K=J.G[b];J.G[b]=a}+function U(a,b){return J.ga?0:b.includes("r")&&!(a.mode&292)||b.includes("w")&&!(a.mode&146)||b.includes("x")&&!(a.mode&73)?2:0}function cb(a,b){if(!M(a.mode))return 54;try{return N(a,b),20}catch(c){}return U(a,"wx")}function db(a,b,c){try{var d=N(a,b)}catch(f){return f.s}if(a=U(a,"wx"))return a;if(c){if(!M(d.mode))return 54;if(J.X(d)||T(d)===J.cwd())return 10}else if(M(d.mode))return 31;return 0}function W(a,b){if(!a)throw new J.g(b);return a}+function Y(a){a=J.va(a);if(!a)throw new J.g(8);return a}function eb(a,b=-1){a=Object.assign(new J.oa,a);if(-1==b)a:{for(b=0;b<=J.pa;b++)if(!J.streams[b])break a;throw new J.g(33);}a.fd=b;return J.streams[b]=a}function fb(a,b=-1){a=eb(a,b);a.i?.Sa?.(a);return a}function gb(a,b,c){var d=a?.i.B;a=d?a:b;d??=b.h.B;W(d,63);d(a,c)}function hb(a){var b=[];for(a=[a];a.length;){var c=a.pop();b.push(c);a.push(...c.M)}return b}+function ib(a){var b={Ia:4096,Va:4096,blocks:1E6,Ha:5E5,Ga:5E5,files:J.Z,Ta:J.Z-1,Wa:42,flags:2,$a:255};a.h.la&&Object.assign(b,a.h.la(a.l.Da.root));return b}function jb(a,b,c){"undefined"==typeof c&&(c=b,b=438);return J.F(a,b|8192,c)}function kb(a,b,c,d){gb(a,b,{mode:c&4095|b.mode&-4096,ctime:Date.now(),ea:d})}function lb(a,b,c){if(M(b.mode))throw new J.g(31);if(!J.isFile(b.mode))throw new J.g(28);var d=U(b,"w");if(d)throw new J.g(d);gb(a,b,{size:c,timestamp:Date.now()})}+function mb(a,b,c,d){a="string"==typeof a?a:T(a);b=H(a+"/"+b);return J.create(b,Va(c,d))}function nb(a){if(!(a.za||a.Aa||a.link||a.j))if(globalThis.XMLHttpRequest)E("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");else try{a.j=p(a.url)}catch(b){throw new J.g(29);}}+var J={root:null,M:[],da:{},streams:[],Z:1,G:null,ba:"/",V:!1,ga:!0,ta:null,P:0,g:class{name="ErrnoError";constructor(a){this.s=a}},oa:class{D={};node=null;get object(){return this.node}set object(a){this.node=a}get flags(){return this.D.flags}set flags(a){this.D.flags=a}get position(){return this.D.position}set position(a){this.D.position=a}},na:class{h={};i={};A=null;constructor(a,b,c,d){a||=this;this.parent=a;this.l=a.l;this.id=J.Z++;this.name=b;this.mode=c;this.rdev=d;this.atime=this.mtime=this.ctime=+Date.now()}get read(){return 365===(this.mode&365)}set read(a){a?this.mode|=365:this.mode&=-366}get write(){return 146===(this.mode&146)}set write(a){a?this.mode|=146:this.mode&=-147}get Aa(){return M(this.mode)}get za(){return 8192===(this.mode&61440)}},createNode(a,b,c,d){a=new J.na(a,b,c,d);bb(a);return a},X(a){return a===a.parent},isFile(a){return 32768===(a&61440)},isFIFO(a){return 4096===(a&61440)},isSocket(a){return 49152===(a&49152)},pa:4096,va:a=>J.streams[a],qa:{open(a){a.i=J.ua(a.node.rdev).i;+a.i.open?.(a)},o(){throw new J.g(70);}},Y:a=>a>>8,Ya:a=>a&255,J:(a,b)=>a<<8|b,ua:a=>J.da[a],ma(a,b){function c(m){J.P--;return b(m)}function d(m){if(m){if(!d.sa)return d.sa=!0,c(m)}else++g>=f.length&&c(null)}"function"==typeof a&&(b=a,a=!1);J.P++;1<J.P&&t(`warning: ${J.P} FS.syncfs operations in flight at once, probably just doing extra work`);var f=hb(J.root.l),g=0,h;for(h of f)h.type.ma?h.type.ma(h,a,d):d(null)},l(a,b,c){var d="/"===c;if(d&&J.root)throw new J.g(10);if(!d&&c){var f=V(c,{O:!1});c=+f.path;f=f.node;if(f.A)throw new J.g(10);if(!M(f.mode))throw new J.g(54);}b={type:a,Da:b,ka:c,M:[]};a=a.l(b);a.l=b;b.root=a;d?J.root=a:f&&(f.A=b,f.l&&f.l.M.push(b));return a},gb(a){a=V(a,{O:!1});if(!a.node.A)throw new J.g(28);a=a.node;var b=a.A,c=hb(b);for([,f]of Object.entries(J.G))for(;f;){var d=f.K;c.includes(f.l)&&Q(f);var f=d}a.A=null;a.l.M.splice(a.l.M.indexOf(b),1)},lookup(a,b){return a.h.lookup(a,b)},F(a,b,c){var d=V(a,{parent:!0}).node;a=I(a);if(!a)throw new J.g(28);if("."===a||".."===a)throw new J.g(20);+var f=cb(d,a);if(f)throw new J.g(f);if(!d.h.F)throw new J.g(63);return d.h.F(d,a,b,c)},la(a){return ib(V(a,{u:!0}).node)},eb(a){return ib(a.node)},create(a,b=438){return J.F(a,b&4095|32768,0)},mkdir(a,b=511){return J.F(a,b&1023|16384,0)},Za(a,b){var c=a.split("/"),d="",f;for(f of c)if(f){if(d||"/"===a.charAt(0))d+="/";d+=f;try{J.mkdir(d,b)}catch(g){if(20!=g.s)throw g;}}},symlink(a,b){if(!Ha(a))throw new J.g(44);var c=V(b,{parent:!0}).node;if(!c)throw new J.g(44);b=I(b);var d=cb(c,b);if(d)throw new J.g(d);+if(!c.h.symlink)throw new J.g(63);return c.h.symlink(c,b,a)},rename(a,b){var c=Da(a),d=Da(b),f=I(a),g=I(b);var h=V(a,{parent:!0});var m=h.node;h=V(b,{parent:!0});h=h.node;if(!m||!h)throw new J.g(44);if(m.l!==h.l)throw new J.g(75);var q=N(m,f);a=Ia(a,d);if("."!==a.charAt(0))throw new J.g(28);a=Ia(b,c);if("."!==a.charAt(0))throw new J.g(55);try{var k=N(h,g)}catch(n){}if(q!==k){b=M(q.mode);if(f=db(m,f,b))throw new J.g(f);if(f=k?db(h,g,b):cb(h,g))throw new J.g(f);if(!m.h.rename)throw new J.g(63);if(q.A||+k&&k.A)throw new J.g(10);if(h!==m&&(f=U(m,"w")))throw new J.g(f);Q(q);try{m.h.rename(q,h,g),q.parent=h}catch(n){throw n;}finally{bb(q)}}},rmdir(a){var b=V(a,{parent:!0}).node;a=I(a);var c=N(b,a),d=db(b,a,!0);if(d)throw new J.g(d);if(!b.h.rmdir)throw new J.g(63);if(c.A)throw new J.g(10);b.h.rmdir(b,a);Q(c)},readdir(a){a=V(a,{u:!0}).node;return W(a.h.readdir,54)(a)},unlink(a){var b=V(a,{parent:!0}).node;if(!b)throw new J.g(44);a=I(a);var c=N(b,a),d=db(b,a,!1);if(d)throw new J.g(d);if(!b.h.unlink)throw new J.g(63);+if(c.A)throw new J.g(10);b.h.unlink(b,a);Q(c)},readlink(a){a=V(a).node;if(!a)throw new J.g(44);if(!a.h.readlink)throw new J.g(28);return a.h.readlink(a)},stat(a,b){a=V(a,{u:!b}).node;return W(a.h.v,63)(a)},fstat(a){var b=Y(a);a=b.node;var c=b.i.v;b=c?b:a;c??=a.h.v;W(c,63);return c(b)},lstat(a){return J.stat(a,!0)},chmod(a,b,c){a="string"==typeof a?V(a,{u:!c}).node:a;kb(null,a,b,c)},lchmod(a,b){J.chmod(a,b,!0)},fchmod(a,b){a=Y(a);kb(a,a.node,b,!1)},chown(a,b,c,d){a="string"==typeof a?V(a,{u:!d}).node:+a;gb(null,a,{timestamp:Date.now(),ea:d})},lchown(a,b,c){J.chown(a,b,c,!0)},fchown(a){a=Y(a);gb(a,a.node,{timestamp:Date.now(),ea:!1})},truncate(a,b){if(0>b)throw new J.g(28);a="string"==typeof a?V(a,{u:!0}).node:a;lb(null,a,b)},Xa(a,b){a=Y(a);if(0>b||0===(a.flags&2097155))throw new J.g(28);lb(a,a.node,b)},hb(a,b,c){a=V(a,{u:!0}).node;W(a.h.B,63)(a,{atime:b,mtime:c})},open(a,b,c=438){if(""===a)throw new J.g(44);if("string"==typeof b){var d={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[b];if("undefined"==+typeof d)throw Error(`Unknown file open mode: ${b}`);b=d}c=b&64?c&4095|32768:0;if("object"==typeof a)d=a;else{var f=a.endsWith("/");var g=V(a,{u:!(b&131072),Ba:!0});d=g.node;a=g.path}g=!1;if(b&64)if(d){if(b&128)throw new J.g(20);}else{if(f)throw new J.g(31);d=J.F(a,c|511,0);g=!0}if(!d)throw new J.g(44);8192===(d.mode&61440)&&(b&=-513);if(b&65536&&!M(d.mode))throw new J.g(54);if(!g&&(d?40960===(d.mode&61440)?f=32:(f=["r","w","rw"][b&3],b&512&&(f+="w"),f=M(d.mode)&&("r"!==f||b&576)?31:U(d,f)):f=44,+f))throw new J.g(f);b&512&&!g&&J.truncate(d,0);b&=-131713;b=eb({node:d,path:T(d),flags:b,seekable:!0,position:0,i:d.i,Ea:[],error:!1});b.i.open&&b.i.open(b);g&&J.chmod(d,c&511);return b},close(a){if(null===a.fd)throw new J.g(8);a.S&&(a.S=null);try{a.i.close&&a.i.close(a)}catch(b){throw b;}finally{J.streams[a.fd]=null}a.fd=null},o(a,b,c){if(null===a.fd)throw new J.g(8);if(!a.seekable||!a.i.o)throw new J.g(70);if(0!=c&&1!=c&&2!=c)throw new J.g(28);a.position=a.i.o(a,b,c);a.Ea=[];return a.position},+read(a,b,c,d,f){if(0>d||0>f)throw new J.g(28);if(null===a.fd)throw new J.g(8);if(1===(a.flags&2097155))throw new J.g(8);if(M(a.node.mode))throw new J.g(31);if(!a.i.read)throw new J.g(28);var g="undefined"!=typeof f;if(!g)f=a.position;else if(!a.seekable)throw new J.g(70);b=a.i.read(a,b,c,d,f);g||(a.position+=b);return b},write(a,b,c,d,f,g){if(0>d||0>f)throw new J.g(28);if(null===a.fd)throw new J.g(8);if(0===(a.flags&2097155))throw new J.g(8);if(M(a.node.mode))throw new J.g(31);if(!a.i.write)throw new J.g(28);+a.seekable&&a.flags&1024&&J.o(a,0,2);var h="undefined"!=typeof f;if(!h)f=a.position;else if(!a.seekable)throw new J.g(70);b=a.i.write(a,b,c,d,f,g);h||(a.position+=b);return b},L(a,b,c,d,f){if(0!==(d&2)&&0===(f&2)&&2!==(a.flags&2097155))throw new J.g(2);if(1===(a.flags&2097155))throw new J.g(2);if(!a.i.L)throw new J.g(43);if(!b)throw new J.g(28);return a.i.L(a,b,c,d,f)},N(a,b,c,d,f){return a.i.N?a.i.N(a,b,c,d,f):0},W(a,b,c){if(!a.i.W)throw new J.g(59);return a.i.W(a,b,c)},readFile(a,b={}){b.flags=+b.flags||0;b.encoding=b.encoding||"binary";"utf8"!==b.encoding&&"binary"!==b.encoding&&E(`Invalid encoding type "${b.encoding}"`);var c=J.open(a,b.flags);a=J.stat(a).size;var d=new Uint8Array(a);J.read(c,d,0,a,0);"utf8"===b.encoding&&(d=K(d));J.close(c);return d},writeFile(a,b,c={}){c.flags=c.flags||577;a=J.open(a,c.flags,c.mode);b=Ua(b);J.write(a,b,0,b.byteLength,void 0,c.Oa);J.close(a)},cwd:()=>J.ba,chdir(a){a=V(a,{u:!0});if(null===a.node)throw new J.g(44);if(!M(a.node.mode))throw new J.g(54);var b=+U(a.node,"x");if(b)throw new J.g(b);J.ba=a.path},cb(){J.V=!1;for(var a of J.streams)a&&J.close(a)},Ua(a,b){try{var c=V(a,{u:!b});a=c.path}catch(g){}var d=!1,f=null;try{c=V(a,{parent:!0}),I(a),c=V(a,{u:!b}),d=!0,f=c.node}catch(g){}return d?f:null},Qa(a,b){a="string"==typeof a?a:T(a);for(b=b.split("/").reverse();b.length;){var c=b.pop();if(c){var d=H(a+"/"+c);try{J.mkdir(d)}catch(f){if(20!=f.s)throw f;}a=d}}return d},I(a,b,c,d){a=Ea("string"==typeof a?a:T(a),b);b=Va(!!c,!!d);var f;(f=J.I).Y??(f.Y=64);+f=J.J(J.I.Y++,0);Qa(f,{open(g){g.seekable=!1},close(){d?.buffer?.length&&d(10)},read(g,h,m,q){for(var k=0,n=0;n<q;n++){try{var r=c()}catch(B){throw new J.g(29);}if(void 0===r&&0===k)throw new J.g(6);if(null===r||void 0===r)break;k++;h[m+n]=r}k&&(g.node.atime=Date.now());return k},write(g,h,m,q){for(var k=0;k<q;k++)try{d(h[m+k])}catch(n){throw new J.g(29);}q&&(g.node.mtime=g.node.ctime=Date.now());return k}});return jb(a,b,f)},Pa(a,b,c,d,f){class g{U=!1;D=[];T=void 0;ia=0;ha=0;get(k){if(!(k>this.length-+1||0>k)){var n=k%this.chunkSize;return this.T(k/this.chunkSize|0)[n]}}Ca(k){this.T=k}ja(){var k=new XMLHttpRequest;k.open("HEAD",c,!1);k.send(null);200<=k.status&&300>k.status||304===k.status||E("Couldn't load "+c+". Status: "+k.status);var n=Number(k.getResponseHeader("Content-length")),r,B=(r=k.getResponseHeader("Accept-Ranges"))&&"bytes"===r;k=(r=k.getResponseHeader("Content-Encoding"))&&"gzip"===r;var A=1048576;B||(A=n);var v=this;v.Ca(O=>{var X=O*A,P=(O+1)*A-1;P=Math.min(P,n-1);if("undefined"==+typeof v.D[O]){var yb=v.D;X>P&&E("invalid range ("+X+", "+P+") or no bytes requested!");P>n-1&&E("only "+n+" bytes available! programmer error!");var y=new XMLHttpRequest;y.open("GET",c,!1);n!==A&&y.setRequestHeader("Range","bytes="+X+"-"+P);y.responseType="arraybuffer";y.overrideMimeType&&y.overrideMimeType("text/plain; charset=x-user-defined");y.send(null);200<=y.status&&300>y.status||304===y.status||E("Couldn't load "+c+". Status: "+y.status);X=void 0!==y.response?new Uint8Array(y.response||[]):+Na(y.responseText||"");yb[O]=X}"undefined"==typeof v.D[O]&&E("doXHR failed!");return v.D[O]});if(k||!n)A=n=1,A=n=this.T(0).length,ha("LazyFiles on gzip forces download of the whole file when length is accessed");this.ia=n;this.ha=A;this.U=!0}get length(){this.U||this.ja();return this.ia}get chunkSize(){this.U||this.ja();return this.ha}}if(globalThis.XMLHttpRequest){l||E("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var h=new g;+var m=void 0}else m=c,h=void 0;var q=mb(a,b,d,f);h?q.j=h:m&&(q.j=null,q.url=m);Object.defineProperties(q,{m:{get:function(){return this.j.length}}});a={};for(const [k,n]of Object.entries(q.i))a[k]=(...r)=>{nb(q);return n(...r)};a.read=(k,n,r,B,A)=>{nb(q);k=k.node.j;if(A>=k.length)n=0;else{B=Math.min(k.length-A,B);if(k.slice)for(var v=0;v<B;v++)n[r+v]=k[A+v];else for(v=0;v<B;v++)n[r+v]=k.get(A+v);n=B}return n};a.L=()=>{nb(q);E();throw new J.g(48);};q.i=a;return q}},F=void 0,ob=0,Z={},pb=a=>{ja=a;Ba||+0<ob||(e.onExit?.(a),ia=!0);ca(a,new wa(a))},qb=a=>{if(!ia)try{a()}catch(b){b instanceof wa||"unwind"==b||ca(1,b)}finally{if(!(Ba||0<ob))try{ja=a=ja,pb(a)}catch(b){b instanceof wa||"unwind"==b||ca(1,b)}}},ub=(a,b,c,d)=>{var f={string:k=>{var n=0;if(null!==k&&void 0!==k&&0!==k){n=La(k)+1;var r=rb(n);Ma(k,z,r,n);n=r}return n},array:k=>{var n=rb(k.length);w.set(k,n);return n}};a=e["_"+a];var g=[],h=0;if(d)for(var m=0;m<d.length;m++){var q=f[c[m]];q?(0===h&&(h=sb()),g[m]=q(d[m])):g[m]=d[m]}c=a(...g);+return c=function(k){0!==h&&tb(h);return"string"===b?k?K(z,k):"":"boolean"===b?!!k:k}(c)};J.Ra=(a,b,c,d,f,g,h,m,q,k)=>{$a(a,b,c,d,f,m,q,k).then(g).catch(h)};J.ab=$a;J.G=Array(4096);J.l(L,{},"/");J.mkdir("/tmp");J.mkdir("/home");J.mkdir("/home/web_user");+(function(){J.mkdir("/dev");Qa(J.J(1,3),{read:()=>0,write:(d,f,g,h)=>h,o:()=>0});jb("/dev/null",J.J(1,3));Pa(J.J(5,0),Sa);Pa(J.J(6,0),Ta);jb("/dev/tty",J.J(5,0));jb("/dev/tty1",J.J(6,0));var a=new Uint8Array(1024),b=0,c=()=>{0===b&&(Ga(a),b=a.byteLength);return a[--b]};J.I("/dev","random",c);J.I("/dev","urandom",c);J.mkdir("/dev/shm");J.mkdir("/dev/shm/tmp")})();+(function(){J.mkdir("/proc");var a=J.mkdir("/proc/self");J.mkdir("/proc/self/fd");J.l({l(){var b=J.createNode(a,"fd",16895,73);b.i={o:L.i.o};b.h={lookup(c,d){c=+d;var f=Y(c);c={parent:null,l:{ka:"fake"},h:{readlink:()=>f.path},id:c+1};return c.parent=c},readdir(){return Array.from(J.streams.entries()).filter(([,c])=>c).map(([c])=>c.toString())}};return b}},{},"/proc/self/fd")})();J.ta={MEMFS:L};e.noExitRuntime&&(Ba=e.noExitRuntime);e.preloadPlugins&&(Xa=e.preloadPlugins);e.print&&(ha=e.print);+e.printErr&&(t=e.printErr);e.wasmBinary&&(u=e.wasmBinary);if(e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.shift()();e.ccall=ub;e.cwrap=(a,b,c,d)=>{var f=!c||c.every(g=>"number"===g||"boolean"===g);return"string"!==b&&f&&!d?e["_"+a]:(...g)=>ub(a,b,c,g,d)};+e.setValue=function(a,b,c="i8"){c.endsWith("*")&&(c="*");switch(c){case "i1":w[a]=b;break;case "i8":w[a]=b;break;case "i16":x[a>>1]=b;break;case "i32":C[a>>2]=b;break;case "i64":ra[a>>3]=BigInt(b);break;case "float":pa[a>>2]=b;break;case "double":qa[a>>3]=b;break;case "*":D[a>>2]=b;break;default:E(`invalid type for setValue: ${c}`)}};+e.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return w[a];case "i8":return w[a];case "i16":return x[a>>1];case "i32":return C[a>>2];case "i64":return ra[a>>3];case "float":return pa[a>>2];case "double":return qa[a>>3];case "*":return D[a>>2];default:E(`invalid type for getValue: ${b}`)}};e.FS=J;+var vb,tb,rb,sb,oa,wb={__syscall_fcntl64:function(a,b,c){F=c;try{var d=Y(a);switch(b){case 0:var f=G();if(0>f)break;for(;J.streams[f];)f++;return fb(d,f).fd;case 1:case 2:return 0;case 3:return d.flags;case 4:return f=G(),d.flags|=f,0;case 12:return f=G(),x[f+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(g){if("undefined"==typeof J||"ErrnoError"!==g.name)throw g;return-g.s}},__syscall_ioctl:function(a,b,c){F=c;try{var d=Y(a);switch(b){case 21509:return d.tty?0:-59;case 21505:if(!d.tty)return-59;+if(d.tty.H.wa){a=[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var f=G();C[f>>2]=25856;C[f+4>>2]=5;C[f+8>>2]=191;C[f+12>>2]=35387;for(var g=0;32>g;g++)w[f+g+17]=a[g]||0}return 0;case 21510:case 21511:case 21512:return d.tty?0:-59;case 21506:case 21507:case 21508:if(!d.tty)return-59;if(d.tty.H.xa)for(f=G(),a=[],g=0;32>g;g++)a.push(w[f+g+17]);return 0;case 21519:if(!d.tty)return-59;f=G();return C[f>>2]=0;case 21520:return d.tty?-28:-59;case 21537:case 21531:return f=G(),+J.W(d,b,f);case 21523:if(!d.tty)return-59;d.tty.H.ya&&(g=[24,80],f=G(),x[f>>1]=g[0],x[f+2>>1]=g[1]);return 0;case 21524:return d.tty?0:-59;case 21515:return d.tty?0:-59;default:return-28}}catch(h){if("undefined"==typeof J||"ErrnoError"!==h.name)throw h;return-h.s}},__syscall_openat:function(a,b,c,d){F=d;try{b=b?K(z,b):"";var f=b;if("/"===f.charAt(0))b=f;else{var g=-100===a?J.cwd():Y(a).path;if(0==f.length)throw new J.g(44);b=g+"/"+f}var h=d?G():0;return J.open(b,c,h).fd}catch(m){if("undefined"==typeof J||+"ErrnoError"!==m.name)throw m;return-m.s}},_abort_js:()=>E(""),_emscripten_runtime_keepalive_clear:()=>{Ba=!1;ob=0},_setitimer_js:(a,b)=>{Z[a]&&(clearTimeout(Z[a].id),delete Z[a]);if(!b)return 0;var c=setTimeout(()=>{delete Z[a];qb(()=>vb(a,performance.now()))},b);Z[a]={id:c,fb:b};return 0},emscripten_resize_heap:a=>{var b=z.length;a>>>=0;if(2147483648<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(a,d)/65536))-oa.buffer.byteLength++65535)/65536|0;try{oa.grow(d);na();var f=1;break a}catch(g){}f=void 0}if(f)return!0}return!1},fd_close:function(a){try{var b=Y(a);J.close(b);return 0}catch(c){if("undefined"==typeof J||"ErrnoError"!==c.name)throw c;return c.s}},fd_read:function(a,b,c,d){try{a:{var f=Y(a);a=b;for(var g,h=b=0;h<c;h++){var m=D[a>>2],q=D[a+4>>2];a+=8;var k=J.read(f,w,m,q,g);if(0>k){var n=-1;break a}b+=k;if(k<q)break;"undefined"!=typeof g&&(g+=k)}n=b}D[d>>2]=n;return 0}catch(r){if("undefined"==typeof J||"ErrnoError"!==+r.name)throw r;return r.s}},fd_seek:function(a,b,c,d){b=-9007199254740992>b||9007199254740992<b?NaN:Number(b);try{if(isNaN(b))return 61;var f=Y(a);J.o(f,b,c);ra[d>>3]=BigInt(f.position);f.S&&0===b&&0===c&&(f.S=null);return 0}catch(g){if("undefined"==typeof J||"ErrnoError"!==g.name)throw g;return g.s}},fd_write:function(a,b,c,d){try{a:{var f=Y(a);a=b;for(var g,h=b=0;h<c;h++){var m=D[a>>2],q=D[a+4>>2];a+=8;var k=J.write(f,w,m,q,g);if(0>k){var n=-1;break a}b+=k;if(k<q)break;"undefined"!=typeof g&&(g+=+k)}n=b}D[d>>2]=n;return 0}catch(r){if("undefined"==typeof J||"ErrnoError"!==r.name)throw r;return r.s}},proc_exit:pb};+function xb(){function a(){e.calledRun=!0;if(!ia){ma=!0;e.noFSInit||J.V||Ya();zb.__wasm_call_ctors();J.ga=!1;ka?.(e);e.onRuntimeInitialized?.();if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var b=e.postRun.shift();ya.push(b)}xa(ya)}}if(0<R)S=xb;else{if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)Aa();xa(za);0<R?S=xb:e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1);a()},1)):a()}}+var zb;+zb=await (async function(){function a(c){c=zb=c.exports;e._detect_init=c.detect_init;e._free=c.free;e._detect_faces=c.detect_faces;e._detect_free=c.detect_free;e._malloc=c.malloc;vb=c._emscripten_timeout;tb=c._emscripten_stack_restore;rb=c._emscripten_stack_alloc;sb=c.emscripten_stack_get_current;oa=c.memory;na();return zb}var b={env:wb,wasi_snapshot_preview1:wb};if(e.instantiateWasm)return new Promise(c=>{e.instantiateWasm(b,(d,f)=>{c(a(d,f))})});sa??=e.locateFile?e.locateFile("detect.wasm",da):+da+"detect.wasm";return a((await va(b)).instance)}());xb();ma?moduleRtn=e:moduleRtn=new Promise((a,b)=>{ka=a;la=b});+;return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=FaceDetModule;module.exports.default=FaceDetModule}else if(typeof define==="function"&&define["amd"])define([],()=>FaceDetModule);diff --git a/detect.wasm b/detect.wasmnew file mode 100644index 0000000..0bae3d2Binary files /dev/null and b/detect.wasm differdiff --git a/docs/demo/index.html b/docs/demo/index.htmlindex 0dbecc4..e3b056b 100644--- a/docs/demo/index.html+++ b/docs/demo/index.html@@ -49,6 +49,10 @@ canvas.hidden { display: none; }<button id="bTest" class="gray" disabled>Self-test</button></div>+<div style="display:flex;gap:8px;justify-content:center;margin-bottom:8px">+ <div style="text-align:center"><canvas id="refVis" width="112" height="112" style="width:80px;height:80px;border-radius:6px;border:1px solid #333;background:#111"></canvas><div style="font-size:10px;color:#666">Reference</div></div>+ <div style="text-align:center"><canvas id="curVis" width="112" height="112" style="width:80px;height:80px;border-radius:6px;border:1px solid #333;background:#111"></canvas><div style="font-size:10px;color:#666">Current</div></div>+</div><div id="result" class="idle"></div><div class="stats" id="stats" style="display:none"><span id="sEmb">—</span>diff --git a/index.html b/index.htmlnew file mode 100644index 0000000..6b58d35--- /dev/null+++ b/index.html@@ -0,0 +1,367 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0">+<title>FaceX — Face Recognition in Your Browser</title>+<style>+* { box-sizing: border-box; margin: 0; padding: 0; }+body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0a0a0a; color: #e0e0e0; min-height: 100vh; }++.header { text-align: center; padding: 24px 16px 8px; }+.header h1 { font-size: 24px; color: #fff; }+.header h1 span { color: #10b981; }+.header p { color: #555; font-size: 13px; margin-top: 4px; }++.status { text-align: center; padding: 8px; font-size: 13px; transition: color 0.3s; }+.status.loading { color: #f59e0b; }+.status.ready { color: #10b981; }+.status.error { color: #ef4444; }++.main { max-width: 480px; margin: 0 auto; padding: 0 12px 40px; }++.video-wrap { position: relative; width: 100%; border-radius: 12px; overflow: hidden; background: #111; margin-bottom: 12px; border: 2px solid #222; transition: border-color 0.3s; }+.video-wrap.match { border-color: #10b981; }+.video-wrap.nomatch { border-color: #ef4444; }+video { width: 100%; display: block; transform: scaleX(-1); }+canvas.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; transform: scaleX(-1); }++.controls { display: flex; gap: 8px; justify-content: center; margin-bottom: 12px; flex-wrap: wrap; }+.btn { padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; border: none; transition: all 0.15s; }+.btn:active { transform: scale(0.97); }+.btn-go { background: #10b981; color: #fff; }+.btn-go:hover { background: #059669; }+.btn-stop { background: #ef4444; color: #fff; }+.btn-sec { background: #222; color: #aaa; border: 1px solid #333; }+.btn-sec:hover { background: #333; }+.btn:disabled { background: #1a1a1a; color: #444; cursor: not-allowed; border-color: #1a1a1a; }++.ref-bar { display: flex; align-items: center; gap: 10px; justify-content: center; margin: 10px 0; padding: 10px; background: #111; border-radius: 10px; border: 1px solid #222; }+.ref-bar canvas { width: 56px; height: 56px; border-radius: 6px; border: 1px solid #333; }+.ref-bar .label { font-size: 12px; color: #888; }++.result-bar { text-align: center; padding: 14px; margin: 10px 0; border-radius: 10px; font-size: 15px; font-weight: 600; transition: all 0.2s; }+.result-bar.match { background: #052e16; color: #10b981; border: 1px solid #166534; }+.result-bar.nomatch { background: #1c0a0a; color: #ef4444; border: 1px solid #7f1d1d; }+.result-bar.idle { background: #111; color: #555; border: 1px solid #222; }++.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; }+.stat { text-align: center; background: #111; border-radius: 8px; padding: 8px 4px; border: 1px solid #1a1a1a; }+.stat-val { font-size: 18px; font-weight: 700; color: #10b981; }+.stat-label { font-size: 10px; color: #555; text-transform: uppercase; letter-spacing: 0.5px; }++.liveness-bar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #111; border-radius: 8px; margin: 8px 0; border: 1px solid #222; }+.liveness-dot { width: 10px; height: 10px; border-radius: 50%; background: #ef4444; transition: background 0.3s; }+.liveness-dot.live { background: #10b981; }+.liveness-text { font-size: 12px; color: #888; }++.info { background: #0d0d0d; border: 1px solid #1a1a1a; border-radius: 10px; padding: 14px; margin-top: 16px; }+.info h3 { font-size: 13px; color: #999; margin-bottom: 8px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }+.info p { font-size: 12px; color: #555; line-height: 1.6; margin-bottom: 4px; }+.info code { background: #1a1a1a; padding: 1px 4px; border-radius: 3px; color: #10b981; font-size: 11px; }++.error-msg { text-align: center; padding: 16px; background: #1c0a0a; border: 1px solid #7f1d1d; border-radius: 10px; margin: 12px 0; color: #ef4444; font-size: 13px; display: none; }+</style>+</head>+<body>++<div class="header">+ <h1>Face<span>X</span></h1>+ <p>74 KB WASM. No server. Everything stays on your device.</p>+</div>++<div id="status" class="status loading">Checking browser support...</div>+<div id="errorMsg" class="error-msg"></div>++<div class="main">+ <div class="video-wrap" id="videoWrap">+ <video id="video" autoplay playsinline muted></video>+ <canvas id="overlay" class="overlay"></canvas>+ </div>++ <div class="controls">+ <button id="btnStart" class="btn btn-go" disabled>Start Camera</button>+ <button id="btnCapture" class="btn btn-sec" disabled>Set Reference</button>+ <button id="btnVerify" class="btn btn-go" disabled style="display:none">Verify</button>+ <button id="btnStop" class="btn btn-stop" style="display:none">Stop</button>+ </div>++ <div id="refBar" class="ref-bar" style="display:none">+ <canvas id="refCanvas" width="112" height="112"></canvas>+ <div><div class="label">Reference face</div></div>+ </div>++ <div id="resultBar" class="result-bar idle">Load engine to begin</div>++ <div id="livenessBar" class="liveness-bar" style="display:none">+ <div id="livenessDot" class="liveness-dot"></div>+ <div id="livenessText" class="liveness-text">Checking liveness...</div>+ </div>++ <div id="statsGrid" class="stats" style="display:none">+ <div class="stat"><div class="stat-val" id="vDet">—</div><div class="stat-label">Detect</div></div>+ <div class="stat"><div class="stat-val" id="vEmb">—</div><div class="stat-label">Embed</div></div>+ <div class="stat"><div class="stat-val" id="vSim">—</div><div class="stat-label">Match</div></div>+ <div class="stat"><div class="stat-val" id="vFps">—</div><div class="stat-label">FPS</div></div>+ </div>++ <div class="info">+ <h3>How it works</h3>+ <p><code>detect.wasm</code> (29 KB) finds faces with RetinaFace INT8 + relaxed SIMD.</p>+ <p><code>facex.wasm</code> (44 KB) computes 512-dim embeddings via EdgeFace-XS.</p>+ <p>5-point alignment ensures accurate matching at any head angle.</p>+ <p>Total: <code>74 KB</code> engine + <code>7.7 MB</code> weights (cached after first load).</p>+ </div>+</div>++<script src="detect.js"></script>+<script src="facex.js"></script>+<script src="align.js"></script>+<script src="liveness.js"></script>+<script>+const $ = id => document.getElementById(id);+const video = $('video');+const overlay = $('overlay');+const ctx = overlay.getContext('2d');+const refCanvas = $('refCanvas');+const refCtx = refCanvas.getContext('2d', { willReadFrequently: true });++let DetMod, FxMod, detH, fxH;+let refEmb = null, running = false;+const liveness = new LivenessDetector();++// Reusable canvases+const srcCv = document.createElement('canvas');+const srcCtx = srcCv.getContext('2d', { willReadFrequently: true });+const cropCv = document.createElement('canvas');+cropCv.width = 112; cropCv.height = 112;+const cropCtxA = cropCv.getContext('2d', { willReadFrequently: true });++// ===== SIMD Check =====+function checkSimd() {+ try {+ return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11]));+ } catch(e) { return false; }+}++// ===== IndexedDB Cache =====+async function cachedFetch(url, key) {+ try {+ const db = await new Promise((res, rej) => {+ const r = indexedDB.open('facex-cache', 1);+ r.onupgradeneeded = () => r.result.createObjectStore('w');+ r.onsuccess = () => res(r.result);+ r.onerror = () => rej(r.error);+ });+ const cached = await new Promise(r => {+ const tx = db.transaction('w','readonly');+ const req = tx.objectStore('w').get(key);+ req.onsuccess = () => r(req.result); req.onerror = () => r(null);+ });+ if (cached) return new Uint8Array(cached);+ const buf = await fetch(url).then(r => r.arrayBuffer());+ try { const tx = db.transaction('w','readwrite'); tx.objectStore('w').put(buf, key); } catch(e) {}+ return new Uint8Array(buf);+ } catch(e) { return new Uint8Array(await fetch(url).then(r => r.arrayBuffer())); }+}++// ===== Init =====+async function init() {+ const s = $('status');+ if (!checkSimd()) {+ showError('WebAssembly SIMD not supported. Use Chrome 91+, Firefox 89+, or Safari 16.4+.');+ return;+ }+ try {+ s.textContent = 'Loading engines...'; s.className = 'status loading';+ [DetMod, FxMod] = await Promise.all([FaceDetModule(), FaceXModule()]);++ s.textContent = 'Loading weights (cached after first load)...';+ const [dw, fw] = await Promise.all([+ cachedFetch('det_500m_int8.bin', 'det'), cachedFetch('edgeface_xs_fp32.bin', 'emb')+ ]);+ DetMod.FS.writeFile('/d.bin', dw); FxMod.FS.writeFile('/e.bin', fw);++ detH = DetMod.cwrap('detect_init','number',['string'])('/d.bin');+ fxH = FxMod.cwrap('facex_init','number',['string','string'])('/e.bin', null);+ if (!detH || !fxH) throw new Error('Engine init failed');++ s.textContent = 'Ready — 74 KB engines loaded'; s.className = 'status ready';+ $('btnStart').disabled = false;+ $('resultBar').textContent = 'Click "Start Camera" to begin';+ } catch(e) { showError(e.message); }+}++function showError(msg) {+ $('status').textContent = 'Error'; $('status').className = 'status error';+ $('errorMsg').textContent = msg; $('errorMsg').style.display = 'block';+}++// ===== Camera =====+$('btnStart').onclick = async () => {+ try {+ const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 320, height: 240, facingMode: 'user' }});+ video.srcObject = stream;+ video.onloadedmetadata = () => { overlay.width = video.videoWidth; overlay.height = video.videoHeight; };+ $('btnStart').disabled = true; $('btnStart').style.display = 'none';+ $('btnCapture').disabled = false;+ $('resultBar').textContent = 'Look at camera and click "Set Reference"';+ } catch(e) { showError('Camera access denied: ' + e.message); }+};++// ===== Detect =====+function runDetect() {+ const W = video.videoWidth, H = video.videoHeight;+ const ds = 160;+ const detCv = document.createElement('canvas'); detCv.width = ds; detCv.height = ds;+ const dCtx = detCv.getContext('2d', { willReadFrequently: true });+ const scale = Math.min(ds/W, ds/H);+ const nw = Math.round(W*scale), nh = Math.round(H*scale);+ const dx = (ds-nw)/2, dy = (ds-nh)/2;+ dCtx.fillStyle = '#000'; dCtx.fillRect(0,0,ds,ds);+ dCtx.drawImage(video, dx, dy, nw, nh);+ const img = dCtx.getImageData(0,0,ds,ds);++ const nPx = ds*ds*3;+ const inP = DetMod._malloc(nPx*4);+ const heap = DetMod.HEAPF32;+ const b = inP>>2;+ for (let i=0; i<ds*ds; i++) {+ heap[b+i*3] = img.data[i*4]/127.5-1; heap[b+i*3+1] = img.data[i*4+1]/127.5-1; heap[b+i*3+2] = img.data[i*4+2]/127.5-1;+ }+ const outP = DetMod._malloc(15*4*10);+ const df = DetMod.cwrap('detect_faces','number',['number','number','number','number','number','number']);+ const t0 = performance.now();+ const n = df(detH, inP, ds, ds, outP, 10);+ const detMs = performance.now() - t0;++ const faces = [];+ for (let i=0; i<n; i++) {+ const fb = (outP>>2)+i*15;+ const f = DetMod.HEAPF32;+ faces.push({+ x1:(f[fb]-dx)/scale, y1:(f[fb+1]-dy)/scale, x2:(f[fb+2]-dx)/scale, y2:(f[fb+3]-dy)/scale,+ score:f[fb+4], kps: Array.from({length:10}, (_,j) => (f[fb+5+j]-(j%2===0?dx:dy))/scale)+ });+ }+ DetMod._free(inP); DetMod._free(outP);+ return { faces, detMs };+}++// ===== Embed =====+function runEmbed(imgData) {+ const N=112*112*3;+ const inP = FxMod._malloc(N*4), outP = FxMod._malloc(512*4);+ const heap = FxMod.HEAPF32, b = inP>>2;+ for (let i=0; i<112*112; i++) {+ heap[b+i*3] = imgData.data[i*4]/127.5-1; heap[b+i*3+1] = imgData.data[i*4+1]/127.5-1; heap[b+i*3+2] = imgData.data[i*4+2]/127.5-1;+ }+ const t0 = performance.now();+ FxMod.cwrap('facex_embed','number',['number','number','number'])(fxH, inP, outP);+ const embMs = performance.now() - t0;+ const emb = new Float32Array(512);+ emb.set(heap.subarray(outP>>2, (outP>>2)+512));+ FxMod._free(inP); FxMod._free(outP);+ return { emb, embMs };+}++function cosSim(a,b) {+ let d=0,na=0,nb=0;+ for (let i=0;i<512;i++) { d+=a[i]*b[i]; na+=a[i]*a[i]; nb+=b[i]*b[i]; }+ return d/Math.sqrt(na*nb);+}++// ===== Align + Crop =====+function alignAndCrop(face) {+ const W = video.videoWidth, H = video.videoHeight;+ srcCv.width = W; srcCv.height = H;+ srcCtx.drawImage(video, 0, 0);+ const kps5 = [];+ for (let i=0; i<5; i++) kps5.push([face.kps[i*2], face.kps[i*2+1]]);+ return alignFace(srcCtx, W, H, kps5, cropCtxA);+}++// ===== Draw =====+function drawFaces(faces, isMatch) {+ ctx.clearRect(0,0,overlay.width,overlay.height);+ for (const f of faces) {+ ctx.strokeStyle = isMatch === undefined ? '#10b981' : (isMatch ? '#10b981' : '#ef4444');+ ctx.lineWidth = 2;+ ctx.strokeRect(f.x1, f.y1, f.x2-f.x1, f.y2-f.y1);+ ctx.fillStyle = ctx.strokeStyle;+ for (let j=0; j<5; j++) { ctx.beginPath(); ctx.arc(f.kps[j*2], f.kps[j*2+1], 2, 0, Math.PI*2); ctx.fill(); }+ }+}++// ===== Capture Reference =====+$('btnCapture').onclick = () => {+ const { faces } = runDetect();+ if (!faces.length) { $('resultBar').textContent = 'No face detected — look at camera'; $('resultBar').className = 'result-bar nomatch'; return; }+ const aligned = alignAndCrop(faces[0]);+ refCtx.putImageData(aligned, 0, 0);+ const { emb } = runEmbed(aligned);+ refEmb = emb;+ $('refBar').style.display = 'flex';+ $('btnVerify').style.display = 'inline-block'; $('btnVerify').disabled = false;+ $('resultBar').textContent = 'Reference set. Click "Verify".'; $('resultBar').className = 'result-bar idle';+ drawFaces(faces);+ liveness.reset();+};++// ===== Verify Loop =====+$('btnVerify').onclick = () => {+ running = true;+ $('btnVerify').style.display = 'none'; $('btnStop').style.display = 'inline-block';+ $('btnCapture').disabled = true;+ $('statsGrid').style.display = 'grid'; $('livenessBar').style.display = 'flex';+ loop();+};+$('btnStop').onclick = () => {+ running = false;+ $('btnStop').style.display = 'none'; $('btnVerify').style.display = 'inline-block'; $('btnVerify').disabled = false;+ $('btnCapture').disabled = false;+ ctx.clearRect(0,0,overlay.width,overlay.height);+ $('videoWrap').className = 'video-wrap';+};++function loop() {+ if (!running) return;+ const tAll = performance.now();+ const { faces, detMs } = runDetect();++ if (!faces.length) {+ drawFaces([]);+ $('resultBar').textContent = 'No face detected'; $('resultBar').className = 'result-bar idle';+ $('videoWrap').className = 'video-wrap';+ $('vDet').textContent = detMs.toFixed(0)+'ms';+ liveness.update(null);+ requestAnimationFrame(loop); return;+ }++ const aligned = alignAndCrop(faces[0]);+ const { emb, embMs } = runEmbed(aligned);+ const sim = cosSim(refEmb, emb);+ const match = sim > 0.3;+ const totalMs = performance.now() - tAll;++ // Liveness+ const live = liveness.update(faces[0]);+ $('livenessDot').className = 'liveness-dot' + (live.alive ? ' live' : '');+ $('livenessText').textContent = live.reason;++ drawFaces(faces, match);+ $('resultBar').textContent = match ? `MATCH — ${(sim*100).toFixed(1)}%` : `NO MATCH — ${(sim*100).toFixed(1)}%`;+ $('resultBar').className = 'result-bar ' + (match ? 'match' : 'nomatch');+ $('videoWrap').className = 'video-wrap ' + (match ? 'match' : 'nomatch');+ $('vDet').textContent = detMs.toFixed(0)+'ms';+ $('vEmb').textContent = embMs.toFixed(0)+'ms';+ $('vSim').textContent = (sim*100).toFixed(1)+'%';+ $('vFps').textContent = (1000/totalMs).toFixed(0);++ requestAnimationFrame(loop);+}++init();+</script>+</body>+</html>diff --git a/src/threadpool_wasm.c b/src/threadpool_wasm.cnew file mode 100644index 0000000..1553dc5--- /dev/null+++ b/src/threadpool_wasm.c@@ -0,0 +1,136 @@+/*+ * threadpool_wasm.c — Thread pool for WASM (Emscripten pthreads).+ * Uses pthread_cond for signaling instead of futex/WaitOnAddress.+ */++#include <pthread.h>+#include <stdatomic.h>+#include <string.h>++typedef void (*tp_task_fn)(void* ctx, int start, int end);++#define MAX_WORKERS 4++static struct {+ tp_task_fn fn;+ void* ctx;+ int total;+ int grain;+ atomic_int next_idx;+ atomic_int done_count;+ int phase;+ pthread_mutex_t mutex;+ pthread_cond_t cond_work;+ pthread_cond_t cond_done;+} g_task;++static struct {+ pthread_t handle;+ int id;+} g_workers[MAX_WORKERS];++static int n_workers = 0;+static int g_shutdown = 0;++static void* worker_fn(void* arg) {+ (void)arg;+ int last_phase = 0;++ while (!g_shutdown) {+ /* Wait for work */+ pthread_mutex_lock(&g_task.mutex);+ while (g_task.phase == last_phase && !g_shutdown)+ pthread_cond_wait(&g_task.cond_work, &g_task.mutex);+ pthread_mutex_unlock(&g_task.mutex);++ if (g_shutdown) break;+ last_phase = g_task.phase;++ /* Execute chunks */+ while (1) {+ int idx = atomic_fetch_add(&g_task.next_idx, g_task.grain);+ if (idx >= g_task.total) break;+ int end = idx + g_task.grain;+ if (end > g_task.total) end = g_task.total;+ g_task.fn(g_task.ctx, idx, end);+ }++ /* Signal done */+ int prev = atomic_fetch_add(&g_task.done_count, 1);+ if (prev + 1 >= n_workers) {+ pthread_mutex_lock(&g_task.mutex);+ pthread_cond_signal(&g_task.cond_done);+ pthread_mutex_unlock(&g_task.mutex);+ }+ }+ return NULL;+}++void tp_init(int n_threads) {+ if (n_threads < 1) n_threads = 1;+ if (n_threads > MAX_WORKERS + 1) n_threads = MAX_WORKERS + 1;+ n_workers = n_threads - 1; /* main thread also participates */++ pthread_mutex_init(&g_task.mutex, NULL);+ pthread_cond_init(&g_task.cond_work, NULL);+ pthread_cond_init(&g_task.cond_done, NULL);+ g_task.phase = 0;++ for (int i = 0; i < n_workers; i++) {+ g_workers[i].id = i;+ pthread_create(&g_workers[i].handle, NULL, worker_fn, &g_workers[i]);+ }+}++void tp_parallel_for(tp_task_fn fn, void* ctx, int total, int grain) {+ if (grain <= 0) grain = 1;++ if (n_workers <= 0 || total <= grain) {+ /* Single-threaded fallback */+ for (int i = 0; i < total; i += grain) {+ int end = i + grain;+ if (end > total) end = total;+ fn(ctx, i, end);+ }+ return;+ }++ /* Setup task */+ g_task.fn = fn;+ g_task.ctx = ctx;+ g_task.total = total;+ g_task.grain = grain;+ atomic_store(&g_task.next_idx, 0);+ atomic_store(&g_task.done_count, 0);++ /* Wake workers */+ pthread_mutex_lock(&g_task.mutex);+ g_task.phase++;+ pthread_cond_broadcast(&g_task.cond_work);+ pthread_mutex_unlock(&g_task.mutex);++ /* Main thread participates */+ while (1) {+ int idx = atomic_fetch_add(&g_task.next_idx, grain);+ if (idx >= total) break;+ int end = idx + grain;+ if (end > total) end = total;+ fn(ctx, idx, end);+ }++ /* Wait for workers */+ pthread_mutex_lock(&g_task.mutex);+ while (atomic_load(&g_task.done_count) < n_workers)+ pthread_cond_wait(&g_task.cond_done, &g_task.mutex);+ pthread_mutex_unlock(&g_task.mutex);+}++void tp_shutdown(void) {+ g_shutdown = 1;+ pthread_mutex_lock(&g_task.mutex);+ g_task.phase++;+ pthread_cond_broadcast(&g_task.cond_work);+ pthread_mutex_unlock(&g_task.mutex);+ for (int i = 0; i < n_workers; i++)+ pthread_join(g_workers[i].handle, NULL);+}diff --git a/wasm/align.js b/wasm/align.jsnew file mode 100644index 0000000..fe32cc8--- /dev/null+++ b/wasm/align.js@@ -0,0 +1,113 @@+/*+ * align.js — 5-point face alignment for FaceX.+ *+ * Takes 5 keypoints from detector (left_eye, right_eye, nose, left_mouth, right_mouth)+ * and produces a 112x112 aligned face using affine transformation.+ *+ * Reference template: ArcFace standard 112x112 alignment targets.+ */++// ArcFace standard reference points for 112x112 output+const REF_POINTS = [+ [38.2946, 51.6963], // left eye+ [73.5318, 51.5014], // right eye+ [56.0252, 71.7366], // nose+ [41.5493, 92.3655], // left mouth+ [70.7299, 92.2041], // right mouth+];++/**+ * Compute similarity transform matrix from src points to dst points.+ * Uses least-squares fit for 2D similarity (rotation + scale + translation).+ * Returns [a, b, tx, ty] where:+ * x' = a*x - b*y + tx+ * y' = b*x + a*y + ty+ */+function getSimilarityTransform(src, dst) {+ const n = src.length;+ let sx = 0, sy = 0, dx = 0, dy = 0;+ for (let i = 0; i < n; i++) {+ sx += src[i][0]; sy += src[i][1];+ dx += dst[i][0]; dy += dst[i][1];+ }+ sx /= n; sy /= n; dx /= n; dy /= n;++ let num1 = 0, num2 = 0, den = 0;+ for (let i = 0; i < n; i++) {+ const sxc = src[i][0] - sx, syc = src[i][1] - sy;+ const dxc = dst[i][0] - dx, dyc = dst[i][1] - dy;+ num1 += dxc * sxc + dyc * syc;+ num2 += dxc * syc - dyc * sxc;+ den += sxc * sxc + syc * syc;+ }++ const a = num1 / den;+ const b = num2 / den;+ const tx = dx - a * sx + b * sy;+ const ty = dy - b * sx - a * sy;++ return [a, b, tx, ty];+}++/**+ * Apply similarity transform to warp source image to 112x112 aligned face.+ *+ * @param {CanvasRenderingContext2D} srcCtx - source canvas context (video frame)+ * @param {number} srcW - source width+ * @param {number} srcH - source height+ * @param {Array<Array<number>>} kps - 5 keypoints [[x,y], ...] in source coords+ * @param {CanvasRenderingContext2D} dstCtx - destination 112x112 canvas context+ * @returns {ImageData} - 112x112 aligned face+ */+function alignFace(srcCtx, srcW, srcH, kps, dstCtx) {+ // Get transform: destination (112x112 ref) → source (video)+ // We need inverse: for each dst pixel, find src pixel+ const [a, b, tx, ty] = getSimilarityTransform(kps, REF_POINTS);++ // Inverse transform: src = inverse(M) * dst+ // M = [a, -b, tx; b, a, ty]+ // M_inv = (1/det) * [a, b, -a*tx-b*ty; -b, a, b*tx-a*ty]+ const det = a * a + b * b;+ const ai = a / det, bi = b / det;+ const txi = -(ai * tx + bi * ty);+ const tyi = (bi * tx - ai * ty);++ const srcData = srcCtx.getImageData(0, 0, srcW, srcH);+ const dstData = dstCtx.createImageData(112, 112);+ const src = srcData.data;+ const dst = dstData.data;++ for (let dy = 0; dy < 112; dy++) {+ for (let dx = 0; dx < 112; dx++) {+ // Map dst → src using inverse transform+ const sx = ai * dx - bi * dy + txi;+ const sy = bi * dx + ai * dy + tyi;++ // Bilinear interpolation+ const x0 = Math.floor(sx), y0 = Math.floor(sy);+ const x1 = x0 + 1, y1 = y0 + 1;+ const fx = sx - x0, fy = sy - y0;++ if (x0 >= 0 && x1 < srcW && y0 >= 0 && y1 < srcH) {+ const i00 = (y0 * srcW + x0) * 4;+ const i10 = (y0 * srcW + x1) * 4;+ const i01 = (y1 * srcW + x0) * 4;+ const i11 = (y1 * srcW + x1) * 4;+ const di = (dy * 112 + dx) * 4;++ for (let c = 0; c < 3; c++) {+ dst[di + c] = Math.round(+ src[i00 + c] * (1-fx) * (1-fy) ++ src[i10 + c] * fx * (1-fy) ++ src[i01 + c] * (1-fx) * fy ++ src[i11 + c] * fx * fy+ );+ }+ dst[di + 3] = 255;+ }+ }+ }++ dstCtx.putImageData(dstData, 0, 0);+ return dstData;+}diff --git a/wasm/cache.js b/wasm/cache.jsnew file mode 100644index 0000000..a206f87--- /dev/null+++ b/wasm/cache.js@@ -0,0 +1,84 @@+/*+ * cache.js — IndexedDB weight caching for FaceX WASM.+ * First load: fetch from network, store in IndexedDB.+ * Subsequent loads: read from IndexedDB (instant).+ */++const CACHE_DB = 'facex-cache';+const CACHE_STORE = 'weights';+const CACHE_VERSION = 1;++function openCacheDB() {+ return new Promise((resolve, reject) => {+ const req = indexedDB.open(CACHE_DB, CACHE_VERSION);+ req.onupgradeneeded = () => {+ req.result.createObjectStore(CACHE_STORE);+ };+ req.onsuccess = () => resolve(req.result);+ req.onerror = () => reject(req.error);+ });+}++async function getCached(key) {+ const db = await openCacheDB();+ return new Promise((resolve) => {+ const tx = db.transaction(CACHE_STORE, 'readonly');+ const req = tx.objectStore(CACHE_STORE).get(key);+ req.onsuccess = () => resolve(req.result || null);+ req.onerror = () => resolve(null);+ });+}++async function putCached(key, data) {+ const db = await openCacheDB();+ return new Promise((resolve) => {+ const tx = db.transaction(CACHE_STORE, 'readwrite');+ tx.objectStore(CACHE_STORE).put(data, key);+ tx.oncomplete = () => resolve();+ tx.onerror = () => resolve();+ });+}++/**+ * Load weights with IndexedDB caching.+ * @param {string} url - URL to fetch weights from+ * @param {string} key - Cache key (e.g. 'det_weights' or 'emb_weights')+ * @param {function} onProgress - callback(loaded, total) for progress+ * @returns {Promise<Uint8Array>}+ */+async function loadWeightsCached(url, key, onProgress) {+ // Try cache first+ const cached = await getCached(key);+ if (cached) {+ if (onProgress) onProgress(cached.byteLength, cached.byteLength);+ return new Uint8Array(cached);+ }++ // Fetch from network with progress+ const response = await fetch(url);+ const total = parseInt(response.headers.get('content-length')) || 0;+ const reader = response.body.getReader();+ const chunks = [];+ let loaded = 0;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ chunks.push(value);+ loaded += value.length;+ if (onProgress) onProgress(loaded, total);+ }++ // Combine chunks+ const data = new Uint8Array(loaded);+ let offset = 0;+ for (const chunk of chunks) {+ data.set(chunk, offset);+ offset += chunk.length;+ }++ // Store in cache+ await putCached(key, data.buffer);++ return data;+}diff --git a/wasm/detect.js b/wasm/detect.jsnew file mode 100644index 0000000..f0ff527--- /dev/null+++ b/wasm/detect.js@@ -0,0 +1,69 @@+var FaceDetModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var e=moduleArg,aa=!!globalThis.window,l=!!globalThis.WorkerGlobalScope,ba=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,ca=(a,b)=>{throw b;};"undefined"!=typeof __filename?_scriptName=__filename:l&&(_scriptName=self.location.href);var da="",ea,p;+if(ba){var fs=require("node:fs");da=__dirname+"/";p=a=>{a=fa(a)?new URL(a):a;return fs.readFileSync(a)};ea=async a=>{a=fa(a)?new URL(a):a;return fs.readFileSync(a,void 0)};process.argv.slice(2);ca=(a,b)=>{process.exitCode=a;throw b;}}else if(aa||l){try{da=(new URL(".",_scriptName)).href}catch{}l&&(p=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)});ea=async a=>{if(fa(a))return new Promise((c,d)=>{var f=new XMLHttpRequest;+f.open("GET",a,!0);f.responseType="arraybuffer";f.onload=()=>{200==f.status||0==f.status&&f.response?c(f.response):d(f.status)};f.onerror=d;f.send(null)});var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);}}var ha=console.log.bind(console),t=console.error.bind(console),u,ia=!1,ja,fa=a=>a.startsWith("file://"),ka,la,ma=!1;+function na(){var a=oa.buffer;w=new Int8Array(a);x=new Int16Array(a);z=new Uint8Array(a);new Uint16Array(a);C=new Int32Array(a);D=new Uint32Array(a);e.HEAPF32=pa=new Float32Array(a);qa=new Float64Array(a);ra=new BigInt64Array(a);new BigUint64Array(a)}function E(a){e.onAbort?.(a);a=`Aborted(${a})`;t(a);ia=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");la?.(a);throw a;}var sa;+async function ta(a){if(!u)try{var b=await ea(a);return new Uint8Array(b)}catch{}if(a==sa&&u)a=new Uint8Array(u);else if(p)a=p(a);else throw"both async and sync fetching of the wasm failed";return a}async function ua(a,b){try{var c=await ta(a);return await WebAssembly.instantiate(c,b)}catch(d){t(`failed to asynchronously prepare wasm: ${d}`),E(d)}}+async function va(a){var b=sa;if(!u&&!fa(b)&&!ba)try{var c=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(c,a)}catch(d){t(`wasm streaming compile failed: ${d}`),t("falling back to ArrayBuffer instantiation")}return ua(b,a)}class wa{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}}+var x,C,ra,w,pa,qa,D,z,xa=a=>{for(;0<a.length;)a.shift()(e)},ya=[],za=[],Aa=()=>{var a=e.preRun.shift();za.push(a)},Ba=!0,G=()=>{var a=C[+F>>2];F+=4;return a},Ca=(a,b)=>{for(var c=0,d=a.length-1;0<=d;d--){var f=a[d];"."===f?a.splice(d,1):".."===f?(a.splice(d,1),c++):c&&(a.splice(d,1),c--)}if(b)for(;c;c--)a.unshift("..");return a},H=a=>{var b="/"===a.charAt(0),c="/"===a.slice(-1);(a=Ca(a.split("/").filter(d=>!!d),!b).join("/"))||b||(a=".");a&&c&&(a+="/");return(b?"/":"")+a},Da=a=>{var b=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1);+a=b[0];b=b[1];if(!a&&!b)return".";b&&=b.slice(0,-1);return a+b},I=a=>a&&a.match(/([^\/]+|\/)\/*$/)[1],Ea=(a,b)=>H(a+"/"+b),Fa=()=>{if(ba){var a=require("node:crypto");return b=>a.randomFillSync(b)}return b=>(crypto.getRandomValues(b),0)},Ga=a=>(Ga=Fa())(a),Ha=(...a)=>{for(var b="",c=!1,d=a.length-1;-1<=d&&!c;d--){c=0<=d?a[d]:J.cwd();if("string"!=typeof c)throw new TypeError("Arguments to path.resolve must be strings");if(!c)return"";b=c+"/"+b;c="/"===c.charAt(0)}b=Ca(b.split("/").filter(f=>!!f),!c).join("/");+return(c?"/":"")+b||"."},Ia=(a,b)=>{function c(h){for(var m=0;m<h.length&&""===h[m];m++);for(var q=h.length-1;0<=q&&""===h[q];q--);return m>q?[]:h.slice(m,q-m+1)}a=Ha(a).slice(1);b=Ha(b).slice(1);a=c(a.split("/"));b=c(b.split("/"));for(var d=Math.min(a.length,b.length),f=d,g=0;g<d;g++)if(a[g]!==b[g]){f=g;break}d=[];for(g=f;g<a.length;g++)d.push("..");d=d.concat(b.slice(f));return d.join("/")},Ja=globalThis.TextDecoder&&new TextDecoder,K=(a,b=0)=>{var c=b;for(var d=c+void 0;a[c]&&!(c>=d);)++c;if(16<+c-b&&a.buffer&&Ja)return Ja.decode(a.subarray(b,c));for(d="";b<c;){var f=a[b++];if(f&128){var g=a[b++]&63;if(192==(f&224))d+=String.fromCharCode((f&31)<<6|g);else{var h=a[b++]&63;f=224==(f&240)?(f&15)<<12|g<<6|h:(f&7)<<18|g<<12|h<<6|a[b++]&63;65536>f?d+=String.fromCharCode(f):(f-=65536,d+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else d+=String.fromCharCode(f)}return d},Ka=[],La=a=>{for(var b=0,c=0;c<a.length;++c){var d=a.charCodeAt(c);127>=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=+3}return b},Ma=(a,b,c,d)=>{if(!(0<d))return 0;var f=c;d=c+d-1;for(var g=0;g<a.length;++g){var h=a.codePointAt(g);if(127>=h){if(c>=d)break;b[c++]=h}else if(2047>=h){if(c+1>=d)break;b[c++]=192|h>>6;b[c++]=128|h&63}else if(65535>=h){if(c+2>=d)break;b[c++]=224|h>>12;b[c++]=128|h>>6&63;b[c++]=128|h&63}else{if(c+3>=d)break;b[c++]=240|h>>18;b[c++]=128|h>>12&63;b[c++]=128|h>>6&63;b[c++]=128|h&63;g++}}b[c]=0;return c-f},Na=a=>{var b=Array(La(a)+1);a=Ma(a,b,0,b.length);b.length=a;return b},Oa=[];+function Pa(a,b){Oa[a]={input:[],output:[],H:b};Qa(a,Ra)}+var Ra={open(a){var b=Oa[a.node.rdev];if(!b)throw new J.g(43);a.tty=b;a.seekable=!1},close(a){a.tty.H.fsync(a.tty)},fsync(a){a.tty.H.fsync(a.tty)},read(a,b,c,d){if(!a.tty||!a.tty.H.fa)throw new J.g(60);for(var f=0,g=0;g<d;g++){try{var h=a.tty.H.fa(a.tty)}catch(m){throw new J.g(29);}if(void 0===h&&0===f)throw new J.g(6);if(null===h||void 0===h)break;f++;b[c+g]=h}f&&(a.node.atime=Date.now());return f},write(a,b,c,d){if(!a.tty||!a.tty.H.$)throw new J.g(60);try{for(var f=0;f<d;f++)a.tty.H.$(a.tty,b[c++f])}catch(g){throw new J.g(29);}d&&(a.node.mtime=a.node.ctime=Date.now());return f}},Sa={fa(){a:{if(!Ka.length){var a=null;if(ba){var b=Buffer.alloc(256),c=0,d=process.stdin.fd;try{c=fs.readSync(d,b,0,256)}catch(f){if(f.toString().includes("EOF"))c=0;else throw f;}0<c&&(a=b.slice(0,c).toString("utf-8"))}else globalThis.window?.prompt&&(a=window.prompt("Input: "),null!==a&&(a+="\n"));if(!a){a=null;break a}Ka=Na(a)}a=Ka.shift()}return a},$(a,b){null===b||10===b?(ha(K(a.output)),a.output=[]):0!=b&&a.output.push(b)},+fsync(a){0<a.output?.length&&(ha(K(a.output)),a.output=[])},wa(){return{La:25856,Na:5,Ka:191,Ma:35387,Ja:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},xa(){return 0},ya(){return[24,80]}},Ta={$(a,b){null===b||10===b?(t(K(a.output)),a.output=[]):0!=b&&a.output.push(b)},fsync(a){0<a.output?.length&&(t(K(a.output)),a.output=[])}},L={C:null,l(){return L.createNode(null,"/",16895,0)},createNode(a,b,c,d){if(24576===(c&61440)||J.isFIFO(c))throw new J.g(63);L.C||(L.C={dir:{node:{v:L.h.v,+B:L.h.B,lookup:L.h.lookup,F:L.h.F,rename:L.h.rename,unlink:L.h.unlink,rmdir:L.h.rmdir,readdir:L.h.readdir,symlink:L.h.symlink},stream:{o:L.i.o}},file:{node:{v:L.h.v,B:L.h.B},stream:{o:L.i.o,read:L.i.read,write:L.i.write,L:L.i.L,N:L.i.N}},link:{node:{v:L.h.v,B:L.h.B,readlink:L.h.readlink},stream:{}},aa:{node:{v:L.h.v,B:L.h.B},stream:J.qa}});c=J.createNode(a,b,c,d);M(c.mode)?(c.h=L.C.dir.node,c.i=L.C.dir.stream,c.j={}):J.isFile(c.mode)?(c.h=L.C.file.node,c.i=L.C.file.stream,c.m=0,c.j=L.ra??(L.ra=new Uint8Array(0))):+40960===(c.mode&61440)?(c.h=L.C.link.node,c.i=L.C.link.stream):8192===(c.mode&61440)&&(c.h=L.C.aa.node,c.i=L.C.aa.stream);c.atime=c.mtime=c.ctime=Date.now();a&&(a.j[b]=c,a.atime=a.mtime=a.ctime=c.atime);return c},h:{v(a){var b={};b.dev=8192===(a.mode&61440)?a.id:1;b.ino=a.id;b.mode=a.mode;b.nlink=1;b.uid=0;b.gid=0;b.rdev=a.rdev;M(a.mode)?b.size=4096:J.isFile(a.mode)?b.size=a.m:40960===(a.mode&61440)?b.size=a.link.length:b.size=0;b.atime=new Date(a.atime);b.mtime=new Date(a.mtime);b.ctime=new Date(a.ctime);+b.blksize=4096;b.blocks=Math.ceil(b.size/b.blksize);return b},B(a,b){for(var c of["mode","atime","mtime","ctime"])null!=b[c]&&(a[c]=b[c]);void 0!==b.size&&(b=b.size,a.m!=b&&(c=a.j,a.j=new Uint8Array(b),a.j.set(c.subarray(0,Math.min(b,a.m))),a.m=b))},lookup(){L.R||(L.R=new J.g(44),L.R.stack="<generic error, no stack>");throw L.R;},F(a,b,c,d){return L.createNode(a,b,c,d)},rename(a,b,c){try{var d=N(b,c)}catch(g){}if(d){if(M(a.mode))for(var f in d.j)throw new J.g(55);Q(d)}delete a.parent.j[a.name];b.j[c]=+a;a.name=c;b.ctime=b.mtime=a.parent.ctime=a.parent.mtime=Date.now()},unlink(a,b){delete a.j[b];a.ctime=a.mtime=Date.now()},rmdir(a,b){var c=N(a,b),d;for(d in c.j)throw new J.g(55);delete a.j[b];a.ctime=a.mtime=Date.now()},readdir(a){return[".","..",...Object.keys(a.j)]},symlink(a,b,c){a=L.createNode(a,b,41471,0);a.link=c;return a},readlink(a){if(40960!==(a.mode&61440))throw new J.g(28);return a.link}},i:{read(a,b,c,d,f){if(f>=a.node.m)return 0;d=Math.min(a.node.m-f,d);b.set(a.node.j.subarray(f,f++d),c);return d},write(a,b,c,d,f,g){b.buffer===w.buffer&&(g=!1);if(!d)return 0;a=a.node;a.mtime=a.ctime=Date.now();if(g)a.j=b.subarray(c,c+d),a.m=d;else if(0===a.m&&0===f)a.j=b.slice(c,c+d),a.m=d;else{g=f+d;var h=a.j.length;h>=g||(g=Math.max(g,h*(1048576>h?2:1.125)>>>0),h&&(g=Math.max(g,256)),h=a.j.subarray(0,a.m),a.j=new Uint8Array(g),a.j.set(h));a.j.set(b.subarray(c,c+d),f);a.m=Math.max(a.m,f+d)}return d},o(a,b,c){1===c?b+=a.position:2===c&&J.isFile(a.node.mode)&&(b+=a.node.m);if(0>b)throw new J.g(28);+return b},L(a,b,c,d,f){if(!J.isFile(a.node.mode))throw new J.g(43);a=a.node.j;if(f&2||a.buffer!==w.buffer){d=!0;E();f=void 0;if(!f)throw new J.g(48);if(a){if(0<c||c+b<a.length)a.subarray?a=a.subarray(c,c+b):a=Array.prototype.slice.call(a,c,c+b);w.set(a,f)}}else d=!1,f=a.byteOffset;return{bb:f,Fa:d}},N(a,b,c,d){L.i.write(a,b,0,d,c,!1);return 0}}},Ua=a=>{"string"==typeof a&&(a=Na(a));a.subarray||(a=new Uint8Array(a));return a},Va=(a,b)=>{var c=0;a&&(c|=365);b&&(c|=146);return c},Wa=async a=>{a=await ea(a);+return new Uint8Array(a)},R=0,S=null,Xa=[],Za=async(a,b)=>{"undefined"!=typeof Browser&&Ya();for(var c of Xa)if(c.canHandle(b))return c.handle(a,b);return a},$a=async(a,b,c,d,f,g,h,m)=>{var q=b?Ha(H(a+"/"+b)):a;R++;e.monitorRunDependencies?.(R);try{var k=c;"string"==typeof c&&(k=await Wa(c));k=await Za(k,q);m?.();if(!g){c=b;a&&(a="string"==typeof a?a:T(a),c=b?H(a+"/"+b):a);var n=Va(d,f),r=J.create(c,n);if(k){k=Ua(k);J.chmod(r,n|146);var B=J.open(r,577);J.write(B,k,0,k.length,0,h);J.close(B);J.chmod(r,+n)}}}finally{R--,e.monitorRunDependencies?.(R),0==R&&S&&(b=S,S=null,b())}};function Ya(){var a,b,c;J.V=!0;a??=e.stdin;b??=e.stdout;c??=e.stderr;a?J.I("/dev","stdin",a):J.symlink("/dev/tty","/dev/stdin");b?J.I("/dev","stdout",null,b):J.symlink("/dev/tty","/dev/stdout");c?J.I("/dev","stderr",null,c):J.symlink("/dev/tty1","/dev/stderr");J.open("/dev/stdin",0);J.open("/dev/stdout",1);J.open("/dev/stderr",1)}function Qa(a,b){J.da[a]={i:b}}function M(a){return 16384===(a&61440)}+function N(a,b){var c=M(a.mode)?(c=U(a,"x"))?c:a.h.lookup?0:2:54;if(c)throw new J.g(c);for(c=J.G[ab(a.id,b)];c;c=c.K){var d=c.name;if(c.parent.id===a.id&&d===b)return c}return J.lookup(a,b)}function Q(a){var b=ab(a.parent.id,a.name);if(J.G[b]===a)J.G[b]=a.K;else for(b=J.G[b];b;){if(b.K===a){b.K=a.K;break}b=b.K}}+function V(a,b={}){if(!a)throw new J.g(44);b.O??(b.O=!0);"/"===a.charAt(0)||(a=J.cwd()+"/"+a);var c=0;a:for(;40>c;c++){a=a.split("/").filter(m=>!!m);for(var d=J.root,f="/",g=0;g<a.length;g++){var h=g===a.length-1;if(h&&b.parent)break;if("."!==a[g])if(".."===a[g])if(f=Da(f),J.X(d)){a=f+"/"+a.slice(g+1).join("/");c--;continue a}else d=d.parent;else{f=H(f+"/"+a[g]);try{d=N(d,a[g])}catch(m){if(44===m?.s&&h&&b.Ba)return{path:f};throw m;}!d.A||h&&!b.O||(d=d.A.root);if(40960===(d.mode&61440)&&(!h||b.u)){if(!d.h.readlink)throw new J.g(52);+d=d.h.readlink(d);"/"===d.charAt(0)||(d=Da(f)+"/"+d);a=d+"/"+a.slice(g+1).join("/");continue a}}}return{path:f,node:d}}throw new J.g(32);}function T(a){for(var b;;){if(J.X(a))return a=a.l.ka,b?"/"!==a[a.length-1]?`${a}/${b}`:a+b:a;b=b?`${a.name}/${b}`:a.name;a=a.parent}}function ab(a,b){for(var c=0,d=0;d<b.length;d++)c=(c<<5)-c+b.charCodeAt(d)|0;return(a+c>>>0)%J.G.length}function bb(a){var b=ab(a.parent.id,a.name);a.K=J.G[b];J.G[b]=a}+function U(a,b){return J.ga?0:b.includes("r")&&!(a.mode&292)||b.includes("w")&&!(a.mode&146)||b.includes("x")&&!(a.mode&73)?2:0}function cb(a,b){if(!M(a.mode))return 54;try{return N(a,b),20}catch(c){}return U(a,"wx")}function db(a,b,c){try{var d=N(a,b)}catch(f){return f.s}if(a=U(a,"wx"))return a;if(c){if(!M(d.mode))return 54;if(J.X(d)||T(d)===J.cwd())return 10}else if(M(d.mode))return 31;return 0}function W(a,b){if(!a)throw new J.g(b);return a}+function Y(a){a=J.va(a);if(!a)throw new J.g(8);return a}function eb(a,b=-1){a=Object.assign(new J.oa,a);if(-1==b)a:{for(b=0;b<=J.pa;b++)if(!J.streams[b])break a;throw new J.g(33);}a.fd=b;return J.streams[b]=a}function fb(a,b=-1){a=eb(a,b);a.i?.Sa?.(a);return a}function gb(a,b,c){var d=a?.i.B;a=d?a:b;d??=b.h.B;W(d,63);d(a,c)}function hb(a){var b=[];for(a=[a];a.length;){var c=a.pop();b.push(c);a.push(...c.M)}return b}+function ib(a){var b={Ia:4096,Va:4096,blocks:1E6,Ha:5E5,Ga:5E5,files:J.Z,Ta:J.Z-1,Wa:42,flags:2,$a:255};a.h.la&&Object.assign(b,a.h.la(a.l.Da.root));return b}function jb(a,b,c){"undefined"==typeof c&&(c=b,b=438);return J.F(a,b|8192,c)}function kb(a,b,c,d){gb(a,b,{mode:c&4095|b.mode&-4096,ctime:Date.now(),ea:d})}function lb(a,b,c){if(M(b.mode))throw new J.g(31);if(!J.isFile(b.mode))throw new J.g(28);var d=U(b,"w");if(d)throw new J.g(d);gb(a,b,{size:c,timestamp:Date.now()})}+function mb(a,b,c,d){a="string"==typeof a?a:T(a);b=H(a+"/"+b);return J.create(b,Va(c,d))}function nb(a){if(!(a.za||a.Aa||a.link||a.j))if(globalThis.XMLHttpRequest)E("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");else try{a.j=p(a.url)}catch(b){throw new J.g(29);}}+var J={root:null,M:[],da:{},streams:[],Z:1,G:null,ba:"/",V:!1,ga:!0,ta:null,P:0,g:class{name="ErrnoError";constructor(a){this.s=a}},oa:class{D={};node=null;get object(){return this.node}set object(a){this.node=a}get flags(){return this.D.flags}set flags(a){this.D.flags=a}get position(){return this.D.position}set position(a){this.D.position=a}},na:class{h={};i={};A=null;constructor(a,b,c,d){a||=this;this.parent=a;this.l=a.l;this.id=J.Z++;this.name=b;this.mode=c;this.rdev=d;this.atime=this.mtime=this.ctime=+Date.now()}get read(){return 365===(this.mode&365)}set read(a){a?this.mode|=365:this.mode&=-366}get write(){return 146===(this.mode&146)}set write(a){a?this.mode|=146:this.mode&=-147}get Aa(){return M(this.mode)}get za(){return 8192===(this.mode&61440)}},createNode(a,b,c,d){a=new J.na(a,b,c,d);bb(a);return a},X(a){return a===a.parent},isFile(a){return 32768===(a&61440)},isFIFO(a){return 4096===(a&61440)},isSocket(a){return 49152===(a&49152)},pa:4096,va:a=>J.streams[a],qa:{open(a){a.i=J.ua(a.node.rdev).i;+a.i.open?.(a)},o(){throw new J.g(70);}},Y:a=>a>>8,Ya:a=>a&255,J:(a,b)=>a<<8|b,ua:a=>J.da[a],ma(a,b){function c(m){J.P--;return b(m)}function d(m){if(m){if(!d.sa)return d.sa=!0,c(m)}else++g>=f.length&&c(null)}"function"==typeof a&&(b=a,a=!1);J.P++;1<J.P&&t(`warning: ${J.P} FS.syncfs operations in flight at once, probably just doing extra work`);var f=hb(J.root.l),g=0,h;for(h of f)h.type.ma?h.type.ma(h,a,d):d(null)},l(a,b,c){var d="/"===c;if(d&&J.root)throw new J.g(10);if(!d&&c){var f=V(c,{O:!1});c=+f.path;f=f.node;if(f.A)throw new J.g(10);if(!M(f.mode))throw new J.g(54);}b={type:a,Da:b,ka:c,M:[]};a=a.l(b);a.l=b;b.root=a;d?J.root=a:f&&(f.A=b,f.l&&f.l.M.push(b));return a},gb(a){a=V(a,{O:!1});if(!a.node.A)throw new J.g(28);a=a.node;var b=a.A,c=hb(b);for([,f]of Object.entries(J.G))for(;f;){var d=f.K;c.includes(f.l)&&Q(f);var f=d}a.A=null;a.l.M.splice(a.l.M.indexOf(b),1)},lookup(a,b){return a.h.lookup(a,b)},F(a,b,c){var d=V(a,{parent:!0}).node;a=I(a);if(!a)throw new J.g(28);if("."===a||".."===a)throw new J.g(20);+var f=cb(d,a);if(f)throw new J.g(f);if(!d.h.F)throw new J.g(63);return d.h.F(d,a,b,c)},la(a){return ib(V(a,{u:!0}).node)},eb(a){return ib(a.node)},create(a,b=438){return J.F(a,b&4095|32768,0)},mkdir(a,b=511){return J.F(a,b&1023|16384,0)},Za(a,b){var c=a.split("/"),d="",f;for(f of c)if(f){if(d||"/"===a.charAt(0))d+="/";d+=f;try{J.mkdir(d,b)}catch(g){if(20!=g.s)throw g;}}},symlink(a,b){if(!Ha(a))throw new J.g(44);var c=V(b,{parent:!0}).node;if(!c)throw new J.g(44);b=I(b);var d=cb(c,b);if(d)throw new J.g(d);+if(!c.h.symlink)throw new J.g(63);return c.h.symlink(c,b,a)},rename(a,b){var c=Da(a),d=Da(b),f=I(a),g=I(b);var h=V(a,{parent:!0});var m=h.node;h=V(b,{parent:!0});h=h.node;if(!m||!h)throw new J.g(44);if(m.l!==h.l)throw new J.g(75);var q=N(m,f);a=Ia(a,d);if("."!==a.charAt(0))throw new J.g(28);a=Ia(b,c);if("."!==a.charAt(0))throw new J.g(55);try{var k=N(h,g)}catch(n){}if(q!==k){b=M(q.mode);if(f=db(m,f,b))throw new J.g(f);if(f=k?db(h,g,b):cb(h,g))throw new J.g(f);if(!m.h.rename)throw new J.g(63);if(q.A||+k&&k.A)throw new J.g(10);if(h!==m&&(f=U(m,"w")))throw new J.g(f);Q(q);try{m.h.rename(q,h,g),q.parent=h}catch(n){throw n;}finally{bb(q)}}},rmdir(a){var b=V(a,{parent:!0}).node;a=I(a);var c=N(b,a),d=db(b,a,!0);if(d)throw new J.g(d);if(!b.h.rmdir)throw new J.g(63);if(c.A)throw new J.g(10);b.h.rmdir(b,a);Q(c)},readdir(a){a=V(a,{u:!0}).node;return W(a.h.readdir,54)(a)},unlink(a){var b=V(a,{parent:!0}).node;if(!b)throw new J.g(44);a=I(a);var c=N(b,a),d=db(b,a,!1);if(d)throw new J.g(d);if(!b.h.unlink)throw new J.g(63);+if(c.A)throw new J.g(10);b.h.unlink(b,a);Q(c)},readlink(a){a=V(a).node;if(!a)throw new J.g(44);if(!a.h.readlink)throw new J.g(28);return a.h.readlink(a)},stat(a,b){a=V(a,{u:!b}).node;return W(a.h.v,63)(a)},fstat(a){var b=Y(a);a=b.node;var c=b.i.v;b=c?b:a;c??=a.h.v;W(c,63);return c(b)},lstat(a){return J.stat(a,!0)},chmod(a,b,c){a="string"==typeof a?V(a,{u:!c}).node:a;kb(null,a,b,c)},lchmod(a,b){J.chmod(a,b,!0)},fchmod(a,b){a=Y(a);kb(a,a.node,b,!1)},chown(a,b,c,d){a="string"==typeof a?V(a,{u:!d}).node:+a;gb(null,a,{timestamp:Date.now(),ea:d})},lchown(a,b,c){J.chown(a,b,c,!0)},fchown(a){a=Y(a);gb(a,a.node,{timestamp:Date.now(),ea:!1})},truncate(a,b){if(0>b)throw new J.g(28);a="string"==typeof a?V(a,{u:!0}).node:a;lb(null,a,b)},Xa(a,b){a=Y(a);if(0>b||0===(a.flags&2097155))throw new J.g(28);lb(a,a.node,b)},hb(a,b,c){a=V(a,{u:!0}).node;W(a.h.B,63)(a,{atime:b,mtime:c})},open(a,b,c=438){if(""===a)throw new J.g(44);if("string"==typeof b){var d={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[b];if("undefined"==+typeof d)throw Error(`Unknown file open mode: ${b}`);b=d}c=b&64?c&4095|32768:0;if("object"==typeof a)d=a;else{var f=a.endsWith("/");var g=V(a,{u:!(b&131072),Ba:!0});d=g.node;a=g.path}g=!1;if(b&64)if(d){if(b&128)throw new J.g(20);}else{if(f)throw new J.g(31);d=J.F(a,c|511,0);g=!0}if(!d)throw new J.g(44);8192===(d.mode&61440)&&(b&=-513);if(b&65536&&!M(d.mode))throw new J.g(54);if(!g&&(d?40960===(d.mode&61440)?f=32:(f=["r","w","rw"][b&3],b&512&&(f+="w"),f=M(d.mode)&&("r"!==f||b&576)?31:U(d,f)):f=44,+f))throw new J.g(f);b&512&&!g&&J.truncate(d,0);b&=-131713;b=eb({node:d,path:T(d),flags:b,seekable:!0,position:0,i:d.i,Ea:[],error:!1});b.i.open&&b.i.open(b);g&&J.chmod(d,c&511);return b},close(a){if(null===a.fd)throw new J.g(8);a.S&&(a.S=null);try{a.i.close&&a.i.close(a)}catch(b){throw b;}finally{J.streams[a.fd]=null}a.fd=null},o(a,b,c){if(null===a.fd)throw new J.g(8);if(!a.seekable||!a.i.o)throw new J.g(70);if(0!=c&&1!=c&&2!=c)throw new J.g(28);a.position=a.i.o(a,b,c);a.Ea=[];return a.position},+read(a,b,c,d,f){if(0>d||0>f)throw new J.g(28);if(null===a.fd)throw new J.g(8);if(1===(a.flags&2097155))throw new J.g(8);if(M(a.node.mode))throw new J.g(31);if(!a.i.read)throw new J.g(28);var g="undefined"!=typeof f;if(!g)f=a.position;else if(!a.seekable)throw new J.g(70);b=a.i.read(a,b,c,d,f);g||(a.position+=b);return b},write(a,b,c,d,f,g){if(0>d||0>f)throw new J.g(28);if(null===a.fd)throw new J.g(8);if(0===(a.flags&2097155))throw new J.g(8);if(M(a.node.mode))throw new J.g(31);if(!a.i.write)throw new J.g(28);+a.seekable&&a.flags&1024&&J.o(a,0,2);var h="undefined"!=typeof f;if(!h)f=a.position;else if(!a.seekable)throw new J.g(70);b=a.i.write(a,b,c,d,f,g);h||(a.position+=b);return b},L(a,b,c,d,f){if(0!==(d&2)&&0===(f&2)&&2!==(a.flags&2097155))throw new J.g(2);if(1===(a.flags&2097155))throw new J.g(2);if(!a.i.L)throw new J.g(43);if(!b)throw new J.g(28);return a.i.L(a,b,c,d,f)},N(a,b,c,d,f){return a.i.N?a.i.N(a,b,c,d,f):0},W(a,b,c){if(!a.i.W)throw new J.g(59);return a.i.W(a,b,c)},readFile(a,b={}){b.flags=+b.flags||0;b.encoding=b.encoding||"binary";"utf8"!==b.encoding&&"binary"!==b.encoding&&E(`Invalid encoding type "${b.encoding}"`);var c=J.open(a,b.flags);a=J.stat(a).size;var d=new Uint8Array(a);J.read(c,d,0,a,0);"utf8"===b.encoding&&(d=K(d));J.close(c);return d},writeFile(a,b,c={}){c.flags=c.flags||577;a=J.open(a,c.flags,c.mode);b=Ua(b);J.write(a,b,0,b.byteLength,void 0,c.Oa);J.close(a)},cwd:()=>J.ba,chdir(a){a=V(a,{u:!0});if(null===a.node)throw new J.g(44);if(!M(a.node.mode))throw new J.g(54);var b=+U(a.node,"x");if(b)throw new J.g(b);J.ba=a.path},cb(){J.V=!1;for(var a of J.streams)a&&J.close(a)},Ua(a,b){try{var c=V(a,{u:!b});a=c.path}catch(g){}var d=!1,f=null;try{c=V(a,{parent:!0}),I(a),c=V(a,{u:!b}),d=!0,f=c.node}catch(g){}return d?f:null},Qa(a,b){a="string"==typeof a?a:T(a);for(b=b.split("/").reverse();b.length;){var c=b.pop();if(c){var d=H(a+"/"+c);try{J.mkdir(d)}catch(f){if(20!=f.s)throw f;}a=d}}return d},I(a,b,c,d){a=Ea("string"==typeof a?a:T(a),b);b=Va(!!c,!!d);var f;(f=J.I).Y??(f.Y=64);+f=J.J(J.I.Y++,0);Qa(f,{open(g){g.seekable=!1},close(){d?.buffer?.length&&d(10)},read(g,h,m,q){for(var k=0,n=0;n<q;n++){try{var r=c()}catch(B){throw new J.g(29);}if(void 0===r&&0===k)throw new J.g(6);if(null===r||void 0===r)break;k++;h[m+n]=r}k&&(g.node.atime=Date.now());return k},write(g,h,m,q){for(var k=0;k<q;k++)try{d(h[m+k])}catch(n){throw new J.g(29);}q&&(g.node.mtime=g.node.ctime=Date.now());return k}});return jb(a,b,f)},Pa(a,b,c,d,f){class g{U=!1;D=[];T=void 0;ia=0;ha=0;get(k){if(!(k>this.length-+1||0>k)){var n=k%this.chunkSize;return this.T(k/this.chunkSize|0)[n]}}Ca(k){this.T=k}ja(){var k=new XMLHttpRequest;k.open("HEAD",c,!1);k.send(null);200<=k.status&&300>k.status||304===k.status||E("Couldn't load "+c+". Status: "+k.status);var n=Number(k.getResponseHeader("Content-length")),r,B=(r=k.getResponseHeader("Accept-Ranges"))&&"bytes"===r;k=(r=k.getResponseHeader("Content-Encoding"))&&"gzip"===r;var A=1048576;B||(A=n);var v=this;v.Ca(O=>{var X=O*A,P=(O+1)*A-1;P=Math.min(P,n-1);if("undefined"==+typeof v.D[O]){var yb=v.D;X>P&&E("invalid range ("+X+", "+P+") or no bytes requested!");P>n-1&&E("only "+n+" bytes available! programmer error!");var y=new XMLHttpRequest;y.open("GET",c,!1);n!==A&&y.setRequestHeader("Range","bytes="+X+"-"+P);y.responseType="arraybuffer";y.overrideMimeType&&y.overrideMimeType("text/plain; charset=x-user-defined");y.send(null);200<=y.status&&300>y.status||304===y.status||E("Couldn't load "+c+". Status: "+y.status);X=void 0!==y.response?new Uint8Array(y.response||[]):+Na(y.responseText||"");yb[O]=X}"undefined"==typeof v.D[O]&&E("doXHR failed!");return v.D[O]});if(k||!n)A=n=1,A=n=this.T(0).length,ha("LazyFiles on gzip forces download of the whole file when length is accessed");this.ia=n;this.ha=A;this.U=!0}get length(){this.U||this.ja();return this.ia}get chunkSize(){this.U||this.ja();return this.ha}}if(globalThis.XMLHttpRequest){l||E("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var h=new g;+var m=void 0}else m=c,h=void 0;var q=mb(a,b,d,f);h?q.j=h:m&&(q.j=null,q.url=m);Object.defineProperties(q,{m:{get:function(){return this.j.length}}});a={};for(const [k,n]of Object.entries(q.i))a[k]=(...r)=>{nb(q);return n(...r)};a.read=(k,n,r,B,A)=>{nb(q);k=k.node.j;if(A>=k.length)n=0;else{B=Math.min(k.length-A,B);if(k.slice)for(var v=0;v<B;v++)n[r+v]=k[A+v];else for(v=0;v<B;v++)n[r+v]=k.get(A+v);n=B}return n};a.L=()=>{nb(q);E();throw new J.g(48);};q.i=a;return q}},F=void 0,ob=0,Z={},pb=a=>{ja=a;Ba||+0<ob||(e.onExit?.(a),ia=!0);ca(a,new wa(a))},qb=a=>{if(!ia)try{a()}catch(b){b instanceof wa||"unwind"==b||ca(1,b)}finally{if(!(Ba||0<ob))try{ja=a=ja,pb(a)}catch(b){b instanceof wa||"unwind"==b||ca(1,b)}}},ub=(a,b,c,d)=>{var f={string:k=>{var n=0;if(null!==k&&void 0!==k&&0!==k){n=La(k)+1;var r=rb(n);Ma(k,z,r,n);n=r}return n},array:k=>{var n=rb(k.length);w.set(k,n);return n}};a=e["_"+a];var g=[],h=0;if(d)for(var m=0;m<d.length;m++){var q=f[c[m]];q?(0===h&&(h=sb()),g[m]=q(d[m])):g[m]=d[m]}c=a(...g);+return c=function(k){0!==h&&tb(h);return"string"===b?k?K(z,k):"":"boolean"===b?!!k:k}(c)};J.Ra=(a,b,c,d,f,g,h,m,q,k)=>{$a(a,b,c,d,f,m,q,k).then(g).catch(h)};J.ab=$a;J.G=Array(4096);J.l(L,{},"/");J.mkdir("/tmp");J.mkdir("/home");J.mkdir("/home/web_user");+(function(){J.mkdir("/dev");Qa(J.J(1,3),{read:()=>0,write:(d,f,g,h)=>h,o:()=>0});jb("/dev/null",J.J(1,3));Pa(J.J(5,0),Sa);Pa(J.J(6,0),Ta);jb("/dev/tty",J.J(5,0));jb("/dev/tty1",J.J(6,0));var a=new Uint8Array(1024),b=0,c=()=>{0===b&&(Ga(a),b=a.byteLength);return a[--b]};J.I("/dev","random",c);J.I("/dev","urandom",c);J.mkdir("/dev/shm");J.mkdir("/dev/shm/tmp")})();+(function(){J.mkdir("/proc");var a=J.mkdir("/proc/self");J.mkdir("/proc/self/fd");J.l({l(){var b=J.createNode(a,"fd",16895,73);b.i={o:L.i.o};b.h={lookup(c,d){c=+d;var f=Y(c);c={parent:null,l:{ka:"fake"},h:{readlink:()=>f.path},id:c+1};return c.parent=c},readdir(){return Array.from(J.streams.entries()).filter(([,c])=>c).map(([c])=>c.toString())}};return b}},{},"/proc/self/fd")})();J.ta={MEMFS:L};e.noExitRuntime&&(Ba=e.noExitRuntime);e.preloadPlugins&&(Xa=e.preloadPlugins);e.print&&(ha=e.print);+e.printErr&&(t=e.printErr);e.wasmBinary&&(u=e.wasmBinary);if(e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.shift()();e.ccall=ub;e.cwrap=(a,b,c,d)=>{var f=!c||c.every(g=>"number"===g||"boolean"===g);return"string"!==b&&f&&!d?e["_"+a]:(...g)=>ub(a,b,c,g,d)};+e.setValue=function(a,b,c="i8"){c.endsWith("*")&&(c="*");switch(c){case "i1":w[a]=b;break;case "i8":w[a]=b;break;case "i16":x[a>>1]=b;break;case "i32":C[a>>2]=b;break;case "i64":ra[a>>3]=BigInt(b);break;case "float":pa[a>>2]=b;break;case "double":qa[a>>3]=b;break;case "*":D[a>>2]=b;break;default:E(`invalid type for setValue: ${c}`)}};+e.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return w[a];case "i8":return w[a];case "i16":return x[a>>1];case "i32":return C[a>>2];case "i64":return ra[a>>3];case "float":return pa[a>>2];case "double":return qa[a>>3];case "*":return D[a>>2];default:E(`invalid type for getValue: ${b}`)}};e.FS=J;+var vb,tb,rb,sb,oa,wb={__syscall_fcntl64:function(a,b,c){F=c;try{var d=Y(a);switch(b){case 0:var f=G();if(0>f)break;for(;J.streams[f];)f++;return fb(d,f).fd;case 1:case 2:return 0;case 3:return d.flags;case 4:return f=G(),d.flags|=f,0;case 12:return f=G(),x[f+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(g){if("undefined"==typeof J||"ErrnoError"!==g.name)throw g;return-g.s}},__syscall_ioctl:function(a,b,c){F=c;try{var d=Y(a);switch(b){case 21509:return d.tty?0:-59;case 21505:if(!d.tty)return-59;+if(d.tty.H.wa){a=[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var f=G();C[f>>2]=25856;C[f+4>>2]=5;C[f+8>>2]=191;C[f+12>>2]=35387;for(var g=0;32>g;g++)w[f+g+17]=a[g]||0}return 0;case 21510:case 21511:case 21512:return d.tty?0:-59;case 21506:case 21507:case 21508:if(!d.tty)return-59;if(d.tty.H.xa)for(f=G(),a=[],g=0;32>g;g++)a.push(w[f+g+17]);return 0;case 21519:if(!d.tty)return-59;f=G();return C[f>>2]=0;case 21520:return d.tty?-28:-59;case 21537:case 21531:return f=G(),+J.W(d,b,f);case 21523:if(!d.tty)return-59;d.tty.H.ya&&(g=[24,80],f=G(),x[f>>1]=g[0],x[f+2>>1]=g[1]);return 0;case 21524:return d.tty?0:-59;case 21515:return d.tty?0:-59;default:return-28}}catch(h){if("undefined"==typeof J||"ErrnoError"!==h.name)throw h;return-h.s}},__syscall_openat:function(a,b,c,d){F=d;try{b=b?K(z,b):"";var f=b;if("/"===f.charAt(0))b=f;else{var g=-100===a?J.cwd():Y(a).path;if(0==f.length)throw new J.g(44);b=g+"/"+f}var h=d?G():0;return J.open(b,c,h).fd}catch(m){if("undefined"==typeof J||+"ErrnoError"!==m.name)throw m;return-m.s}},_abort_js:()=>E(""),_emscripten_runtime_keepalive_clear:()=>{Ba=!1;ob=0},_setitimer_js:(a,b)=>{Z[a]&&(clearTimeout(Z[a].id),delete Z[a]);if(!b)return 0;var c=setTimeout(()=>{delete Z[a];qb(()=>vb(a,performance.now()))},b);Z[a]={id:c,fb:b};return 0},emscripten_resize_heap:a=>{var b=z.length;a>>>=0;if(2147483648<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(a,d)/65536))-oa.buffer.byteLength++65535)/65536|0;try{oa.grow(d);na();var f=1;break a}catch(g){}f=void 0}if(f)return!0}return!1},fd_close:function(a){try{var b=Y(a);J.close(b);return 0}catch(c){if("undefined"==typeof J||"ErrnoError"!==c.name)throw c;return c.s}},fd_read:function(a,b,c,d){try{a:{var f=Y(a);a=b;for(var g,h=b=0;h<c;h++){var m=D[a>>2],q=D[a+4>>2];a+=8;var k=J.read(f,w,m,q,g);if(0>k){var n=-1;break a}b+=k;if(k<q)break;"undefined"!=typeof g&&(g+=k)}n=b}D[d>>2]=n;return 0}catch(r){if("undefined"==typeof J||"ErrnoError"!==+r.name)throw r;return r.s}},fd_seek:function(a,b,c,d){b=-9007199254740992>b||9007199254740992<b?NaN:Number(b);try{if(isNaN(b))return 61;var f=Y(a);J.o(f,b,c);ra[d>>3]=BigInt(f.position);f.S&&0===b&&0===c&&(f.S=null);return 0}catch(g){if("undefined"==typeof J||"ErrnoError"!==g.name)throw g;return g.s}},fd_write:function(a,b,c,d){try{a:{var f=Y(a);a=b;for(var g,h=b=0;h<c;h++){var m=D[a>>2],q=D[a+4>>2];a+=8;var k=J.write(f,w,m,q,g);if(0>k){var n=-1;break a}b+=k;if(k<q)break;"undefined"!=typeof g&&(g+=+k)}n=b}D[d>>2]=n;return 0}catch(r){if("undefined"==typeof J||"ErrnoError"!==r.name)throw r;return r.s}},proc_exit:pb};+function xb(){function a(){e.calledRun=!0;if(!ia){ma=!0;e.noFSInit||J.V||Ya();zb.__wasm_call_ctors();J.ga=!1;ka?.(e);e.onRuntimeInitialized?.();if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var b=e.postRun.shift();ya.push(b)}xa(ya)}}if(0<R)S=xb;else{if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)Aa();xa(za);0<R?S=xb:e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1);a()},1)):a()}}+var zb;+zb=await (async function(){function a(c){c=zb=c.exports;e._detect_init=c.detect_init;e._free=c.free;e._detect_faces=c.detect_faces;e._detect_free=c.detect_free;e._malloc=c.malloc;vb=c._emscripten_timeout;tb=c._emscripten_stack_restore;rb=c._emscripten_stack_alloc;sb=c.emscripten_stack_get_current;oa=c.memory;na();return zb}var b={env:wb,wasi_snapshot_preview1:wb};if(e.instantiateWasm)return new Promise(c=>{e.instantiateWasm(b,(d,f)=>{c(a(d,f))})});sa??=e.locateFile?e.locateFile("detect.wasm",da):+da+"detect.wasm";return a((await va(b)).instance)}());xb();ma?moduleRtn=e:moduleRtn=new Promise((a,b)=>{ka=a;la=b});+;return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=FaceDetModule;module.exports.default=FaceDetModule}else if(typeof define==="function"&&define["amd"])define([],()=>FaceDetModule);diff --git a/wasm/detect.wasm b/wasm/detect.wasmnew file mode 100644index 0000000..e8e3513Binary files /dev/null and b/wasm/detect.wasm differdiff --git a/wasm/facex-sdk.d.ts b/wasm/facex-sdk.d.tsnew file mode 100644index 0000000..f950beb--- /dev/null+++ b/wasm/facex-sdk.d.ts@@ -0,0 +1,95 @@+/**+ * FaceX Browser SDK — Face recognition in WebAssembly.+ * 74 KB engine. No server. No dependencies.+ */++export interface FaceXOptions {+ /** Detection input size (default: 160) */+ detSize?: number;+ /** Cosine similarity threshold for match (default: 0.3) */+ threshold?: number;+ /** URL to detector weights (default: 'det_500m_int8.bin') */+ detWeightsUrl?: string;+ /** URL to embedder weights (default: 'edgeface_xs_fp32.bin') */+ embWeightsUrl?: string;+ /** Progress callback */+ onProgress?: (message: string) => void;+}++export interface Face {+ /** Bounding box */+ x1: number;+ y1: number;+ x2: number;+ y2: number;+ /** Detection confidence 0-1 */+ score: number;+ /** 5 keypoints as flat array [lx,ly, rx,ry, nx,ny, lmx,lmy, rmx,rmy] */+ kps: number[];+}++export interface ProcessResult {+ /** Detected faces */+ faces: Face[];+ /** 512-dim embedding for each face */+ embeddings: Float32Array[];+ /** Total processing time in ms */+ ms: number;+}++export interface VerifyResult {+ /** Whether faces match */+ match: boolean;+ /** Cosine similarity 0-1 */+ similarity: number;+ /** Detected faces */+ faces: Face[];+ /** Embedding of detected face (if any) */+ embedding?: Float32Array;+ /** Total time in ms */+ ms: number;+ /** True if no face detected */+ noFace?: boolean;+}++export interface CaptureResult {+ /** Reference embedding */+ embedding: Float32Array;+ /** Detected face */+ face: Face;+ /** Canvas with aligned 112x112 face */+ alignedCanvas: HTMLCanvasElement;+}++export declare class FaceXSDK {+ constructor(options?: FaceXOptions);++ /** Whether the SDK is loaded and ready */+ readonly ready: boolean;++ /** Load engines and weights. Call once before using. */+ load(): Promise<FaceXSDK>;++ /** Detect faces in video/image/canvas */+ detect(source: HTMLVideoElement | HTMLCanvasElement | HTMLImageElement): Face[];++ /** Compute 512-dim embedding from 112x112 face ImageData */+ embed(faceImageData: ImageData): Float32Array;++ /** Full pipeline: detect → align → embed */+ process(source: HTMLVideoElement | HTMLCanvasElement | HTMLImageElement): ProcessResult;++ /** Verify live source against reference embedding */+ verify(+ source: HTMLVideoElement | HTMLCanvasElement | HTMLImageElement,+ refEmbedding: Float32Array+ ): VerifyResult;++ /** Capture reference from current frame */+ captureReference(+ source: HTMLVideoElement | HTMLCanvasElement | HTMLImageElement+ ): CaptureResult | null;++ /** Cosine similarity between two 512-dim embeddings */+ cosSim(a: Float32Array, b: Float32Array): number;+}diff --git a/wasm/facex-sdk.js b/wasm/facex-sdk.jsnew file mode 100644index 0000000..6cceac3--- /dev/null+++ b/wasm/facex-sdk.js@@ -0,0 +1,312 @@+/*+ * facex-sdk.js — Unified FaceX browser SDK.+ *+ * Single entry point for face detection + alignment + embedding.+ *+ * Usage:+ * const fx = new FaceXSDK();+ * await fx.load();+ * const result = await fx.verify(videoElement, referenceEmbedding);+ * // { match: true, similarity: 0.87, faces: [...], ms: 17 }+ */++class FaceXSDK {+ constructor(options = {}) {+ this.detSize = options.detSize || 160;+ this.threshold = options.threshold || 0.3;+ this.detWeightsUrl = options.detWeightsUrl || 'det_500m_int8.bin';+ this.embWeightsUrl = options.embWeightsUrl || 'edgeface_xs_fp32.bin';+ this.onProgress = options.onProgress || null;++ this._det = null;+ this._fx = null;+ this._detHandle = 0;+ this._fxHandle = 0;+ this._ready = false;++ // Reusable canvases+ this._detCanvas = document.createElement('canvas');+ this._detCtx = this._detCanvas.getContext('2d', { willReadFrequently: true });+ this._cropCanvas = document.createElement('canvas');+ this._cropCanvas.width = 112;+ this._cropCanvas.height = 112;+ this._cropCtx = this._cropCanvas.getContext('2d', { willReadFrequently: true });+ this._srcCanvas = document.createElement('canvas');+ this._srcCtx = this._srcCanvas.getContext('2d', { willReadFrequently: true });+ }++ /** Load engines and weights. Call once. */+ async load() {+ // Check SIMD support+ if (!this._checkSimd()) {+ throw new Error('WebAssembly SIMD not supported. Chrome 91+, Firefox 89+, Safari 16.4+ required.');+ }++ this._progress('Loading detection engine...');+ this._det = await FaceDetModule();++ this._progress('Loading embedding engine...');+ this._fx = await FaceXModule();++ // Load weights with caching+ this._progress('Loading detector weights (670 KB)...');+ const detW = await this._loadCached(this.detWeightsUrl, 'facex_det_weights');+ this._det.FS.writeFile('/det.bin', detW);++ this._progress('Loading embedding weights (7 MB)...');+ const fxW = await this._loadCached(this.embWeightsUrl, 'facex_emb_weights');+ this._fx.FS.writeFile('/emb.bin', fxW);++ // Init engines+ const di = this._det.cwrap('detect_init', 'number', ['string']);+ this._detHandle = di('/det.bin');+ if (!this._detHandle) throw new Error('Face detector initialization failed');++ const fi = this._fx.cwrap('facex_init', 'number', ['string', 'string']);+ this._fxHandle = fi('/emb.bin', null);+ if (!this._fxHandle) throw new Error('Face embedder initialization failed');++ this._ready = true;+ this._progress('Ready');+ return this;+ }++ /** Check if SDK is loaded and ready */+ get ready() { return this._ready; }++ /**+ * Detect faces in a video/image/canvas element.+ * @returns {Array<{x1,y1,x2,y2,score,kps}>}+ */+ detect(source) {+ if (!this._ready) throw new Error('SDK not loaded. Call load() first.');+ const { pixels, W, H } = this._prepareDetInput(source);+ return this._runDetect(pixels, W, H);+ }++ /**+ * Compute 512-dim embedding from aligned 112x112 face.+ * @param {ImageData} faceImageData - 112x112 RGBA image+ * @returns {Float32Array} 512-dim embedding+ */+ embed(faceImageData) {+ if (!this._ready) throw new Error('SDK not loaded');+ return this._runEmbed(faceImageData);+ }++ /**+ * Full pipeline: detect → align → embed from video/image source.+ * @returns {{faces, embeddings, ms}}+ */+ process(source) {+ if (!this._ready) throw new Error('SDK not loaded');+ const t0 = performance.now();++ const { pixels, W, H, scale, dx, dy } = this._prepareDetInput(source);+ const rawFaces = this._runDetect(pixels, W, H);++ // Map faces back to source coordinates+ const faces = rawFaces.map(f => ({+ x1: (f.x1 - dx) / scale,+ y1: (f.y1 - dy) / scale,+ x2: (f.x2 - dx) / scale,+ y2: (f.y2 - dy) / scale,+ score: f.score,+ kps: f.kps.map((v, i) => (v - (i % 2 === 0 ? dx : dy)) / scale)+ }));++ // Align and embed each face+ const sourceW = this._srcCanvas.width;+ const sourceH = this._srcCanvas.height;+ const embeddings = faces.map(face => {+ const kps5 = [];+ for (let i = 0; i < 5; i++)+ kps5.push([face.kps[i * 2], face.kps[i * 2 + 1]]);++ const aligned = alignFace(this._srcCtx, sourceW, sourceH, kps5, this._cropCtx);+ return this._runEmbed(aligned);+ });++ return {+ faces,+ embeddings,+ ms: performance.now() - t0+ };+ }++ /**+ * Verify: compare live source against a reference embedding.+ * @returns {{match, similarity, faces, ms}}+ */+ verify(source, refEmbedding) {+ const result = this.process(source);+ if (result.embeddings.length === 0) {+ return { match: false, similarity: 0, faces: result.faces, ms: result.ms, noFace: true };+ }+ const sim = this.cosSim(result.embeddings[0], refEmbedding);+ return {+ match: sim > this.threshold,+ similarity: sim,+ faces: result.faces,+ embedding: result.embeddings[0],+ ms: result.ms+ };+ }++ /** Cosine similarity between two embeddings */+ cosSim(a, b) {+ let dot = 0, na = 0, nb = 0;+ for (let i = 0; i < 512; i++) {+ dot += a[i] * b[i];+ na += a[i] * a[i];+ nb += b[i] * b[i];+ }+ return dot / (Math.sqrt(na) * Math.sqrt(nb));+ }++ /** Capture reference embedding from current video frame */+ captureReference(source) {+ const result = this.process(source);+ if (result.embeddings.length === 0) return null;+ return {+ embedding: result.embeddings[0],+ face: result.faces[0],+ alignedCanvas: this._cropCanvas+ };+ }++ // ============ Internal methods ============++ _progress(msg) {+ if (this.onProgress) this.onProgress(msg);+ }++ _checkSimd() {+ try {+ return WebAssembly.validate(new Uint8Array([+ 0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,+ 253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11+ ]));+ } catch(e) { return false; }+ }++ async _loadCached(url, key) {+ // Try IndexedDB cache+ try {+ const db = await new Promise((res, rej) => {+ const r = indexedDB.open('facex-cache', 1);+ r.onupgradeneeded = () => r.result.createObjectStore('weights');+ r.onsuccess = () => res(r.result);+ r.onerror = () => rej(r.error);+ });+ const cached = await new Promise(res => {+ const tx = db.transaction('weights', 'readonly');+ const req = tx.objectStore('weights').get(key);+ req.onsuccess = () => res(req.result);+ req.onerror = () => res(null);+ });+ if (cached) return new Uint8Array(cached);++ // Fetch and cache+ const buf = await fetch(url).then(r => r.arrayBuffer());+ const tx = db.transaction('weights', 'readwrite');+ tx.objectStore('weights').put(buf, key);+ return new Uint8Array(buf);+ } catch(e) {+ // Fallback: no cache+ return new Uint8Array(await fetch(url).then(r => r.arrayBuffer()));+ }+ }++ _prepareDetInput(source) {+ // Draw source to srcCanvas at full res+ let w, h;+ if (source instanceof HTMLVideoElement) {+ w = source.videoWidth; h = source.videoHeight;+ } else if (source instanceof HTMLCanvasElement) {+ w = source.width; h = source.height;+ } else if (source instanceof HTMLImageElement) {+ w = source.naturalWidth; h = source.naturalHeight;+ } else {+ throw new Error('Source must be video, canvas, or image element');+ }++ this._srcCanvas.width = w;+ this._srcCanvas.height = h;+ this._srcCtx.drawImage(source, 0, 0);++ // Letterbox to detSize+ const ds = this.detSize;+ this._detCanvas.width = ds;+ this._detCanvas.height = ds;+ const scale = Math.min(ds / w, ds / h);+ const nw = Math.round(w * scale), nh = Math.round(h * scale);+ const dx = (ds - nw) / 2, dy = (ds - nh) / 2;+ this._detCtx.fillStyle = '#000';+ this._detCtx.fillRect(0, 0, ds, ds);+ this._detCtx.drawImage(source, dx, dy, nw, nh);++ const imgData = this._detCtx.getImageData(0, 0, ds, ds);+ const nPx = ds * ds;+ const pixels = new Float32Array(nPx * 3);+ for (let i = 0; i < nPx; i++) {+ pixels[i * 3] = imgData.data[i * 4] / 127.5 - 1.0;+ pixels[i * 3 + 1] = imgData.data[i * 4 + 1] / 127.5 - 1.0;+ pixels[i * 3 + 2] = imgData.data[i * 4 + 2] / 127.5 - 1.0;+ }+ return { pixels, W: ds, H: ds, scale, dx, dy };+ }++ _runDetect(pixels, W, H) {+ const nPx = W * H * 3;+ const inPtr = this._det._malloc(nPx * 4);+ this._det.HEAPF32.set(pixels, inPtr >> 2);++ const maxFaces = 10;+ const outPtr = this._det._malloc(15 * 4 * maxFaces);++ const df = this._det.cwrap('detect_faces', 'number',+ ['number', 'number', 'number', 'number', 'number', 'number']);+ const n = df(this._detHandle, inPtr, W, H, outPtr, maxFaces);++ const faces = [];+ for (let i = 0; i < n; i++) {+ const base = (outPtr >> 2) + i * 15;+ const f = this._det.HEAPF32;+ faces.push({+ x1: f[base], y1: f[base+1], x2: f[base+2], y2: f[base+3],+ score: f[base+4],+ kps: Array.from(f.subarray(base + 5, base + 15))+ });+ }++ this._det._free(inPtr);+ this._det._free(outPtr);+ return faces;+ }++ _runEmbed(imageData) {+ const N = 112 * 112 * 3;+ const inPtr = this._fx._malloc(N * 4);+ const outPtr = this._fx._malloc(512 * 4);++ const heap = this._fx.HEAPF32;+ const base = inPtr >> 2;+ const px = imageData.data;+ for (let i = 0; i < 112 * 112; i++) {+ heap[base + i * 3] = px[i * 4] / 127.5 - 1.0;+ heap[base + i * 3 + 1] = px[i * 4 + 1] / 127.5 - 1.0;+ heap[base + i * 3 + 2] = px[i * 4 + 2] / 127.5 - 1.0;+ }++ const fe = this._fx.cwrap('facex_embed', 'number', ['number', 'number', 'number']);+ fe(this._fxHandle, inPtr, outPtr);++ const emb = new Float32Array(512);+ emb.set(heap.subarray(outPtr >> 2, (outPtr >> 2) + 512));++ this._fx._free(inPtr);+ this._fx._free(outPtr);+ return emb;+ }+}diff --git a/wasm/facex.js b/wasm/facex.jsindex 89fb916..26fa954 100644--- a/wasm/facex.js+++ b/wasm/facex.js@@ -64,5 +64,5 @@ g.name)throw g;return g.s}},fd_write:function(a,b,c,d){try{a:{var f=Y(a);a=b;forfunction wb(){function a(){e.calledRun=!0;if(!ha){la=!0;e.noFSInit||J.V||Wa();yb.__wasm_call_ctors();J.ga=!1;ja?.(e);e.onRuntimeInitialized?.();if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var b=e.postRun.shift();wa.push(b)}va(wa)}}if(0<R)S=wb;else{if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)ya();va(xa);0<R?S=wb:e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1);a()},1)):a()}}var yb;yb=await (async function(){function a(c){c=yb=c.exports;e._facex_init=c.facex_init;e._free=c.free;e._facex_embed=c.facex_embed;e._facex_similarity=c.facex_similarity;e._facex_free=c.facex_free;e._facex_version=c.facex_version;e._malloc=c.malloc;tb=c._emscripten_timeout;rb=c._emscripten_stack_restore;pb=c._emscripten_stack_alloc;qb=c.emscripten_stack_get_current;ub=c.memory;c=ub.buffer;D=new Int8Array(c);z=new Int16Array(c);ua=new Uint8Array(c);new Uint16Array(c);C=new Int32Array(c);E=new Uint32Array(c);-sa=new Float32Array(c);ta=new Float64Array(c);ra=new BigInt64Array(c);new BigUint64Array(c);return yb}var b={env:vb,wasi_snapshot_preview1:vb};if(e.instantiateWasm)return new Promise(c=>{e.instantiateWasm(b,(d,f)=>{c(a(d,f))})});ma??=e.locateFile?e.locateFile("facex.wasm",ca):ca+"facex.wasm";return a((await pa(b)).instance)}());wb();la?moduleRtn=e:moduleRtn=new Promise((a,b)=>{ja=a;ka=b});+e.HEAPF32=sa=new Float32Array(c);ta=new Float64Array(c);ra=new BigInt64Array(c);new BigUint64Array(c);return yb}var b={env:vb,wasi_snapshot_preview1:vb};if(e.instantiateWasm)return new Promise(c=>{e.instantiateWasm(b,(d,f)=>{c(a(d,f))})});ma??=e.locateFile?e.locateFile("facex.wasm",ca):ca+"facex.wasm";return a((await pa(b)).instance)}());wb();la?moduleRtn=e:moduleRtn=new Promise((a,b)=>{ja=a;ka=b});;return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=FaceXModule;module.exports.default=FaceXModule}else if(typeof define==="function"&&define["amd"])define([],()=>FaceXModule);diff --git a/wasm/facex.wasm b/wasm/facex.wasmindex b064217..568010d 100644Binary files a/wasm/facex.wasm and b/wasm/facex.wasm differdiff --git a/wasm/liveness.js b/wasm/liveness.jsnew file mode 100644index 0000000..003168b--- /dev/null+++ b/wasm/liveness.js@@ -0,0 +1,140 @@+/*+ * liveness.js — Basic liveness detection using face keypoints.+ *+ * Detects:+ * 1. Face motion (frame-to-frame bbox movement)+ * 2. Blink detection (eye aspect ratio changes)+ * 3. Multiple frame consistency (not a static photo)+ *+ * Not a security-grade anti-spoofing solution — detects basic+ * photo/screen attacks but not 3D masks or deepfakes.+ */++class LivenessDetector {+ constructor(options = {}) {+ this.historySize = options.historySize || 30; // frames to track+ this.motionThreshold = options.motionThreshold || 2.0; // pixels+ this.blinkThreshold = options.blinkThreshold || 0.22; // EAR ratio++ this._history = [];+ this._blinkCount = 0;+ this._lastEAR = 1.0;+ this._wasEyeClosed = false;+ }++ /**+ * Update with new face detection.+ * @param {Object} face - {x1,y1,x2,y2,kps:[10 values]}+ * @returns {{alive: boolean, confidence: number, reason: string}}+ */+ update(face) {+ if (!face) {+ this._history = [];+ return { alive: false, confidence: 0, reason: 'No face' };+ }++ const entry = {+ cx: (face.x1 + face.x2) / 2,+ cy: (face.y1 + face.y2) / 2,+ w: face.x2 - face.x1,+ h: face.y2 - face.y1,+ ear: this._computeEAR(face.kps),+ t: Date.now()+ };++ this._history.push(entry);+ if (this._history.length > this.historySize)+ this._history.shift();++ // Need at least 10 frames+ if (this._history.length < 10) {+ return { alive: false, confidence: 0.1, reason: 'Collecting frames...' };+ }++ // Check 1: Motion — face must move slightly (not a static photo)+ const motion = this._computeMotion();+ const hasMotion = motion > this.motionThreshold;++ // Check 2: Blink detection+ this._detectBlink(entry.ear);+ const hasBlinked = this._blinkCount > 0;++ // Check 3: Size variation (breathing, micro-movements)+ const sizeVar = this._computeSizeVariation();+ const hasSizeChange = sizeVar > 0.005;++ // Compute confidence+ let confidence = 0;+ if (hasMotion) confidence += 0.35;+ if (hasBlinked) confidence += 0.40;+ if (hasSizeChange) confidence += 0.25;++ let reason;+ if (confidence >= 0.6) reason = 'Live person detected';+ else if (!hasMotion) reason = 'No motion detected — hold still and blink';+ else if (!hasBlinked) reason = 'Please blink';+ else reason = 'Analyzing...';++ return {+ alive: confidence >= 0.6,+ confidence,+ reason,+ details: { motion, blinks: this._blinkCount, sizeVar }+ };+ }++ /** Reset state */+ reset() {+ this._history = [];+ this._blinkCount = 0;+ this._lastEAR = 1.0;+ this._wasEyeClosed = false;+ }++ // ============ Internal ============++ /** Eye Aspect Ratio from 5 keypoints.+ * kps: [lex, ley, rex, rey, nx, ny, lmx, lmy, rmx, rmy]+ * EAR ≈ distance(mouth) / distance(eyes) as a proxy.+ * Real EAR needs 6 eye landmarks — we approximate from 5 points. */+ _computeEAR(kps) {+ // left eye (0,1), right eye (2,3), nose (4,5), left mouth (6,7), right mouth (8,9)+ const eyeDist = Math.sqrt((kps[2]-kps[0])**2 + (kps[3]-kps[1])**2);+ const mouthDist = Math.sqrt((kps[8]-kps[6])**2 + (kps[9]-kps[7])**2);+ const noseToEyeL = Math.sqrt((kps[4]-kps[0])**2 + (kps[5]-kps[1])**2);+ const noseToEyeR = Math.sqrt((kps[4]-kps[2])**2 + (kps[5]-kps[3])**2);++ // Use ratio of vertical to horizontal distances as EAR proxy+ if (eyeDist < 1) return 1.0;+ return (noseToEyeL + noseToEyeR) / (2 * eyeDist);+ }++ _detectBlink(ear) {+ if (ear < this.blinkThreshold && !this._wasEyeClosed) {+ this._wasEyeClosed = true;+ } else if (ear > this.blinkThreshold + 0.05 && this._wasEyeClosed) {+ this._wasEyeClosed = false;+ this._blinkCount++;+ }+ this._lastEAR = ear;+ }++ _computeMotion() {+ if (this._history.length < 2) return 0;+ let totalMotion = 0;+ for (let i = 1; i < this._history.length; i++) {+ const dx = this._history[i].cx - this._history[i-1].cx;+ const dy = this._history[i].cy - this._history[i-1].cy;+ totalMotion += Math.sqrt(dx*dx + dy*dy);+ }+ return totalMotion / (this._history.length - 1);+ }++ _computeSizeVariation() {+ if (this._history.length < 5) return 0;+ const sizes = this._history.map(h => h.w * h.h);+ const mean = sizes.reduce((a,b) => a+b) / sizes.length;+ const variance = sizes.reduce((a,s) => a + (s-mean)**2, 0) / sizes.length;+ return Math.sqrt(variance) / mean; // coefficient of variation+ }+}diff --git a/wasm/package.json b/wasm/package.jsonnew file mode 100644index 0000000..a6efac5--- /dev/null+++ b/wasm/package.json@@ -0,0 +1,36 @@+{+ "name": "facex-web",+ "version": "1.0.0",+ "description": "Face recognition in the browser. 74 KB WASM. No server, no dependencies.",+ "main": "facex-sdk.js",+ "types": "facex-sdk.d.ts",+ "files": [+ "facex-sdk.js",+ "facex-sdk.d.ts",+ "align.js",+ "detect.js",+ "detect.wasm",+ "facex.js",+ "facex.wasm"+ ],+ "keywords": [+ "face-recognition",+ "face-detection",+ "face-embedding",+ "webassembly",+ "wasm",+ "simd",+ "browser",+ "privacy",+ "zero-dependencies",+ "offline"+ ],+ "author": "Baurzhan Atinov",+ "license": "Apache-2.0",+ "homepage": "https://github.com/facex-engine/facex",+ "repository": {+ "type": "git",+ "url": "https://github.com/facex-engine/facex.git",+ "directory": "wasm"+ }+}diff --git a/wasm/simd_check.js b/wasm/simd_check.jsnew file mode 100644index 0000000..43a8a65--- /dev/null+++ b/wasm/simd_check.js@@ -0,0 +1,39 @@+/*+ * simd_check.js — Check if browser supports WebAssembly SIMD.+ * Returns true if WASM SIMD is available, false otherwise.+ */++function checkWasmSimd() {+ try {+ // Minimal WASM module that uses v128 SIMD type+ const bytes = new Uint8Array([+ 0x00, 0x61, 0x73, 0x6d, // magic+ 0x01, 0x00, 0x00, 0x00, // version+ 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7b, // type section: () -> v128+ 0x03, 0x02, 0x01, 0x00, // function section+ 0x0a, 0x0a, 0x01, 0x08, 0x00, 0xfd, 0x0c, // code section: v128.const+ 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00,+ 0x0b // end+ ]);+ return WebAssembly.validate(bytes);+ } catch (e) {+ return false;+ }+}++function checkBrowserSupport() {+ const issues = [];++ if (typeof WebAssembly === 'undefined')+ issues.push('WebAssembly not supported');+ else if (!checkWasmSimd())+ issues.push('WebAssembly SIMD not supported (Chrome 91+, Firefox 89+, Safari 16.4+ required)');++ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia)+ issues.push('Camera API not available (HTTPS required)');++ return issues;+}diff --git a/wasm/src/detect.c b/wasm/src/detect.cnew file mode 100644index 0000000..9036a16--- /dev/null+++ b/wasm/src/detect.c@@ -0,0 +1,1126 @@+/*+ * retinaface_forward_int8.c — Native C99 INT8 inference for det_500m.+ *+ * Full pipeline: image → backbone → FPN → 3 detection heads → face results.+ * Reuses FastFace kernels + new depthwise + upsample.+ *+ * See EXECUTION_MAP.md for tensor flow details.+ */++#include <stdio.h>+#include <stdlib.h>+#include <stdint.h>+#include <string.h>+#include <math.h>+#include <time.h>+#ifdef _OPENMP+#include <omp.h>+#endif+#ifdef _WIN32+#include <io.h>+#include <fcntl.h>+#endif++/* ============ Model structures ============ */++#define MAX_LAYERS 64++typedef struct {+ uint8_t type; /* 0=STD, 1=DW, 2=PW */+ uint16_t cin, cout;+ uint8_t kh, kw, sh, sw, pad;+ int8_t* w; /* INT8 weights */+ int w_size;+ float* w_scale; /* per-channel [cout] */+ float* bias; /* FP32 [cout] or NULL */+ float* act_scale; /* activation scale [cout] */+ int n_act;+ /* c8-packed GEMM data (pre-packed at load time for PW/STD layers) */+ void* packed_w; /* c8-format packed weights, or NULL for DW */+ int32_t* col_sums; /* compensation array [cout], or NULL */+ int gemm_K; /* K dimension for GEMM (Cin for PW, Cin*Kh*Kw for STD) */+} Layer;++typedef struct {+ int n_layers;+ Layer layers[MAX_LAYERS];+} Model;++/* INT8 tensor: NHWC layout */+typedef struct { int8_t* d; int H, W, C; } T8;+/* INT32 accumulator */+typedef struct { int32_t* d; int H, W, C; } T32;+/* FP32 output */+typedef struct { float* d; int H, W, C; } TF;++static T8 t8_alloc(int H, int W, int C) { T8 t={(int8_t*)malloc((size_t)H*W*C),H,W,C}; return t; }+static T32 t32_alloc(int H, int W, int C) { T32 t={(int32_t*)malloc((size_t)H*W*C*4),H,W,C}; return t; }+static TF tf_alloc(int H, int W, int C) { TF t={calloc((size_t)H*W*C,4),H,W,C}; return t; }+static void t8_free(T8* t) { free(t->d); t->d=NULL; }+static void t32_free(T32* t) { free(t->d); t->d=NULL; }+static void tf_free(TF* t) { free(t->d); t->d=NULL; }++/* ============ External kernels ============ */++extern void depthwise_conv3x3_int8_fast(+ const int8_t* in, int H, int W, int C,+ const int8_t* w, int32_t* out, int stride, int pad);++extern void upsample2x_int8(const int8_t* in, int H, int W, int C, int8_t* out);++extern void depthwise_conv3x3_int8_fused(+ const int8_t* in, int H, int W, int C,+ const int8_t* w, int8_t* out, int stride, int pad,+ const float* w_scale, const float* bias, const float* act_scale,+ float in_scale, int do_relu);++extern void add_int8_per_channel(+ const int8_t* a, const float* a_scale,+ const int8_t* b, const float* b_scale,+ int8_t* out, const float* inv_out,+ int N_pos, int C);++/* ============ Fast GEMM (external) ============ */+extern void gemm_int8_fast(const int8_t* A, int M, int K, const int8_t* B, int N, int32_t* C);++/* ============ c8-packed GEMM (external) ============ */+extern void int8_gemm_4x8c8(+ const int8_t* A, int M, int K, int N,+ const void* B_packed, int32_t* C, const int32_t* col_sums);+extern void pack_weights_4x8c8(+ const int8_t* weights, const float* bias, int K, int Cout,+ void* packed_w, int32_t* col_sums);+extern int packed_weights_size_4x8c8(int K, int Cout);+extern void int8_gemm_4x8c8_fused(+ const int8_t* A, int M, int K, int N,+ const void* B_packed, int8_t* out, const int32_t* col_sums,+ const float* w_scales, const float* bias, const float* act_scale, int do_relu);++/* ============ Optimized GEMM for 1x1 pointwise conv ============ */+#ifdef __AVX2__+#include <immintrin.h>+#ifdef __wasm_simd128__+#include "../../include/wasm_compat.h"+#endif+#endif++/* Pointwise 1x1 as c8-packed GEMM */+static void gemm_pw_int8_c8(+ const int8_t* in, int N, int Cin,+ const void* packed_w, const int32_t* col_sums, int Cout,+ int32_t* out)+{+ int8_gemm_4x8c8(in, N, Cin, Cout, packed_w, out, col_sums);+}++/* Specialized stem conv: STD 3→16 3x3 s2 pad=1+ * "Activation stationary": for each output position, gather 27 input values,+ * then accumulate across all 16 output channels using pre-transposed weights.+ * Avoids im2col allocation (2.76MB) and GEMM overhead for tiny K=27. */+static void conv_stem_3x16(+ const int8_t* in, int H, int W,+ const int8_t* w_orig, /* [16, 3*3*3] row-major */+ int32_t* out)+{+ int OH = (H + 2 - 3) / 2 + 1;+ int OW = (W + 2 - 3) / 2 + 1;++ /* Pre-transpose weights: w_T[27][16] from w[16][27], padded to [27][16] */+ int8_t w_T[27][16] __attribute__((aligned(32)));+ memset(w_T, 0, sizeof(w_T));+ for (int co = 0; co < 16; co++)+ for (int k = 0; k < 27; k++)+ w_T[k][co] = w_orig[co * 27 + k];++#ifdef __AVX2__+ /* Pack weights for vpmaddwd: for each spatial position (ky,kx),+ * pack 3 channels + 1 zero as int16 pairs for 8 output channels.+ * w_packed[9][2]: lo=channels 0-7, hi=channels 8-15+ * Each __m256i has 16 int16: [w0_c0, w0_c1, w0_c2, 0, w1_c0, w1_c1, w1_c2, 0,+ * w2_c0, w2_c1, w2_c2, 0, w3_c0, w3_c1, w3_c2, 0]+ * Then vpmaddwd with [a_c0, a_c1, a_c2, 0, ...] gives 8 partial sums.+ * But that's 4 output channels per 256-bit, need 2 loads for 8. Hmm, suboptimal.+ *+ * Simpler: keep original per-channel approach but process 3 ci in unrolled loop. */+ __m256i w16_lo[27], w16_hi[27];+ for (int k = 0; k < 27; k++) {+ __m128i v8 = _mm_loadu_si128((const __m128i*)w_T[k]);+ w16_lo[k] = _mm256_cvtepi8_epi16(v8);+ __m128i v8_hi = _mm_srli_si128(v8, 8);+ w16_hi[k] = _mm256_cvtepi8_epi16(v8_hi);+ }+#endif++ #pragma omp parallel for schedule(static)+ for (int oy = 0; oy < OH; oy++) {+ for (int ox = 0; ox < OW; ox++) {+ int32_t* out_ptr = out + ((size_t)oy * OW + ox) * 16;++#ifdef __AVX2__+ __m256i acc_lo = _mm256_setzero_si256();+ __m256i acc_hi = _mm256_setzero_si256();++ for (int ky = 0; ky < 3; ky++) {+ int iy = oy * 2 - 1 + ky;+ if (iy < 0 || iy >= H) continue; /* skip padding rows entirely */+ for (int kx = 0; kx < 3; kx++) {+ int ix = ox * 2 - 1 + kx;+ if (ix < 0 || ix >= W) continue;+ int ki = ky * 9 + kx * 3;+ const int8_t* pix = in + ((size_t)iy * W + ix) * 3;++ /* Unroll 3 channels */+ __m256i va0 = _mm256_set1_epi16((int16_t)pix[0]);+ __m256i va1 = _mm256_set1_epi16((int16_t)pix[1]);+ __m256i va2 = _mm256_set1_epi16((int16_t)pix[2]);++ /* Low 8 channels */+ __m256i p0 = _mm256_mullo_epi16(va0, w16_lo[ki]);+ __m256i p1 = _mm256_mullo_epi16(va1, w16_lo[ki+1]);+ __m256i p2 = _mm256_mullo_epi16(va2, w16_lo[ki+2]);+ /* Sum 3 int16 products: max |sum| = 3*127*127 = 48387 > 32767!+ * But after mullo_epi16 each product is int16 (wraps at ±32768).+ * Products are ≤ 127*127=16129, so each fits in int16.+ * Sum of 3: max 48387 overflows. Sum of 2 fits: max 32258.+ * So: sum 2, extend, add third. */+ __m256i sum01 = _mm256_add_epi16(p0, p1); /* fits in int16 */+ acc_lo = _mm256_add_epi32(acc_lo,+ _mm256_cvtepi16_epi32(_mm256_castsi256_si128(sum01)));+ acc_lo = _mm256_add_epi32(acc_lo,+ _mm256_cvtepi16_epi32(_mm256_castsi256_si128(p2)));++ /* High 8 channels */+ p0 = _mm256_mullo_epi16(va0, w16_hi[ki]);+ p1 = _mm256_mullo_epi16(va1, w16_hi[ki+1]);+ p2 = _mm256_mullo_epi16(va2, w16_hi[ki+2]);+ sum01 = _mm256_add_epi16(p0, p1);+ acc_hi = _mm256_add_epi32(acc_hi,+ _mm256_cvtepi16_epi32(_mm256_castsi256_si128(sum01)));+ acc_hi = _mm256_add_epi32(acc_hi,+ _mm256_cvtepi16_epi32(_mm256_castsi256_si128(p2)));+ }+ }++ _mm256_storeu_si256((__m256i*)(out_ptr), acc_lo);+ _mm256_storeu_si256((__m256i*)(out_ptr + 8), acc_hi);+#else+ memset(out_ptr, 0, 16 * sizeof(int32_t));+ int ki = 0;+ for (int ky = 0; ky < 3; ky++) {+ int iy = oy * 2 - 1 + ky;+ for (int kx = 0; kx < 3; kx++) {+ int ix = ox * 2 - 1 + kx;+ for (int ci = 0; ci < 3; ci++, ki++) {+ int8_t a = 0;+ if (iy >= 0 && iy < H && ix >= 0 && ix < W)+ a = in[((size_t)iy * W + ix) * 3 + ci];+ for (int co = 0; co < 16; co++)+ out_ptr[co] += (int32_t)a * (int32_t)w_T[ki][co];+ }+ }+ }+#endif+ }+ }+}++/* im2col: extract patches into matrix for 3x3 conv → GEMM */+static void im2col_int8(+ const int8_t* in, int H, int W, int Cin,+ int Kh, int Kw, int stride, int pad,+ int8_t* col) /* output: [OH*OW, Cin*Kh*Kw] */+{+ int OH = (H + 2*pad - Kh) / stride + 1;+ int OW = (W + 2*pad - Kw) / stride + 1;+ int K = Cin * Kh * Kw;++ for (int oy = 0; oy < OH; oy++) {+ for (int ox = 0; ox < OW; ox++) {+ int8_t* col_row = col + ((size_t)oy * OW + ox) * K;+ int idx = 0;+ for (int ky = 0; ky < Kh; ky++) {+ int iy = oy * stride - pad + ky;+ for (int kx = 0; kx < Kw; kx++) {+ int ix = ox * stride - pad + kx;+ if (iy >= 0 && iy < H && ix >= 0 && ix < W) {+ const int8_t* src = in + ((size_t)iy * W + ix) * Cin;+ memcpy(col_row + idx, src, Cin);+ } else {+ memset(col_row + idx, 0, Cin);+ }+ idx += Cin;+ }+ }+ }+ }+}++/* Standard 3x3 conv via im2col + c8-packed GEMM */+static void conv_std_int8_gemm_c8(+ const int8_t* in, int H, int W, int Cin,+ const void* packed_w, const int32_t* col_sums,+ int Cout, int Kh, int Kw,+ int stride, int pad,+ int32_t* out)+{+ int OH = (H + 2*pad - Kh) / stride + 1;+ int OW = (W + 2*pad - Kw) / stride + 1;+ int K = Cin * Kh * Kw;+ int M = OH * OW;++ /* im2col */+ int8_t* col = (int8_t*)malloc((size_t)M * K);+ im2col_int8(in, H, W, Cin, Kh, Kw, stride, pad, col);++ /* GEMM: col[M, K] × packed_w → out[M, Cout] */+ int8_gemm_4x8c8(col, M, K, Cout, packed_w, out, col_sums);++ free(col);+}++/* Standard 3x3 conv with AVX2 inner loop (fallback) */+static void conv_std_int8(+ const int8_t* in, int H, int W, int Cin,+ const int8_t* w, int Cout, int Kh, int Kw,+ int stride, int pad,+ int32_t* out)+{+ int OH = (H + 2*pad - Kh) / stride + 1;+ int OW = (W + 2*pad - Kw) / stride + 1;++ #pragma omp parallel for schedule(dynamic)+ for (int oy = 0; oy < OH; oy++) {+ for (int ox = 0; ox < OW; ox++) {+ int32_t* out_ptr = out + ((size_t)oy * OW + ox) * Cout;+ memset(out_ptr, 0, Cout * sizeof(int32_t));++ for (int ky = 0; ky < Kh; ky++) {+ int iy = oy * stride - pad + ky;+ if (iy < 0 || iy >= H) continue;+ for (int kx = 0; kx < Kw; kx++) {+ int ix = ox * stride - pad + kx;+ if (ix < 0 || ix >= W) continue;++ const int8_t* in_ptr = in + ((size_t)iy * W + ix) * Cin;+ int k_offset = (ky * Kw + kx) * Cin;++ for (int co = 0; co < Cout; co++) {+ const int8_t* ww = w + (size_t)co * Kh * Kw * Cin + k_offset;+ int32_t sum = 0;+ int ci = 0;++#ifdef __AVX2__+ /* Vectorize inner product along Cin dimension */+ __m256i vacc = _mm256_setzero_si256();+ for (; ci + 16 <= Cin; ci += 16) {+ __m128i vi8 = _mm_loadu_si128((const __m128i*)(in_ptr + ci));+ __m128i vw8 = _mm_loadu_si128((const __m128i*)(ww + ci));+ /* Extend to 16-bit and multiply */+ __m256i vi16 = _mm256_cvtepi8_epi16(vi8);+ __m256i vw16 = _mm256_cvtepi8_epi16(vw8);+ __m256i prod = _mm256_mullo_epi16(vi16, vw16);+ /* Extend to 32-bit and accumulate */+ __m256i prod_lo = _mm256_cvtepi16_epi32(_mm256_castsi256_si128(prod));+ __m256i prod_hi = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(prod, 1));+ vacc = _mm256_add_epi32(vacc, prod_lo);+ vacc = _mm256_add_epi32(vacc, prod_hi);+ }+ /* Horizontal sum */+ __m128i lo = _mm256_castsi256_si128(vacc);+ __m128i hi = _mm256_extracti128_si256(vacc, 1);+ lo = _mm_add_epi32(lo, hi);+ lo = _mm_add_epi32(lo, _mm_srli_si128(lo, 8));+ lo = _mm_add_epi32(lo, _mm_srli_si128(lo, 4));+ sum = _mm_cvtsi128_si32(lo);+#endif+ for (; ci < Cin; ci++) {+ sum += (int32_t)in_ptr[ci] * (int32_t)ww[ci];+ }+ out_ptr[co] += sum;+ }+ }+ }+ }+ }+}++/* Dequant + bias + ReLU + requant epilogue — AVX2 vectorized */+static void epilogue_relu_requant(+ const int32_t* acc, int N_pos, int Cout,+ float in_scale, const float* w_scales, const float* bias,+ const float* out_act_scale,+ int8_t* out, int do_relu)+{+ /* Precompute combined scale and inv_out per channel — stack alloc for small Cout */+ float combined_scale_buf[512], inv_out_buf[512];+ float* combined_scale = (Cout <= 512) ? combined_scale_buf : (float*)malloc(Cout * sizeof(float));+ float* inv_out = (Cout <= 512) ? inv_out_buf : (float*)malloc(Cout * sizeof(float));+ for (int c = 0; c < Cout; c++) {+ combined_scale[c] = in_scale * w_scales[c];+ inv_out[c] = 1.0f / (out_act_scale[c] + 1e-9f);+ }++ #pragma omp parallel for schedule(static)+ for (int p = 0; p < N_pos; p++) {+ const int32_t* row = acc + (size_t)p * Cout;+ int8_t* orow = out + (size_t)p * Cout;+ int c = 0;++#ifdef __AVX2__+ __m256 vzero = _mm256_setzero_ps();+ __m256 vhalf = _mm256_set1_ps(0.5f);++ for (; c + 8 <= Cout; c += 8) {+ /* Load 8 int32 accumulators → float */+ __m256i vi32 = _mm256_loadu_si256((const __m256i*)(row + c));+ __m256 vfp = _mm256_cvtepi32_ps(vi32);++ /* Multiply by combined scale */+ __m256 vcs = _mm256_loadu_ps(combined_scale + c);+ vfp = _mm256_mul_ps(vfp, vcs);++ /* Add bias */+ if (bias) vfp = _mm256_add_ps(vfp, _mm256_loadu_ps(bias + c));++ /* ReLU: max(0, x) */+ if (do_relu) vfp = _mm256_max_ps(vfp, vzero);++ /* Requantize: multiply by inv_out, round, clamp to int8 */+ __m256 vio = _mm256_loadu_ps(inv_out + c);+ vfp = _mm256_mul_ps(vfp, vio);++ /* Round to nearest */+ __m256 sign_bit = _mm256_and_ps(vfp, _mm256_castsi256_ps(_mm256_set1_epi32(0x80000000)));+ __m256 rounder = _mm256_or_ps(vhalf, sign_bit);+ __m256i vi = _mm256_cvttps_epi32(_mm256_add_ps(vfp, rounder));++ /* Clamp [-128, 127] */+ vi = _mm256_max_epi32(vi, _mm256_set1_epi32(-128));+ vi = _mm256_min_epi32(vi, _mm256_set1_epi32(127));++ /* Pack int32 → int8 */+ __m128i lo = _mm256_castsi256_si128(vi);+ __m128i hi = _mm256_extracti128_si256(vi, 1);+ __m128i i16 = _mm_packs_epi32(lo, hi);+ __m128i i8 = _mm_packs_epi16(i16, i16);+ _mm_storel_epi64((__m128i*)(orow + c), i8);+ }+#endif+ for (; c < Cout; c++) {+ float fp = (float)row[c] * combined_scale[c];+ if (bias) fp += bias[c];+ if (do_relu && fp < 0) fp = 0;+ int q = (int)lrintf(fp * inv_out[c]);+ if (q > 127) q = 127;+ if (q < -128) q = -128;+ orow[c] = (int8_t)q;+ }+ }+ if (Cout > 512) { free(combined_scale); free(inv_out); }+}++/* Dequant + bias (no requant) → FP32 output for detection heads */+static void epilogue_to_fp32(+ const int32_t* acc, int N_pos, int Cout,+ float in_scale, const float* w_scales, const float* bias,+ float* out)+{+ for (int p = 0; p < N_pos; p++) {+ const int32_t* row = acc + (size_t)p * Cout;+ float* orow = out + (size_t)p * Cout;+ for (int c = 0; c < Cout; c++) {+ float fp = (float)row[c] * in_scale * w_scales[c];+ if (bias) fp += bias[c];+ orow[c] = fp;+ }+ }+}++/* ============ Run one conv layer ============ */++/* Per-layer profiling (enabled via global flag) */+static int g_profile = 0;+static double g_layer_ms[MAX_LAYERS];+static int g_layer_idx = 0;++static double time_ms(void) {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;+}++static T8 run_conv(Layer* L, T8 input, float in_scale, int do_relu) {+ int OH = (input.H + 2*L->pad - L->kh) / L->sh + 1;+ int OW = (input.W + 2*L->pad - L->kw) / L->sw + 1;++ double t0 = g_profile ? time_ms() : 0;++ /* Fused DW path: conv + epilogue in single pass, no int32 buffer */+ if (L->type == 1 && L->kh == 3 && L->kw == 3) {+ T8 out = t8_alloc(OH, OW, L->cout);+ depthwise_conv3x3_int8_fused(+ input.d, input.H, input.W, input.C,+ L->w, out.d, L->sh, L->pad,+ L->w_scale, L->bias, L->act_scale, in_scale, do_relu);++ if (g_profile && g_layer_idx < MAX_LAYERS)+ g_layer_ms[g_layer_idx++] = time_ms() - t0;+ return out;+ }++ /* Fused path: PW conv with c8 GEMM — skip int32 intermediate buffer */+ if (L->packed_w && L->type == 2 && L->kh == 1 && L->kw == 1 && L->sh == 1) {+ T8 out = t8_alloc(OH, OW, L->cout);+ int8_gemm_4x8c8_fused(+ input.d, OH * OW, input.C, L->cout,+ L->packed_w, out.d, L->col_sums,+ L->w_scale, L->bias, L->act_scale, do_relu);++ if (g_profile && g_layer_idx < MAX_LAYERS)+ g_layer_ms[g_layer_idx++] = time_ms() - t0;+ return out;+ }++ T32 acc = t32_alloc(OH, OW, L->cout);++ if (L->type == 1) { /* DW */+ depthwise_conv3x3_int8_fast(input.d, input.H, input.W, input.C,+ L->w, acc.d, L->sh, L->pad);+ } else if (L->type == 0 && L->cin == 3 && L->cout == 16 &&+ L->kh == 3 && L->kw == 3 && L->sh == 2) {+ /* Stem conv — still needs int32 buffer for now */+ conv_stem_3x16(input.d, input.H, input.W, L->w, acc.d);+ } else if (L->packed_w && L->kh >= 3) {+ /* STD conv via im2col + fused c8 GEMM (skip int32 buffer) */+ int K = L->cin * L->kh * L->kw;+ int M = OH * OW;+ int8_t* col = (int8_t*)malloc((size_t)M * K);+ im2col_int8(input.d, input.H, input.W, input.C,+ L->kh, L->kw, L->sh, L->pad, col);+ T8 out_fused = t8_alloc(OH, OW, L->cout);+ int8_gemm_4x8c8_fused(col, M, K, L->cout,+ L->packed_w, out_fused.d, L->col_sums,+ L->w_scale, L->bias, L->act_scale, do_relu);+ free(col);+ if (g_profile && g_layer_idx < MAX_LAYERS)+ g_layer_ms[g_layer_idx++] = time_ms() - t0;+ return out_fused;+ } else if (L->packed_w) {+ /* Other conv via im2col + c8 GEMM */+ conv_std_int8_gemm_c8(input.d, input.H, input.W, input.C,+ L->packed_w, L->col_sums,+ L->cout, L->kh, L->kw, L->sh, L->pad, acc.d);+ } else {+ conv_std_int8(input.d, input.H, input.W, input.C,+ L->w, L->cout, L->kh, L->kw, L->sh, L->pad, acc.d);+ }++ T8 out = t8_alloc(OH, OW, L->cout);+ epilogue_relu_requant(acc.d, OH * OW, L->cout,+ in_scale, L->w_scale, L->bias,+ L->act_scale, out.d, do_relu);+ t32_free(&acc);++ if (g_profile && g_layer_idx < MAX_LAYERS) {+ g_layer_ms[g_layer_idx++] = time_ms() - t0;+ }++ return out;+}++/* Run conv with FP32 output (for detection head finals) */+static TF run_conv_fp32(Layer* L, T8 input, float in_scale) {+ int OH = (input.H + 2*L->pad - L->kh) / L->sh + 1;+ int OW = (input.W + 2*L->pad - L->kw) / L->sw + 1;++ T32 acc = t32_alloc(OH, OW, L->cout);+ if (L->packed_w) {+ if (L->type == 2 && L->kh == 1 && L->kw == 1 && L->sh == 1) {+ gemm_pw_int8_c8(input.d, input.H * input.W, input.C,+ L->packed_w, L->col_sums, L->cout, acc.d);+ } else {+ conv_std_int8_gemm_c8(input.d, input.H, input.W, input.C,+ L->packed_w, L->col_sums,+ L->cout, L->kh, L->kw, L->sh, L->pad, acc.d);+ }+ } else {+ conv_std_int8(input.d, input.H, input.W, input.C,+ L->w, L->cout, L->kh, L->kw, L->sh, L->pad, acc.d);+ }++ TF out = tf_alloc(OH, OW, L->cout);+ epilogue_to_fp32(acc.d, OH * OW, L->cout,+ in_scale, L->w_scale, L->bias, out.d);+ t32_free(&acc);+ return out;+}++/* ============ Input quantization ============ */++static T8 quantize_input(const float* rgb_hwc, int H, int W) {+ T8 out = t8_alloc(H, W, 3);+ int n = H * W * 3;+ int i = 0;+#ifdef __AVX2__+ __m256 v127 = _mm256_set1_ps(127.0f);+ for (; i + 8 <= n; i += 8) {+ __m256 vf = _mm256_loadu_ps(rgb_hwc + i);+ __m256i vi = _mm256_cvtps_epi32(_mm256_mul_ps(vf, v127));+ vi = _mm256_max_epi32(vi, _mm256_set1_epi32(-128));+ vi = _mm256_min_epi32(vi, _mm256_set1_epi32(127));+ /* Pack int32 → int8 */+ __m128i lo = _mm256_castsi256_si128(vi);+ __m128i hi = _mm256_extracti128_si256(vi, 1);+ __m128i i16 = _mm_packs_epi32(lo, hi);+ __m128i i8 = _mm_packs_epi16(i16, i16);+ *(int64_t*)(out.d + i) = _mm_extract_epi64(i8, 0);+ }+#endif+ for (; i < n; i++) {+ int q = (int)lrintf(rgb_hwc[i] * 127.0f);+ if (q > 127) q = 127; if (q < -128) q = -128;+ out.d[i] = (int8_t)q;+ }+ return out;+}++/* ============ Load DET8 ============ */++static int load_model(const char* path, Model* m) {+ FILE* f = fopen(path, "rb");+ if (!f) { fprintf(stderr, "Cannot open %s\n", path); return -1; }++ char magic[4]; fread(magic, 1, 4, f);+ if (memcmp(magic, "DET8", 4)) { fclose(f); return -1; }+ uint8_t ver; fread(&ver, 1, 1, f);+ uint32_t nl; fread(&nl, 4, 1, f);+ m->n_layers = (int)nl;++ for (int i = 0; i < m->n_layers; i++) {+ Layer* L = &m->layers[i];+ fread(&L->type, 1, 1, f);+ fread(&L->cin, 2, 1, f); fread(&L->cout, 2, 1, f);+ fread(&L->kh, 1, 1, f); fread(&L->kw, 1, 1, f);+ fread(&L->sh, 1, 1, f); fread(&L->sw, 1, 1, f);+ fread(&L->pad, 1, 1, f);++ uint32_t ws; fread(&ws, 4, 1, f);+ L->w_size = ws; L->w = malloc(ws); fread(L->w, 1, ws, f);++ uint32_t ns; fread(&ns, 4, 1, f);+ L->w_scale = malloc(ns * 4); fread(L->w_scale, 4, ns, f);++ uint32_t nb; fread(&nb, 4, 1, f);+ if (nb) { L->bias = malloc(nb * 4); fread(L->bias, 4, nb, f); }+ else L->bias = NULL;++ uint32_t na; fread(&na, 4, 1, f);+ L->n_act = na; L->act_scale = malloc(na * 4); fread(L->act_scale, 4, na, f);++ /* Pre-pack weights for c8 GEMM (non-DW layers) */+ L->packed_w = NULL;+ L->col_sums = NULL;+ L->gemm_K = 0;+ if (L->type != 1) { /* PW (type=2) or STD (type=0) */+ int K;+ if (L->type == 2 && L->kh == 1 && L->kw == 1) {+ K = L->cin; /* Pointwise: K = Cin */+ } else {+ K = L->cin * L->kh * L->kw; /* Standard: K = Cin*Kh*Kw */+ }+ L->gemm_K = K;+ int pw_size = packed_weights_size_4x8c8(K, L->cout);+ L->packed_w = malloc(pw_size);+ L->col_sums = (int32_t*)calloc(((L->cout + 7) & ~7), sizeof(int32_t));+ pack_weights_4x8c8(L->w, NULL, K, L->cout,+ L->packed_w, L->col_sums);+ }+ }+ fclose(f);+ fprintf(stderr, "DET8: %d layers loaded (c8-packed GEMM)\n", m->n_layers);+ return 0;+}++/* ============ Get activation scale (scalar approximation) ============ */+static float mean_scale(float* scales, int n) {+ float sum = 0;+ for (int i = 0; i < n; i++) sum += scales[i];+ return sum / n;+}+/* Use geometric mean — better balance for per-channel variation */+static float geomean_scale(float* scales, int n) {+ double log_sum = 0;+ int count = 0;+ for (int i = 0; i < n; i++) {+ if (scales[i] > 1e-9f) {+ log_sum += log((double)scales[i]);+ count++;+ }+ }+ return count > 0 ? (float)exp(log_sum / count) : 1e-6f;+}++/* ============ Main forward pass ============ */++typedef struct {+ float* cls; /* [N, 1] after sigmoid */+ float* bbox; /* [N, 4] */+ float* kps; /* [N, 10] */+ int N;+} HeadOutput;++/* Pre-allocated workspace to avoid malloc during inference */+typedef struct {+ int8_t* buf_a; /* ping buffer for INT8 tensors */+ int8_t* buf_b; /* pong buffer */+ int32_t* acc; /* INT32 accumulator */+ int8_t* im2col; /* im2col scratch */+ size_t buf_size; /* size of each ping/pong buffer */+ size_t acc_size;+ size_t col_size;+} Workspace;++static Workspace ws = {0};++static void init_workspace(int max_H, int max_W, int max_C) {+ /* Allocate once, reuse forever */+ ws.buf_size = (size_t)max_H * max_W * max_C;+ ws.acc_size = (size_t)max_H * max_W * max_C * sizeof(int32_t);+ ws.col_size = (size_t)max_H * max_W * max_C * 9; /* 3x3 kernel worst case */+ ws.buf_a = (int8_t*)calloc(ws.buf_size, 1);+ ws.buf_b = (int8_t*)calloc(ws.buf_size, 1);+ ws.acc = (int32_t*)calloc(ws.buf_size, sizeof(int32_t));+ ws.im2col = (int8_t*)calloc(ws.col_size, 1);+}++static void forward(Model* m, const float* input_hwc, int H, int W,+ HeadOutput* head8, HeadOutput* head16, HeadOutput* head32) {++ /* Init workspace on first call */+ if (!ws.buf_a) init_workspace(H, W, 320); /* max 320×320×288 won't exceed this */++ /* With v2 folded weights, in_scale = 1.0 everywhere.+ * Per-channel activation variation is absorbed into weights.+ * act_scale is per-tensor (same value for all channels). */+ float input_scale = 1.0f;++ /* Quantize input */+ T8 x = quantize_input(input_hwc, H, W);++ /* ====== BACKBONE layers 0-28 ====== */+ /* Each conv: x → conv → relu → x' */+ /* Save feature_8 (after layer 12), feature_16 (after layer 16), feature_32 (after layer 28) */++ T8 feature_8 = {0}, feature_16 = {0};+ int x_is_saved = 0;++ /* Pre-allocate workspace for DW→PW intermediate (reused across pairs) */+ size_t max_intermediate = (size_t)320 * 320 * 288; /* covers all backbone sizes */+ int8_t* dw_pw_buf = (int8_t*)malloc(max_intermediate);++ for (int i = 0; i <= 28; i++) {+ Layer* L = &m->layers[i];+ Layer* L_next = (i + 1 <= 28) ? &m->layers[i + 1] : NULL;++ /* Detect DW+PW pair and fuse: DW output goes to workspace, PW reads from it */+ if (L->type == 1 && L_next && L_next->type == 2 &&+ L->kh == 3 && L_next->kh == 1) {+ int OH_dw = (x.H + 2*L->pad - 3) / L->sh + 1;+ int OW_dw = (x.W + 2*L->pad - 3) / L->sw + 1;++ double t0 = g_profile ? time_ms() : 0;++ /* DW → workspace buffer (no malloc) */+ depthwise_conv3x3_int8_fused(+ x.d, x.H, x.W, x.C,+ L->w, dw_pw_buf, L->sh, L->pad,+ L->w_scale, L->bias, L->act_scale, 1.0f, 1);++ if (g_profile && g_layer_idx < MAX_LAYERS)+ g_layer_ms[g_layer_idx++] = time_ms() - t0;++ /* PW reads from workspace, outputs to new alloc */+ T8 pw_out = t8_alloc(OH_dw, OW_dw, L_next->cout);+ t0 = g_profile ? time_ms() : 0;++ int8_gemm_4x8c8_fused(+ dw_pw_buf, OH_dw * OW_dw, L_next->cin, L_next->cout,+ L_next->packed_w, pw_out.d, L_next->col_sums,+ L_next->w_scale, L_next->bias, L_next->act_scale, 1);++ if (g_profile && g_layer_idx < MAX_LAYERS)+ g_layer_ms[g_layer_idx++] = time_ms() - t0;++ if (!x_is_saved) t8_free(&x);+ x_is_saved = 0;+ x = pw_out;+ i++; /* skip PW layer (already processed) */+ } else {+ T8 out = run_conv(L, x, 1.0f, 1);+ if (!x_is_saved) t8_free(&x);+ x_is_saved = 0;+ x = out;+ }++ if (i == 12) {+ feature_8 = t8_alloc(x.H, x.W, x.C);+ memcpy(feature_8.d, x.d, (size_t)x.H * x.W * x.C);+ }+ if (i == 16) {+ feature_16 = t8_alloc(x.H, x.W, x.C);+ memcpy(feature_16.d, x.d, (size_t)x.H * x.W * x.C);+ }+ }+ free(dw_pw_buf);+ T8 feature_32 = x;++ /* ====== FPN LATERALS layers 29-31 ====== */+ T8 lat8 = run_conv(&m->layers[29], feature_8, 1.0f, 0);+ T8 lat16 = run_conv(&m->layers[30], feature_16, 1.0f, 0);+ T8 lat32 = run_conv(&m->layers[31], feature_32, 1.0f, 0);++ float lat8_ms = mean_scale(m->layers[29].act_scale, m->layers[29].n_act);+ float lat16_ms = mean_scale(m->layers[30].act_scale, m->layers[30].n_act);+ float lat32_ms = mean_scale(m->layers[31].act_scale, m->layers[31].n_act);++ t8_free(&feature_8); t8_free(&feature_16); t8_free(&feature_32);++ /* ====== FPN TOP-DOWN MERGE (fused upsample+add) ====== */+ float lat16_s = m->layers[30].act_scale[0];+ float lat32_s = m->layers[31].act_scale[0];+ float lat8_s = m->layers[29].act_scale[0];+ float inv16 = 1.0f / (lat16_s + 1e-9f);+ float inv8 = 1.0f / (lat8_s + 1e-9f);++ /* Fused upsample(lat32) + add(lat16) → merged16 — AVX2 for C=16 */+ T8 merged16 = t8_alloc(lat16.H, lat16.W, lat16.C);+ {+ int C = lat16.C, H16 = lat16.H, W16 = lat16.W;+#ifdef __AVX2__+ __m256 va_sc = _mm256_set1_ps(lat16_s);+ __m256 vb_sc = _mm256_set1_ps(lat32_s);+ __m256 vinv = _mm256_set1_ps(inv16);+#endif+ #pragma omp parallel for schedule(static)+ for (int y = 0; y < H16; y++) {+ for (int x = 0; x < W16; x++) {+ const int8_t* a = lat16.d + ((size_t)y * W16 + x) * C;+ const int8_t* b = lat32.d + ((size_t)(y/2) * lat32.W + x/2) * C;+ int8_t* o = merged16.d + ((size_t)y * W16 + x) * C;+ int c = 0;+#ifdef __AVX2__+ for (; c + 8 <= C; c += 8) {+ __m256 fa = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*)(a+c))));+ __m256 fb = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*)(b+c))));+ __m256 fp = _mm256_fmadd_ps(fa, va_sc, _mm256_mul_ps(fb, vb_sc));+ __m256i vi = _mm256_cvtps_epi32(_mm256_mul_ps(fp, vinv));+ vi = _mm256_max_epi32(vi, _mm256_set1_epi32(-128));+ vi = _mm256_min_epi32(vi, _mm256_set1_epi32(127));+ __m128i lo = _mm256_castsi256_si128(vi);+ __m128i hi = _mm256_extracti128_si256(vi, 1);+ __m128i i16 = _mm_packs_epi32(lo, hi);+ __m128i i8 = _mm_packs_epi16(i16, i16);+ *(int64_t*)(o+c) = _mm_extract_epi64(i8, 0);+ }+#endif+ for (; c < C; c++) {+ float fp = (float)a[c] * lat16_s + (float)b[c] * lat32_s;+ int q = (int)lrintf(fp * inv16);+ o[c] = (int8_t)(q > 127 ? 127 : (q < -128 ? -128 : q));+ }+ }+ }+ }++ /* Fused upsample(merged16) + add(lat8) → merged8 — AVX2 */+ T8 merged8 = t8_alloc(lat8.H, lat8.W, lat8.C);+ {+ int C = lat8.C, H8 = lat8.H, W8 = lat8.W, W16 = lat16.W;+#ifdef __AVX2__+ __m256 va_sc2 = _mm256_set1_ps(lat8_s);+ __m256 vb_sc2 = _mm256_set1_ps(lat16_s);+ __m256 vinv2 = _mm256_set1_ps(inv8);+#endif+ #pragma omp parallel for schedule(static)+ for (int y = 0; y < H8; y++) {+ for (int x = 0; x < W8; x++) {+ const int8_t* a = lat8.d + ((size_t)y * W8 + x) * C;+ const int8_t* b = merged16.d + ((size_t)(y/2) * W16 + x/2) * C;+ int8_t* o = merged8.d + ((size_t)y * W8 + x) * C;+ int c = 0;+#ifdef __AVX2__+ for (; c + 8 <= C; c += 8) {+ __m256 fa = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*)(a+c))));+ __m256 fb = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_loadl_epi64((const __m128i*)(b+c))));+ __m256 fp = _mm256_fmadd_ps(fa, va_sc2, _mm256_mul_ps(fb, vb_sc2));+ __m256i vi = _mm256_cvtps_epi32(_mm256_mul_ps(fp, vinv2));+ vi = _mm256_max_epi32(vi, _mm256_set1_epi32(-128));+ vi = _mm256_min_epi32(vi, _mm256_set1_epi32(127));+ __m128i lo = _mm256_castsi256_si128(vi);+ __m128i hi = _mm256_extracti128_si256(vi, 1);+ __m128i i16 = _mm_packs_epi32(lo, hi);+ __m128i i8 = _mm_packs_epi16(i16, i16);+ *(int64_t*)(o+c) = _mm_extract_epi64(i8, 0);+ }+#endif+ for (; c < C; c++) {+ float fp = (float)a[c] * lat8_s + (float)b[c] * lat16_s;+ int q = (int)lrintf(fp * inv8);+ o[c] = (int8_t)(q > 127 ? 127 : (q < -128 ? -128 : q));+ }+ }+ }+ }+ t8_free(&lat8); t8_free(&lat16);++ /* ====== FPN OUTPUT CONVS layers 32-38 ====== */+ T8 fpn8 = run_conv(&m->layers[32], merged8, 1.0f, 0);+ t8_free(&merged8);++ T8 t417 = run_conv(&m->layers[33], merged16, 1.0f, 0);+ t8_free(&merged16);++ T8 t418 = run_conv(&m->layers[34], lat32, 1.0f, 0);+ t8_free(&lat32);++ T8 t419 = run_conv(&m->layers[35], fpn8, 1.0f, 0);++ float t417_s = m->layers[33].act_scale[0]; /* per-tensor */+ float t419_s = m->layers[35].act_scale[0];+ T8 fpn16 = t8_alloc(t417.H, t417.W, t417.C);+ {+ int C = t417.C;+ float a_sc[320], b_sc[320], inv_sc[320];+ for (int c=0;c<C;c++) { a_sc[c]=t417_s; b_sc[c]=t419_s; inv_sc[c]=1.0f/(t417_s+1e-9f); }+ add_int8_per_channel(t417.d, a_sc, t419.d, b_sc, fpn16.d, inv_sc, t417.H*t417.W, C);+ }+ t8_free(&t417); t8_free(&t419);++ T8 t421 = run_conv(&m->layers[36], fpn16, 1.0f, 0);++ float t418_s = m->layers[34].act_scale[0];+ float t421_s = m->layers[36].act_scale[0];+ T8 fpn32 = t8_alloc(t418.H, t418.W, t418.C);+ {+ int C = t418.C;+ float a_sc[320], b_sc[320], inv_sc[320];+ for (int c=0;c<C;c++) { a_sc[c]=t418_s; b_sc[c]=t421_s; inv_sc[c]=1.0f/(t418_s+1e-9f); }+ add_int8_per_channel(t418.d, a_sc, t421.d, b_sc, fpn32.d, inv_sc, t418.H*t418.W, C);+ }+ t8_free(&t418); t8_free(&t421);++ T8 head_in_16 = run_conv(&m->layers[37], fpn16, 1.0f, 0);+ t8_free(&fpn16);++ T8 head_in_32 = run_conv(&m->layers[38], fpn32, 1.0f, 0);+ t8_free(&fpn32);++ /* ====== DETECTION HEADS ====== */+ #define RUN_HEAD(start_layer, input_tensor, head_out) do { \+ T8 h1 = run_conv(&m->layers[start_layer], input_tensor, 1.0f, 1); \+ T8 h2 = run_conv(&m->layers[start_layer+1], h1, 1.0f, 1); \+ t8_free(&h1); \+ T8 h3 = run_conv(&m->layers[start_layer+2], h2, 1.0f, 1); \+ t8_free(&h2); \+ T8 h4 = run_conv(&m->layers[start_layer+3], h3, 1.0f, 1); \+ t8_free(&h3); \+ TF cls_f = run_conv_fp32(&m->layers[start_layer+4], h4, 1.0f); \+ TF bbox_f = run_conv_fp32(&m->layers[start_layer+5], h4, 1.0f); \+ TF kps_f = run_conv_fp32(&m->layers[start_layer+6], h4, 1.0f); \+ t8_free(&h4); \+ /* Apply sigmoid to cls */ \+ int n_cls = cls_f.H * cls_f.W * cls_f.C; \+ for (int j = 0; j < n_cls; j++) \+ cls_f.d[j] = 1.0f / (1.0f + expf(-cls_f.d[j])); \+ (head_out).cls = cls_f.d; \+ (head_out).bbox = bbox_f.d; \+ (head_out).kps = kps_f.d; \+ (head_out).N = cls_f.H * cls_f.W; \+ } while(0)++ /* Head stride 8 (layers 39-45, input: fpn8) */+ RUN_HEAD(39, fpn8, *head8);+ t8_free(&fpn8);++ RUN_HEAD(46, head_in_16, *head16);+ t8_free(&head_in_16);++ RUN_HEAD(53, head_in_32, *head32);+ t8_free(&head_in_32);++ #undef RUN_HEAD+}++/* ============ External postprocess ============ */++typedef struct {+ float x1, y1, x2, y2;+ float score;+ float kps[5][2];+} Face;++extern int postprocess_retinaface(+ const float* cls8, const float* bbox8, const float* kps8,+ const float* cls16, const float* bbox16, const float* kps16,+ const float* cls32, const float* bbox32, const float* kps32,+ int det_size, int img_w, int img_h,+ float conf_thresh, float iou_thresh,+ Face* out_faces, int max_out);++extern void print_faces(const Face* faces, int n);++/* ============ Server mode ============ */++/*+ * Binary protocol (stdin/stdout):+ * Input: uint32 width, uint32 height, float32[H*W*3] normalized HWC [-1,1]+ * Output: uint32 num_faces, per face: float32[4] bbox, float32 score, float32[10] kps+ */+static void server_loop(Model* model) {+#ifdef _WIN32+ /* Set stdin/stdout to binary mode and increase buffer */+ _setmode(_fileno(stdin), _O_BINARY);+ _setmode(_fileno(stdout), _O_BINARY);+ /* Increase stdio buffers for large blobs */+ setvbuf(stdin, NULL, _IOFBF, 1024 * 1024); /* 1MB input buffer */+ setvbuf(stdout, NULL, _IOFBF, 64 * 1024); /* 64KB output buffer */+#endif+ fprintf(stderr, "fastdet_int8: server mode ready\n");++ while (1) {+ uint32_t w, h;+ if (fread(&w, 4, 1, stdin) != 1) break;+ if (fread(&h, 4, 1, stdin) != 1) break;++ size_t n_floats = (size_t)h * w * 3;+ float* input = (float*)malloc(n_floats * sizeof(float));+ if (fread(input, sizeof(float), n_floats, stdin) != n_floats) {+ free(input);+ break;+ }++ /* Run detection */+ HeadOutput h8, h16, h32;+ forward(model, input, (int)h, (int)w, &h8, &h16, &h32);++ /* Postprocess */+ Face faces[256];+ int n_faces = postprocess_retinaface(+ h8.cls, h8.bbox, h8.kps,+ h16.cls, h16.bbox, h16.kps,+ h32.cls, h32.bbox, h32.kps,+ (int)(w > h ? w : h), (int)w, (int)h,+ 0.40f, 0.4f,+ faces, 256);++ /* Write output */+ uint32_t nf = (uint32_t)n_faces;+ fwrite(&nf, 4, 1, stdout);+ for (int i = 0; i < n_faces; i++) {+ fwrite(&faces[i].x1, 4, 1, stdout);+ fwrite(&faces[i].y1, 4, 1, stdout);+ fwrite(&faces[i].x2, 4, 1, stdout);+ fwrite(&faces[i].y2, 4, 1, stdout);+ fwrite(&faces[i].score, 4, 1, stdout);+ fwrite(faces[i].kps, 4, 10, stdout);+ }+ fflush(stdout);++ /* Cleanup */+ free(h8.cls); free(h8.bbox); free(h8.kps);+ free(h16.cls); free(h16.bbox); free(h16.kps);+ free(h32.cls); free(h32.bbox); free(h32.kps);+ free(input);+ }+}++/* ============ Main ============ */+#ifndef DETECT_NO_MAIN+int main(int argc, char** argv) {+ if (argc < 2) {+ fprintf(stderr, "Usage: fastdet_int8 <det8_weights> [--server|--test]\n");+ return 1;+ }++ /* OpenMP tuning for inference: active spinning + core binding */+ #ifdef _WIN32+ _putenv("OMP_WAIT_POLICY=active");+ _putenv("OMP_PROC_BIND=close");+ #else+ setenv("OMP_WAIT_POLICY", "active", 0);+ setenv("OMP_PROC_BIND", "close", 0);+ #endif++ Model model;+ if (load_model(argv[1], &model) != 0) return 1;++ if (argc > 2 && strcmp(argv[2], "--server") == 0) {+ server_loop(&model);+ } else if (argc > 2 && strcmp(argv[2], "--test") == 0) {+ int det_size = (argc > 3) ? atoi(argv[3]) : 640;+ int H = det_size, W = det_size;+ float* input = calloc((size_t)H * W * 3, sizeof(float));+ for (int i = 0; i < H * W * 3; i++)+ input[i] = ((float)(i % 256) - 127.5f) / 128.0f;++ fprintf(stderr, "Running forward pass on %dx%d dummy input...\n", H, W);++ /* Enable profiling */+ g_profile = 1;+ g_layer_idx = 0;++ struct timespec t0, t1;+ clock_gettime(CLOCK_MONOTONIC, &t0);++ HeadOutput h8, h16, h32;+ forward(&model, input, H, W, &h8, &h16, &h32);++ clock_gettime(CLOCK_MONOTONIC, &t1);+ double ms = (t1.tv_sec - t0.tv_sec) * 1000.0 + (t1.tv_nsec - t0.tv_nsec) / 1e6;++ /* Postprocess */+ Face faces[256];+ int n = postprocess_retinaface(+ h8.cls, h8.bbox, h8.kps,+ h16.cls, h16.bbox, h16.kps,+ h32.cls, h32.bbox, h32.kps,+ det_size, det_size, det_size, 0.3f, 0.4f,+ faces, 256);++ printf("Forward: %.1f ms, %d faces detected\n", ms, n);+ print_faces(faces, n);++ /* Print per-layer profile */+ printf("\n=== Per-layer profile (%d layers timed) ===\n", g_layer_idx);+ double dw_total = 0, pw_total = 0, std_total = 0;+ for (int li = 0; li < g_layer_idx && li < model.n_layers; li++) {+ Layer* L = &model.layers[li];+ const char* ty = L->type == 1 ? "DW" : (L->type == 2 ? "PW" : "STD");+ printf(" [%2d] %3s %3d->%3d k=%dx%d s=%d %.2f ms\n",+ li, ty, L->cin, L->cout, L->kh, L->kw, L->sh, g_layer_ms[li]);+ if (L->type == 1) dw_total += g_layer_ms[li];+ else if (L->type == 2) pw_total += g_layer_ms[li];+ else std_total += g_layer_ms[li];+ }+ printf(" Totals: DW=%.1fms PW=%.1fms STD=%.1fms sum=%.1fms\n",+ dw_total, pw_total, std_total, dw_total + pw_total + std_total);++ free(h8.cls); free(h8.bbox); free(h8.kps);+ free(h16.cls); free(h16.bbox); free(h16.kps);+ free(h32.cls); free(h32.bbox); free(h32.kps);+ free(input);+ } else {+ printf("RetinaFace INT8 engine (%d layers). Use --server or --test.\n", model.n_layers);+ }++ for (int i = 0; i < model.n_layers; i++) {+ free(model.layers[i].w);+ free(model.layers[i].w_scale);+ if (model.layers[i].bias) free(model.layers[i].bias);+ free(model.layers[i].act_scale);+ if (model.layers[i].packed_w) free(model.layers[i].packed_w);+ if (model.layers[i].col_sums) free(model.layers[i].col_sums);+ }+ return 0;+}+#endif /* DETECT_NO_MAIN */diff --git a/wasm/src/detect_api.c b/wasm/src/detect_api.cnew file mode 100644index 0000000..623cb32--- /dev/null+++ b/wasm/src/detect_api.c@@ -0,0 +1,97 @@+/*+ * detect_api.c — WASM API for face detection.+ * Wraps retinaface_forward_int8 into clean C functions exportable to JS.+ *+ * API:+ * detect_init(weights_path) → handle+ * detect_faces(handle, rgb_hwc, W, H, out_faces, max_faces) → n_faces+ * detect_free(handle)+ */++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* Include detect.c but skip its main() */+#define DETECT_NO_MAIN+#include "detect.c"++/* ============ WASM API ============ */++typedef struct {+ Model model;+ int ready;+} DetectCtx;++DetectCtx* detect_init(const char* weights_path) {+ DetectCtx* ctx = (DetectCtx*)calloc(1, sizeof(DetectCtx));+ if (!ctx) return NULL;++ if (load_model(weights_path, &ctx->model) != 0) {+ free(ctx);+ return NULL;+ }+ ctx->ready = 1;+ return ctx;+}++/* Output face struct for JS — flat floats for easy reading */+typedef struct {+ float x1, y1, x2, y2; /* bounding box */+ float score;+ float kps[10]; /* 5 keypoints × (x,y) */+} DetectFace;++int detect_faces(DetectCtx* ctx, const float* rgb_hwc, int W, int H,+ DetectFace* out_faces, int max_faces) {+ if (!ctx || !ctx->ready) return 0;++ /* Run forward pass */+ HeadOutput h8, h16, h32;+ forward(&ctx->model, rgb_hwc, H, W, &h8, &h16, &h32);++ /* Postprocess — NMS + decode */+ Face faces[256];+ int det_size = W > H ? W : H;+ int n = postprocess_retinaface(+ h8.cls, h8.bbox, h8.kps,+ h16.cls, h16.bbox, h16.kps,+ h32.cls, h32.bbox, h32.kps,+ det_size, W, H,+ 0.30f, 0.4f,+ faces, 256);++ /* Copy to output */+ if (n > max_faces) n = max_faces;+ for (int i = 0; i < n; i++) {+ out_faces[i].x1 = faces[i].x1;+ out_faces[i].y1 = faces[i].y1;+ out_faces[i].x2 = faces[i].x2;+ out_faces[i].y2 = faces[i].y2;+ out_faces[i].score = faces[i].score;+ for (int j = 0; j < 5; j++) {+ out_faces[i].kps[j*2] = faces[i].kps[j][0];+ out_faces[i].kps[j*2+1] = faces[i].kps[j][1];+ }+ }++ /* Cleanup head outputs */+ free(h8.cls); free(h8.bbox); free(h8.kps);+ free(h16.cls); free(h16.bbox); free(h16.kps);+ free(h32.cls); free(h32.bbox); free(h32.kps);++ return n;+}++void detect_free(DetectCtx* ctx) {+ if (!ctx) return;+ for (int i = 0; i < ctx->model.n_layers; i++) {+ free(ctx->model.layers[i].w);+ free(ctx->model.layers[i].w_scale);+ if (ctx->model.layers[i].bias) free(ctx->model.layers[i].bias);+ free(ctx->model.layers[i].act_scale);+ if (ctx->model.layers[i].packed_w) free(ctx->model.layers[i].packed_w);+ if (ctx->model.layers[i].col_sums) free(ctx->model.layers[i].col_sums);+ }+ free(ctx);+}diff --git a/wasm/src/dw_conv_fused.c b/wasm/src/dw_conv_fused.cnew file mode 100644index 0000000..1c1ca4a--- /dev/null+++ b/wasm/src/dw_conv_fused.c@@ -0,0 +1,178 @@+/*+ * depthwise_conv3x3_int8_fused.c — Fused DW conv + epilogue.+ *+ * Combines depthwise 3x3 INT8 convolution with dequant+bias+ReLU+requant+ * in a single pass, eliminating the intermediate INT32 buffer.+ *+ * For each output position: accumulate 9 kernel positions in registers,+ * then apply epilogue inline → write int8 directly.+ *+ * This saves one full read+write of the INT32 buffer (~6.4MB for 320x320x16).+ */++#include <stdint.h>+#include <string.h>+#include <math.h>++#ifdef __AVX2__+#include <immintrin.h>+#ifdef __wasm_simd128__+#include "../../include/wasm_compat.h"+#endif+#endif++void depthwise_conv3x3_int8_fused(+ const int8_t* in, int H, int W, int C,+ const int8_t* weights_9xC, /* [9, C] layout */+ int8_t* out, /* [OH, OW, C] int8 output (fused) */+ int stride, int pad,+ const float* w_scale, /* [C] weight scale per channel */+ const float* bias, /* [C] bias or NULL */+ const float* act_scale, /* [C] output activation scale (per-tensor: all same) */+ float in_scale, /* input activation scale (1.0 with fold) */+ int do_relu)+{+ int OH = (H + 2 * pad - 3) / stride + 1;+ int OW = (W + 2 * pad - 3) / stride + 1;++ /* Precompute combined scale and inv_out per channel */+ float cs_buf[320], inv_buf[320];+ for (int c = 0; c < C; c++) {+ cs_buf[c] = in_scale * w_scale[c];+ inv_buf[c] = 1.0f / (act_scale[c] + 1e-9f);+ }++#ifdef __AVX2__+ /* Preload scale vectors for channels (process 8 at a time) */+ #pragma omp parallel for schedule(static)+ for (int oy = 0; oy < OH; oy++) {+ for (int ox = 0; ox < OW; ox++) {+ int8_t* out_ptr = out + ((size_t)oy * OW + ox) * C;+ int c = 0;++ for (; c + 8 <= C; c += 8) {+ /* Accumulate 9 kernel positions in int32 registers */+ __m256i vacc = _mm256_setzero_si256();++ for (int ky = 0; ky < 3; ky++) {+ int iy = oy * stride - pad + ky;+ if (iy < 0 || iy >= H) continue;++ for (int kx = 0; kx < 3; kx++) {+ int ix = ox * stride - pad + kx;+ if (ix < 0 || ix >= W) continue;++ const int8_t* in_ptr = in + ((size_t)iy * W + ix) * C + c;+ int ki = ky * 3 + kx;+ const int8_t* w_ptr = weights_9xC + (size_t)ki * C + c;++ /* Load 8 int8 input and weight values */+ __m128i vi8 = _mm_loadl_epi64((const __m128i*)in_ptr);+ __m128i vw8 = _mm_loadl_epi64((const __m128i*)w_ptr);++ /* Sign-extend to int16 */+ __m256i vi16 = _mm256_cvtepi8_epi16(vi8);+ __m256i vw16 = _mm256_cvtepi8_epi16(vw8);++ /* Multiply pairs and add adjacent → int32 (8 results) */+ /* Actually mullo_epi16 gives 16 int16 products, need extend */+ __m256i prod16 = _mm256_mullo_epi16(vi16, vw16);++ /* Extend int16 products to int32 */+ __m128i prod_lo = _mm256_castsi256_si128(prod16);+ __m128i prod_hi = _mm256_extracti128_si256(prod16, 1);+ __m256i prod32_lo = _mm256_cvtepi16_epi32(prod_lo);+ __m256i prod32_hi = _mm256_cvtepi16_epi32(prod_hi);++ /* We have 16 int32 products but only need 8 channels */+ /* cvtepi8_epi16 on 8 bytes gives 8 int16 in low 128 bits + 0 in high */+ /* Wait: _mm_loadl_epi64 loads 8 bytes into low 64 bits of 128-bit */+ /* _mm256_cvtepi8_epi16 extends 16 bytes from 128-bit to 16 int16 in 256-bit */+ /* But we only loaded 8 bytes! The high 8 bytes are garbage. */+ /* Fix: only use the low 8 products */+ vacc = _mm256_add_epi32(vacc, prod32_lo);+ }+ }++ /* Epilogue: dequant + bias + relu + requant (8 channels at once) */+ __m256 vfp = _mm256_cvtepi32_ps(vacc);+ __m256 vcs = _mm256_loadu_ps(cs_buf + c);+ vfp = _mm256_mul_ps(vfp, vcs);++ if (bias) vfp = _mm256_add_ps(vfp, _mm256_loadu_ps(bias + c));+ if (do_relu) vfp = _mm256_max_ps(vfp, _mm256_setzero_ps());++ __m256 vinv = _mm256_loadu_ps(inv_buf + c);+ vfp = _mm256_mul_ps(vfp, vinv);++ /* Round to nearest */+ __m256i vi32 = _mm256_cvtps_epi32(vfp);++ /* Clamp [-128, 127] */+ vi32 = _mm256_max_epi32(vi32, _mm256_set1_epi32(-128));+ vi32 = _mm256_min_epi32(vi32, _mm256_set1_epi32(127));++ /* Pack int32 → int8 */+ __m128i lo = _mm256_castsi256_si128(vi32);+ __m128i hi = _mm256_extracti128_si256(vi32, 1);+ __m128i i16 = _mm_packs_epi32(lo, hi);+ __m128i i8 = _mm_packs_epi16(i16, i16);+ /* Store 8 bytes */+ _mm_storel_epi64((__m128i*)(out_ptr + c), i8);+ }++ /* Scalar remainder */+ for (; c < C; c++) {+ int32_t acc = 0;+ for (int ky = 0; ky < 3; ky++) {+ int iy = oy * stride - pad + ky;+ if (iy < 0 || iy >= H) continue;+ for (int kx = 0; kx < 3; kx++) {+ int ix = ox * stride - pad + kx;+ if (ix < 0 || ix >= W) continue;+ int ki = ky * 3 + kx;+ acc += (int32_t)in[((size_t)iy * W + ix) * C + c]+ * (int32_t)weights_9xC[(size_t)ki * C + c];+ }+ }+ float fp = (float)acc * cs_buf[c];+ if (bias) fp += bias[c];+ if (do_relu && fp < 0) fp = 0;+ int q = (int)lrintf(fp * inv_buf[c]);+ if (q > 127) q = 127;+ if (q < -128) q = -128;+ out_ptr[c] = (int8_t)q;+ }+ }+ }+#else+ /* Scalar fallback */+ #pragma omp parallel for schedule(static)+ for (int oy = 0; oy < OH; oy++) {+ for (int ox = 0; ox < OW; ox++) {+ int8_t* out_ptr = out + ((size_t)oy * OW + ox) * C;+ for (int c = 0; c < C; c++) {+ int32_t acc = 0;+ for (int ky = 0; ky < 3; ky++) {+ int iy = oy * stride - pad + ky;+ if (iy < 0 || iy >= H) continue;+ for (int kx = 0; kx < 3; kx++) {+ int ix = ox * stride - pad + kx;+ if (ix < 0 || ix >= W) continue;+ int ki = ky * 3 + kx;+ acc += (int32_t)in[((size_t)iy * W + ix) * C + c]+ * (int32_t)weights_9xC[(size_t)ki * C + c];+ }+ }+ float fp = (float)acc * cs_buf[c];+ if (bias) fp += bias[c];+ if (do_relu && fp < 0) fp = 0;+ int q = (int)lrintf(fp * inv_buf[c]);+ if (q > 127) q = 127;+ if (q < -128) q = -128;+ out_ptr[c] = (int8_t)q;+ }+ }+ }+#endif+}diff --git a/wasm/src/dw_conv_int8.c b/wasm/src/dw_conv_int8.cnew file mode 100644index 0000000..b162231--- /dev/null+++ b/wasm/src/dw_conv_int8.c@@ -0,0 +1,222 @@+/*+ * Depthwise 3x3 convolution for INT8 inference.+ *+ * NHWC layout: input[H, W, C], output[OH, OW, C]+ * Each channel has its own 3x3 kernel (groups == C).+ *+ * Supports stride 1 and stride 2, padding 1.+ * INT8 input × INT8 weight → INT32 accumulator.+ *+ * The caller applies dequant + bias + activation via fused_epilogue_int8().+ */++#include <stdint.h>+#include <string.h>+#include <stdio.h>+#ifdef _OPENMP+#include <omp.h>+#endif++#ifdef __AVX2__+#include <immintrin.h>+#ifdef __wasm_simd128__+#include "../../include/wasm_compat.h"+#endif+#endif++/*+ * depthwise_conv3x3_int8:+ * in: [H, W, C] int8, NHWC layout+ * weights: [C, 9] int8, per-channel 3x3 filter (row-major)+ * out: [OH, OW, C] int32, NHWC layout (accumulator before dequant)+ *+ * H, W: input spatial dims+ * C: number of channels (= groups)+ * stride: 1 or 2+ * pad: 1 (standard 3x3 same padding)+ *+ * OH = (H + 2*pad - 3) / stride + 1+ * OW = (W + 2*pad - 3) / stride + 1+ */+void depthwise_conv3x3_int8(+ const int8_t* in, int H, int W, int C,+ const int8_t* weights, /* [C, 9] */+ int32_t* out,+ int stride, int pad)+{+ int OH = (H + 2 * pad - 3) / stride + 1;+ int OW = (W + 2 * pad - 3) / stride + 1;++ #pragma omp parallel for schedule(static) collapse(2)+ for (int oy = 0; oy < OH; oy++) {+ for (int ox = 0; ox < OW; ox++) {+ int32_t* out_ptr = out + ((size_t)oy * OW + ox) * C;++ /* Zero the output for this position */+ memset(out_ptr, 0, C * sizeof(int32_t));++ /* 3x3 kernel loop */+ for (int ky = 0; ky < 3; ky++) {+ int iy = oy * stride - pad + ky;+ if (iy < 0 || iy >= H) continue;++ for (int kx = 0; kx < 3; kx++) {+ int ix = ox * stride - pad + kx;+ if (ix < 0 || ix >= W) continue;++ const int8_t* in_ptr = in + ((size_t)iy * W + ix) * C;+ int ki = ky * 3 + kx; /* kernel index 0..8 */++ int c = 0;++#ifdef __AVX2__+ /* Process 32 channels at a time */+ for (; c + 32 <= C; c += 32) {+ __m256i vi = _mm256_loadu_si256((const __m256i*)(in_ptr + c));+ /* Load 32 weight bytes for this kernel position */+ /* weights layout: [C, 9], stride = 9 per channel */+ /* We need weights[c+0..c+31][ki] — scattered! */+ /* Gather would be slow, so use scalar for now */+ /* TODO: repack weights to [9, C] layout for vectorization */++ /* Scalar fallback for scattered weights */+ for (int cc = 0; cc < 32; cc++) {+ out_ptr[c + cc] += (int32_t)in_ptr[c + cc] * (int32_t)weights[(c + cc) * 9 + ki];+ }+ }+#endif+ /* Scalar remainder */+ for (; c < C; c++) {+ out_ptr[c] += (int32_t)in_ptr[c] * (int32_t)weights[c * 9 + ki];+ }+ }+ }+ }+ }+}+++/*+ * Optimized version with repacked weights: [9, C] layout instead of [C, 9].+ * This allows vectorized loads for all channels at each kernel position.+ */+void depthwise_conv3x3_int8_fast(+ const int8_t* in, int H, int W, int C,+ const int8_t* weights_9xC, /* [9, C] layout — repacked */+ int32_t* out,+ int stride, int pad)+{+ int OH = (H + 2 * pad - 3) / stride + 1;+ int OW = (W + 2 * pad - 3) / stride + 1;+ fprintf(stderr, " [DW_fast] H=%d W=%d C=%d pad=%d stride=%d -> OH=%d OW=%d out_bytes=%d\n",+ H, W, C, pad, stride, OH, OW, (int)((size_t)OH*OW*C*4)); fflush(stderr);++ #pragma omp parallel for schedule(static) collapse(2)+ for (int oy = 0; oy < OH; oy++) {+ for (int ox = 0; ox < OW; ox++) {+ int32_t* out_ptr = out + ((size_t)oy * OW + ox) * C;+ memset(out_ptr, 0, C * sizeof(int32_t));++ for (int ky = 0; ky < 3; ky++) {+ int iy = oy * stride - pad + ky;+ if (iy < 0 || iy >= H) continue;++ for (int kx = 0; kx < 3; kx++) {+ int ix = ox * stride - pad + kx;+ if (ix < 0 || ix >= W) continue;++ const int8_t* in_ptr = in + ((size_t)iy * W + ix) * C;+ int ki = ky * 3 + kx;+ const int8_t* w_ptr = weights_9xC + (size_t)ki * C;++ int c = 0;++#ifdef __AVX2__+ /* Process 32 channels at a time with vectorized loads */+ for (; c + 32 <= C; c += 32) {+ __m256i vi = _mm256_loadu_si256((const __m256i*)(in_ptr + c));+ __m256i vw = _mm256_loadu_si256((const __m256i*)(w_ptr + c));++ /* Multiply int8 × int8 → int16, then accumulate to int32 */+ /* Split into low and high 128-bit halves */+ __m128i vi_lo = _mm256_castsi256_si128(vi);+ __m128i vi_hi = _mm256_extracti128_si256(vi, 1);+ __m128i vw_lo = _mm256_castsi256_si128(vw);+ __m128i vw_hi = _mm256_extracti128_si256(vw, 1);++ /* Extend to int16 and multiply */+ /* Process 8 elements at a time → int32 */+ /* Low quarter: elements 0..7 */+ __m256i vi16_0 = _mm256_cvtepi8_epi16(vi_lo);+ __m256i vw16_0 = _mm256_cvtepi8_epi16(vw_lo);+ __m256i prod_0 = _mm256_mullo_epi16(vi16_0, vw16_0);++ /* Extend int16 products to int32 and accumulate */+ __m256i prod_lo = _mm256_cvtepi16_epi32(_mm256_castsi256_si128(prod_0));+ __m256i prod_hi = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(prod_0, 1));++ __m256i acc_0 = _mm256_loadu_si256((__m256i*)(out_ptr + c));+ __m256i acc_1 = _mm256_loadu_si256((__m256i*)(out_ptr + c + 8));+ acc_0 = _mm256_add_epi32(acc_0, prod_lo);+ acc_1 = _mm256_add_epi32(acc_1, prod_hi);+ _mm256_storeu_si256((__m256i*)(out_ptr + c), acc_0);+ _mm256_storeu_si256((__m256i*)(out_ptr + c + 8), acc_1);++ /* High quarter: elements 8..15 already handled, now 16..23 */+ __m256i vi16_1 = _mm256_cvtepi8_epi16(vi_hi);+ __m256i vw16_1 = _mm256_cvtepi8_epi16(vw_hi);+ __m256i prod_1 = _mm256_mullo_epi16(vi16_1, vw16_1);++ __m256i prod_lo2 = _mm256_cvtepi16_epi32(_mm256_castsi256_si128(prod_1));+ __m256i prod_hi2 = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(prod_1, 1));++ __m256i acc_2 = _mm256_loadu_si256((__m256i*)(out_ptr + c + 16));+ __m256i acc_3 = _mm256_loadu_si256((__m256i*)(out_ptr + c + 24));+ acc_2 = _mm256_add_epi32(acc_2, prod_lo2);+ acc_3 = _mm256_add_epi32(acc_3, prod_hi2);+ _mm256_storeu_si256((__m256i*)(out_ptr + c + 16), acc_2);+ _mm256_storeu_si256((__m256i*)(out_ptr + c + 24), acc_3);+ }++ /* Process 16 channels */+ for (; c + 16 <= C; c += 16) {+ __m128i vi8 = _mm_loadu_si128((const __m128i*)(in_ptr + c));+ __m128i vw8 = _mm_loadu_si128((const __m128i*)(w_ptr + c));++ __m256i vi16 = _mm256_cvtepi8_epi16(vi8);+ __m256i vw16 = _mm256_cvtepi8_epi16(vw8);+ __m256i prod = _mm256_mullo_epi16(vi16, vw16);++ __m256i prod_lo3 = _mm256_cvtepi16_epi32(_mm256_castsi256_si128(prod));+ __m256i prod_hi3 = _mm256_cvtepi16_epi32(_mm256_extracti128_si256(prod, 1));++ __m256i a0 = _mm256_loadu_si256((__m256i*)(out_ptr + c));+ __m256i a1 = _mm256_loadu_si256((__m256i*)(out_ptr + c + 8));+ a0 = _mm256_add_epi32(a0, prod_lo3);+ a1 = _mm256_add_epi32(a1, prod_hi3);+ _mm256_storeu_si256((__m256i*)(out_ptr + c), a0);+ _mm256_storeu_si256((__m256i*)(out_ptr + c + 8), a1);+ }+#endif+ for (; c < C; c++) {+ out_ptr[c] += (int32_t)in_ptr[c] * (int32_t)w_ptr[c];+ }+ }+ }+ }+ }+}+++/*+ * Repack weights from [C, 9] to [9, C] layout.+ * Call once at model load time.+ */+void repack_dw_weights(const int8_t* src_Cx9, int8_t* dst_9xC, int C)+{+ for (int c = 0; c < C; c++) {+ for (int ki = 0; ki < 9; ki++) {+ dst_9xC[ki * C + c] = src_Cx9[c * 9 + ki];+ }+ }+}diff --git a/wasm/src/gemm_int8_rsimd.c b/wasm/src/gemm_int8_rsimd.cnew file mode 100644index 0000000..3c21050--- /dev/null+++ b/wasm/src/gemm_int8_rsimd.c@@ -0,0 +1,132 @@+/*+ * gemm_int8_rsimd.c — INT8 GEMM for WASM with Relaxed SIMD dot product.+ *+ * Matches exact signatures expected by detect.c (retinaface_forward_int8).+ * Uses wasm_i32x4_relaxed_dot_i8x16_i7x16_add() → VPDPBUSD on x86, SDOT on ARM.+ */++#include <stdint.h>+#include <stdlib.h>+#include <string.h>+#include <wasm_simd128.h>++/* ============ Weight packing ============ */++void pack_weights_4x8c8(const int8_t* weights, const float* bias, int K, int Cout,+ void* packed_w, int32_t* col_sums) {+ (void)bias;+ int K16 = (K + 15) & ~15;+ int8_t* dst = (int8_t*)packed_w;+ memset(dst, 0, (size_t)Cout * K16);++ for (int n = 0; n < Cout; n++)+ for (int k = 0; k < K; k++)+ dst[n * K16 + k] = weights[n * K + k];++ if (col_sums) {+ int Cout8 = (Cout + 7) & ~7;+ memset(col_sums, 0, Cout8 * sizeof(int32_t));+ for (int n = 0; n < Cout; n++) {+ int32_t s = 0;+ for (int k = 0; k < K; k++) s += (int32_t)weights[n * K + k];+ col_sums[n] = s;+ }+ }+}++int packed_weights_size_4x8c8(int K, int Cout) {+ return Cout * ((K + 15) & ~15);+}++/* ============ Core GEMM ============ */+/* C_i32[M,N] = A_s8[M,K] @ B_s8[N,K]^T+ * Note: relaxed dot treats first arg as unsigned, second as signed.+ * Our A is signed int8 — we offset by 128 to make it unsigned,+ * then compensate via col_sums. */++void int8_gemm_4x8c8(const int8_t* A, int M, int K, int N,+ const void* B_packed, int32_t* C, const int32_t* col_sums) {+ const int8_t* B = (const int8_t*)B_packed;+ int K16 = (K + 15) & ~15;++ for (int m = 0; m < M; m++) {+ for (int n = 0; n < N; n++) {+ v128_t acc = wasm_i32x4_splat(0);+ int k = 0;++ for (; k + 16 <= K; k += 16) {+ /* Convert A from signed to unsigned: a_u8 = a_s8 + 128 */+ v128_t va_s8 = wasm_v128_load(A + m * K + k);+ v128_t offset = wasm_i8x16_splat(-128); /* 0x80 */+ v128_t va_u8 = wasm_i8x16_sub(va_s8, offset); /* a + 128 = unsigned */++ v128_t vb = wasm_v128_load(B + n * K16 + k);+ acc = wasm_i32x4_relaxed_dot_i8x16_i7x16_add(va_u8, vb, acc);+ }++ int32_t sum = wasm_i32x4_extract_lane(acc, 0)+ + wasm_i32x4_extract_lane(acc, 1)+ + wasm_i32x4_extract_lane(acc, 2)+ + wasm_i32x4_extract_lane(acc, 3);++ /* Scalar remainder */+ for (; k < K; k++)+ sum += (int32_t)A[m * K + k] * (int32_t)B[n * K16 + k];++ /* Compensate for unsigned offset: subtract 128 * col_sum */+ if (col_sums)+ sum -= 128 * col_sums[n];++ C[m * N + n] = sum;+ }+ }+}++/* ============ Fused GEMM + dequant + bias + relu + requant ============ */++void int8_gemm_4x8c8_fused(+ const int8_t* A, int M, int K, int N,+ const void* B_packed, int8_t* out, const int32_t* col_sums,+ const float* w_scales, const float* bias, const float* act_scale, int do_relu) {++ const int8_t* B = (const int8_t*)B_packed;+ int K16 = (K + 15) & ~15;++ for (int m = 0; m < M; m++) {+ for (int n = 0; n < N; n++) {+ v128_t acc = wasm_i32x4_splat(0);+ int k = 0;++ for (; k + 16 <= K; k += 16) {+ v128_t va_s8 = wasm_v128_load(A + m * K + k);+ v128_t offset = wasm_i8x16_splat(-128);+ v128_t va_u8 = wasm_i8x16_sub(va_s8, offset);+ v128_t vb = wasm_v128_load(B + n * K16 + k);+ acc = wasm_i32x4_relaxed_dot_i8x16_i7x16_add(va_u8, vb, acc);+ }++ int32_t isum = wasm_i32x4_extract_lane(acc, 0)+ + wasm_i32x4_extract_lane(acc, 1)+ + wasm_i32x4_extract_lane(acc, 2)+ + wasm_i32x4_extract_lane(acc, 3);++ for (; k < K; k++)+ isum += (int32_t)A[m * K + k] * (int32_t)B[n * K16 + k];++ if (col_sums)+ isum -= 128 * col_sums[n];++ /* Dequant to float */+ float val = (float)isum * w_scales[n];+ if (bias) val += bias[n];+ if (do_relu && val < 0) val = 0;++ /* Requant to INT8 */+ float scale = act_scale ? act_scale[n] : 1.0f;+ int q = (int)(val / scale + (val >= 0 ? 0.5f : -0.5f));+ if (q > 127) q = 127;+ if (q < -128) q = -128;+ out[m * N + n] = (int8_t)q;+ }+ }+}diff --git a/wasm/src/gemm_int8_scalar.c b/wasm/src/gemm_int8_scalar.cnew file mode 100644index 0000000..44b7858--- /dev/null+++ b/wasm/src/gemm_int8_scalar.c@@ -0,0 +1,92 @@+/*+ * gemm_int8_scalar.c — Scalar INT8 GEMM for WASM builds.+ * Replaces AVX2 gemm_int8_4x8c8 with portable scalar implementation.+ * Used by detector (retinaface_forward_int8).+ */++#include <stdint.h>+#include <stdlib.h>+#include <string.h>++/* Pack weights into c8 format — for WASM we store as-is since no SIMD packing needed */+void pack_weights_4x8c8(const int8_t* w, const float* scales, int K, int N,+ void* packed, int32_t* col_sums) {+ /* Simple copy — WASM scalar GEMM reads weights linearly */+ int N8 = (N + 7) & ~7;+ memset(packed, 0, (size_t)N8 * K);+ int8_t* dst = (int8_t*)packed;+ for (int n = 0; n < N; n++) {+ for (int k = 0; k < K; k++) {+ dst[n * K + k] = w[n * K + k];+ }+ }+ /* Compute column sums for zero-point compensation */+ if (col_sums) {+ memset(col_sums, 0, N8 * sizeof(int32_t));+ for (int n = 0; n < N; n++) {+ int32_t sum = 0;+ for (int k = 0; k < K; k++)+ sum += (int32_t)w[n * K + k];+ col_sums[n] = sum;+ }+ }+}++int packed_weights_size_4x8c8(int K, int N) {+ int N8 = (N + 7) & ~7;+ return N8 * K;+}++/* Scalar INT8 GEMM: C[M,N] = A_u8[M,K] @ B_s8[N,K]^T+ * A is unsigned (uint8_t), B is signed (int8_t in packed format).+ * Output is int32 accumulators. */+void int8_gemm_4x8c8(int M, int N, int K,+ const uint8_t* A, int lda,+ const void* B_packed,+ const int32_t* col_sums,+ int32_t* C, int ldc) {+ const int8_t* B = (const int8_t*)B_packed;+ for (int m = 0; m < M; m++) {+ for (int n = 0; n < N; n++) {+ int32_t acc = 0;+ for (int k = 0; k < K; k++) {+ acc += (int32_t)A[m * lda + k] * (int32_t)B[n * K + k];+ }+ C[m * ldc + n] = acc;+ }+ }+}++/* Fused version with dequant + bias + requant */+void int8_gemm_4x8c8_fused(+ int M, int N, int K,+ const uint8_t* A, int lda,+ const void* B_packed,+ const int32_t* col_sums,+ const float* w_scales, const float* act_scale,+ const float* bias,+ float a_scale, uint8_t a_zero,+ int8_t* out, int out_stride,+ float out_scale) {+ const int8_t* B = (const int8_t*)B_packed;+ for (int m = 0; m < M; m++) {+ for (int n = 0; n < N; n++) {+ int32_t acc = 0;+ for (int k = 0; k < K; k++)+ acc += (int32_t)A[m * lda + k] * (int32_t)B[n * K + k];+ /* Dequant: acc * a_scale * w_scale - col_sum * a_zero * w_scale + bias */+ float val = (float)acc * a_scale * w_scales[n];+ if (col_sums)+ val -= (float)col_sums[n] * (float)a_zero * w_scales[n];+ if (bias)+ val += bias[n];+ /* Requant to INT8 */+ if (out_scale > 0) {+ int q = (int)(val / out_scale + 0.5f);+ if (q > 127) q = 127;+ if (q < -128) q = -128;+ out[m * out_stride + n] = (int8_t)q;+ }+ }+ }+}diff --git a/wasm/src/postprocess.c b/wasm/src/postprocess.cnew file mode 100644index 0000000..d5b4dc8--- /dev/null+++ b/wasm/src/postprocess.c@@ -0,0 +1,188 @@+/*+ * retinaface_postprocess.c — NMS + bbox/kps decode for RetinaFace det_500m.+ *+ * Takes FP32 head outputs (cls, bbox, kps × 3 strides) and produces+ * a list of detected faces with bounding boxes and 5 landmarks.+ */++#include <stdio.h>+#include <stdlib.h>+#include <stdint.h>+#include <math.h>++#define MAX_FACES 256++typedef struct {+ float x1, y1, x2, y2;+ float score;+ float kps[5][2]; /* left_eye, right_eye, nose, left_mouth, right_mouth */+} Face;++/* Decode one stride's outputs into face candidates */+static int decode_stride(+ const float* cls, const float* bbox, const float* kps_data,+ int feat_h, int feat_w, int stride, int num_anchors,+ float conf_thresh, float inv_scale,+ Face* out_faces, int max_faces)+{+ int count = 0;++ for (int y = 0; y < feat_h; y++) {+ for (int x = 0; x < feat_w; x++) {+ for (int a = 0; a < num_anchors; a++) {+ int idx = (y * feat_w + x) * num_anchors + a;+ float score = cls[idx]; /* already sigmoid */++ if (score < conf_thresh || count >= max_faces)+ continue;++ float cx = (x + 0.5f) * stride;+ float cy = (y + 0.5f) * stride;+ float s = (float)stride;++ /* Decode bbox: distance format (left, top, right, bottom) */+ int bi = idx * 4;+ float x1 = (cx - bbox[bi + 0] * s) * inv_scale;+ float y1 = (cy - bbox[bi + 1] * s) * inv_scale;+ float x2 = (cx + bbox[bi + 2] * s) * inv_scale;+ float y2 = (cy + bbox[bi + 3] * s) * inv_scale;++ /* INT8 bbox correction: subtract systematic +5% shift+ * caused by quantization-induced feature map centroid offset */+ float bw = x2 - x1, bh = y2 - y1;+ x1 -= 0.050f * bw; y1 -= 0.040f * bh;+ x2 -= 0.055f * bw; y2 -= 0.047f * bh;++ /* Decode keypoints */+ int ki = idx * 10;+ Face* f = &out_faces[count];+ f->x1 = x1; f->y1 = y1;+ f->x2 = x2; f->y2 = y2;+ f->score = score;++ for (int k = 0; k < 5; k++) {+ f->kps[k][0] = (cx + kps_data[ki + k * 2] * s) * inv_scale - 0.050f * bw;+ f->kps[k][1] = (cy + kps_data[ki + k * 2 + 1] * s) * inv_scale - 0.040f * bh;+ }+ count++;+ }+ }+ }+ return count;+}++/* IoU between two faces */+static float iou(const Face* a, const Face* b) {+ float xx1 = a->x1 > b->x1 ? a->x1 : b->x1;+ float yy1 = a->y1 > b->y1 ? a->y1 : b->y1;+ float xx2 = a->x2 < b->x2 ? a->x2 : b->x2;+ float yy2 = a->y2 < b->y2 ? a->y2 : b->y2;+ float w = xx2 - xx1 > 0 ? xx2 - xx1 : 0;+ float h = yy2 - yy1 > 0 ? yy2 - yy1 : 0;+ float inter = w * h;+ float area_a = (a->x2 - a->x1) * (a->y2 - a->y1);+ float area_b = (b->x2 - b->x1) * (b->y2 - b->y1);+ return inter / (area_a + area_b - inter + 1e-9f);+}++/* Simple insertion sort by score descending */+static void sort_faces(Face* faces, int n) {+ for (int i = 1; i < n; i++) {+ Face key = faces[i];+ int j = i - 1;+ while (j >= 0 && faces[j].score < key.score) {+ faces[j + 1] = faces[j];+ j--;+ }+ faces[j + 1] = key;+ }+}++/* Greedy NMS */+static int nms_faces(Face* faces, int n, float iou_thresh) {+ if (n <= 1) return n;+ sort_faces(faces, n);++ int* suppressed = (int*)calloc(n, sizeof(int));+ int keep = 0;++ for (int i = 0; i < n; i++) {+ if (suppressed[i]) continue;+ if (keep != i) faces[keep] = faces[i];+ for (int j = i + 1; j < n; j++) {+ if (!suppressed[j] && iou(&faces[i], &faces[j]) > iou_thresh) {+ suppressed[j] = 1;+ }+ }+ keep++;+ }+ free(suppressed);+ return keep;+}++/*+ * postprocess: Decode all 3 heads + NMS.+ *+ * head_cls/bbox/kps arrays are in NHWC→reshaped format:+ * cls: [feat_h * feat_w, num_anchors] (already sigmoid)+ * bbox: [feat_h * feat_w * num_anchors, 4]+ * kps: [feat_h * feat_w * num_anchors, 10]+ *+ * det_size: input image size (e.g. 640)+ * img_w, img_h: original image dimensions (for scaling)+ * conf_thresh: minimum confidence (e.g. 0.5)+ *+ * Returns number of faces written to out_faces.+ */+int postprocess_retinaface(+ const float* cls8, const float* bbox8, const float* kps8,+ const float* cls16, const float* bbox16, const float* kps16,+ const float* cls32, const float* bbox32, const float* kps32,+ int det_size, int img_w, int img_h,+ float conf_thresh, float iou_thresh,+ Face* out_faces, int max_out)+{+ float scale = (float)det_size / (float)(img_w > img_h ? img_w : img_h);+ float inv_scale = 1.0f / scale;++ /* Collect candidates from all strides */+ Face candidates[MAX_FACES * 3];+ int total = 0;++ int strides[] = {8, 16, 32};+ const float* cls_ptrs[] = {cls8, cls16, cls32};+ const float* bbox_ptrs[] = {bbox8, bbox16, bbox32};+ const float* kps_ptrs[] = {kps8, kps16, kps32};++ for (int s = 0; s < 3; s++) {+ int feat = det_size / strides[s];+ int n = decode_stride(+ cls_ptrs[s], bbox_ptrs[s], kps_ptrs[s],+ feat, feat, strides[s], 2, /* 2 anchors per position */+ conf_thresh, inv_scale,+ candidates + total, MAX_FACES * 3 - total);+ total += n;+ }++ if (total == 0) return 0;++ /* NMS */+ int n_keep = nms_faces(candidates, total, iou_thresh);+ if (n_keep > max_out) n_keep = max_out;++ for (int i = 0; i < n_keep; i++)+ out_faces[i] = candidates[i];++ return n_keep;+}++/* Print face results */+void print_faces(const Face* faces, int n) {+ for (int i = 0; i < n; i++) {+ const Face* f = &faces[i];+ printf("face[%d] bbox=(%.0f,%.0f,%.0f,%.0f) score=%.3f\n",+ i, f->x1, f->y1, f->x2, f->y2, f->score);+ for (int k = 0; k < 5; k++)+ printf(" kp[%d]=(%.1f,%.1f)\n", k, f->kps[k][0], f->kps[k][1]);+ }+}diff --git a/wasm/src/upsample.c b/wasm/src/upsample.cnew file mode 100644index 0000000..1e06051--- /dev/null+++ b/wasm/src/upsample.c@@ -0,0 +1,111 @@+/*+ * Nearest-neighbor 2x upsample for INT8 NHWC tensors.+ * Used in FPN to merge feature maps from different strides.+ *+ * Input: [H, W, C] int8+ * Output: [2*H, 2*W, C] int8+ *+ * Each input pixel is replicated to a 2x2 block.+ */++#include <stdint.h>+#include <string.h>+#ifdef _OPENMP+#include <omp.h>+#endif++#ifdef __AVX2__+#include <immintrin.h>+#ifdef __wasm_simd128__+#include "../../include/wasm_compat.h"+#endif+#endif++void upsample2x_int8(+ const int8_t* in, int H, int W, int C,+ int8_t* out)+{+ int OW = W * 2;+ size_t row_bytes = (size_t)C * sizeof(int8_t);++ #pragma omp parallel for schedule(static)+ for (int y = 0; y < H; y++) {+ for (int x = 0; x < W; x++) {+ const int8_t* src = in + ((size_t)y * W + x) * C;+ /* Copy to 4 positions: (2y,2x), (2y,2x+1), (2y+1,2x), (2y+1,2x+1) */+ int8_t* dst00 = out + ((size_t)(2*y) * OW + 2*x) * C;+ int8_t* dst01 = out + ((size_t)(2*y) * OW + 2*x + 1) * C;+ int8_t* dst10 = out + ((size_t)(2*y + 1) * OW + 2*x) * C;+ int8_t* dst11 = out + ((size_t)(2*y + 1) * OW + 2*x + 1) * C;++ memcpy(dst00, src, row_bytes);+ memcpy(dst01, src, row_bytes);+ memcpy(dst10, src, row_bytes);+ memcpy(dst11, src, row_bytes);+ }+ }+}++/*+ * Element-wise add of two INT8 tensors with per-channel requantization.+ * Used in FPN: upsampled_feature + lateral_feature → merged+ *+ * out[i] = clip(round((a[i] * a_scale[c] + b[i] * b_scale[c]) * inv_out_scale[c]), -128, 127)+ *+ * NHWC layout: channel is innermost dimension.+ */+void add_int8_per_channel(+ const int8_t* a, const float* a_scale,+ const int8_t* b, const float* b_scale,+ int8_t* out, const float* inv_out_scale,+ int N_pos, int C)+{+ #pragma omp parallel for schedule(static)+ for (int p = 0; p < N_pos; p++) {+ const int8_t* ar = a + (size_t)p * C;+ const int8_t* br = b + (size_t)p * C;+ int8_t* orow = out + (size_t)p * C;++ int c = 0;+#ifdef __AVX2__+ for (; c + 8 <= C; c += 8) {+ /* Load 8 int8 values and sign-extend to int32 */+ __m128i ai8 = _mm_loadl_epi64((const __m128i*)(ar + c));+ __m128i bi8 = _mm_loadl_epi64((const __m128i*)(br + c));+ __m256 af = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(ai8));+ __m256 bf = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(bi8));++ __m256 as = _mm256_loadu_ps(a_scale + c);+ __m256 bs = _mm256_loadu_ps(b_scale + c);+ __m256 inv = _mm256_loadu_ps(inv_out_scale + c);++ __m256 result = _mm256_fmadd_ps(af, as, _mm256_mul_ps(bf, bs));+ result = _mm256_mul_ps(result, inv);++ /* Round to nearest */+ __m256 half = _mm256_set1_ps(0.5f);+ __m256 sign = _mm256_and_ps(result, _mm256_castsi256_ps(_mm256_set1_epi32(0x80000000)));+ __m256 rounder = _mm256_or_ps(half, sign);+ __m256i vi = _mm256_cvttps_epi32(_mm256_add_ps(result, rounder));++ /* Clamp to [-128, 127] */+ vi = _mm256_max_epi32(vi, _mm256_set1_epi32(-128));+ vi = _mm256_min_epi32(vi, _mm256_set1_epi32(127));++ /* Pack int32 → int8 */+ __m128i lo = _mm256_castsi256_si128(vi);+ __m128i hi = _mm256_extracti128_si256(vi, 1);+ __m128i i16 = _mm_packs_epi32(lo, hi);+ __m128i i8 = _mm_packs_epi16(i16, i16);+ _mm_storel_epi64((__m128i*)(orow + c), i8);+ }+#endif+ for (; c < C; c++) {+ float fp = (float)ar[c] * a_scale[c] + (float)br[c] * b_scale[c];+ int q = (int)(fp * inv_out_scale[c] + (fp >= 0 ? 0.5f : -0.5f));+ if (q > 127) q = 127;+ if (q < -128) q = -128;+ orow[c] = (int8_t)q;+ }+ }+}diff --git a/wasm/worker.js b/wasm/worker.jsnew file mode 100644index 0000000..3115118--- /dev/null+++ b/wasm/worker.js@@ -0,0 +1,115 @@+/*+ * worker.js — FaceX inference in a Web Worker.+ * Keeps main thread responsive while running detection + embedding.+ *+ * Messages:+ * {type: 'init'} → loads engines and weights+ * {type: 'detect', pixels: Float32Array, W, H} → returns faces+ * {type: 'embed', pixels: Float32Array} → returns embedding Float32Array+ */++importScripts('detect.js', 'facex.js');++let DetMod = null, FxMod = null;+let detHandle = 0, fxHandle = 0;++async function init() {+ DetMod = await FaceDetModule();+ FxMod = await FaceXModule();++ // Fetch weights+ const [detW, fxW] = await Promise.all([+ fetch('det_500m_int8.bin').then(r => r.arrayBuffer()),+ fetch('edgeface_xs_fp32.bin').then(r => r.arrayBuffer())+ ]);++ DetMod.FS.writeFile('/det.bin', new Uint8Array(detW));+ FxMod.FS.writeFile('/emb.bin', new Uint8Array(fxW));++ const di = DetMod.cwrap('detect_init', 'number', ['string']);+ detHandle = di('/det.bin');++ const fi = FxMod.cwrap('facex_init', 'number', ['string', 'string']);+ fxHandle = fi('/emb.bin', null);++ postMessage({ type: 'ready' });+}++function detect(pixels, W, H) {+ const nPx = W * H * 3;+ const inPtr = DetMod._malloc(nPx * 4);+ for (let i = 0; i < nPx; i++)+ DetMod.HEAPF32[(inPtr >> 2) + i] = pixels[i];++ const faceSize = 15 * 4;+ const maxFaces = 10;+ const outPtr = DetMod._malloc(faceSize * maxFaces);++ const df = DetMod.cwrap('detect_faces', 'number',+ ['number', 'number', 'number', 'number', 'number', 'number']);+ const nFaces = df(detHandle, inPtr, W, H, outPtr, maxFaces);++ const faces = [];+ for (let i = 0; i < nFaces; i++) {+ const base = (outPtr >> 2) + i * 15;+ faces.push({+ x1: DetMod.HEAPF32[base], y1: DetMod.HEAPF32[base+1],+ x2: DetMod.HEAPF32[base+2], y2: DetMod.HEAPF32[base+3],+ score: DetMod.HEAPF32[base+4],+ kps: Array.from(DetMod.HEAPF32.subarray(base+5, base+15))+ });+ }++ DetMod._free(inPtr);+ DetMod._free(outPtr);+ return faces;+}++function embed(pixels) {+ const N = 112 * 112 * 3;+ const inPtr = FxMod._malloc(N * 4);+ const outPtr = FxMod._malloc(512 * 4);++ for (let i = 0; i < N; i++)+ FxMod.HEAPF32[(inPtr >> 2) + i] = pixels[i];++ const fe = FxMod.cwrap('facex_embed', 'number', ['number', 'number', 'number']);+ fe(fxHandle, inPtr, outPtr);++ const emb = new Float32Array(512);+ emb.set(FxMod.HEAPF32.subarray(outPtr >> 2, (outPtr >> 2) + 512));++ FxMod._free(inPtr);+ FxMod._free(outPtr);+ return emb;+}++onmessage = async function(e) {+ const msg = e.data;+ switch (msg.type) {+ case 'init':+ await init();+ break;+ case 'detect':+ const faces = detect(msg.pixels, msg.W, msg.H);+ postMessage({ type: 'detect', faces });+ break;+ case 'embed':+ const emb = embed(msg.pixels);+ postMessage({ type: 'embed', emb }, [emb.buffer]);+ break;+ case 'pipeline': {+ const t0 = performance.now();+ const f = detect(msg.detPixels, msg.detW, msg.detH);+ const detMs = performance.now() - t0;+ let emb = null, embMs = 0;+ if (msg.embPixels) {+ const t1 = performance.now();+ emb = embed(msg.embPixels);+ embMs = performance.now() - t1;+ }+ postMessage({ type: 'pipeline', faces: f, emb, detMs, embMs }, emb ? [emb.buffer] : []);+ break;+ }+ }+};