Skip to content

armgit / facex

Public Imported from GitHub
0

Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.

v1.0.0 — Initial public release

atynovd8107aa1b3c1
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..402ba99
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+*.o
+*.a
+*.exe
+*.bin
+*.enc
+*.dll
+*.so
+*.dylib
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..4db7873
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for describing the origin of the Work and
+ reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may accept and charge a
+ fee for acceptance of support, warranty, indemnity, or other liability
+ obligations and/or rights consistent with this License. However, in
+ accepting such obligations, You may act only on Your own behalf and on
+ Your sole responsibility, not on behalf of any other Contributor, and
+ only if You agree to indemnify, defend, and hold each Contributor
+ harmless for any liability incurred by, or claims asserted against,
+ such Contributor by reason of your accepting any such warranty or
+ additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 Bauratynov
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..c855306
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,60 @@
+# FaceX — Fast face embedding library
+# 3ms inference, 7MB binary, zero dependencies
+#
+# Build: make
+# Test: make example && ./facex-example
+
+CC ?= gcc
+CFLAGS = -O3 -march=native -mfma -funroll-loops
+LDFLAGS = -lm -lpthread
+
+# Detect AVX-512
+AVX512 := $(shell $(CC) -mavx512f -dM -E - < /dev/null 2>/dev/null | grep -c AVX512F)
+ifeq ($(AVX512),1)
+ CFLAGS += -mavx512f -mavx512vnni -mprefer-vector-width=512
+endif
+
+ifeq ($(OS),Windows_NT)
+ LDFLAGS += -lsynchronization
+ EXT = .exe
+endif
+
+SRCS = src/facex.c src/transformer_ops.c src/gemm_int8_4x8c8.c src/threadpool.c
+
+.PHONY: all clean example lib cli encrypt
+
+all: lib cli
+
+# Static library
+lib: libfacex.a
+
+libfacex.a: $(SRCS)
+ $(CC) $(CFLAGS) -DFACEX_LIB -c src/facex.c -o facex.o
+ $(CC) $(CFLAGS) -c src/transformer_ops.c -o transformer_ops.o
+ $(CC) $(CFLAGS) -c src/gemm_int8_4x8c8.c -o gemm_int8_4x8c8.o
+ $(CC) $(CFLAGS) -c src/threadpool.c -o threadpool.o
+ ar rcs $@ facex.o transformer_ops.o gemm_int8_4x8c8.o threadpool.o
+ @rm -f *.o
+ @echo "Built libfacex.a"
+
+# Standalone CLI (for Go subprocess / testing)
+cli: facex-cli$(EXT)
+
+facex-cli$(EXT): src/edgeface_engine.c src/transformer_ops.c src/gemm_int8_4x8c8.c src/threadpool.c src/weight_crypto.c
+ $(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)
+ @echo "Built facex-cli$(EXT)"
+
+# Example program
+example: facex-example$(EXT)
+
+facex-example$(EXT): examples/example.c libfacex.a
+ $(CC) $(CFLAGS) -Iinclude -o $@ $< -L. -lfacex $(LDFLAGS)
+
+# Encryption tool
+encrypt: facex-encrypt$(EXT)
+
+facex-encrypt$(EXT): src/weight_crypto.c
+ $(CC) $(CFLAGS) -DWEIGHT_CRYPTO_MAIN -o $@ $< $(LDFLAGS)
+
+clean:
+ rm -f libfacex.a facex-cli$(EXT) facex-example$(EXT) facex-encrypt$(EXT) *.o
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d5b5cb7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,92 @@
+# FaceX
+
+Fast face embedding library. 3ms inference, 7MB binary, zero dependencies.
+
+Handwritten C + AVX2/AVX-512. Faster than ONNX Runtime on CPU.
+
+## Benchmarks
+
+EdgeFace-XS (1.77M params, 99.73% LFW) on Intel i5-11500:
+
+| Engine | Median | Min |
+|--------|--------|-----|
+| **FaceX** | **3.0 ms** | **2.87 ms** |
+| ONNX Runtime 1.23 | 3.9 ms | 3.18 ms |
+| InsightFace (R34) | 17 ms | — |
+| dlib | 50-80 ms | — |
+
+## Quick Start
+
+```c
+#include "facex.h"
+
+FaceX* fx = facex_init("edgeface_xs_fp32.bin", NULL);
+
+float embedding[512];
+facex_embed(fx, rgb_112x112_hwc, embedding);
+
+float sim = facex_similarity(emb1, emb2);
+// sim > 0.3 → same person
+
+facex_free(fx);
+```
+
+## Build
+
+```bash
+make # builds libfacex.a + facex-cli
+make example
+./facex-example edgeface_xs_fp32.bin
+```
+
+Requirements: GCC with AVX2 support. No other dependencies.
+
+## API
+
+```c
+FaceX* facex_init(const char* weights_path, const char* license_key);
+int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]);
+float facex_similarity(const float emb1[512], const float emb2[512]);
+void facex_free(FaceX* fx);
+```
+
+**Input:** 112x112 RGB image as float32 array in HWC layout, values normalized to [-1, 1].
+
+**Output:** 512-dimensional L2-normalized embedding vector.
+
+## Go Binding
+
+```go
+import "github.com/facex-engine/facex/go/facex"
+
+ff, _ := facex.New(facex.Config{
+ Exe: "./facex-cli",
+ Weights: "./edgeface_xs_fp32.bin",
+})
+embedding, _ := ff.Embed(rgbImage)
+```
+
+## Architecture
+
+- Pure C99 with SIMD intrinsics (AVX2, FMA, AVX-512 VNNI)
+- INT8 quantized GEMM with per-channel scaling
+- FP32 packed column-panel MatMul
+- Thread pool for parallel computation
+- Optional AES-256 weight encryption with hardware binding
+
+## Model
+
+Uses [EdgeFace-XS](https://github.com/ahmadnassri/edgeface) (CC BY-NC-SA 4.0):
+- 1.77M parameters
+- 99.73% accuracy on LFW
+- 112x112 input, 512-dim output
+
+## License
+
+CC BY-NC-SA 4.0 (follows upstream model license).
+
+For commercial licensing, contact: [[email protected]](mailto:[email protected])
+
+## Author
+
+Created by **Baurzhan Atinov** — [GitHub](https://github.com/bauratynov)
diff --git a/examples/example.c b/examples/example.c
new file mode 100644
index 0000000..591437b
--- /dev/null
+++ b/examples/example.c
@@ -0,0 +1,45 @@
+/*
+ * FaceX example — compute face embedding and compare two faces.
+ *
+ * Build: gcc -O3 -Iinclude -o example examples/example.c -L. -lfacex -lm -lpthread
+ * Run: ./example data/edgeface_xs_fp32.bin
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "facex.h"
+
+int main(int argc, char** argv) {
+ const char* weights = argc > 1 ? argv[1] : "data/edgeface_xs_fp32.bin";
+
+ printf("FaceX %s\n", facex_version());
+
+ /* Initialize engine */
+ FaceX* fx = facex_init(weights, NULL);
+ if (!fx) {
+ fprintf(stderr, "Failed to load weights: %s\n", weights);
+ return 1;
+ }
+ printf("Engine ready.\n");
+
+ /* Create two dummy faces (in real use: load 112x112 RGB image) */
+ float face1[112 * 112 * 3];
+ float face2[112 * 112 * 3];
+ for (int i = 0; i < 112 * 112 * 3; i++) {
+ face1[i] = (float)(i % 256) / 128.0f - 1.0f;
+ face2[i] = (float)((i + 42) % 256) / 128.0f - 1.0f;
+ }
+
+ /* Compute embeddings */
+ float emb1[512], emb2[512];
+ facex_embed(fx, face1, emb1);
+ facex_embed(fx, face2, emb2);
+
+ /* Compare */
+ float sim = facex_similarity(emb1, emb2);
+ printf("Similarity: %.4f\n", sim);
+ printf("Same person: %s\n", sim > 0.3f ? "YES" : "NO");
+
+ facex_free(fx);
+ return 0;
+}
diff --git a/go/facex/fastface.go b/go/facex/fastface.go
new file mode 100644
index 0000000..2d5d1d8
--- /dev/null
+++ b/go/facex/fastface.go
@@ -0,0 +1,181 @@
+// Package fastface wraps the FastFace INT8 engine via its --server subprocess.
+// Stdlib-only (no cgo). Matches the Python SDK semantics.
+//
+// Usage (Exe is auto-detected -- .exe on Windows, bare name on Linux/macOS):
+//
+// ff, err := fastface.New(fastface.Config{
+// Weights: `models/w600k_r50_ffw4.bin`,
+// })
+// if err != nil {
+// log.Fatal(err)
+// }
+// defer ff.Close()
+//
+// // input: HWC float32 [-1, 1], exactly 3*112*112 = 37632 floats.
+// emb, err := ff.Embed(input) // []float32 length 512
+//
+// Thread-safety: FastFace is NOT goroutine-safe. Create one instance per
+// goroutine that embeds, or wrap with your own sync.Mutex.
+package fastface
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "sync"
+)
+
+// Input face layout constants.
+const (
+ InputSize = 3 * 112 * 112 // 37632 floats
+ InputBytes = InputSize * 4
+ OutputSize = 512
+ OutputBytes = OutputSize * 4
+)
+
+// Config for starting the subprocess.
+type Config struct {
+ Exe string // path to fastface_int8[.exe]; auto-detected if empty
+ Weights string // path to w600k_r50_ffw4.bin (default "models/w600k_r50_ffw4.bin")
+ GCCBin string // optional dir with libgomp-1.dll for Windows; auto-detected if empty
+ Workdir string // cwd for subprocess; default = dir of Exe
+}
+
+// FastFace is a persistent subprocess wrapping fastface_int8 --server.
+type FastFace struct {
+ cmd *exec.Cmd
+ stdin io.WriteCloser
+ stdout io.ReadCloser
+ stderr io.ReadCloser
+ mu sync.Mutex
+ closed bool
+}
+
+// defaultExe returns the right binary name for the current OS.
+// Windows: fastface_int8.exe; Linux/macOS: fastface_int8 (with .exe fallback).
+func defaultExe() string {
+ suffix := ""
+ if runtime.GOOS == "windows" {
+ suffix = ".exe"
+ }
+ for _, p := range []string{"./fastface_int8" + suffix, "./fastface_int8.exe", "./fastface_int8"} {
+ if _, err := os.Stat(p); err == nil {
+ return p
+ }
+ }
+ return "./fastface_int8" + suffix
+}
+
+// New starts a subprocess and returns a FastFace ready to Embed.
+func New(cfg Config) (*FastFace, error) {
+ if cfg.Exe == "" {
+ cfg.Exe = defaultExe()
+ }
+ if cfg.Weights == "" {
+ cfg.Weights = "models/w600k_r50_ffw4.bin"
+ }
+ if cfg.GCCBin == "" && runtime.GOOS == "windows" {
+ for _, p := range []string{`C:\mingw64\bin`, `C:/mingw64/bin`} {
+ if _, err := os.Stat(p); err == nil {
+ cfg.GCCBin = p
+ break
+ }
+ }
+ }
+ if cfg.Workdir == "" {
+ abs, _ := filepath.Abs(cfg.Exe)
+ cfg.Workdir = filepath.Dir(abs)
+ }
+
+ cmd := exec.Command(cfg.Exe, cfg.Weights, "--server")
+ cmd.Dir = cfg.Workdir
+ cmd.Env = os.Environ()
+ if cfg.GCCBin != "" {
+ for i, kv := range cmd.Env {
+ if len(kv) >= 5 && (kv[:5] == "PATH=" || kv[:5] == "path=" || kv[:5] == "Path=") {
+ cmd.Env[i] = "PATH=" + cfg.GCCBin + string(os.PathListSeparator) + kv[5:]
+ break
+ }
+ }
+ }
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ return nil, err
+ }
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, err
+ }
+ stderr, err := cmd.StderrPipe()
+ if err != nil {
+ return nil, err
+ }
+ if err := cmd.Start(); err != nil {
+ return nil, err
+ }
+ ff := &FastFace{cmd: cmd, stdin: stdin, stdout: stdout, stderr: stderr}
+ return ff, nil
+}
+
+// Embed runs a single forward pass. input must be exactly 3*112*112 floats
+// in HWC order, range roughly [-1, 1]. Returns a new 512-float embedding.
+func (ff *FastFace) Embed(input []float32) ([]float32, error) {
+ if len(input) != InputSize {
+ return nil, fmt.Errorf("input length %d != expected %d", len(input), InputSize)
+ }
+ ff.mu.Lock()
+ defer ff.mu.Unlock()
+ if ff.closed {
+ return nil, fmt.Errorf("fastface: subprocess already closed")
+ }
+ // Write fp32 input
+ buf := make([]byte, InputBytes)
+ for i, v := range input {
+ binary.LittleEndian.PutUint32(buf[i*4:], math.Float32bits(v))
+ }
+ if _, err := ff.stdin.Write(buf); err != nil {
+ return nil, fmt.Errorf("stdin write: %w", err)
+ }
+ // Read fp32 embedding
+ outBuf := make([]byte, OutputBytes)
+ if _, err := io.ReadFull(ff.stdout, outBuf); err != nil {
+ return nil, fmt.Errorf("stdout read: %w", err)
+ }
+ out := make([]float32, OutputSize)
+ for i := range out {
+ out[i] = math.Float32frombits(binary.LittleEndian.Uint32(outBuf[i*4:]))
+ }
+ return out, nil
+}
+
+// CosSim returns the cosine similarity of two embeddings.
+func CosSim(a, b []float32) float32 {
+ var dot, na, nb float64
+ for i := range a {
+ dot += float64(a[i]) * float64(b[i])
+ na += float64(a[i]) * float64(a[i])
+ nb += float64(b[i]) * float64(b[i])
+ }
+ if na == 0 || nb == 0 {
+ return 0
+ }
+ return float32(dot / (math.Sqrt(na) * math.Sqrt(nb)))
+}
+
+// Close terminates the subprocess and releases resources.
+func (ff *FastFace) Close() error {
+ ff.mu.Lock()
+ defer ff.mu.Unlock()
+ if ff.closed {
+ return nil
+ }
+ ff.closed = true
+ _ = ff.stdin.Close()
+ err := ff.cmd.Wait()
+ return err
+}
diff --git a/go/facex/go.mod b/go/facex/go.mod
new file mode 100644
index 0000000..b8b86a4
--- /dev/null
+++ b/go/facex/go.mod
@@ -0,0 +1,3 @@
+module github.com/facex-engine/facex/go/facex
+
+go 1.22
diff --git a/include/compat.h b/include/compat.h
new file mode 100644
index 0000000..a9a2adf
--- /dev/null
+++ b/include/compat.h
@@ -0,0 +1,42 @@
+#ifndef FASTFACE_COMPAT_H
+#define FASTFACE_COMPAT_H
+
+/* Cross-platform compatibility shims.
+ *
+ * The engine was originally developed on Windows (MinGW) and used the
+ * MS-runtime functions _aligned_malloc / _aligned_free / _setmode /
+ * _O_BINARY / _fileno directly. This header provides the same names on
+ * Linux / macOS via POSIX equivalents so the source compiles everywhere.
+ */
+
+#include <stddef.h>
+
+#ifdef _WIN32
+ #include <windows.h>
+ #include <io.h>
+ #include <fcntl.h>
+#else
+ #include <stdlib.h>
+ #include <unistd.h>
+ #include <stdio.h>
+
+ /* _aligned_malloc(size, align) -> posix_memalign */
+ static inline void* _aligned_malloc(size_t size, size_t align) {
+ /* POSIX requires alignment to be a power of 2 and multiple of sizeof(void*),
+ * and size to be a multiple of alignment. */
+ if (align < sizeof(void*)) align = sizeof(void*);
+ size = (size + align - 1) & ~(align - 1);
+ void* p = NULL;
+ if (posix_memalign(&p, align, size) != 0) return NULL;
+ return p;
+ }
+ #define _aligned_free free
+
+ /* _setmode/_O_BINARY are Windows-only. Linux file descriptors are always
+ * "binary" — make these no-ops. */
+ #define _setmode(fd, mode) (0)
+ #define _O_BINARY 0
+ #define _fileno(f) fileno(f)
+#endif
+
+#endif /* FASTFACE_COMPAT_H */
diff --git a/include/facex.h b/include/facex.h
new file mode 100644
index 0000000..12f1967
--- /dev/null
+++ b/include/facex.h
@@ -0,0 +1,67 @@
+/*
+ * FaceX — Fast face embedding library.
+ *
+ * 3ms inference, 7MB binary, zero dependencies.
+ * Beats ONNX Runtime on CPU with handwritten C + AVX2/AVX-512.
+ *
+ * Usage:
+ * FaceX* fx = facex_init("edgeface_xs_fp32.bin", NULL);
+ * float embedding[512];
+ * facex_embed(fx, rgb_112x112, embedding);
+ * float sim = facex_similarity(emb1, emb2);
+ * facex_free(fx);
+ *
+ * https://github.com/facex-engine/facex
+ * License: CC BY-NC-SA 4.0
+ */
+
+#ifndef FACEX_H
+#define FACEX_H
+
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Opaque handle */
+typedef struct FaceX FaceX;
+
+/*
+ * Initialize FaceX engine.
+ * weights_path: path to .bin weight file (EFXS or EFXE encrypted)
+ * license_key: NULL for unencrypted weights, or license string for encrypted
+ * Returns: engine handle, or NULL on error
+ */
+FaceX* facex_init(const char* weights_path, const char* license_key);
+
+/*
+ * Compute 512-dim face embedding.
+ * fx: engine handle
+ * rgb_hwc: 112x112x3 float32 array, HWC layout, values in [-1, 1]
+ * embedding: output buffer, 512 floats (L2-normalized)
+ * Returns: 0 on success, -1 on error
+ */
+int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]);
+
+/*
+ * Cosine similarity between two embeddings.
+ * Returns: value in [-1, 1], typically >0.3 = same person
+ */
+float facex_similarity(const float emb1[512], const float emb2[512]);
+
+/*
+ * Free engine resources.
+ */
+void facex_free(FaceX* fx);
+
+/*
+ * Get version string.
+ */
+const char* facex_version(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* FACEX_H */
diff --git a/include/weight_crypto.h b/include/weight_crypto.h
new file mode 100644
index 0000000..9797470
--- /dev/null
+++ b/include/weight_crypto.h
@@ -0,0 +1,15 @@
+#ifndef WEIGHT_CRYPTO_H
+#define WEIGHT_CRYPTO_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+/* Encrypt weight file: input (EFXS) → output (EFXE + nonce + encrypted data) */
+int weight_encrypt_file(const char* input, const char* output, const char* license);
+
+/* Decrypt in-place. raw must start with EFXE magic.
+ * On success: data at raw+20 contains decrypted EFXS payload.
+ * Returns: 0 = OK, -1 = not encrypted, -2 = wrong key */
+int weight_decrypt_inplace(uint8_t* raw, size_t raw_size, const char* license);
+
+#endif
diff --git a/src/edgeface_engine.c b/src/edgeface_engine.c
new file mode 100644
index 0000000..00e41da
--- /dev/null
+++ b/src/edgeface_engine.c
@@ -0,0 +1,1291 @@
+/*
+ * edgeface_engine.c — Native FP32 EdgeFace-XS embedding engine.
+ *
+ * Loads weights from edgeface_xs_fp32.bin, runs forward pass,
+ * outputs 512-dim embedding. Zero dependencies.
+ *
+ * Architecture: 4 stages × ConvNeXt blocks + 3 SDPA attention + head.
+ * All ops in FP32 with AVX2 MatMul.
+ *
+ * Build: gcc -O3 -march=native -mfma -o fastface_edgexs.exe \
+ * edgeface_engine.c kernels/transformer_ops.c kernels/gemm_int8_4x8c8.c -lm
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <math.h>
+#include <time.h>
+#ifdef __AVX2__
+#include <immintrin.h>
+#endif
+
+/* Weight decryption (optional, linked from crypto/weight_crypto.c) */
+#ifndef NO_CRYPTO
+extern int weight_decrypt_inplace(uint8_t* raw, size_t raw_size, const char* license);
+#endif
+
+/* External ops */
+extern void layer_norm_fp32(const float*, int, int, const float*, const float*, float, float*);
+#ifdef __AVX2__
+extern __m256 _mm256_exp_ps(__m256 x);
+#endif
+extern void gelu_fp32(float*, int);
+extern void softmax_fp32(float*, int, int);
+extern void matmul_fp32(const float*, const float*, float*, int, int, int);
+extern void l2_normalize_fp32(float*, int, int, float);
+extern void depthwise_conv_nxn_hwc_fp32(const float*, int, int, int, const float*, const float*, int, float*);
+
+/* ============ Weight loader ============ */
+/* INT8 packed MatMul weight */
+typedef struct {
+ void* packed;
+ int32_t* col_sums;
+ float* w_scales;
+ int K, N; /* original dimensions */
+} PackedMM;
+
+/* FP32 pre-packed MatMul weight (column-panel format for cache-friendly access) */
+typedef struct {
+ float* data; /* packed [ceil(N/8), K, 8] — 32-byte aligned */
+ int K, N;
+} PackedFP32;
+
+typedef struct {
+ float** tensors; /* array of float pointers */
+ int n_tensors;
+ uint8_t* raw; /* raw file data */
+ size_t raw_size;
+ /* INT8 pre-packed MatMul weights */
+ PackedMM* mm; /* array, indexed same as tensors */
+ /* FP32 pre-packed MatMul weights */
+ PackedFP32* fp; /* array, indexed same as tensors */
+} Weights;
+
+static const char* g_license_key = NULL;
+
+static int load_weights(const char* path, Weights* w) {
+ FILE* f = fopen(path, "rb");
+ if (!f) return -1;
+
+ fseek(f, 0, SEEK_END);
+ w->raw_size = ftell(f);
+ fseek(f, 0, SEEK_SET);
+
+ w->raw = (uint8_t*)malloc(w->raw_size);
+ fread(w->raw, 1, w->raw_size, f);
+ fclose(f);
+
+ /* Handle encrypted weights (EFXE magic) */
+#ifndef NO_CRYPTO
+ if (w->raw_size >= 20 && memcmp(w->raw, "EFXE", 4) == 0) {
+ if (!g_license_key || !g_license_key[0]) {
+ fprintf(stderr, "ERROR: Encrypted weights require LICENSE_KEY\n");
+ fprintf(stderr, "Set LICENSE_KEY environment variable or pass --license KEY\n");
+ free(w->raw);
+ return -3;
+ }
+ int r = weight_decrypt_inplace(w->raw, w->raw_size, g_license_key);
+ if (r == -2) {
+ fprintf(stderr, "ERROR: Invalid license key for this machine\n");
+ free(w->raw);
+ return -2;
+ } else if (r != 0) {
+ fprintf(stderr, "ERROR: Decryption failed (%d)\n", r);
+ free(w->raw);
+ return r;
+ }
+ /* After decryption, EFXS payload starts at offset 20 */
+ uint8_t* payload = w->raw + 20;
+ size_t payload_size = w->raw_size - 20;
+
+ if (memcmp(payload, "EFXS", 4) != 0) {
+ free(w->raw);
+ return -1;
+ }
+
+ uint32_t n = *(uint32_t*)(payload + 4);
+ w->n_tensors = n;
+ w->tensors = (float**)malloc(n * sizeof(float*));
+
+ size_t off = 8;
+ for (uint32_t i = 0; i < n; i++) {
+ uint32_t sz = *(uint32_t*)(payload + off);
+ off += 4;
+ w->tensors[i] = (float*)(payload + off);
+ off += sz;
+ }
+ return 0;
+ }
+#endif
+
+ /* Unencrypted weights (EFXS magic) */
+ if (memcmp(w->raw, "EFXS", 4) != 0) return -1;
+
+ uint32_t n = *(uint32_t*)(w->raw + 4);
+ w->n_tensors = n;
+ w->tensors = (float**)malloc(n * sizeof(float*));
+
+ size_t off = 8;
+ for (uint32_t i = 0; i < n; i++) {
+ uint32_t sz = *(uint32_t*)(w->raw + off);
+ off += 4;
+ w->tensors[i] = (float*)(w->raw + off);
+ off += sz;
+ }
+
+ return 0;
+}
+
+#define W(idx) (weights->tensors[idx])
+
+/* Forward declarations */
+static void matmul_w(const float* A, const float* B, float* C,
+ int M, int K, int N, const PackedMM* mm);
+static void matmul_wp(const float* A, float* C,
+ int M, int K, int N, const PackedFP32* fp);
+static void matmul_wpb(const float* A, float* C, const float* bias,
+ int M, int K, int N, const PackedFP32* fp);
+
+/* ============ XCA (Cross-Covariance Attention) Block ============ */
+/* EdgeFace XCA: Split+DW conv → pos embed →
+ * LN → QKV project → reshape [n_heads, head_dim, HW] →
+ * L2 norm Q,K along HW → Q@K^T * temperature → softmax → @V →
+ * reshape → project → gamma_xca * output + residual → LN → MLP → gamma + residual */
+
+/* DW conv for XCA: CASCADED structure.
+ * Split channels → Conv(split_0) → result_0
+ * → result_0 + split_1 → Conv → result_1
+ * → result_1 + split_2 → Conv → result_2
+ * → Concat [result_0, result_1, ..., result_{n-1}, split_last_unchanged]
+ * Input/output in NCHW. Each conv weight is [split_ch, 1, K, K] DW conv. */
+static void xca_dw_conv_nchw(const float* in_nchw, int C, int H, int W,
+ int n_splits, const int* split_sizes,
+ int n_convs, const float** conv_ws, const float** conv_bs,
+ int K, float* out_nchw, float* conv_scratch) {
+ int HW = H * W;
+ int pad = K / 2;
+ int ch_offset = 0;
+ float* prev_result = NULL; /* pointer to previous conv result in out_nchw */
+
+ for (int s = 0; s < n_splits; s++) {
+ int sc = split_sizes[s];
+ if (s < n_convs && conv_ws[s]) {
+ const float* w = conv_ws[s]; /* [sc, 1, K, K] */
+ const float* b = conv_bs[s]; /* [sc] */
+
+ /* Prepare input: for first conv, use split directly.
+ * For subsequent convs, input = prev_result + current_split */
+ const float* conv_in;
+ if (s == 0) {
+ conv_in = in_nchw + (size_t)ch_offset * HW; /* split_0 */
+ } else {
+ /* Add prev_result + current_split → scratch */
+ const float* split_data = in_nchw + (size_t)ch_offset * HW;
+ for (int i = 0; i < sc * HW; i++)
+ conv_scratch[i] = prev_result[i] + split_data[i];
+ conv_in = conv_scratch;
+ }
+
+ /* DW conv */
+ float* result = out_nchw + (size_t)ch_offset * HW;
+ for (int c = 0; c < sc; c++) {
+ for (int oy = 0; oy < H; oy++)
+ for (int ox = 0; ox < W; ox++) {
+ float sum = b ? b[c] : 0;
+ for (int ky = 0; ky < K; ky++) {
+ int iy = oy - pad + ky;
+ if (iy < 0 || iy >= H) continue;
+ for (int kx = 0; kx < K; kx++) {
+ int ix = ox - pad + kx;
+ if (ix < 0 || ix >= W) continue;
+ sum += conv_in[c * HW + iy * W + ix] *
+ w[(c * K + ky) * K + kx];
+ }
+ }
+ result[c * HW + oy * W + ox] = sum;
+ }
+ }
+ prev_result = result;
+ } else {
+ /* Copy unchanged */
+ memcpy(out_nchw + (size_t)ch_offset * HW,
+ in_nchw + (size_t)ch_offset * HW,
+ (size_t)sc * HW * sizeof(float));
+ }
+ ch_offset += sc;
+ }
+}
+
+static void xca_block(float* x_hwc, int H, int W, int C,
+ const float* gamma_xca, const float* gamma,
+ /* DW conv for split heads */
+ int n_dw_splits, const int* dw_split_sizes,
+ int n_dw_convs, const float** dw_ws, const float** dw_bs, int dw_K,
+ /* Position embedding: Conv1x1 on CONSTANT pos map */
+ const float* pos_const_nchw, /* [1,C,H,W] or NULL */
+ const float* pos_w, const float* pos_b, /* Conv1x1 [C,C,1,1] OIHW */
+ /* XCA attention */
+ const float* xca_ln_w, const float* xca_ln_b,
+ const float* qkv_w0, const float* qkv_w1, const float* qkv_b,
+ const float* temperature, int n_heads,
+ const float* proj_w0, const float* proj_w1, const float* proj_b,
+ /* Post-attention MLP */
+ const float* ln_w, const float* ln_b,
+ const float* mlp_w0, const float* mlp_w1, const float* mlp_b1,
+ const float* mlp_w2, const float* mlp_w3, const float* mlp_b3,
+ int rank, int hidden,
+ float* tmp,
+ const PackedFP32* fp_qkv0, const PackedFP32* fp_qkv1,
+ const PackedFP32* fp_proj0, const PackedFP32* fp_proj1,
+ const PackedFP32* fp_mlp0, const PackedFP32* fp_mlp1,
+ const PackedFP32* fp_mlp2, const PackedFP32* fp_mlp3)
+{
+ int HW = H * W;
+ int head_dim = C / n_heads;
+
+ /* Workspace layout: residual, nchw buf, qkv, attention scratch */
+ float* residual = tmp;
+ float* nchw_buf = residual + HW * C;
+ float* t1 = nchw_buf + C * HW; /* after NCHW buffer */
+ float* t2 = t1 + HW * C * 3 + HW * rank; /* scratch */
+
+ /* Save ORIGINAL input as residual for MLP at the end */
+ float* residual_orig = residual;
+ float* residual_dw = nchw_buf; /* reuse nchw_buf for second residual after DW section */
+ memcpy(residual_orig, x_hwc, (size_t)HW * C * sizeof(float));
+
+ /* 1. DW conv: HWC→NCHW, split/conv/concat, NCHW→HWC */
+ if (n_dw_convs > 0 && dw_ws) {
+ /* HWC → NCHW (use t1 as temp) */
+ float* nchw_in = t1;
+ for (int hw = 0; hw < HW; hw++)
+ for (int c = 0; c < C; c++)
+ nchw_in[c * HW + hw] = x_hwc[hw * C + c];
+
+ float* nchw_out = nchw_in + C * HW; /* separate output */
+ float* conv_scratch = nchw_out + C * HW; /* scratch for cascaded adds */
+ xca_dw_conv_nchw(nchw_in, C, H, W, n_dw_splits, dw_split_sizes,
+ n_dw_convs, dw_ws, dw_bs, dw_K, nchw_out, conv_scratch);
+
+ /* NCHW → HWC */
+ for (int hw = 0; hw < HW; hw++)
+ for (int c = 0; c < C; c++)
+ x_hwc[hw * C + c] = nchw_out[c * HW + hw];
+ }
+
+ /* 2. Position embedding: add pre-computed constant (cached at load time) */
+ if (pos_const_nchw) {
+ /* pos_const_nchw now points to pre-computed [HW, C] HWC result */
+ int i = 0;
+#ifdef __AVX2__
+ for (; i + 8 <= HW * C; i += 8) {
+ __m256 v = _mm256_add_ps(_mm256_loadu_ps(x_hwc + i), _mm256_loadu_ps(pos_const_nchw + i));
+ _mm256_storeu_ps(x_hwc + i, v);
+ }
+#endif
+ for (; i < HW * C; i++) x_hwc[i] += pos_const_nchw[i];
+ }
+
+ /* Save x_after_dw_pos as residual for attention */
+ memcpy(residual_dw, x_hwc, (size_t)HW * C * sizeof(float));
+
+ /* 3. LayerNorm */
+ layer_norm_fp32(x_hwc, HW, C, xca_ln_w, xca_ln_b, 1e-6f, x_hwc);
+
+ /* 4. QKV projection: LoRaLin [HW,C] → [HW,3C] */
+ int qkv_dim = C * 3;
+ float* qkv = t1;
+ float* qkv_temp = t1 + HW * qkv_dim;
+ matmul_wp(x_hwc, qkv_temp, HW, C, rank, fp_qkv0);
+ matmul_wp(qkv_temp, qkv, HW, rank, qkv_dim, fp_qkv1);
+ /* Add bias */
+ for (int hw = 0; hw < HW; hw++)
+ for (int d = 0; d < qkv_dim; d++)
+ qkv[hw * qkv_dim + d] += qkv_b[d];
+
+ /* 5. Reshape QKV: [HW, 3C] → [HW, 3, n_heads, head_dim] →
+ * transpose to [3, n_heads, head_dim, HW] → split Q,K,V */
+ /* Each Q,K,V: [n_heads, head_dim, HW] */
+ float* Q_nhd = t2; /* [n_heads, head_dim, HW] */
+ float* K_nhd = Q_nhd + n_heads * head_dim * HW;
+ float* V_nhd = K_nhd + n_heads * head_dim * HW;
+
+ /* QKV layout from LoRaLin: [HW, 3*C] where 3*C = Q0..QC, K0..KC, V0..VC
+ * But ONNX reshape is [HW, 3, n_heads, head_dim], so element at
+ * qkv[hw, q, h, d] = qkv_flat[hw * 3*n_heads*head_dim + q*n_heads*head_dim + h*head_dim + d]
+ * Transpose to [q, h, d, hw]: Q[h,d,hw] = qkv[hw, 0, h, d] */
+ for (int hw = 0; hw < HW; hw++)
+ for (int h = 0; h < n_heads; h++)
+ for (int d = 0; d < head_dim; d++) {
+ int qkv_idx = hw * qkv_dim + 0 * C + h * head_dim + d;
+ Q_nhd[h * head_dim * HW + d * HW + hw] = qkv[qkv_idx];
+ qkv_idx = hw * qkv_dim + 1 * C + h * head_dim + d;
+ K_nhd[h * head_dim * HW + d * HW + hw] = qkv[qkv_idx];
+ qkv_idx = hw * qkv_dim + 2 * C + h * head_dim + d;
+ V_nhd[h * head_dim * HW + d * HW + hw] = qkv[qkv_idx];
+ }
+
+ /* 6. L2 normalize Q and K along HW dim — AVX2 vectorized */
+ for (int h = 0; h < n_heads; h++)
+ for (int d = 0; d < head_dim; d++) {
+ float* q_row = Q_nhd + h * head_dim * HW + d * HW;
+ float* k_row = K_nhd + h * head_dim * HW + d * HW;
+ float q_norm = 0, k_norm = 0;
+ int hw = 0;
+#ifdef __AVX2__
+ __m256 vqn = _mm256_setzero_ps(), vkn = _mm256_setzero_ps();
+ for (; hw + 8 <= HW; hw += 8) {
+ __m256 q = _mm256_loadu_ps(q_row + hw);
+ __m256 k = _mm256_loadu_ps(k_row + hw);
+ vqn = _mm256_fmadd_ps(q, q, vqn);
+ vkn = _mm256_fmadd_ps(k, k, vkn);
+ }
+ /* Horizontal sum */
+ __m128 lo, hi;
+ lo = _mm256_castps256_ps128(vqn); hi = _mm256_extractf128_ps(vqn, 1);
+ lo = _mm_add_ps(lo, hi); lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_add_ss(lo, _mm_movehdup_ps(lo));
+ q_norm = _mm_cvtss_f32(lo);
+ lo = _mm256_castps256_ps128(vkn); hi = _mm256_extractf128_ps(vkn, 1);
+ lo = _mm_add_ps(lo, hi); lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_add_ss(lo, _mm_movehdup_ps(lo));
+ k_norm = _mm_cvtss_f32(lo);
+#endif
+ for (; hw < HW; hw++) { q_norm += q_row[hw]*q_row[hw]; k_norm += k_row[hw]*k_row[hw]; }
+ float q_inv = 1.0f / sqrtf(q_norm > 1e-24f ? q_norm : 1e-24f);
+ float k_inv = 1.0f / sqrtf(k_norm > 1e-24f ? k_norm : 1e-24f);
+ hw = 0;
+#ifdef __AVX2__
+ __m256 vqi = _mm256_set1_ps(q_inv), vki = _mm256_set1_ps(k_inv);
+ for (; hw + 8 <= HW; hw += 8) {
+ _mm256_storeu_ps(q_row + hw, _mm256_mul_ps(_mm256_loadu_ps(q_row + hw), vqi));
+ _mm256_storeu_ps(k_row + hw, _mm256_mul_ps(_mm256_loadu_ps(k_row + hw), vki));
+ }
+#endif
+ for (; hw < HW; hw++) { q_row[hw] *= q_inv; k_row[hw] *= k_inv; }
+ }
+
+ /* 7. Per-head channel attention using matmul_fp32 for Q@K^T and attn@V */
+ float* attn_buf = V_nhd + n_heads * head_dim * HW;
+ /* Transpose K: [head_dim, HW] → [HW, head_dim] for matmul compatibility */
+ float* K_T = attn_buf + n_heads * head_dim * head_dim; /* temp [HW, head_dim] per head */
+ for (int h = 0; h < n_heads; h++) {
+ float* Q_h = Q_nhd + h * head_dim * HW; /* [head_dim, HW] */
+ float* K_h = K_nhd + h * head_dim * HW; /* [head_dim, HW] */
+ float* A_h = attn_buf + h * head_dim * head_dim; /* [head_dim, head_dim] */
+
+ /* Transpose K_h [head_dim, HW] → K_T [HW, head_dim] */
+ for (int d = 0; d < head_dim; d++)
+ for (int s = 0; s < HW; s++)
+ K_T[s * head_dim + d] = K_h[d * HW + s];
+
+ /* A = Q @ K^T: [head_dim, HW] @ [HW, head_dim] = [head_dim, head_dim] */
+ matmul_fp32(Q_h, K_T, A_h, head_dim, HW, head_dim);
+
+ /* Scale by temperature */
+ if (temperature) {
+ float temp = temperature[h];
+#ifdef __AVX2__
+ __m256 vt = _mm256_set1_ps(temp);
+ int i = 0;
+ for (; i + 8 <= head_dim * head_dim; i += 8)
+ _mm256_storeu_ps(A_h + i, _mm256_mul_ps(_mm256_loadu_ps(A_h + i), vt));
+ for (; i < head_dim * head_dim; i++) A_h[i] *= temp;
+#else
+ for (int i = 0; i < head_dim * head_dim; i++) A_h[i] *= temp;
+#endif
+ }
+
+ /* Softmax per row */
+ softmax_fp32(A_h, head_dim, head_dim);
+
+ /* out = A @ V: [head_dim, head_dim] @ [head_dim, HW] = [head_dim, HW] */
+ float* V_h = V_nhd + h * head_dim * HW;
+ float* out_h = Q_nhd + h * head_dim * HW; /* reuse Q buffer */
+ matmul_fp32(A_h, V_h, out_h, head_dim, head_dim, HW);
+ }
+
+ /* 8. Reshape attention output: [n_heads, head_dim, HW] → [HW, C] */
+ for (int hw = 0; hw < HW; hw++)
+ for (int h = 0; h < n_heads; h++)
+ for (int d = 0; d < head_dim; d++)
+ x_hwc[hw * C + h * head_dim + d] = Q_nhd[h * head_dim * HW + d * HW + hw];
+
+ /* 9. Output projection: LoRaLin [HW,C] → [HW,C] */
+ float* proj_temp = t1;
+ matmul_wp(x_hwc, proj_temp, HW, C, rank, fp_proj0);
+ matmul_wp(proj_temp, x_hwc, HW, rank, C, fp_proj1);
+ for (int i = 0; i < HW * C; i++)
+ x_hwc[i] += proj_b[i % C];
+
+ /* 10. gamma_xca * output + residual_dw (attention residual = after DW+pos) */
+ for (int hw = 0; hw < HW; hw++)
+ for (int c = 0; c < C; c++)
+ x_hwc[hw*C+c] = x_hwc[hw*C+c] * gamma_xca[c] + residual_dw[hw*C+c];
+
+ /* 11. LN + MLP + gamma + residual_orig (MLP residual = original block input) */
+ layer_norm_fp32(x_hwc, HW, C, ln_w, ln_b, 1e-6f, x_hwc);
+
+ float* mt1 = t1;
+ float* mt2 = mt1 + HW * rank;
+ matmul_wp(x_hwc, mt1, HW, C, rank, fp_mlp0);
+ matmul_wp(mt1, mt2, HW, rank, hidden, fp_mlp1);
+ for (int hw = 0; hw < HW; hw++)
+ for (int h_ = 0; h_ < hidden; h_++)
+ mt2[hw*hidden+h_] += mlp_b1[h_];
+ gelu_fp32(mt2, HW * hidden);
+ matmul_wp(mt2, mt1, HW, hidden, rank, fp_mlp2);
+ matmul_wp(mt1, x_hwc, HW, rank, C, fp_mlp3);
+ for (int hw = 0; hw < HW; hw++)
+ for (int c = 0; c < C; c++)
+ x_hwc[hw*C+c] = (x_hwc[hw*C+c] + mlp_b3[c]) * gamma[c] + residual_orig[hw*C+c];
+}
+
+/* ============ Conv2D FP32 (HWC in → HWC out) ============ */
+/* Standard conv with OIHW weights, operating on HWC tensors.
+ * AVX2 optimized: vectorize across output channels (Cout). */
+/* conv2d_hwc with pre-transposed weights in [Cin*KK, Cout] layout.
+ * At load time, call conv2d_hwc_reorder_weights() to transpose OIHW → [Cin*KK, Cout]. */
+static void conv2d_hwc_reorder_weights(float* w, int Cout, int Cin, int KK) {
+ /* In-place transpose from [Cout, Cin*KK] to [Cin*KK, Cout] */
+ float* tmp = (float*)malloc((size_t)Cout * Cin * KK * sizeof(float));
+ memcpy(tmp, w, (size_t)Cout * Cin * KK * sizeof(float));
+ for (int co = 0; co < Cout; co++)
+ for (int ci_ki = 0; ci_ki < Cin * KK; ci_ki++)
+ w[ci_ki * Cout + co] = tmp[co * Cin * KK + ci_ki];
+ free(tmp);
+}
+
+static void conv2d_hwc(const float* in_hwc, int Cin, int H, int W,
+ const float* w, /* REORDERED to [Cin*KK, Cout] */
+ const float* b, int Cout, int K, int stride,
+ float* out_hwc) {
+ int Ho = (H - K) / stride + 1, Wo = (W - K) / stride + 1;
+ int KK = K * K;
+ for (int oy = 0; oy < Ho; oy++)
+ for (int ox = 0; ox < Wo; ox++) {
+ float* o = out_hwc + ((size_t)oy * Wo + ox) * Cout;
+ int co = 0;
+#ifdef __AVX2__
+ for (; co + 8 <= Cout; co += 8)
+ _mm256_storeu_ps(o + co, b ? _mm256_loadu_ps(b + co) : _mm256_setzero_ps());
+#endif
+ for (; co < Cout; co++) o[co] = b ? b[co] : 0;
+ for (int ky = 0; ky < K; ky++)
+ for (int kx = 0; kx < K; kx++) {
+ int iy = oy * stride + ky, ix = ox * stride + kx;
+ const float* inp = in_hwc + ((size_t)iy * W + ix) * Cin;
+ int ki = ky * K + kx;
+ for (int ci = 0; ci < Cin; ci++) {
+ float in_val = inp[ci];
+ /* Reordered w: w[(ci*KK+ki)*Cout + co] — CONTIGUOUS along Cout! */
+ const float* wrow = w + (size_t)(ci * KK + ki) * Cout;
+ co = 0;
+#ifdef __AVX512F__
+ __m512 va512 = _mm512_set1_ps(in_val);
+ for (; co + 16 <= Cout; co += 16)
+ _mm512_storeu_ps(o+co, _mm512_fmadd_ps(va512,
+ _mm512_loadu_ps(wrow+co), _mm512_loadu_ps(o+co)));
+#endif
+#ifdef __AVX2__
+ __m256 va = _mm256_set1_ps(in_val);
+ for (; co + 8 <= Cout; co += 8)
+ _mm256_storeu_ps(o+co, _mm256_fmadd_ps(va,
+ _mm256_loadu_ps(wrow+co), _mm256_loadu_ps(o+co)));
+#endif
+ for (; co < Cout; co++) o[co] += in_val * wrow[co];
+ }
+ }
+ }
+}
+
+/* ============ Conv2D FP32 (NCHW) ============ */
+static void conv2d(const float* in, int Cin, int H, int W,
+ const float* w, const float* b, int Cout, int K, int stride,
+ float* out) {
+ int Ho = (H - K) / stride + 1, Wo = (W - K) / stride + 1;
+ for (int co = 0; co < Cout; co++) {
+ float bias = b ? b[co] : 0;
+ for (int oy = 0; oy < Ho; oy++)
+ for (int ox = 0; ox < Wo; ox++) {
+ float sum = bias;
+ for (int ci = 0; ci < Cin; ci++)
+ for (int ky = 0; ky < K; ky++)
+ for (int kx = 0; kx < K; kx++)
+ sum += in[((size_t)ci*H + oy*stride+ky)*W + ox*stride+kx] *
+ w[(((size_t)co*Cin+ci)*K+ky)*K+kx];
+ out[((size_t)co*Ho+oy)*Wo+ox] = sum;
+ }
+ }
+}
+
+/* ============ MatMul with optional INT8 acceleration ============ */
+static void matmul_auto(const float* A, int M, int K, int N,
+ const float* B_fp32, const PackedMM* mm)
+{
+ /* Allocate output — caller must know where to put result */
+ /* Actually this doesn't work — we need output pointer. Rethink. */
+}
+
+/* Use matmul that checks for pre-packed FP32 or INT8 weights */
+extern void matmul_fp32_packed(const float*, const float*, float*, int, int, int);
+
+static void matmul_w(const float* A, const float* B, float* C,
+ int M, int K, int N, const PackedMM* mm)
+{
+ (void)mm; /* INT8 disabled for now */
+ /* Check for FP32 packed weight — stored in the global weights struct */
+ /* We pass B as the ORIGINAL weight pointer; the caller checks fp[] */
+ matmul_fp32(A, B, C, M, K, N);
+}
+
+/* Packed FP32 matmul — uses pre-packed weights for cache-friendly access.
+ * Optional bias: added to each output row during store (avoids separate pass). */
+extern void matmul_fp32_packed_bias(const float*, const float*, const float*, float*, int, int, int);
+
+extern void matmul_specialized(const float*, const float*, float*, int, int, int);
+extern void matmul_jit_or_packed(const float*, const float*, float*, int, int, int);
+
+static Weights* _g_weights = NULL; /* set in forward pass for INT8 lookup */
+
+/* Zero-overhead matmul: inline, direct call, no dispatch */
+static inline void matmul_wp(const float* A, float* C,
+ int M, int K, int N, const PackedFP32* fp)
+{
+ matmul_fp32_packed(A, fp->data, C, M, fp->K, fp->N);
+}
+static void matmul_wpb(const float* A, float* C, const float* bias,
+ int M, int K, int N, const PackedFP32* fp)
+{
+ if (fp && fp->data)
+ matmul_fp32_packed_bias(A, fp->data, bias, C, M, K, N);
+}
+
+/* ============ Threaded MLP worker (file scope for proper compilation) ============ */
+#include "threadpool.h"
+typedef struct {
+ float *x, *t1, *t2, *residual;
+ const float *gamma, *mlp_b1, *mlp_b3;
+ const PackedFP32 *fp0, *fp1, *fp2, *fp3;
+ int C, rank, hidden;
+} MlpCtx;
+
+static void _mlp_rows(void* ctx_, int start, int end) {
+ MlpCtx* g = (MlpCtx*)ctx_;
+ int rows = end - start;
+ if (rows <= 0) return;
+ float* x_s = g->x + start * g->C;
+ float* t1_s = g->t1 + start * g->rank;
+ float* t2_s = g->t2 + start * g->hidden;
+ float* res_s = g->residual + start * g->C;
+ matmul_fp32_packed(x_s, g->fp0->data, t1_s, rows, g->fp0->K, g->fp0->N);
+ matmul_fp32_packed(t1_s, g->fp1->data, t2_s, rows, g->fp1->K, g->fp1->N);
+ for (int r = 0; r < rows; r++) {
+ float* row = t2_s + r * g->hidden;
+ for (int h = 0; h < g->hidden; h++) row[h] += g->mlp_b1[h];
+ }
+ gelu_fp32(t2_s, rows * g->hidden);
+ matmul_fp32_packed(t2_s, g->fp2->data, t1_s, rows, g->fp2->K, g->fp2->N);
+ matmul_fp32_packed(t1_s, g->fp3->data, x_s, rows, g->fp3->K, g->fp3->N);
+ for (int r = 0; r < rows; r++)
+ for (int c = 0; c < g->C; c++)
+ x_s[r*g->C+c] = (x_s[r*g->C+c] + g->mlp_b3[c]) * g->gamma[c] + res_s[r*g->C+c];
+}
+
+/* ============ ConvNeXt Block (HWC in/out, NCHW for DW) ============ */
+/* x[HW,C] → LN → DW Conv → gamma*x → LN → MLP(4 MatMul) → +residual */
+static void convnext_block(float* x_hwc, int H, int W, int C,
+ const float* gamma,
+ const float* dw_w, const float* dw_b, int K,
+ const float* ln_w, const float* ln_b,
+ const float* mlp_w0, const float* mlp_w1,
+ const float* mlp_b1,
+ const float* mlp_w2, const float* mlp_w3,
+ const float* mlp_b3,
+ int rank, int hidden,
+ float* tmp,
+ const PackedFP32* fp0, const PackedFP32* fp1,
+ const PackedFP32* fp2, const PackedFP32* fp3)
+{
+ int HW = H * W;
+ float* residual = tmp;
+ float* dw_out = residual + HW * C;
+ float* t1 = dw_out + HW * C;
+ float* t2 = t1 + HW * rank;
+
+ memcpy(residual, x_hwc, (size_t)HW * C * sizeof(float));
+
+ /* DW Conv: output to dw_out, then use dw_out for LN+MLP (avoids memcpy!) */
+ depthwise_conv_nxn_hwc_fp32(x_hwc, H, W, C, dw_w, dw_b, K, dw_out);
+ /* No memcpy — use dw_out directly for subsequent ops */
+
+ /* LayerNorm on dw_out (in-place) */
+ layer_norm_fp32(dw_out, HW, C, ln_w, ln_b, 1e-6f, dw_out);
+
+ {
+ /* Single-threaded MLP operating on dw_out */
+ matmul_wp(dw_out, t1, HW, C, rank, fp0);
+ matmul_wp(t1, t2, HW, rank, hidden, fp1);
+ /* Bias + GELU */
+ for (int hw = 0; hw < HW; hw++) {
+ float* row = t2 + hw * hidden;
+ int h = 0;
+#ifdef __AVX512F__
+ for (; h + 16 <= hidden; h += 16)
+ _mm512_storeu_ps(row+h, _mm512_add_ps(_mm512_loadu_ps(row+h), _mm512_loadu_ps(mlp_b1+h)));
+#elif defined(__AVX2__)
+ for (; h + 8 <= hidden; h += 8)
+ _mm256_storeu_ps(row+h, _mm256_add_ps(_mm256_loadu_ps(row+h), _mm256_loadu_ps(mlp_b1+h)));
+#endif
+ for (; h < hidden; h++) row[h] += mlp_b1[h];
+ }
+ gelu_fp32(t2, HW * hidden);
+ matmul_wp(t2, t1, HW, hidden, rank, fp2);
+ matmul_wp(t1, dw_out, HW, rank, C, fp3); /* → dw_out, not x_hwc */
+ /* Fused bias + gamma + residual with AVX-512 */
+ for (int hw = 0; hw < HW; hw++) {
+ int c = 0;
+#ifdef __AVX512F__
+ for (; c + 16 <= C; c += 16) {
+ __m512 v = _mm512_loadu_ps(dw_out + hw*C + c);
+ v = _mm512_add_ps(v, _mm512_loadu_ps(mlp_b3 + c));
+ v = _mm512_fmadd_ps(v, _mm512_loadu_ps(gamma + c), _mm512_loadu_ps(residual + hw*C + c));
+ _mm512_storeu_ps(x_hwc + hw*C + c, v);
+ }
+#endif
+#ifdef __AVX2__
+ for (; c + 8 <= C; c += 8) {
+ __m256 v = _mm256_loadu_ps(dw_out + hw*C + c);
+ v = _mm256_add_ps(v, _mm256_loadu_ps(mlp_b3 + c));
+ v = _mm256_fmadd_ps(v, _mm256_loadu_ps(gamma + c), _mm256_loadu_ps(residual + hw*C + c));
+ _mm256_storeu_ps(x_hwc + hw*C + c, v);
+ }
+#endif
+ for (; c < C; c++)
+ x_hwc[hw*C+c] = (dw_out[hw*C+c] + mlp_b3[c]) * gamma[c] + residual[hw*C+c];
+ }
+ }
+}
+
+/* ============ Forward Pass ============ */
+static void edgeface_forward(const float* input_chw, /* [3, 112, 112] */
+ Weights* weights,
+ float* embedding) /* [512] */
+{
+ _g_weights = weights; /* enable INT8 lookup in matmul_wp */
+ /* Static workspace — avoids malloc overhead on every call */
+ static float work[2 * 1024 * 1024]; /* 8MB — plenty for all stages */
+ static float x_buf[28 * 28 * 192]; /* largest: 784 positions × 192 channels */
+
+ float* x = x_buf;
+
+ /* === STEM: Conv 3→32 4×4 s4 → output directly in HWC === */
+ {
+ const float* sw = W(0); /* [32, 3, 4, 4] OIHW */
+ const float* sb = W(1); /* [32] */
+ for (int oy = 0; oy < 28; oy++)
+ for (int ox = 0; ox < 28; ox++) {
+ float* o = x + (oy * 28 + ox) * 32;
+ int co = 0;
+#ifdef __AVX2__
+ for (; co + 8 <= 32; co += 8)
+ _mm256_storeu_ps(o + co, _mm256_loadu_ps(sb + co));
+#endif
+ for (; co < 32; co++) o[co] = sb[co];
+ for (int ci = 0; ci < 3; ci++)
+ for (int ky = 0; ky < 4; ky++)
+ for (int kx = 0; kx < 4; kx++) {
+ float iv = input_chw[(size_t)ci*112*112 + (oy*4+ky)*112 + ox*4+kx];
+ co = 0;
+#ifdef __AVX2__
+ __m256 va = _mm256_set1_ps(iv);
+ for (; co + 8 <= 32; co += 8) {
+ int wi = (co * 3 + ci) * 16 + ky * 4 + kx;
+ /* Gather weights: w[co+j, ci, ky, kx] for j=0..7 */
+ float wv[8];
+ for (int j = 0; j < 8; j++)
+ wv[j] = sw[((co+j)*3+ci)*16 + ky*4+kx];
+ _mm256_storeu_ps(o+co, _mm256_fmadd_ps(va, _mm256_loadu_ps(wv),
+ _mm256_loadu_ps(o+co)));
+ }
+#endif
+ for (; co < 32; co++)
+ o[co] += iv * sw[(co*3+ci)*16 + ky*4+kx];
+ }
+ }
+ }
+
+ layer_norm_fp32(x, 784, 32, W(2), W(3), 1e-6f, x);
+
+ /* === STAGE 0: 3 ConvNeXt blocks (C=32, K=3, rank=19, hidden=128) === */
+ /* Block 0: gamma=17, dw_w=4, dw_b=5, ln_w=6, ln_b=7,
+ * mlp_w0=8[32,19], mlp_w1=9[19,128], mlp_b1=10,
+ * mlp_w2=14[128,19], mlp_w3=15[19,32], mlp_b3=16 */
+ /* Test: INT8 for first block only, FP32 for rest */
+ #define FP(i) (&weights->fp[i])
+ #define I8(i) (&weights->mm[i]) /* INT8 packed */
+
+ /* TEST: first block INT8 to verify correctness */
+ convnext_block(x, 28,28,32, W(17), W(4),W(5),3, W(6),W(7),
+ W(8),W(9),W(10), W(14),W(15),W(16), 19,128, work,
+ FP(8),FP(9),FP(14),FP(15));
+ /* Note: INT8 test disabled — need to change convnext_block to accept PackedMM* */
+
+ convnext_block(x, 28,28,32, W(28), W(18),W(19),3, W(20),W(21),
+ W(22),W(23),W(24), W(25),W(26),W(27), 19,128, work,
+ FP(22),FP(23),FP(25),FP(26));
+
+ convnext_block(x, 28,28,32, W(39), W(29),W(30),3, W(31),W(32),
+ W(33),W(34),W(35), W(36),W(37),W(38), 19,128, work,
+ FP(33),FP(34),FP(36),FP(37));
+ /* === DOWNSAMPLE 0→1: LN(40,41) + Conv 32→64 2×2 s2 (42,43) — all HWC === */
+ layer_norm_fp32(x, 784, 32, W(40), W(41), 1e-6f, x);
+ {
+ float tmp_hwc[196 * 64];
+ conv2d_hwc(x, 32, 28, 28, W(42), W(43), 64, 2, 2, tmp_hwc);
+ memcpy(x, tmp_hwc, 196 * 64 * sizeof(float));
+ }
+
+ /* === STAGE 1: 2 ConvNeXt blocks (C=64, K=5, rank=38, hidden=256) === */
+ /* x already has enough space for all stages */
+
+ convnext_block(x, 14,14,64, W(54), W(44),W(45),5, W(46),W(47),
+ W(48),W(49),W(50), W(51),W(52),W(53), 38,256, work,
+ FP(48),FP(49),FP(51),FP(52));
+ convnext_block(x, 14,14,64, W(65), W(55),W(56),5, W(57),W(58),
+ W(59),W(60),W(61), W(62),W(63),W(64), 38,256, work,
+ FP(59),FP(60),FP(62),FP(63));
+
+ /* Stage 1 XCA attention (tensors 66-100) */
+ /* DW: split [32,32], conv first 32 only. Pos: Conv1x1(const[69],W70,W71). */
+ {
+ int s1_dw_splits[] = {32, 32};
+ const float* s1_dw_ws[] = {W(66)};
+ const float* s1_dw_bs[] = {W(67)};
+ xca_block(x, 14,14,64,
+ W(90)/*gamma_xca*/, W(100)/*gamma*/,
+ 2, s1_dw_splits, 1, s1_dw_ws, s1_dw_bs, 3, /* DW conv */
+ W(69)/*pos_const_nchw*/, W(70), W(71), /* pos embed */
+ W(72),W(73), /* xca LN */
+ W(74),W(75),W(76), /* QKV LoRaLin + bias (192 = 3×64) */
+ W(85), 4, /* temperature, n_heads */
+ W(87),W(88),W(89), /* proj LoRaLin + bias */
+ W(92),W(93), /* post-attn LN */
+ W(94),W(95),W(96), W(97),W(98),W(99), /* MLP */
+ 38, 256, work,
+ FP(74),FP(75),FP(87),FP(88),
+ FP(94),FP(95),FP(97),FP(98));
+ }
+
+ /* === DOWNSAMPLE 1→2: LN(101,102) + Conv 64→100 2×2 s2 (103,104) — HWC === */
+ layer_norm_fp32(x, 196, 64, W(101), W(102), 1e-6f, x);
+ {
+ float tmp_hwc[49 * 100];
+ conv2d_hwc(x, 64, 14, 14, W(103), W(104), 100, 2, 2, tmp_hwc);
+ memcpy(x, tmp_hwc, 49 * 100 * sizeof(float));
+ }
+
+ /* === STAGE 2: 8 ConvNeXt blocks === */
+ for (int b = 0; b < 8; b++) {
+ int base = 105 + b * 11;
+ convnext_block(x, 7,7,100, W(base+10), W(base),W(base+1),7,
+ W(base+2),W(base+3),
+ W(base+4),W(base+5),W(base+6), W(base+7),W(base+8),W(base+9),
+ 60,400, work,
+ FP(base+4),FP(base+5),FP(base+7),FP(base+8));
+ }
+
+ /* Stage 2 XCA attention (tensors 193-220) */
+ /* DW: split [34,34,32], conv first 2 splits. No pos embed. */
+ {
+ int s2_dw_splits[] = {34, 34, 32};
+ const float* s2_dw_ws[] = {W(193), W(195)};
+ const float* s2_dw_bs[] = {W(194), W(196)};
+ xca_block(x, 7,7,100,
+ W(210), W(220),
+ 3, s2_dw_splits, 2, s2_dw_ws, s2_dw_bs, 3, /* DW conv */
+ NULL, NULL, NULL, /* No pos embed */
+ W(198),W(199),
+ W(200),W(201),W(202),
+ W(205), 4,
+ W(207),W(208),W(209),
+ W(212),W(213),
+ W(214),W(215),W(216), W(217),W(218),W(219),
+ 60, 400, work,
+ FP(200),FP(201),FP(207),FP(208),
+ FP(214),FP(215),FP(217),FP(218));
+ }
+
+ /* === DOWNSAMPLE 2→3: LN(221,222) + Conv 100→192 2×2 s2 (223,224) — HWC === */
+ layer_norm_fp32(x, 49, 100, W(221), W(222), 1e-6f, x);
+ {
+ int Ho = (7-2)/2+1; /* =3 */
+ float tmp_hwc[9 * 192]; /* 3×3 × 192 */
+ conv2d_hwc(x, 100, 7, 7, W(223), W(224), 192, 2, 2, tmp_hwc);
+ memcpy(x, tmp_hwc, (size_t)Ho * Ho * 192 * sizeof(float));
+ }
+ int H3 = 3, W3 = 3;
+
+ /* === STAGE 3: 2 ConvNeXt blocks (C=192, K=9, rank=115, hidden=768) === */
+ /* Block 0: tensors 225-235 */
+ convnext_block(x, H3,W3,192, W(235), W(225),W(226),9, W(227),W(228),
+ W(229),W(230),W(231), W(232),W(233),W(234), 115,768, work,
+ FP(229),FP(230),FP(232),FP(233));
+ convnext_block(x, H3,W3,192, W(246), W(236),W(237),9, W(238),W(239),
+ W(240),W(241),W(242), W(243),W(244),W(245), 115,768, work,
+ FP(240),FP(241),FP(243),FP(244));
+
+ /* Stage 3 XCA attention (tensors 247-276) */
+ /* DW: split [48,48,48,48], conv first 3 splits. No pos embed. */
+ {
+ int s3_dw_splits[] = {48, 48, 48, 48};
+ const float* s3_dw_ws[] = {W(247), W(249), W(251)};
+ const float* s3_dw_bs[] = {W(248), W(250), W(252)};
+ xca_block(x, H3,W3,192,
+ W(266), W(276),
+ 4, s3_dw_splits, 3, s3_dw_ws, s3_dw_bs, 3, /* DW conv */
+ NULL, NULL, NULL, /* No pos embed */
+ W(254),W(255),
+ W(256),W(257),W(258),
+ W(261), 4,
+ W(263),W(264),W(265),
+ W(268),W(269),
+ W(270),W(271),W(272), W(273),W(274),W(275),
+ 115, 768, work,
+ FP(256),FP(257),FP(263),FP(264),
+ FP(270),FP(271),FP(273),FP(274));
+ }
+
+ /* === HEAD: ReduceMean + LN + FC(192→115) + FC(115→512) === */
+ /* Global average pool: x[H3*W3, 192] → mean across positions → [192] */
+ float pooled[192];
+ int HW3 = H3 * W3;
+ for (int c = 0; c < 192; c++) {
+ float sum = 0;
+ for (int hw = 0; hw < HW3; hw++) sum += x[hw * 192 + c];
+ pooled[c] = sum / HW3;
+ }
+
+ /* LN(280,281) */
+ layer_norm_fp32(pooled, 1, 192, W(280), W(281), 1e-6f, pooled);
+
+ /* FC: 192→115 (W283 = [115,192] transposed → use as [192,115] directly) */
+ /* W283 stored as Gemm transB: W[n,k]. We need pooled[k]*W[n,k] = pooled @ W^T.
+ * But our packed matmul does A[M,K] @ B[K,N]. Here A=pooled[1,192], need B=[192,115].
+ * W283 is [115,192] — this is the TRANSPOSED version. Need to transpose at load time
+ * or use it as-is with a transposed dot product. Since M=1, just use vectorized dots. */
+ float fc1[115];
+ {
+ const float* wt = W(283); /* [115, 192] = w[n, k] */
+ for (int n = 0; n < 115; n++) {
+ float sum = 0;
+ int k = 0;
+#ifdef __AVX2__
+ __m256 vs = _mm256_setzero_ps();
+ for (; k + 8 <= 192; k += 8)
+ vs = _mm256_fmadd_ps(_mm256_loadu_ps(pooled+k), _mm256_loadu_ps(wt+n*192+k), vs);
+ /* Horizontal sum */
+ __m128 lo = _mm256_castps256_ps128(vs);
+ __m128 hi = _mm256_extractf128_ps(vs, 1);
+ lo = _mm_add_ps(lo, hi);
+ lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_add_ss(lo, _mm_movehdup_ps(lo));
+ sum = _mm_cvtss_f32(lo);
+#endif
+ for (; k < 192; k++) sum += pooled[k] * wt[n*192+k];
+ fc1[n] = sum;
+ }
+ }
+
+ /* FC: 115→512 + bias */
+ {
+ const float* wt = W(284); /* [512, 115] = w[n, k] */
+ const float* bias = W(285);
+ for (int n = 0; n < 512; n++) {
+ float sum = bias[n];
+ int k = 0;
+#ifdef __AVX2__
+ __m256 vs = _mm256_setzero_ps();
+ for (; k + 8 <= 115; k += 8)
+ vs = _mm256_fmadd_ps(_mm256_loadu_ps(fc1+k), _mm256_loadu_ps(wt+n*115+k), vs);
+ __m128 lo = _mm256_castps256_ps128(vs);
+ __m128 hi = _mm256_extractf128_ps(vs, 1);
+ lo = _mm_add_ps(lo, hi);
+ lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_add_ss(lo, _mm_movehdup_ps(lo));
+ sum += _mm_cvtss_f32(lo);
+#endif
+ for (; k < 115; k++) sum += fc1[k] * wt[n*115+k];
+ embedding[n] = sum;
+ }
+ }
+
+ /* x and work are static — no free needed */
+}
+
+/* ============ Engine Init (used by both main and library API) ============ */
+static int engine_init(const char* weights_path, Weights* weights) {
+ /* Init thread pool for parallel GEMM */
+ {
+ extern void tp_init(int);
+ tp_init(4);
+ }
+
+ if (load_weights(weights_path, weights) != 0) {
+ fprintf(stderr, "Failed to load %s\n", weights_path);
+ return -1;
+ }
+ /* Allocate packed MatMul weight arrays */
+ weights->mm = (PackedMM*)calloc(weights->n_tensors, sizeof(PackedMM));
+ weights->fp = (PackedFP32*)calloc(weights->n_tensors, sizeof(PackedFP32));
+
+
+ /* Pre-pack MatMul weights to INT8 c8 format */
+ {
+ extern void pack_weights_4x8c8(const int8_t*, const float*, int, int, void*, int32_t*);
+ extern int packed_weights_size_4x8c8(int, int);
+
+ /* MatMul weight indices (2D tensors used in MatMul) */
+ int mm_idx[] = {8,9,14,15,22,23,25,26,33,34,36,37,48,49,51,52,59,60,62,63,
+ 74,75,87,88,94,95,97,98,109,110,112,113,120,121,123,124,
+ 131,132,134,135,142,143,145,146,153,154,156,157,164,165,
+ 167,168,175,176,178,179,186,187,189,190,200,201,207,208,
+ 214,215,217,218,229,230,232,233,240,241,243,244,256,257,
+ 263,264,270,271,273,274,283,284,-1};
+
+ /* Weight sizes from names.txt (K×N pairs) */
+ /* Each weight W[K,N] is used as: A[M,K] @ W[K,N] → C[M,N]
+ * c8 GEMM expects B as [N, K] (Cout=N, K=K)
+ * So we need to transpose W to [N, K] before packing */
+ int mm_shapes[][2] = {
+ {32,19},{19,128},{128,19},{19,32}, /* stage 0 block 0 */
+ {32,19},{19,128},{128,19},{19,32}, /* stage 0 block 1 */
+ {32,19},{19,128},{128,19},{19,32}, /* stage 0 block 2 */
+ {64,38},{38,256},{256,38},{38,64}, /* stage 1 block 0 */
+ {64,38},{38,256},{256,38},{38,64}, /* stage 1 block 1 */
+ {64,38},{38,192}, /* stage 1 attn QKV proj */
+ {64,38},{38,64}, /* stage 1 attn out proj */
+ {64,38},{38,256},{256,38},{38,64}, /* stage 1 attn MLP */
+ /* stage 2: 8 blocks × 4 weights */
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ /* stage 2 attn */
+ {100,60},{60,300},
+ {100,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ /* stage 3: 2 blocks */
+ {192,115},{115,768},{768,115},{115,192},
+ {192,115},{115,768},{768,115},{115,192},
+ /* stage 3 attn */
+ {192,115},{115,576},
+ {192,115},{115,192},
+ {192,115},{115,768},{768,115},{115,192},
+ /* head */
+ {115,192},{512,115},
+ };
+
+ int packed_count = 0;
+ for (int i = 0; mm_idx[i] >= 0; i++) {
+ int idx = mm_idx[i];
+ int K = mm_shapes[i][0], N = mm_shapes[i][1];
+
+ if (N < 8) continue; /* Skip tiny N (c8 GEMM needs N≥8) */
+
+ float* w_fp32 = weights->tensors[idx]; /* [K, N] row-major */
+
+ /* Quantize per-output-channel: transpose to [N, K], quantize per N */
+ int8_t* w_int8 = (int8_t*)malloc((size_t)N * K);
+ float* w_scales = (float*)malloc(N * sizeof(float));
+
+ for (int n = 0; n < N; n++) {
+ float mx = 0;
+ for (int k = 0; k < K; k++) {
+ float v = w_fp32[k * N + n];
+ if (v < 0) v = -v;
+ if (v > mx) mx = v;
+ }
+ w_scales[n] = (mx > 1e-8f) ? mx / 127.0f : 1e-8f;
+ for (int k = 0; k < K; k++) {
+ float v = w_fp32[k * N + n] / w_scales[n];
+ int q = (int)(v + (v >= 0 ? 0.5f : -0.5f));
+ if (q > 127) q = 127; if (q < -128) q = -128;
+ w_int8[n * K + k] = (int8_t)q; /* [N, K] layout for c8 pack */
+ }
+ }
+
+ int pw_size = packed_weights_size_4x8c8(K, N);
+ void* packed = malloc(pw_size);
+ int32_t* col_sums = (int32_t*)calloc(((N+7)&~7), sizeof(int32_t));
+ pack_weights_4x8c8(w_int8, NULL, K, N, packed, col_sums);
+
+ weights->mm[idx].packed = packed;
+ weights->mm[idx].col_sums = col_sums;
+ weights->mm[idx].w_scales = w_scales;
+ weights->mm[idx].K = K;
+ weights->mm[idx].N = N;
+ packed_count++;
+
+ free(w_int8);
+ }
+ }
+
+ /* Pre-pack FP32 MatMul weights into column-panel format [ceil(N/8), K, 8] */
+ {
+ extern void pack_b_fp32(const float*, int, int, float*);
+ extern int packed_b_fp32_size(int, int);
+ /* Same indices and shapes as INT8 packing */
+ int fp_idx[] = {8,9,14,15,22,23,25,26,33,34,36,37,48,49,51,52,59,60,62,63,
+ 74,75,87,88,94,95,97,98, /* stage 1 XCA */
+ 109,110,112,113,120,121,123,124,131,132,134,135,142,143,145,146,
+ 153,154,156,157,164,165,167,168,175,176,178,179,186,187,189,190,
+ 200,201,207,208,214,215,217,218, /* stage 2 XCA */
+ 229,230,232,233,240,241,243,244,
+ 256,257,263,264,270,271,273,274, /* stage 3 XCA */
+ -1};
+ int fp_shapes[][2] = {
+ {32,19},{19,128},{128,19},{19,32},
+ {32,19},{19,128},{128,19},{19,32},
+ {32,19},{19,128},{128,19},{19,32},
+ {64,38},{38,256},{256,38},{38,64},
+ {64,38},{38,256},{256,38},{38,64},
+ {64,38},{38,192}, {64,38},{38,64}, {64,38},{38,256},{256,38},{38,64}, /* s1 XCA */
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,400},{400,60},{60,100},
+ {100,60},{60,300}, {100,60},{60,100}, {100,60},{60,400},{400,60},{60,100}, /* s2 XCA */
+ {192,115},{115,768},{768,115},{115,192},
+ {192,115},{115,768},{768,115},{115,192},
+ {192,115},{115,576}, {192,115},{115,192}, {192,115},{115,768},{768,115},{115,192}, /* s3 XCA */
+ };
+ for (int i = 0; fp_idx[i] >= 0; i++) {
+ int idx = fp_idx[i];
+ int K_ = fp_shapes[i][0], N_ = fp_shapes[i][1];
+ int sz = packed_b_fp32_size(K_, N_);
+ float* packed;
+#ifdef _WIN32
+#ifdef _WIN32
+ packed = (float*)_aligned_malloc((size_t)sz * sizeof(float), 64);
+#else
+ if (posix_memalign((void**)&packed, 64, (size_t)sz * sizeof(float)) != 0) packed = NULL;
+#endif
+#else
+ packed = (float*)aligned_alloc(32, (size_t)sz * sizeof(float));
+#endif
+ if (!packed) packed = (float*)malloc((size_t)sz * sizeof(float));
+ pack_b_fp32(weights->tensors[idx], K_, N_, packed);
+ weights->fp[idx].data = packed;
+ weights->fp[idx].K = K_;
+ weights->fp[idx].N = N_;
+ }
+ }
+
+ /* Pre-transpose DW conv weights: [C, K*K] → [K*K, C] for HWC AVX2 loads */
+ /* DW weight tensor indices from names.txt */
+ int dw_indices[] = {4,18,29, 44,55, 66, 105,116,127,138,149,160,171,182, 193,195,
+ 225,236, 247,249,251, -1};
+ int dw_K[] = {3,3,3, 5,5, 3, 7,7,7,7,7,7,7,7, 3,3, 9,9, 3,3,3};
+ for (int di = 0; dw_indices[di] >= 0; di++) {
+ int idx = dw_indices[di];
+ int K = dw_K[di];
+ int KK = K * K;
+ /* Find C from weight shape: weight is [C, 1, K, K] = C*KK floats */
+ /* We need to know C — get from the next tensor (bias) which has C floats */
+ /* Actually just compute: total_floats / KK */
+ /* But we don't store sizes... just hardcode known C values */
+ }
+ /* Simpler: transpose in-place in the weight buffer */
+ /* DW weights are [C, K*K] stored contiguously. Transpose to [K*K, C] */
+ {
+ /* Stage 0: C=32, K=3, indices 4,18,29 */
+ int stage0_dw[] = {4, 18, 29};
+ for (int j = 0; j < 3; j++) {
+ int idx = stage0_dw[j]; int C = 32, KK = 9;
+ float* tmp = (float*)malloc(C * KK * sizeof(float));
+ memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
+ for (int c = 0; c < C; c++)
+ for (int ki = 0; ki < KK; ki++)
+ weights->tensors[idx][ki * C + c] = tmp[c * KK + ki];
+ free(tmp);
+ }
+ /* Stage 1: C=64, K=5, indices 44,55 */
+ int stage1_dw[] = {44, 55};
+ for (int j = 0; j < 2; j++) {
+ int idx = stage1_dw[j]; int C = 64, KK = 25;
+ float* tmp = (float*)malloc(C * KK * sizeof(float));
+ memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
+ for (int c = 0; c < C; c++)
+ for (int ki = 0; ki < KK; ki++)
+ weights->tensors[idx][ki * C + c] = tmp[c * KK + ki];
+ free(tmp);
+ }
+ /* Stage 2: C=100, K=7, indices 105..182 (every 11) */
+ for (int b = 0; b < 8; b++) {
+ int idx = 105 + b * 11; int C = 100, KK = 49;
+ float* tmp = (float*)malloc(C * KK * sizeof(float));
+ memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
+ for (int c = 0; c < C; c++)
+ for (int ki = 0; ki < KK; ki++)
+ weights->tensors[idx][ki * C + c] = tmp[c * KK + ki];
+ free(tmp);
+ }
+ /* Stage 3: C=192, K=9, indices 225, 236 */
+ int stage3_dw[] = {225, 236};
+ for (int j = 0; j < 2; j++) {
+ int idx = stage3_dw[j]; int C = 192, KK = 81;
+ float* tmp = (float*)malloc(C * KK * sizeof(float));
+ memcpy(tmp, weights->tensors[idx], C * KK * sizeof(float));
+ for (int c = 0; c < C; c++)
+ for (int ki = 0; ki < KK; ki++)
+ weights->tensors[idx][ki * C + c] = tmp[c * KK + ki];
+ free(tmp);
+ }
+ }
+
+ /* Reorder downsample conv weights: OIHW [Cout,Cin,K,K] → [Cin*KK, Cout] for AVX2 */
+ conv2d_hwc_reorder_weights(weights->tensors[42], 64, 32, 4); /* ds 0→1: 32→64 2×2 */
+ conv2d_hwc_reorder_weights(weights->tensors[103], 100, 64, 4); /* ds 1→2: 64→100 2×2 */
+ conv2d_hwc_reorder_weights(weights->tensors[223], 192, 100, 4);/* ds 2→3: 100→192 2×2 */
+
+ /* Register JIT kernels for small-K matmuls (optional — link jit_gemm.c) */
+#ifdef USE_JIT
+ {
+ extern void jit_register(int, int);
+ int jit_sizes[][2] = {
+ {32,19},{19,128},{128,19},{19,32},
+ {64,38},{38,256},{256,38},{38,64},
+ {38,192},{60,400},{60,100},{60,300},
+ {-1,-1}
+ };
+ for (int i = 0; jit_sizes[i][0] > 0; i++)
+ jit_register(jit_sizes[i][0], jit_sizes[i][1]);
+ }
+#endif
+
+ /* Pre-compute stage 1 position embedding: Conv1x1(const[69], W70, W71) → [196, 64] HWC */
+ /* This is constant — same result every forward pass. Cache it in tensor 69's slot. */
+ {
+ int HW = 196, C = 64;
+ float* pos_cached = (float*)malloc((size_t)HW * C * sizeof(float));
+ const float* pos_const = weights->tensors[69]; /* [1, 64, 14, 14] NCHW */
+ const float* pos_w = weights->tensors[70]; /* [64, 64, 1, 1] = [Cout, Cin] */
+ const float* pos_b = weights->tensors[71]; /* [64] */
+ for (int hw = 0; hw < HW; hw++)
+ for (int co = 0; co < C; co++) {
+ float sum = pos_b[co];
+ for (int ci = 0; ci < C; ci++)
+ sum += pos_const[ci * HW + hw] * pos_w[co * C + ci];
+ pos_cached[hw * C + co] = sum;
+ }
+ weights->tensors[69] = pos_cached; /* Replace with pre-computed HWC result */
+ }
+
+ return 0;
+}
+
+/* ============ Main ============ */
+#ifndef FACEX_LIB
+int main(int argc, char** argv) {
+ const char* weights_path = "data/edgeface_xs_fp32.bin";
+ if (argc > 1) weights_path = argv[1];
+
+ /* Parse --license KEY from args or LICENSE_KEY env */
+ for (int i = 1; i < argc - 1; i++) {
+ if (strcmp(argv[i], "--license") == 0) {
+ g_license_key = argv[i + 1];
+ break;
+ }
+ }
+ if (!g_license_key) g_license_key = getenv("LICENSE_KEY");
+
+ Weights weights;
+ if (engine_init(weights_path, &weights) != 0) {
+ fprintf(stderr, "Failed to load %s\n", weights_path);
+ return 1;
+ }
+
+ /* Load input: if --stdin, read 112*112*3 floats (CHW, [-1,1] normalized) */
+ float input[3 * 112 * 112];
+ if (argc > 2 && strcmp(argv[2], "--stdin") == 0) {
+ #ifdef _WIN32
+ _setmode(_fileno(stdin), 0x8000); /* _O_BINARY */
+ #endif
+ size_t rd = fread(input, sizeof(float), 3*112*112, stdin);
+ if (rd != 3*112*112) {
+ fprintf(stderr, "Expected %d floats, got %zu\n", 3*112*112, rd);
+ return 1;
+ }
+ } else {
+ for (int i = 0; i < 3*112*112; i++)
+ input[i] = (float)(i % 256) / 128.0f - 1.0f;
+ }
+
+ float embedding[512];
+
+ /* Mode selection */
+ const char* mode = (argc > 2) ? argv[2] : "";
+ int is_server = (strcmp(mode, "--server") == 0);
+ int is_batch = (strcmp(mode, "--batch") == 0);
+
+ if (is_server || is_batch) {
+ #ifdef _WIN32
+ _setmode(_fileno(stdin), 0x8000);
+ _setmode(_fileno(stdout), 0x8000);
+ #endif
+ float hwc_buf[3 * 112 * 112];
+ /* --server: reads HWC float32, converts to CHW (Go server protocol)
+ * --batch: reads CHW float32 directly (Python test protocol) */
+ while (1) {
+ float* read_buf = is_server ? hwc_buf : input;
+ if (fread(read_buf, sizeof(float), 3*112*112, stdin) != 3*112*112)
+ break;
+ if (is_server) {
+ /* HWC → CHW conversion */
+ for (int h = 0; h < 112; h++)
+ for (int w = 0; w < 112; w++)
+ for (int c = 0; c < 3; c++)
+ input[c * 112 * 112 + h * 112 + w] = hwc_buf[(h * 112 + w) * 3 + c];
+ }
+ edgeface_forward(input, &weights, embedding);
+ fwrite(embedding, sizeof(float), 512, stdout);
+ fflush(stdout);
+ }
+ } else {
+ /* Single image: warmup + benchmark */
+ edgeface_forward(input, &weights, embedding);
+
+ struct timespec t0, t1;
+ int ITERS = 200;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ for (int i = 0; i < ITERS; i++)
+ edgeface_forward(input, &weights, embedding);
+ clock_gettime(CLOCK_MONOTONIC, &t1);
+ double ms = ((t1.tv_sec-t0.tv_sec)*1e3 + (t1.tv_nsec-t0.tv_nsec)/1e6) / ITERS;
+
+ fprintf(stderr, "EdgeFace-XS forward: %.2f ms\n", ms);
+ fprintf(stderr, "Embedding[0..4]: %.4f %.4f %.4f %.4f %.4f\n",
+ embedding[0], embedding[1], embedding[2], embedding[3], embedding[4]);
+ #ifdef _WIN32
+ _setmode(_fileno(stdout), 0x8000);
+ #endif
+ fwrite(embedding, sizeof(float), 512, stdout);
+ fflush(stdout);
+ }
+
+ free(weights.tensors);
+ free(weights.raw);
+ return 0;
+}
+#endif /* FACEX_LIB */
diff --git a/src/facex.c b/src/facex.c
new file mode 100644
index 0000000..7b51ef6
--- /dev/null
+++ b/src/facex.c
@@ -0,0 +1,73 @@
+/*
+ * facex.c — Public API implementation for FaceX library.
+ * See include/facex.h for documentation.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include "../include/facex.h"
+
+#define FACEX_VERSION "1.0.0"
+
+/* Include the engine (main() excluded via FACEX_LIB) */
+#ifndef FACEX_LIB
+#define FACEX_LIB
+#endif
+#include "edgeface_engine.c"
+
+struct FaceX {
+ Weights weights;
+ int ready;
+};
+
+FaceX* facex_init(const char* weights_path, const char* license_key) {
+ if (license_key) g_license_key = license_key;
+
+ FaceX* fx = (FaceX*)calloc(1, sizeof(FaceX));
+ if (!fx) return NULL;
+
+ if (engine_init(weights_path, &fx->weights) != 0) {
+ free(fx);
+ return NULL;
+ }
+
+ fx->ready = 1;
+ return fx;
+}
+
+int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]) {
+ if (!fx || !fx->ready) return -1;
+
+ /* HWC -> CHW conversion */
+ float input_chw[3 * 112 * 112];
+ for (int h = 0; h < 112; h++)
+ for (int w = 0; w < 112; w++)
+ for (int c = 0; c < 3; c++)
+ input_chw[c * 112 * 112 + h * 112 + w] = rgb_hwc[(h * 112 + w) * 3 + c];
+
+ edgeface_forward(input_chw, &fx->weights, embedding);
+ return 0;
+}
+
+float facex_similarity(const float emb1[512], const float emb2[512]) {
+ float dot = 0, n1 = 0, n2 = 0;
+ for (int i = 0; i < 512; i++) {
+ dot += emb1[i] * emb2[i];
+ n1 += emb1[i] * emb1[i];
+ n2 += emb2[i] * emb2[i];
+ }
+ float denom = sqrtf(n1) * sqrtf(n2);
+ return denom > 1e-8f ? dot / denom : 0.0f;
+}
+
+void facex_free(FaceX* fx) {
+ if (!fx) return;
+ if (fx->weights.raw) free(fx->weights.raw);
+ if (fx->weights.tensors) free(fx->weights.tensors);
+ free(fx);
+}
+
+const char* facex_version(void) {
+ return FACEX_VERSION;
+}
diff --git a/src/gemm_int8_4x8c8.c b/src/gemm_int8_4x8c8.c
new file mode 100644
index 0000000..e055fc7
--- /dev/null
+++ b/src/gemm_int8_4x8c8.c
@@ -0,0 +1,434 @@
+/*
+ * gemm_int8_4x8c8.c — Production INT8 GEMM microkernel for AVX2.
+ *
+ * Tile: MR=4, NR=8, KR=8 (c8 packing)
+ * Instructions: vpmaddubsw (u8×s8→s16) + vpmaddwd (s16→s32) + vpaddd
+ * Throughput: 32 INT8 ops/cycle on Skylake+
+ *
+ * Handles signed×signed via offset trick:
+ * A_u8 = A_s8 + 128
+ * compensation = 128 * column_sum(W) per output channel
+ *
+ * Weight packing layout per NR=8 group:
+ * [8 x int32 bias] [K/8 blocks of 64 bytes: 8 columns, each 8 k-values contiguous]
+ *
+ * B block layout (64 bytes per KR=8 block):
+ * Columns 0-3 in first 32 bytes (vb_lo), columns 4-7 in next 32 bytes (vb_hi).
+ * Within each 32-byte half: 4 columns × 8 bytes each, k-values contiguous per column.
+ * Memory: [n0_k0..k7, n1_k0..k7, n2_k0..k7, n3_k0..k7 | n4_k0..k7, ..., n7_k0..k7]
+ *
+ * A loading: broadcastq (8 bytes → 4 copies filling 256 bits).
+ * va = [a_k0..k7, a_k0..k7, a_k0..k7, a_k0..k7]
+ *
+ * vpmaddubsw(va, vb_lo) per lane (16 bytes = 2 columns × 8 k-values):
+ * s16[0] = a_k0*n_X_k0 + a_k1*n_X_k1 (col X partial, k=0,1)
+ * s16[1] = a_k2*n_X_k2 + a_k3*n_X_k3 (col X partial, k=2,3)
+ * s16[2] = a_k4*n_X_k4 + a_k5*n_X_k5 (col X partial, k=4,5)
+ * s16[3] = a_k6*n_X_k6 + a_k7*n_X_k7 (col X partial, k=6,7)
+ * s16[4..7] = same for col X+1
+ *
+ * vpmaddwd(result, vones) → s32: [partial_nX(k0-3), partial_nX(k4-7),
+ * partial_nX+1(k0-3), partial_nX+1(k4-7)]
+ *
+ * After K loop: hadd pairs → [sum_n0, sum_n1, sum_n4, sum_n5 | sum_n2, sum_n3, sum_n6, sum_n7]
+ * permute4x64(0xD8) → [sum_n0..n3 | sum_n4..n7] = 8 output columns.
+ *
+ * Used for: pointwise 1x1 conv and standard 3x3 conv (via im2col)
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <immintrin.h>
+
+/* ============ Weight packing ============ */
+
+/*
+ * Pack weights from [Cout, K] row-major (int8) to c8 format.
+ * Output layout per NR=8 column group:
+ * [8 x int32 bias] [K/8 blocks of 64 bytes]
+ *
+ * Each 64-byte block: columns 0-3 then 4-7, k-values contiguous per column.
+ * Also computes col_sums for signed offset compensation.
+ */
+void pack_weights_4x8c8(
+ const int8_t* weights, /* [Cout, K] row-major */
+ const float* bias, /* [Cout] or NULL */
+ int K, int Cout,
+ void* packed_w, /* output: packed weights */
+ int32_t* col_sums) /* output: 128 * sum(w) per output channel [Cout] */
+{
+ uint8_t* out = (uint8_t*)packed_w;
+ int K_padded = (K + 7) & ~7;
+
+ for (int co = 0; co < Cout; co += 8) {
+ /* Write bias (8 x int32) */
+ int32_t* bias_ptr = (int32_t*)out;
+ for (int j = 0; j < 8; j++) {
+ if (bias && (co + j) < Cout)
+ bias_ptr[j] = (int32_t)(bias[co + j]);
+ else
+ bias_ptr[j] = 0;
+ }
+ out += 8 * sizeof(int32_t);
+
+ /* Compute column sums for compensation */
+ for (int j = 0; j < 8; j++) {
+ int32_t sum = 0;
+ if ((co + j) < Cout) {
+ for (int k = 0; k < K; k++) {
+ sum += (int32_t)weights[(co + j) * K + k];
+ }
+ }
+ col_sums[co + j] = 128 * sum;
+ }
+
+ /* Pack weights in c8 layout: [col, 8 k-values].
+ * B weights CLAMPED to ±63 to prevent vpmaddubsw saturation. */
+ for (int k = 0; k < K_padded; k += 8) {
+ for (int j = 0; j < 8; j++) {
+ for (int kk = 0; kk < 8; kk++) {
+ if ((co + j) < Cout && (k + kk) < K) {
+ *out++ = (uint8_t)weights[(co + j) * K + (k + kk)];
+ } else {
+ *out++ = 0;
+ }
+ }
+ }
+ }
+ }
+}
+
+/* Size of packed weights buffer */
+int packed_weights_size_4x8c8(int K, int Cout) {
+ int K_padded = (K + 7) & ~7;
+ int nr_groups = (Cout + 7) / 8;
+ /* Per group: 8*int32 bias + K_padded*8 bytes weights */
+ return nr_groups * (8 * sizeof(int32_t) + K_padded * 8);
+}
+
+/* ============ Activation packing: signed→unsigned ============ */
+
+void convert_s8_to_u8(const int8_t* in, uint8_t* out, int n) {
+ int i = 0;
+#ifdef __AVX2__
+ __m256i v128 = _mm256_set1_epi8((char)128);
+ for (; i + 32 <= n; i += 32) {
+ __m256i v = _mm256_loadu_si256((const __m256i*)(in + i));
+ __m256i vu = _mm256_xor_si256(v, v128);
+ _mm256_storeu_si256((__m256i*)(out + i), vu);
+ }
+#endif
+ for (; i < n; i++) {
+ out[i] = (uint8_t)((int)in[i] + 128);
+ }
+}
+
+/* ============ GEMM Microkernel ============ */
+
+/*
+ * gemm_4x8c8_ukernel: MR=4 rows × NR=8 columns.
+ *
+ * Uses broadcastq for A (all 32 bytes active), separate accumulators
+ * for cols 0-3 (vacc_lo) and cols 4-7 (vacc_hi), with hadd+permute
+ * at the end to produce 8 output columns per row.
+ */
+/* AVX-512 VNNI microkernel: uses VPDPBUSD for u8×s8→s32 WITHOUT saturation.
+ * One instruction replaces vpmaddubsw+vpmaddwd. Full ±127 B range (no clamping). */
+static void gemm_4x8c8_ukernel(
+ const int8_t* a, int a_stride,
+ const int8_t* w,
+ int32_t* c, int c_stride,
+ int K, int mr)
+{
+#ifdef __AVX512VNNI__
+ /* AVX-512 VNNI path: MR=4, NR=16 (process all 8 cols + padding in one ZMM).
+ * VPDPBUSD(acc, a_u8, b_s8): acc += sum_of_4(a_u8[i]*b_s8[i]) per 32-bit lane.
+ * Each ZMM holds 64 bytes = 16 groups of 4 bytes. With c8 layout, one ZMM = 2 cols × 8 k-values.
+ * So we need 4 ZMM loads for 8 cols. */
+
+ /* Actually, simpler: use the same c8 layout but process with 512-bit registers.
+ * Load 64 bytes (8 cols × 8 k-values) into one ZMM. VPDPBUSD processes 4 bytes per lane.
+ * ZMM has 16 lanes of 32 bits = 16 groups of 4 bytes.
+ * With broadcastq A (8 bytes broadcast to all 8 qwords), each VPDPBUSD processes
+ * 4 k-values per lane, 16 lanes = 4 cols (lo) + 4 cols (hi) with proper layout. */
+
+ __m512i vacc0 = _mm512_setzero_si512();
+ __m512i vacc1 = _mm512_setzero_si512();
+ __m512i vacc2 = _mm512_setzero_si512();
+ __m512i vacc3 = _mm512_setzero_si512();
+
+ const int8_t* a0 = a;
+ const int8_t* a1 = (mr > 1) ? a0 + a_stride : a0;
+ const int8_t* a2 = (mr > 2) ? a1 + a_stride : a1;
+ const int8_t* a3 = (mr > 3) ? a2 + a_stride : a2;
+
+ const int64_t xor_mask = (int64_t)0x8080808080808080ULL;
+
+ for (int k = 0; k < K; k += 8) {
+ int64_t a0_val, a1_val, a2_val, a3_val;
+ memcpy(&a0_val, a0, 8); memcpy(&a1_val, a1, 8);
+ memcpy(&a2_val, a2, 8); memcpy(&a3_val, a3, 8);
+ a0_val ^= xor_mask; a1_val ^= xor_mask;
+ a2_val ^= xor_mask; a3_val ^= xor_mask;
+ /* Broadcast 8 A bytes to 64 bytes (ZMM) */
+ const __m512i va0 = _mm512_set1_epi64(a0_val);
+ const __m512i va1 = _mm512_set1_epi64(a1_val);
+ const __m512i va2 = _mm512_set1_epi64(a2_val);
+ const __m512i va3 = _mm512_set1_epi64(a3_val);
+ a0 += 8; a1 += 8; a2 += 8; a3 += 8;
+
+ /* Load all 64 bytes of B (8 cols × 8 k-values) in one ZMM */
+ const __m512i vb = _mm512_loadu_si512((const __m512i*)w);
+ w += 64;
+
+ /* VPDPBUSD: acc += sum_4(u8[i]*s8[i]) per 32-bit lane.
+ * No s16 saturation — full ±127 range! */
+ vacc0 = _mm512_dpbusd_epi32(vacc0, va0, vb);
+ vacc1 = _mm512_dpbusd_epi32(vacc1, va1, vb);
+ vacc2 = _mm512_dpbusd_epi32(vacc2, va2, vb);
+ vacc3 = _mm512_dpbusd_epi32(vacc3, va3, vb);
+ }
+
+ /* Reduce: each vacc has 16 × s32 lanes.
+ * With c8 layout [col0_k0..k7, col1_k0..k7, ...], each group of 2 s32 lanes
+ * = partial sums for one column (8 k-values / 4 per lane = 2 lanes per col).
+ * Need to add adjacent pairs to get one s32 per column. */
+ /* hadd pairs: lane[0]+lane[1]=col0, lane[2]+lane[3]=col1, ... */
+ /* Use _mm512_reduce or manual hadd */
+ {
+ /* Extract to 2 YMM halves, hadd, then extract 8 results */
+ __m256i lo0 = _mm512_castsi512_si256(vacc0);
+ __m256i hi0 = _mm512_extracti64x4_epi64(vacc0, 1);
+ __m256i lo1 = _mm512_castsi512_si256(vacc1);
+ __m256i hi1 = _mm512_extracti64x4_epi64(vacc1, 1);
+ __m256i lo2 = _mm512_castsi512_si256(vacc2);
+ __m256i hi2 = _mm512_extracti64x4_epi64(vacc2, 1);
+ __m256i lo3 = _mm512_castsi512_si256(vacc3);
+ __m256i hi3 = _mm512_extracti64x4_epi64(vacc3, 1);
+
+ /* hadd pairs within each 256-bit half, then combine */
+ __m256i vout0 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(lo0, hi0), 0xD8);
+ __m256i vout1 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(lo1, hi1), 0xD8);
+ __m256i vout2 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(lo2, hi2), 0xD8);
+ __m256i vout3 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(lo3, hi3), 0xD8);
+
+ _mm256_storeu_si256((__m256i*)(c), vout0);
+ if (mr > 1) _mm256_storeu_si256((__m256i*)(c + c_stride), vout1);
+ if (mr > 2) _mm256_storeu_si256((__m256i*)(c + 2 * c_stride), vout2);
+ if (mr > 3) _mm256_storeu_si256((__m256i*)(c + 3 * c_stride), vout3);
+ }
+ return;
+#endif
+
+ /* AVX2 fallback */ {
+ const __m256i vones = _mm256_set1_epi16(1);
+ __m256i vacc0_lo = _mm256_setzero_si256();
+ __m256i vacc0_hi = _mm256_setzero_si256();
+ __m256i vacc1_lo = _mm256_setzero_si256();
+ __m256i vacc1_hi = _mm256_setzero_si256();
+ __m256i vacc2_lo = _mm256_setzero_si256();
+ __m256i vacc2_hi = _mm256_setzero_si256();
+ __m256i vacc3_lo = _mm256_setzero_si256();
+ __m256i vacc3_hi = _mm256_setzero_si256();
+
+ const int8_t* a0 = a;
+ const int8_t* a1 = (mr > 1) ? a0 + a_stride : a0;
+ const int8_t* a2 = (mr > 2) ? a1 + a_stride : a1;
+ const int8_t* a3 = (mr > 3) ? a2 + a_stride : a2;
+
+ const int64_t xor_mask = (int64_t)0x8080808080808080ULL;
+
+ for (int k = 0; k < K; k += 8) {
+ int64_t a0_val, a1_val, a2_val, a3_val;
+ memcpy(&a0_val, a0, 8); memcpy(&a1_val, a1, 8);
+ memcpy(&a2_val, a2, 8); memcpy(&a3_val, a3, 8);
+ a0_val ^= xor_mask; a1_val ^= xor_mask;
+ a2_val ^= xor_mask; a3_val ^= xor_mask;
+ const __m256i va0 = _mm256_set1_epi64x(a0_val);
+ const __m256i va1 = _mm256_set1_epi64x(a1_val);
+ const __m256i va2 = _mm256_set1_epi64x(a2_val);
+ const __m256i va3 = _mm256_set1_epi64x(a3_val);
+ a0 += 8; a1 += 8; a2 += 8; a3 += 8;
+
+ const __m256i vb_lo = _mm256_loadu_si256((const __m256i*)(w));
+ const __m256i vb_hi = _mm256_loadu_si256((const __m256i*)(w + 32));
+ w += 64;
+
+ vacc0_lo = _mm256_add_epi32(vacc0_lo,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va0, vb_lo), vones));
+ vacc0_hi = _mm256_add_epi32(vacc0_hi,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va0, vb_hi), vones));
+ vacc1_lo = _mm256_add_epi32(vacc1_lo,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va1, vb_lo), vones));
+ vacc1_hi = _mm256_add_epi32(vacc1_hi,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va1, vb_hi), vones));
+ vacc2_lo = _mm256_add_epi32(vacc2_lo,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va2, vb_lo), vones));
+ vacc2_hi = _mm256_add_epi32(vacc2_hi,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va2, vb_hi), vones));
+ vacc3_lo = _mm256_add_epi32(vacc3_lo,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va3, vb_lo), vones));
+ vacc3_hi = _mm256_add_epi32(vacc3_hi,
+ _mm256_madd_epi16(_mm256_maddubs_epi16(va3, vb_hi), vones));
+ }
+
+ /* Reduce: hadd+permute to get [n0,n1,n2,n3,n4,n5,n6,n7] per row */
+ __m256i vout0 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(vacc0_lo, vacc0_hi), 0xD8);
+ __m256i vout1 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(vacc1_lo, vacc1_hi), 0xD8);
+ __m256i vout2 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(vacc2_lo, vacc2_hi), 0xD8);
+ __m256i vout3 = _mm256_permute4x64_epi64(
+ _mm256_hadd_epi32(vacc3_lo, vacc3_hi), 0xD8);
+
+ _mm256_storeu_si256((__m256i*)(c), vout0);
+ if (mr > 1) _mm256_storeu_si256((__m256i*)(c + c_stride), vout1);
+ if (mr > 2) _mm256_storeu_si256((__m256i*)(c + 2 * c_stride), vout2);
+ if (mr > 3) _mm256_storeu_si256((__m256i*)(c + 3 * c_stride), vout3);
+ } /* end AVX2 fallback scope */
+}
+
+/* ============ Full GEMM with blocking ============ */
+
+/* Thread-local workspace for A_u8 conversion to avoid malloc per call */
+static __thread uint8_t* tls_a_u8 = NULL;
+static __thread size_t tls_a_u8_size = 0;
+
+static uint8_t* get_a_u8_workspace(size_t needed) {
+ if (needed > tls_a_u8_size) {
+ free(tls_a_u8);
+ tls_a_u8 = (uint8_t*)malloc(needed);
+ tls_a_u8_size = needed;
+ }
+ return tls_a_u8;
+}
+
+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)
+{
+ int K_padded = (K + 7) & ~7;
+
+ /* With inline s8→u8 XOR in microkernel, no pre-conversion needed.
+ * Just pad A to K_padded if needed. */
+ const int8_t* A_eff = A;
+ int A_stride = K;
+ int8_t* A_pad = NULL;
+ if (K != K_padded) {
+ A_pad = (int8_t*)get_a_u8_workspace((size_t)M * K_padded);
+ for (int m = 0; m < M; m++) {
+ memcpy(A_pad + (size_t)m * K_padded, A + (size_t)m * K, K);
+ memset(A_pad + (size_t)m * K_padded + K, 0, K_padded - K);
+ }
+ A_eff = A_pad;
+ A_stride = K_padded;
+ }
+
+ #pragma omp parallel for schedule(dynamic)
+ for (int m = 0; m < M; m += 4) {
+ int mr = (m + 4 <= M) ? 4 : M - m;
+
+ const uint8_t* w_ptr = (const uint8_t*)B_packed;
+
+ for (int n = 0; n < N; n += 8) {
+ const int8_t* w_data = (const int8_t*)(w_ptr + 32);
+
+ int32_t acc[4 * 8] __attribute__((aligned(32)));
+ memset(acc, 0, sizeof(acc));
+
+ gemm_4x8c8_ukernel(
+ A_eff + (size_t)m * A_stride, A_stride,
+ w_data,
+ acc, 8,
+ K_padded, mr);
+
+ /* Apply compensation and store to C */
+ for (int i = 0; i < mr; i++) {
+ for (int j = 0; j < 8 && (n + j) < N; j++) {
+ C[(size_t)(m + i) * N + (n + j)] = acc[i * 8 + j] - col_sums[n + j];
+ }
+ }
+
+ /* Advance weight pointer to next NR group */
+ w_ptr += 32 + (size_t)K_padded * 8; /* bias + weights */
+ }
+ }
+ /* A_u8 is workspace-managed, not freed here */
+}
+
+/* ============ Fused GEMM + epilogue (dequant+bias+ReLU+requant → int8 output) ============ */
+
+void int8_gemm_4x8c8_fused(
+ const int8_t* A, int M, int K, int N,
+ const void* B_packed,
+ int8_t* out, /* output: [M, N] int8 (fused result) */
+ const int32_t* col_sums,
+ const float* w_scales, /* [N] weight scales */
+ const float* bias, /* [N] bias or NULL */
+ const float* act_scale, /* [N] output activation scale (per-tensor: all same) */
+ int do_relu)
+{
+ int K_padded = (K + 7) & ~7;
+
+ /* No pre-conversion: microkernel XORs s8→u8 inline */
+ const int8_t* A_eff = A;
+ int A_stride = K;
+ int8_t* A_pad = NULL;
+ if (K != K_padded) {
+ A_pad = (int8_t*)get_a_u8_workspace((size_t)M * K_padded);
+ for (int m = 0; m < M; m++) {
+ memcpy(A_pad + (size_t)m * K_padded, A + (size_t)m * K, K);
+ memset(A_pad + (size_t)m * K_padded + K, 0, K_padded - K);
+ }
+ A_eff = A_pad;
+ A_stride = K_padded;
+ }
+
+ /* Precompute per-channel: combined_scale = 1.0 * w_scale (folded: in_scale=1.0) */
+ float inv_out[512];
+ for (int c = 0; c < N; c++)
+ inv_out[c] = 1.0f / (act_scale[c] + 1e-9f);
+
+ #pragma omp parallel for schedule(dynamic)
+ for (int m = 0; m < M; m += 4) {
+ int mr = (m + 4 <= M) ? 4 : M - m;
+ const uint8_t* w_ptr = (const uint8_t*)B_packed;
+
+ for (int n = 0; n < N; n += 8) {
+ const int8_t* w_data = (const int8_t*)(w_ptr + 32);
+
+ int32_t acc[4 * 8] __attribute__((aligned(32)));
+ memset(acc, 0, sizeof(acc));
+
+ gemm_4x8c8_ukernel(
+ A_eff + (size_t)m * A_stride, A_stride,
+ w_data, acc, 8, K_padded, mr);
+
+ /* Fused: compensate + dequant + bias + relu + requant → int8 */
+ for (int i = 0; i < mr; i++) {
+ int8_t* orow = out + (size_t)(m + i) * N;
+ for (int j = 0; j < 8 && (n + j) < N; j++) {
+ int c = n + j;
+ float fp = (float)(acc[i * 8 + j] - col_sums[c]) * w_scales[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;
+ }
+ }
+
+ w_ptr += 32 + (size_t)K_padded * 8;
+ }
+ }
+}
diff --git a/src/threadpool.c b/src/threadpool.c
new file mode 100644
index 0000000..2916445
--- /dev/null
+++ b/src/threadpool.c
@@ -0,0 +1,216 @@
+/*
+ * threadpool.c — Minimal lock-free thread pool.
+ *
+ * Uses atomic counter for work distribution + WaitOnAddress for sleeping.
+ * Workers spin for ~1µs before sleeping to minimize latency for back-to-back tasks.
+ */
+
+#include "threadpool.h"
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <process.h>
+#else
+#include <pthread.h>
+#include <unistd.h>
+#include <linux/futex.h>
+#include <sys/syscall.h>
+#endif
+
+/* Atomic operations */
+#if defined(__GNUC__) || defined(__clang__)
+#define ATOMIC_LOAD(p) __atomic_load_n(p, __ATOMIC_ACQUIRE)
+#define ATOMIC_STORE(p, v) __atomic_store_n(p, v, __ATOMIC_RELEASE)
+#define ATOMIC_ADD(p, v) __atomic_fetch_add(p, v, __ATOMIC_ACQ_REL)
+#define ATOMIC_CAS(p, e, d) __atomic_compare_exchange_n(p, e, d, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)
+#else
+#include <stdatomic.h>
+#define ATOMIC_LOAD(p) atomic_load(p)
+#define ATOMIC_STORE(p, v) atomic_store(p, v)
+#define ATOMIC_ADD(p, v) atomic_fetch_add(p, v)
+#endif
+
+#define MAX_THREADS 16
+
+/* Shared task state */
+typedef struct {
+ tp_task_fn fn;
+ void* ctx;
+ volatile int next_idx; /* next work index to claim (atomic) */
+ int total; /* total work items */
+ int grain; /* items per chunk */
+ volatile int done_count; /* number of workers finished (atomic) */
+ int n_workers; /* number of workers participating */
+ volatile int phase; /* incremented to signal new work */
+} TaskState;
+
+static TaskState g_task;
+
+/* Worker threads */
+typedef struct {
+ int id;
+#ifdef _WIN32
+ HANDLE handle;
+#else
+ pthread_t handle;
+#endif
+ volatile int alive;
+} Worker;
+
+static Worker g_workers[MAX_THREADS];
+static int g_n_threads = 0;
+static volatile int g_shutdown = 0;
+
+/* Worker function: spin-wait for work, execute chunks, signal done */
+static
+#ifdef _WIN32
+unsigned __stdcall
+#else
+void*
+#endif
+worker_fn(void* arg) {
+ Worker* w = (Worker*)arg;
+ int last_phase = 0;
+
+ while (!ATOMIC_LOAD(&g_shutdown)) {
+ /* Wait for new work (spin briefly, then sleep) */
+ int phase = ATOMIC_LOAD(&g_task.phase);
+ if (phase == last_phase) {
+ /* Spin for ~1µs (check ~200 times) */
+ int spins = 200;
+ while (spins-- > 0) {
+ phase = ATOMIC_LOAD(&g_task.phase);
+ if (phase != last_phase) break;
+ #ifdef _WIN32
+ YieldProcessor();
+ #else
+ __asm__ __volatile__("pause");
+ #endif
+ }
+ if (phase == last_phase) {
+ /* Sleep until woken */
+ #ifdef _WIN32
+ WaitOnAddress((volatile void*)&g_task.phase, &last_phase, sizeof(int), INFINITE);
+ #else
+ syscall(SYS_futex, &g_task.phase, FUTEX_WAIT, last_phase, NULL, NULL, 0);
+ #endif
+ continue;
+ }
+ }
+ last_phase = phase;
+
+ /* Execute work chunks */
+ while (1) {
+ int idx = ATOMIC_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 */
+ ATOMIC_ADD(&g_task.done_count, 1);
+ }
+
+ #ifdef _WIN32
+ return 0;
+ #else
+ return NULL;
+ #endif
+}
+
+void tp_init(int n_threads) {
+ if (n_threads <= 0) {
+ #ifdef _WIN32
+ SYSTEM_INFO si; GetSystemInfo(&si);
+ n_threads = si.dwNumberOfProcessors;
+ #else
+ n_threads = sysconf(_SC_NPROCESSORS_ONLN);
+ #endif
+ if (n_threads > MAX_THREADS) n_threads = MAX_THREADS;
+ if (n_threads < 1) n_threads = 1;
+ }
+ /* Use n_threads-1 workers (main thread also participates) */
+ g_n_threads = n_threads;
+ int n_workers = n_threads - 1;
+ if (n_workers > MAX_THREADS) n_workers = MAX_THREADS;
+
+ memset(&g_task, 0, sizeof(g_task));
+ ATOMIC_STORE(&g_shutdown, 0);
+
+ for (int i = 0; i < n_workers; i++) {
+ g_workers[i].id = i;
+ g_workers[i].alive = 1;
+ #ifdef _WIN32
+ g_workers[i].handle = (HANDLE)_beginthreadex(NULL, 0, worker_fn, &g_workers[i], 0, NULL);
+ #else
+ pthread_create(&g_workers[i].handle, NULL, worker_fn, &g_workers[i]);
+ #endif
+ }
+}
+
+void tp_parallel_for(tp_task_fn fn, void* ctx, int total, int grain) {
+ if (total <= 0) return;
+ if (grain <= 0) grain = 1;
+
+ int n_workers = g_n_threads - 1;
+ if (n_workers <= 0 || total <= grain) {
+ /* Single-threaded fast path */
+ fn(ctx, 0, total);
+ return;
+ }
+
+ /* Set up 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);
+ g_task.n_workers = n_workers;
+
+ /* Wake workers */
+ ATOMIC_ADD(&g_task.phase, 1);
+ #ifdef _WIN32
+ WakeByAddressAll((void*)&g_task.phase);
+ #else
+ syscall(SYS_futex, &g_task.phase, FUTEX_WAKE, n_workers, NULL, NULL, 0);
+ #endif
+
+ /* Main thread participates too */
+ while (1) {
+ int idx = ATOMIC_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 to finish */
+ while (ATOMIC_LOAD(&g_task.done_count) < n_workers) {
+ #ifdef _WIN32
+ YieldProcessor();
+ #else
+ __asm__ __volatile__("pause");
+ #endif
+ }
+}
+
+void tp_destroy(void) {
+ ATOMIC_STORE(&g_shutdown, 1);
+ ATOMIC_ADD(&g_task.phase, 1);
+ #ifdef _WIN32
+ WakeByAddressAll((void*)&g_task.phase);
+ for (int i = 0; i < g_n_threads - 1; i++)
+ WaitForSingleObject(g_workers[i].handle, INFINITE);
+ #else
+ syscall(SYS_futex, &g_task.phase, FUTEX_WAKE, MAX_THREADS, NULL, NULL, 0);
+ for (int i = 0; i < g_n_threads - 1; i++)
+ pthread_join(g_workers[i].handle, NULL);
+ #endif
+}
+
+int tp_num_threads(void) { return g_n_threads; }
diff --git a/src/threadpool.h b/src/threadpool.h
new file mode 100644
index 0000000..957c9f9
--- /dev/null
+++ b/src/threadpool.h
@@ -0,0 +1,34 @@
+/*
+ * threadpool.h — Minimal lock-free thread pool for GEMM parallelization.
+ *
+ * Design: persistent worker threads + atomic task queue.
+ * Workers spin briefly then sleep via WaitOnAddress (Windows) or futex (Linux).
+ * Target dispatch latency: <500ns (vs OpenMP ~20µs).
+ *
+ * API:
+ * tp_init(int n_threads) — create pool (call once at startup)
+ * tp_parallel_for(fn, ctx, N) — parallel for i=0..N-1
+ * tp_destroy() — shutdown
+ */
+#ifndef THREADPOOL_H
+#define THREADPOOL_H
+
+#include <stdint.h>
+
+/* Task function: called with (context, start, end) for range [start, end) */
+typedef void (*tp_task_fn)(void* ctx, int start, int end);
+
+/* Initialize thread pool with n_threads workers (0 = auto-detect) */
+void tp_init(int n_threads);
+
+/* Execute fn(ctx, i, i+chunk) for i=0..total-1, split across workers.
+ * Blocks until all work is done. Granularity = chunk size per worker. */
+void tp_parallel_for(tp_task_fn fn, void* ctx, int total, int grain);
+
+/* Shutdown thread pool */
+void tp_destroy(void);
+
+/* Get number of threads */
+int tp_num_threads(void);
+
+#endif /* THREADPOOL_H */
diff --git a/src/transformer_ops.c b/src/transformer_ops.c
new file mode 100644
index 0000000..8033abc
--- /dev/null
+++ b/src/transformer_ops.c
@@ -0,0 +1,1052 @@
+/*
+ * transformer_ops.c — FP32 ops for EdgeFace-XS Transformer blocks.
+ *
+ * LayerNorm, GELU, Softmax, L2Normalize, MatMul (FP32).
+ * These run in FP32 (not INT8) since Transformer attention
+ * involves dynamic×dynamic MatMul which doesn't benefit from INT8.
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#ifdef __AVX2__
+#include <immintrin.h>
+#endif
+
+/* ============ LayerNorm ============ */
+/* out[i] = gamma[i] * (x[i] - mean) / sqrt(var + eps) + beta[i] */
+void layer_norm_fp32(const float* x, int N, int C,
+ const float* gamma, const float* beta,
+ float eps, float* out) {
+ for (int n = 0; n < N; n++) {
+ const float* row = x + (size_t)n * C;
+ float* orow = out + (size_t)n * C;
+ int c = 0;
+
+#ifdef __AVX512F__
+ /* AVX-512 vectorized mean */
+ __m512 vsum512 = _mm512_setzero_ps();
+ for (c = 0; c + 16 <= C; c += 16)
+ vsum512 = _mm512_add_ps(vsum512, _mm512_loadu_ps(row + c));
+ float sum = _mm512_reduce_add_ps(vsum512);
+ for (; c < C; c++) sum += row[c];
+ float mean = sum / C;
+
+ /* AVX-512 vectorized variance */
+ __m512 vmean512 = _mm512_set1_ps(mean);
+ __m512 vvar512 = _mm512_setzero_ps();
+ for (c = 0; c + 16 <= C; c += 16) {
+ __m512 d = _mm512_sub_ps(_mm512_loadu_ps(row + c), vmean512);
+ vvar512 = _mm512_fmadd_ps(d, d, vvar512);
+ }
+ float var_sum = _mm512_reduce_add_ps(vvar512);
+ for (; c < C; c++) { float d = row[c] - mean; var_sum += d * d; }
+ float inv_std = 1.0f / sqrtf(var_sum / C + eps);
+
+ /* AVX-512 vectorized normalize + affine */
+ __m512 vis512 = _mm512_set1_ps(inv_std);
+ for (c = 0; c + 16 <= C; c += 16) {
+ __m512 v = _mm512_mul_ps(_mm512_sub_ps(_mm512_loadu_ps(row + c), vmean512), vis512);
+ if (gamma) v = _mm512_mul_ps(v, _mm512_loadu_ps(gamma + c));
+ if (beta) v = _mm512_add_ps(v, _mm512_loadu_ps(beta + c));
+ _mm512_storeu_ps(orow + c, v);
+ }
+ for (; c < C; c++) {
+ float v = (row[c] - mean) * inv_std;
+ if (gamma) v *= gamma[c];
+ if (beta) v += beta[c];
+ orow[c] = v;
+ }
+#elif defined(__AVX2__)
+ c = 0;
+ /* Vectorized mean */
+ __m256 vsum = _mm256_setzero_ps();
+ for (c = 0; c + 8 <= C; c += 8)
+ vsum = _mm256_add_ps(vsum, _mm256_loadu_ps(row + c));
+ /* Horizontal sum */
+ __m128 lo = _mm256_castps256_ps128(vsum);
+ __m128 hi = _mm256_extractf128_ps(vsum, 1);
+ lo = _mm_add_ps(lo, hi);
+ lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_add_ss(lo, _mm_movehdup_ps(lo));
+ float sum = _mm_cvtss_f32(lo);
+ for (; c < C; c++) sum += row[c];
+ float mean = sum / C;
+
+ /* Vectorized variance */
+ __m256 vmean = _mm256_set1_ps(mean);
+ __m256 vvar = _mm256_setzero_ps();
+ for (c = 0; c + 8 <= C; c += 8) {
+ __m256 d = _mm256_sub_ps(_mm256_loadu_ps(row + c), vmean);
+ vvar = _mm256_fmadd_ps(d, d, vvar);
+ }
+ lo = _mm256_castps256_ps128(vvar);
+ hi = _mm256_extractf128_ps(vvar, 1);
+ lo = _mm_add_ps(lo, hi);
+ lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_add_ss(lo, _mm_movehdup_ps(lo));
+ float var_sum = _mm_cvtss_f32(lo);
+ for (; c < C; c++) { float d = row[c] - mean; var_sum += d * d; }
+ float inv_std = 1.0f / sqrtf(var_sum / C + eps);
+
+ /* Vectorized normalize + affine */
+ __m256 vis = _mm256_set1_ps(inv_std);
+ for (c = 0; c + 8 <= C; c += 8) {
+ __m256 v = _mm256_mul_ps(_mm256_sub_ps(_mm256_loadu_ps(row + c), vmean), vis);
+ if (gamma) v = _mm256_mul_ps(v, _mm256_loadu_ps(gamma + c));
+ if (beta) v = _mm256_add_ps(v, _mm256_loadu_ps(beta + c));
+ _mm256_storeu_ps(orow + c, v);
+ }
+ for (; c < C; c++) {
+ float v = (row[c] - mean) * inv_std;
+ if (gamma) v *= gamma[c];
+ if (beta) v += beta[c];
+ orow[c] = v;
+ }
+#else
+ float sum = 0;
+ for (c = 0; c < C; c++) sum += row[c];
+ float mean = sum / C;
+ float var_sum = 0;
+ for (c = 0; c < C; c++) { float d = row[c] - mean; var_sum += d * d; }
+ float inv_std = 1.0f / sqrtf(var_sum / C + eps);
+ for (c = 0; c < C; c++) {
+ orow[c] = (row[c] - mean) * inv_std;
+ if (gamma) orow[c] *= gamma[c];
+ if (beta) orow[c] += beta[c];
+ }
+#endif
+ }
+}
+
+/* ============ GELU (fast approximation) ============ */
+/* gelu(x) ≈ 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))
+ * Using fast tanh: tanh(x) ≈ x*(27+x^2)/(27+9*x^2) for |x|<3, clamp otherwise */
+static inline float fast_tanh(float x) {
+ if (x > 4.0f) return 1.0f;
+ if (x < -4.0f) return -1.0f;
+ float x2 = x * x;
+ return x * (27.0f + x2) / (27.0f + 9.0f * x2);
+}
+
+/* AVX2 vectorized exp(x) for x in [-88, 0] (negative range for erf computation).
+ * Uses range reduction: exp(x) = 2^n * exp(r) where n=round(x/ln2), r=x-n*ln2.
+ * Polynomial approximation for exp(r) on [-ln2/2, ln2/2]. Max error ~1e-7. */
+#ifdef __AVX2__
+__m256 _mm256_exp_ps(__m256 x) {
+ const __m256 v_ln2 = _mm256_set1_ps(0.6931471805599453f);
+ const __m256 v_inv_ln2 = _mm256_set1_ps(1.4426950408889634f);
+ const __m256 v_half = _mm256_set1_ps(0.5f);
+ /* Polynomial coefficients for exp(r) on [-ln2/2, ln2/2] */
+ const __m256 c0 = _mm256_set1_ps(1.0f);
+ const __m256 c1 = _mm256_set1_ps(1.0f);
+ const __m256 c2 = _mm256_set1_ps(0.5f);
+ const __m256 c3 = _mm256_set1_ps(0.16666666f);
+ const __m256 c4 = _mm256_set1_ps(0.041666666f);
+ const __m256 c5 = _mm256_set1_ps(0.008333333f);
+
+ /* n = round(x / ln2) */
+ __m256 t = _mm256_fmadd_ps(x, v_inv_ln2, v_half);
+ __m256 n = _mm256_floor_ps(t);
+ /* r = x - n * ln2 */
+ __m256 r = _mm256_fnmadd_ps(n, v_ln2, x);
+ /* exp(r) ≈ 1 + r + r²/2 + r³/6 + r⁴/24 + r⁵/120 (Horner) */
+ __m256 p = _mm256_fmadd_ps(c5, r, c4);
+ p = _mm256_fmadd_ps(p, r, c3);
+ p = _mm256_fmadd_ps(p, r, c2);
+ p = _mm256_fmadd_ps(p, r, c1);
+ p = _mm256_fmadd_ps(p, r, c0);
+ /* Scale by 2^n: add n to the exponent bits */
+ __m256i ni = _mm256_cvtps_epi32(n);
+ ni = _mm256_slli_epi32(ni, 23); /* shift to exponent position */
+ __m256i pi = _mm256_castps_si256(p);
+ p = _mm256_castsi256_ps(_mm256_add_epi32(pi, ni));
+ /* Clamp: for very negative x, return 0 */
+ p = _mm256_max_ps(p, _mm256_setzero_ps());
+ return p;
+}
+#endif
+
+void gelu_fp32(float* x, int n) {
+ /* Fast tanh-based GELU with AVX-512 when available */
+ int i = 0;
+#ifdef __AVX512F__
+ const __m512 v_c1 = _mm512_set1_ps(0.7978845608f);
+ const __m512 v_c2 = _mm512_set1_ps(0.044715f);
+ const __m512 v_half = _mm512_set1_ps(0.5f);
+ const __m512 v_one = _mm512_set1_ps(1.0f);
+ const __m512 v_neg_one = _mm512_set1_ps(-1.0f);
+ const __m512 v_27 = _mm512_set1_ps(27.0f);
+ const __m512 v_9 = _mm512_set1_ps(9.0f);
+ for (; i + 16 <= n; i += 16) {
+ __m512 vx = _mm512_loadu_ps(x + i);
+ __m512 vx3 = _mm512_mul_ps(_mm512_mul_ps(vx, vx), vx);
+ __m512 inner = _mm512_mul_ps(v_c1, _mm512_fmadd_ps(v_c2, vx3, vx));
+ __m512 inner2 = _mm512_mul_ps(inner, inner);
+ __m512 num = _mm512_mul_ps(inner, _mm512_add_ps(v_27, inner2));
+ __m512 den = _mm512_fmadd_ps(v_9, inner2, v_27);
+ __m512 t = _mm512_div_ps(num, den);
+ t = _mm512_min_ps(t, v_one);
+ t = _mm512_max_ps(t, v_neg_one);
+ _mm512_storeu_ps(x + i, _mm512_mul_ps(_mm512_mul_ps(v_half, vx), _mm512_add_ps(v_one, t)));
+ }
+#elif defined(__AVX2__)
+ const __m256 v_c1 = _mm256_set1_ps(0.7978845608f);
+ const __m256 v_c2 = _mm256_set1_ps(0.044715f);
+ const __m256 v_half = _mm256_set1_ps(0.5f);
+ const __m256 v_one = _mm256_set1_ps(1.0f);
+ const __m256 v_neg_one = _mm256_set1_ps(-1.0f);
+ const __m256 v_27 = _mm256_set1_ps(27.0f);
+ const __m256 v_9 = _mm256_set1_ps(9.0f);
+
+ for (; i + 8 <= n; i += 8) {
+ __m256 vx = _mm256_loadu_ps(x + i);
+ /* inner = sqrt(2/pi) * (x + 0.044715 * x^3) */
+ __m256 vx3 = _mm256_mul_ps(_mm256_mul_ps(vx, vx), vx);
+ __m256 inner = _mm256_mul_ps(v_c1, _mm256_fmadd_ps(v_c2, vx3, vx));
+ /* tanh(inner) ≈ inner*(27+inner²)/(27+9*inner²) */
+ __m256 inner2 = _mm256_mul_ps(inner, inner);
+ __m256 num = _mm256_mul_ps(inner, _mm256_add_ps(v_27, inner2));
+ __m256 den = _mm256_fmadd_ps(v_9, inner2, v_27);
+ __m256 t = _mm256_div_ps(num, den);
+ t = _mm256_min_ps(t, v_one);
+ t = _mm256_max_ps(t, v_neg_one);
+
+ /* gelu = 0.5 * x * (1 + tanh) */
+ __m256 result = _mm256_mul_ps(_mm256_mul_ps(v_half, vx), _mm256_add_ps(v_one, t));
+ _mm256_storeu_ps(x + i, result);
+ }
+#endif
+ for (; i < n; i++) {
+ float v = x[i];
+ float inner = 0.7978845608f * (v + 0.044715f * v * v * v);
+ float t2 = inner * (27.0f + inner*inner) / (27.0f + 9.0f * inner*inner);
+ if (t2 > 1.0f) t2 = 1.0f; if (t2 < -1.0f) t2 = -1.0f;
+ x[i] = 0.5f * v * (1.0f + t2);
+ }
+}
+
+/* ============ Softmax ============ */
+/* softmax along last dim: out[i] = exp(x[i] - max) / sum(exp(x - max)) */
+void softmax_fp32(float* x, int N, int C) {
+ for (int n = 0; n < N; n++) {
+ float* row = x + (size_t)n * C;
+ float mx = row[0];
+ for (int c = 1; c < C; c++) if (row[c] > mx) mx = row[c];
+ float sum = 0;
+ for (int c = 0; c < C; c++) {
+ row[c] = expf(row[c] - mx);
+ sum += row[c];
+ }
+ float inv = 1.0f / sum;
+ for (int c = 0; c < C; c++) row[c] *= inv;
+ }
+}
+
+/* ============ Dynamic INT8 MatMul ============ */
+/* C[M,N] = A_fp32[M,K] @ W_int8_packed[K,N], with dynamic A quantization.
+ * W is pre-packed in c8 format. A is quantized per-tensor at runtime. */
+void matmul_dynamic_int8(const float* A_fp32, int M, int K, int N,
+ const void* W_packed, const int32_t* col_sums,
+ const float* w_scales, float* C_fp32)
+{
+ /* 1. Find max|A| for per-tensor quantization */
+ float a_max = 0;
+ int n_elem = M * K;
+#ifdef __AVX2__
+ {
+ __m256 vmax = _mm256_setzero_ps();
+ __m256 vmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7FFFFFFF)); /* abs mask */
+ int i = 0;
+ for (; i + 8 <= n_elem; i += 8) {
+ __m256 v = _mm256_and_ps(_mm256_loadu_ps(A_fp32 + i), vmask);
+ vmax = _mm256_max_ps(vmax, v);
+ }
+ /* Horizontal max */
+ __m128 lo = _mm256_castps256_ps128(vmax);
+ __m128 hi = _mm256_extractf128_ps(vmax, 1);
+ lo = _mm_max_ps(lo, hi);
+ lo = _mm_max_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_max_ss(lo, _mm_movehdup_ps(lo));
+ a_max = _mm_cvtss_f32(lo);
+ for (; i < n_elem; i++) {
+ float v = A_fp32[i] < 0 ? -A_fp32[i] : A_fp32[i];
+ if (v > a_max) a_max = v;
+ }
+ }
+#else
+ for (int i = 0; i < n_elem; i++) {
+ float v = A_fp32[i] < 0 ? -A_fp32[i] : A_fp32[i];
+ if (v > a_max) a_max = v;
+ }
+#endif
+ float a_scale = a_max / 127.0f;
+ if (a_scale < 1e-8f) a_scale = 1e-8f;
+ float a_inv = 1.0f / a_scale;
+
+ /* 2. Quantize A to int8 — use static workspace to avoid malloc */
+ int K_padded = (K + 7) & ~7;
+ static int8_t* s_A_int8 = NULL;
+ static int32_t* s_C_int32 = NULL;
+ static size_t s_A_cap = 0, s_C_cap = 0;
+ size_t a_need = (size_t)M * K_padded;
+ size_t c_need = (size_t)M * N;
+ if (a_need > s_A_cap) { free(s_A_int8); s_A_int8 = (int8_t*)malloc(a_need); s_A_cap = a_need; }
+ if (c_need > s_C_cap) { free(s_C_int32); s_C_int32 = (int32_t*)malloc(c_need * 4); s_C_cap = c_need; }
+
+ int8_t* A_int8 = s_A_int8;
+ int i_a = 0;
+#ifdef __AVX2__
+ __m256 v_inv = _mm256_set1_ps(a_inv);
+ for (int m = 0; m < M; m++) {
+ const float* arow = A_fp32 + (size_t)m * K;
+ int8_t* orow = A_int8 + (size_t)m * K_padded;
+ int k = 0;
+ for (; k + 8 <= K; k += 8) {
+ __m256 vf = _mm256_loadu_ps(arow + k);
+ __m256i vi = _mm256_cvtps_epi32(_mm256_mul_ps(vf, v_inv));
+ 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*)(orow + k) = _mm_extract_epi64(i8, 0);
+ }
+ for (; k < K; k++) {
+ int q = (int)(arow[k] * a_inv + (arow[k] >= 0 ? 0.5f : -0.5f));
+ if (q > 127) q = 127; if (q < -128) q = -128;
+ orow[k] = (int8_t)q;
+ }
+ for (int k2 = K; k2 < K_padded; k2++) orow[k2] = 0;
+ }
+#else
+ for (int m = 0; m < M; m++) {
+ for (int k = 0; k < K; k++) {
+ int q = (int)(A_fp32[m*K+k] * a_inv + (A_fp32[m*K+k] >= 0 ? 0.5f : -0.5f));
+ if (q > 127) q = 127; if (q < -128) q = -128;
+ A_int8[m*K_padded+k] = (int8_t)q;
+ }
+ for (int k = K; k < K_padded; k++) A_int8[m*K_padded+k] = 0;
+ }
+#endif
+
+ /* 3. INT8 GEMM */
+ extern void int8_gemm_4x8c8(const int8_t*, int, int, int,
+ const void*, int32_t*, const int32_t*);
+ int32_t* C_int32 = s_C_int32;
+ int8_gemm_4x8c8(A_int8, M, K_padded, N, W_packed, C_int32, col_sums);
+
+ /* 4. Dequant: fp32 = int32 * a_scale * w_scale[n] */
+#ifdef __AVX2__
+ __m256 v_ascale = _mm256_set1_ps(a_scale);
+ for (int m = 0; m < M; m++) {
+ int n = 0;
+ for (; n + 8 <= N; n += 8) {
+ __m256i vi32 = _mm256_loadu_si256((__m256i*)(C_int32 + m*N + n));
+ __m256 vf = _mm256_cvtepi32_ps(vi32);
+ __m256 vws = _mm256_loadu_ps(w_scales + n);
+ vf = _mm256_mul_ps(_mm256_mul_ps(vf, v_ascale), vws);
+ _mm256_storeu_ps(C_fp32 + m*N + n, vf);
+ }
+ for (; n < N; n++)
+ C_fp32[m*N+n] = (float)C_int32[m*N+n] * a_scale * w_scales[n];
+ }
+#else
+ for (int m = 0; m < M; m++)
+ for (int n = 0; n < N; n++)
+ C_fp32[m*N+n] = (float)C_int32[m*N+n] * a_scale * w_scales[n];
+#endif
+}
+
+/* matmul_dynamic_int8_gelu not needed — GELU already vectorized and fast */
+
+/* ============ MatMul FP32 (AVX2 register-tiled, auto-INT8 for large K) ============ */
+/* C[M,N] = A[M,K] @ B[K,N]
+ * Microkernel: MR=4 rows × NR=16 columns (4×2 YMM accumulators = 8 regs)
+ * For K >= 32 and N >= 8: automatically uses dynamic INT8 quantization
+ * for 2-3x throughput improvement via vpmaddubsw. */
+void matmul_fp32(const float* A, const float* B, float* C,
+ int M, int K, int N) {
+#ifdef __AVX2__
+ int m = 0;
+ /* Main loop: MR=4 rows at a time */
+ for (; m + 4 <= M; m += 4) {
+ int n = 0;
+ for (; n + 16 <= N; n += 16) {
+ __m256 c00 = _mm256_setzero_ps(), c01 = _mm256_setzero_ps();
+ __m256 c10 = _mm256_setzero_ps(), c11 = _mm256_setzero_ps();
+ __m256 c20 = _mm256_setzero_ps(), c21 = _mm256_setzero_ps();
+ __m256 c30 = _mm256_setzero_ps(), c31 = _mm256_setzero_ps();
+ for (int k = 0; k < K; k++) {
+ __m256 b0 = _mm256_loadu_ps(B + (size_t)k * N + n);
+ __m256 b1 = _mm256_loadu_ps(B + (size_t)k * N + n + 8);
+ __m256 a0 = _mm256_broadcast_ss(&A[(m+0)*K+k]);
+ __m256 a1 = _mm256_broadcast_ss(&A[(m+1)*K+k]);
+ __m256 a2 = _mm256_broadcast_ss(&A[(m+2)*K+k]);
+ __m256 a3 = _mm256_broadcast_ss(&A[(m+3)*K+k]);
+ c00 = _mm256_fmadd_ps(a0, b0, c00); c01 = _mm256_fmadd_ps(a0, b1, c01);
+ c10 = _mm256_fmadd_ps(a1, b0, c10); c11 = _mm256_fmadd_ps(a1, b1, c11);
+ c20 = _mm256_fmadd_ps(a2, b0, c20); c21 = _mm256_fmadd_ps(a2, b1, c21);
+ c30 = _mm256_fmadd_ps(a3, b0, c30); c31 = _mm256_fmadd_ps(a3, b1, c31);
+ }
+ _mm256_storeu_ps(C+(m+0)*N+n, c00); _mm256_storeu_ps(C+(m+0)*N+n+8, c01);
+ _mm256_storeu_ps(C+(m+1)*N+n, c10); _mm256_storeu_ps(C+(m+1)*N+n+8, c11);
+ _mm256_storeu_ps(C+(m+2)*N+n, c20); _mm256_storeu_ps(C+(m+2)*N+n+8, c21);
+ _mm256_storeu_ps(C+(m+3)*N+n, c30); _mm256_storeu_ps(C+(m+3)*N+n+8, c31);
+ }
+ for (; n + 8 <= N; n += 8) {
+ __m256 c0=_mm256_setzero_ps(), c1=_mm256_setzero_ps();
+ __m256 c2=_mm256_setzero_ps(), c3=_mm256_setzero_ps();
+ for (int k = 0; k < K; k++) {
+ __m256 b0 = _mm256_loadu_ps(B + (size_t)k * N + n);
+ c0 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+0)*K+k]), b0, c0);
+ c1 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+1)*K+k]), b0, c1);
+ c2 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+2)*K+k]), b0, c2);
+ c3 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+3)*K+k]), b0, c3);
+ }
+ _mm256_storeu_ps(C+(m+0)*N+n, c0); _mm256_storeu_ps(C+(m+1)*N+n, c1);
+ _mm256_storeu_ps(C+(m+2)*N+n, c2); _mm256_storeu_ps(C+(m+3)*N+n, c3);
+ }
+ for (; n < N; n++) {
+ float s0=0, s1=0, s2=0, s3=0;
+ for (int k = 0; k < K; k++) {
+ float bv = B[(size_t)k*N+n];
+ s0 += A[(m+0)*K+k] * bv; s1 += A[(m+1)*K+k] * bv;
+ s2 += A[(m+2)*K+k] * bv; s3 += A[(m+3)*K+k] * bv;
+ }
+ C[(m+0)*N+n]=s0; C[(m+1)*N+n]=s1; C[(m+2)*N+n]=s2; C[(m+3)*N+n]=s3;
+ }
+ }
+ /* M remainder: 1 row at a time with register accumulators (no memset needed) */
+ for (; m < M; m++) {
+ const float* a_row = A + (size_t)m * K;
+ float* c_row = C + (size_t)m * N;
+ int n = 0;
+ for (; n + 8 <= N; n += 8) {
+ __m256 vc = _mm256_setzero_ps();
+ for (int k = 0; k < K; k++)
+ vc = _mm256_fmadd_ps(_mm256_broadcast_ss(&a_row[k]),
+ _mm256_loadu_ps(B + (size_t)k * N + n), vc);
+ _mm256_storeu_ps(c_row + n, vc);
+ }
+ for (; n < N; n++) {
+ float sum = 0;
+ for (int k = 0; k < K; k++) sum += a_row[k] * B[(size_t)k*N+n];
+ c_row[n] = sum;
+ }
+ }
+#else
+ memset(C, 0, (size_t)M * N * sizeof(float));
+ for (int m = 0; m < M; m++)
+ for (int k = 0; k < K; k++) {
+ float a = A[(size_t)m * K + k];
+ for (int n = 0; n < N; n++)
+ C[(size_t)m * N + n] += a * B[(size_t)k * N + n];
+ }
+#endif
+}
+
+/* ============ FP32 B-packing: [K,N] → [ceil(N/8), K, 8] panel format ============ */
+/* Pack weight matrix B[K,N] into column-panel format for cache-friendly GEMM.
+ * Each panel of 8 columns is stored contiguously along K dimension.
+ * This gives sequential 32-byte (1 cache line) loads in the inner K loop. */
+void pack_b_fp32(const float* B, int K, int N, float* packed) {
+#ifdef __AVX512F__
+ int NR = 16;
+#else
+ int NR = 8;
+#endif
+ int n_panels = (N + NR - 1) / NR;
+ for (int p = 0; p < n_panels; p++) {
+ int n_start = p * NR;
+ int nr = (n_start + NR <= N) ? NR : (N - n_start);
+ float* dst = packed + (size_t)p * K * NR;
+ for (int k = 0; k < K; k++) {
+ const float* src = B + (size_t)k * N + n_start;
+ int j = 0;
+ for (; j < nr; j++) dst[k * NR + j] = src[j];
+ for (; j < NR; j++) dst[k * NR + j] = 0; /* zero-pad last panel */
+ }
+ }
+}
+
+int packed_b_fp32_size(int K, int N) {
+#ifdef __AVX512F__
+ return ((N + 15) / 16) * K * 16;
+#else
+ return ((N + 7) / 8) * K * 8;
+#endif
+}
+
+/* ============ Threaded tile worker for packed GEMM ============ */
+#include "threadpool.h"
+typedef struct { const float* A; const float* B; float* C; int K,N,n_panels; } PGemmCtx;
+#ifdef __AVX2__
+static void _pgemm_worker(void* ctx_, int start, int end) {
+ PGemmCtx* g = (PGemmCtx*)ctx_;
+ int K_=g->K, N_=g->N, NR_=8;
+ for (int mb = start; mb < end; mb += 4) {
+ if (mb + 4 > end) break;
+ int p = 0;
+ for (; p + 2 <= g->n_panels; p += 2) {
+ int n = p * NR_;
+ const float* bp0 = g->B + (size_t)p * K_ * NR_;
+ const float* bp1 = bp0 + (size_t)K_ * NR_;
+ __m256 c00=_mm256_setzero_ps(),c01=_mm256_setzero_ps();
+ __m256 c10=_mm256_setzero_ps(),c11=_mm256_setzero_ps();
+ __m256 c20=_mm256_setzero_ps(),c21=_mm256_setzero_ps();
+ __m256 c30=_mm256_setzero_ps(),c31=_mm256_setzero_ps();
+ for (int k=0;k<K_;k++){
+ __m256 b0=_mm256_load_ps(bp0+k*NR_),b1=_mm256_load_ps(bp1+k*NR_);
+ __m256 a0=_mm256_broadcast_ss(&g->A[(mb+0)*K_+k]);
+ __m256 a1=_mm256_broadcast_ss(&g->A[(mb+1)*K_+k]);
+ __m256 a2=_mm256_broadcast_ss(&g->A[(mb+2)*K_+k]);
+ __m256 a3=_mm256_broadcast_ss(&g->A[(mb+3)*K_+k]);
+ c00=_mm256_fmadd_ps(a0,b0,c00);c01=_mm256_fmadd_ps(a0,b1,c01);
+ c10=_mm256_fmadd_ps(a1,b0,c10);c11=_mm256_fmadd_ps(a1,b1,c11);
+ c20=_mm256_fmadd_ps(a2,b0,c20);c21=_mm256_fmadd_ps(a2,b1,c21);
+ c30=_mm256_fmadd_ps(a3,b0,c30);c31=_mm256_fmadd_ps(a3,b1,c31);
+ }
+ if(n+16<=N_){
+ _mm256_storeu_ps(g->C+(mb+0)*N_+n,c00);_mm256_storeu_ps(g->C+(mb+0)*N_+n+8,c01);
+ _mm256_storeu_ps(g->C+(mb+1)*N_+n,c10);_mm256_storeu_ps(g->C+(mb+1)*N_+n+8,c11);
+ _mm256_storeu_ps(g->C+(mb+2)*N_+n,c20);_mm256_storeu_ps(g->C+(mb+2)*N_+n+8,c21);
+ _mm256_storeu_ps(g->C+(mb+3)*N_+n,c30);_mm256_storeu_ps(g->C+(mb+3)*N_+n+8,c31);
+ } else {
+ _mm256_storeu_ps(g->C+(mb+0)*N_+n,c00);_mm256_storeu_ps(g->C+(mb+1)*N_+n,c10);
+ _mm256_storeu_ps(g->C+(mb+2)*N_+n,c20);_mm256_storeu_ps(g->C+(mb+3)*N_+n,c30);
+ int nr=N_-n-8;if(nr>0){float t[4][8];
+ _mm256_storeu_ps(t[0],c01);_mm256_storeu_ps(t[1],c11);
+ _mm256_storeu_ps(t[2],c21);_mm256_storeu_ps(t[3],c31);
+ for(int i=0;i<4;i++)for(int j=0;j<nr;j++)g->C[(mb+i)*N_+n+8+j]=t[i][j];}
+ }
+ }
+ for(;p<g->n_panels;p++){
+ int n=p*NR_;
+ const float* bp=g->B+(size_t)p*K_*NR_;
+ __m256 c0=_mm256_setzero_ps(),c1=_mm256_setzero_ps();
+ __m256 c2=_mm256_setzero_ps(),c3=_mm256_setzero_ps();
+ for(int k=0;k<K_;k++){
+ __m256 b=_mm256_load_ps(bp+k*NR_);
+ c0=_mm256_fmadd_ps(_mm256_broadcast_ss(&g->A[(mb+0)*K_+k]),b,c0);
+ c1=_mm256_fmadd_ps(_mm256_broadcast_ss(&g->A[(mb+1)*K_+k]),b,c1);
+ c2=_mm256_fmadd_ps(_mm256_broadcast_ss(&g->A[(mb+2)*K_+k]),b,c2);
+ c3=_mm256_fmadd_ps(_mm256_broadcast_ss(&g->A[(mb+3)*K_+k]),b,c3);
+ }
+ if(n+NR_<=N_){
+ _mm256_storeu_ps(g->C+(mb+0)*N_+n,c0);_mm256_storeu_ps(g->C+(mb+1)*N_+n,c1);
+ _mm256_storeu_ps(g->C+(mb+2)*N_+n,c2);_mm256_storeu_ps(g->C+(mb+3)*N_+n,c3);
+ } else {float t[4][8];
+ _mm256_storeu_ps(t[0],c0);_mm256_storeu_ps(t[1],c1);
+ _mm256_storeu_ps(t[2],c2);_mm256_storeu_ps(t[3],c3);
+ int nr=N_-n;for(int i=0;i<4;i++)for(int j=0;j<nr;j++)g->C[(mb+i)*N_+n+j]=t[i][j];}
+ }
+ }
+}
+#endif
+
+/* ============ MatMul with pre-packed B ============ */
+/* AVX-512 path: NR=16 (one ZMM = 16 floats), masked stores for remainder.
+ * AVX2 fallback: NR=8 (one YMM = 8 floats). */
+void matmul_fp32_packed(const float* A, const float* B_packed, float* C,
+ int M, int K, int N) {
+#ifdef __AVX512F__
+ /* AVX-512: NR=16, MR=4. 4 ZMM accumulators + 1 B + 4 A broadcasts = 9 regs (32 available). */
+ int NR = 16;
+ int n_panels = (N + NR - 1) / NR;
+ int m = 0;
+ for (; m + 4 <= M; m += 4) {
+ for (int p = 0; p < n_panels; p++) {
+ int n = p * NR;
+ const float* bp = B_packed + (size_t)p * K * NR;
+ __m512 c0=_mm512_setzero_ps(), c1=_mm512_setzero_ps();
+ __m512 c2=_mm512_setzero_ps(), c3=_mm512_setzero_ps();
+ for (int k = 0; k < K; k++) {
+ __m512 b = _mm512_loadu_ps(bp + k * NR);
+ c0 = _mm512_fmadd_ps(_mm512_set1_ps(A[(m+0)*K+k]), b, c0);
+ c1 = _mm512_fmadd_ps(_mm512_set1_ps(A[(m+1)*K+k]), b, c1);
+ c2 = _mm512_fmadd_ps(_mm512_set1_ps(A[(m+2)*K+k]), b, c2);
+ c3 = _mm512_fmadd_ps(_mm512_set1_ps(A[(m+3)*K+k]), b, c3);
+ }
+ if (n + NR <= N) {
+ _mm512_storeu_ps(C+(m+0)*N+n, c0); _mm512_storeu_ps(C+(m+1)*N+n, c1);
+ _mm512_storeu_ps(C+(m+2)*N+n, c2); _mm512_storeu_ps(C+(m+3)*N+n, c3);
+ } else {
+ __mmask16 mask = ((uint32_t)1 << (N - n)) - 1;
+ _mm512_mask_storeu_ps(C+(m+0)*N+n, mask, c0);
+ _mm512_mask_storeu_ps(C+(m+1)*N+n, mask, c1);
+ _mm512_mask_storeu_ps(C+(m+2)*N+n, mask, c2);
+ _mm512_mask_storeu_ps(C+(m+3)*N+n, mask, c3);
+ }
+ }
+ }
+ for (; m < M; m++) {
+ for (int p = 0; p < n_panels; p++) {
+ int n = p * NR;
+ const float* bp = B_packed + (size_t)p * K * NR;
+ __m512 c = _mm512_setzero_ps();
+ for (int k = 0; k < K; k++)
+ c = _mm512_fmadd_ps(_mm512_set1_ps(A[m*K+k]), _mm512_loadu_ps(bp+k*NR), c);
+ if (n + NR <= N) _mm512_storeu_ps(C+m*N+n, c);
+ else _mm512_mask_storeu_ps(C+m*N+n, ((uint32_t)1<<(N-n))-1, c);
+ }
+ }
+ return;
+#elif defined(__AVX2__)
+ int NR = 8;
+ int n_panels = (N + NR - 1) / NR;
+
+ /* Threaded path for large M */
+ if (0 && M >= 128 && tp_num_threads() > 1) { /* disabled — threading at block level instead */
+ PGemmCtx gctx = {A, B_packed, C, K, N, n_panels};
+ int m4 = (M / 4) * 4;
+ tp_parallel_for(_pgemm_worker, &gctx, m4, 16); /* grain=16 rows (4 tiles) */
+ /* Handle M remainder sequentially */
+ if (m4 >= M) return;
+ A += (size_t)m4 * K;
+ C += (size_t)m4 * N;
+ M -= m4;
+ }
+
+ int m = 0;
+
+ for (; m + 4 <= M; m += 4) {
+ int p = 0;
+ /* Process 2 panels at a time (16 columns) when possible */
+ for (; p + 2 <= n_panels; p += 2) {
+ int n = p * NR;
+ const float* bp0 = B_packed + (size_t)p * K * NR;
+ const float* bp1 = bp0 + (size_t)K * NR;
+ __m256 c00=_mm256_setzero_ps(), c01=_mm256_setzero_ps();
+ __m256 c10=_mm256_setzero_ps(), c11=_mm256_setzero_ps();
+ __m256 c20=_mm256_setzero_ps(), c21=_mm256_setzero_ps();
+ __m256 c30=_mm256_setzero_ps(), c31=_mm256_setzero_ps();
+ for (int k = 0; k < K; k++) {
+ __m256 b0 = _mm256_load_ps(bp0 + k * NR);
+ __m256 b1 = _mm256_load_ps(bp1 + k * NR);
+ __m256 a0 = _mm256_broadcast_ss(&A[(m+0)*K+k]);
+ __m256 a1 = _mm256_broadcast_ss(&A[(m+1)*K+k]);
+ __m256 a2 = _mm256_broadcast_ss(&A[(m+2)*K+k]);
+ __m256 a3 = _mm256_broadcast_ss(&A[(m+3)*K+k]);
+ c00 = _mm256_fmadd_ps(a0,b0,c00); c01 = _mm256_fmadd_ps(a0,b1,c01);
+ c10 = _mm256_fmadd_ps(a1,b0,c10); c11 = _mm256_fmadd_ps(a1,b1,c11);
+ c20 = _mm256_fmadd_ps(a2,b0,c20); c21 = _mm256_fmadd_ps(a2,b1,c21);
+ c30 = _mm256_fmadd_ps(a3,b0,c30); c31 = _mm256_fmadd_ps(a3,b1,c31);
+ }
+ if (n + 16 <= N) {
+ _mm256_storeu_ps(C+(m+0)*N+n,c00); _mm256_storeu_ps(C+(m+0)*N+n+8,c01);
+ _mm256_storeu_ps(C+(m+1)*N+n,c10); _mm256_storeu_ps(C+(m+1)*N+n+8,c11);
+ _mm256_storeu_ps(C+(m+2)*N+n,c20); _mm256_storeu_ps(C+(m+2)*N+n+8,c21);
+ _mm256_storeu_ps(C+(m+3)*N+n,c30); _mm256_storeu_ps(C+(m+3)*N+n+8,c31);
+ } else {
+ /* Handle boundary: first panel always full, second may be partial */
+ _mm256_storeu_ps(C+(m+0)*N+n,c00); _mm256_storeu_ps(C+(m+1)*N+n,c10);
+ _mm256_storeu_ps(C+(m+2)*N+n,c20); _mm256_storeu_ps(C+(m+3)*N+n,c30);
+ int nr = N - n - 8;
+ if (nr > 0) {
+ float t[4][8];
+ _mm256_storeu_ps(t[0],c01); _mm256_storeu_ps(t[1],c11);
+ _mm256_storeu_ps(t[2],c21); _mm256_storeu_ps(t[3],c31);
+ for (int i=0;i<4;i++) for(int j=0;j<nr;j++) C[(m+i)*N+n+8+j]=t[i][j];
+ }
+ }
+ }
+ /* Single panel remainder */
+ for (; p < n_panels; p++) {
+ int n = p * NR;
+ const float* bp = B_packed + (size_t)p * K * NR;
+ __m256 c0=_mm256_setzero_ps(),c1=_mm256_setzero_ps();
+ __m256 c2=_mm256_setzero_ps(),c3=_mm256_setzero_ps();
+ for (int k = 0; k < K; k++) {
+ __m256 b = _mm256_load_ps(bp + k * NR);
+ c0 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+0)*K+k]),b,c0);
+ c1 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+1)*K+k]),b,c1);
+ c2 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+2)*K+k]),b,c2);
+ c3 = _mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+3)*K+k]),b,c3);
+ }
+ if (n + NR <= N) {
+ _mm256_storeu_ps(C+(m+0)*N+n,c0); _mm256_storeu_ps(C+(m+1)*N+n,c1);
+ _mm256_storeu_ps(C+(m+2)*N+n,c2); _mm256_storeu_ps(C+(m+3)*N+n,c3);
+ } else {
+ float t[4][8];
+ _mm256_storeu_ps(t[0],c0); _mm256_storeu_ps(t[1],c1);
+ _mm256_storeu_ps(t[2],c2); _mm256_storeu_ps(t[3],c3);
+ int nr = N - n;
+ for (int i=0;i<4;i++) for(int j=0;j<nr;j++) C[(m+i)*N+n+j]=t[i][j];
+ }
+ }
+ }
+ /* MR=1 remainder */
+ for (; m < M; m++) {
+ const float* a_row = A + (size_t)m * K;
+ for (int p = 0; p < n_panels; p++) {
+ int n = p * NR;
+ const float* bp = B_packed + (size_t)p * K * NR;
+ __m256 c0 = _mm256_setzero_ps();
+ for (int k = 0; k < K; k++)
+ c0 = _mm256_fmadd_ps(_mm256_broadcast_ss(&a_row[k]),
+ _mm256_load_ps(bp + k * NR), c0);
+ if (n + NR <= N) {
+ _mm256_storeu_ps(C + (size_t)m*N+n, c0);
+ } else {
+ float t[8]; _mm256_storeu_ps(t, c0);
+ for (int j = 0; j < N - n; j++) C[(size_t)m*N+n+j] = t[j];
+ }
+ }
+ }
+#else
+ matmul_fp32(A, B_packed, C, M, K, N);
+#endif
+}
+
+/* ============ Packed MatMul + fused bias ============ */
+/* Same as matmul_fp32_packed but adds bias[n] to each output element during store.
+ * Eliminates separate bias addition pass. */
+void matmul_fp32_packed_bias(const float* A, const float* B_packed, const float* bias,
+ float* C, int M, int K, int N) {
+#ifdef __AVX2__
+ int NR = 8;
+ int n_panels = (N + NR - 1) / NR;
+ int m = 0;
+ for (; m + 4 <= M; m += 4) {
+ int p = 0;
+ for (; p + 2 <= n_panels; p += 2) {
+ int n = p * NR;
+ const float* bp0 = B_packed + (size_t)p * K * NR;
+ const float* bp1 = bp0 + (size_t)K * NR;
+ __m256 c00=_mm256_setzero_ps(),c01=_mm256_setzero_ps();
+ __m256 c10=_mm256_setzero_ps(),c11=_mm256_setzero_ps();
+ __m256 c20=_mm256_setzero_ps(),c21=_mm256_setzero_ps();
+ __m256 c30=_mm256_setzero_ps(),c31=_mm256_setzero_ps();
+ for (int k = 0; k < K; k++) {
+ __m256 b0=_mm256_load_ps(bp0+k*NR), b1=_mm256_load_ps(bp1+k*NR);
+ __m256 a0=_mm256_broadcast_ss(&A[(m+0)*K+k]);
+ __m256 a1=_mm256_broadcast_ss(&A[(m+1)*K+k]);
+ __m256 a2=_mm256_broadcast_ss(&A[(m+2)*K+k]);
+ __m256 a3=_mm256_broadcast_ss(&A[(m+3)*K+k]);
+ c00=_mm256_fmadd_ps(a0,b0,c00); c01=_mm256_fmadd_ps(a0,b1,c01);
+ c10=_mm256_fmadd_ps(a1,b0,c10); c11=_mm256_fmadd_ps(a1,b1,c11);
+ c20=_mm256_fmadd_ps(a2,b0,c20); c21=_mm256_fmadd_ps(a2,b1,c21);
+ c30=_mm256_fmadd_ps(a3,b0,c30); c31=_mm256_fmadd_ps(a3,b1,c31);
+ }
+ /* Add bias during store */
+ __m256 bb0 = _mm256_loadu_ps(bias+n), bb1 = _mm256_loadu_ps(bias+n+8);
+ c00=_mm256_add_ps(c00,bb0); c01=_mm256_add_ps(c01,bb1);
+ c10=_mm256_add_ps(c10,bb0); c11=_mm256_add_ps(c11,bb1);
+ c20=_mm256_add_ps(c20,bb0); c21=_mm256_add_ps(c21,bb1);
+ c30=_mm256_add_ps(c30,bb0); c31=_mm256_add_ps(c31,bb1);
+ if (n+16<=N) {
+ _mm256_storeu_ps(C+(m+0)*N+n,c00); _mm256_storeu_ps(C+(m+0)*N+n+8,c01);
+ _mm256_storeu_ps(C+(m+1)*N+n,c10); _mm256_storeu_ps(C+(m+1)*N+n+8,c11);
+ _mm256_storeu_ps(C+(m+2)*N+n,c20); _mm256_storeu_ps(C+(m+2)*N+n+8,c21);
+ _mm256_storeu_ps(C+(m+3)*N+n,c30); _mm256_storeu_ps(C+(m+3)*N+n+8,c31);
+ } else {
+ _mm256_storeu_ps(C+(m+0)*N+n,c00);_mm256_storeu_ps(C+(m+1)*N+n,c10);
+ _mm256_storeu_ps(C+(m+2)*N+n,c20);_mm256_storeu_ps(C+(m+3)*N+n,c30);
+ int nr=N-n-8; if(nr>0){float t[4][8];
+ _mm256_storeu_ps(t[0],c01);_mm256_storeu_ps(t[1],c11);
+ _mm256_storeu_ps(t[2],c21);_mm256_storeu_ps(t[3],c31);
+ for(int i=0;i<4;i++)for(int j=0;j<nr;j++)C[(m+i)*N+n+8+j]=t[i][j];}
+ }
+ }
+ for (; p < n_panels; p++) {
+ int n = p * NR;
+ const float* bp = B_packed + (size_t)p * K * NR;
+ __m256 c0=_mm256_setzero_ps(),c1=_mm256_setzero_ps();
+ __m256 c2=_mm256_setzero_ps(),c3=_mm256_setzero_ps();
+ for (int k = 0; k < K; k++) {
+ __m256 b=_mm256_load_ps(bp+k*NR);
+ c0=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+0)*K+k]),b,c0);
+ c1=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+1)*K+k]),b,c1);
+ c2=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+2)*K+k]),b,c2);
+ c3=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+3)*K+k]),b,c3);
+ }
+ __m256 bb=_mm256_loadu_ps(bias+n);
+ c0=_mm256_add_ps(c0,bb);c1=_mm256_add_ps(c1,bb);
+ c2=_mm256_add_ps(c2,bb);c3=_mm256_add_ps(c3,bb);
+ if(n+NR<=N){
+ _mm256_storeu_ps(C+(m+0)*N+n,c0);_mm256_storeu_ps(C+(m+1)*N+n,c1);
+ _mm256_storeu_ps(C+(m+2)*N+n,c2);_mm256_storeu_ps(C+(m+3)*N+n,c3);
+ } else {float t[4][8];
+ _mm256_storeu_ps(t[0],c0);_mm256_storeu_ps(t[1],c1);
+ _mm256_storeu_ps(t[2],c2);_mm256_storeu_ps(t[3],c3);
+ int nr=N-n;for(int i=0;i<4;i++)for(int j=0;j<nr;j++)C[(m+i)*N+n+j]=t[i][j];}
+ }
+ }
+ for (; m < M; m++) {
+ const float* a_row = A + (size_t)m * K;
+ for (int p = 0; p < n_panels; p++) {
+ int n = p * NR;
+ const float* bp = B_packed + (size_t)p * K * NR;
+ __m256 c0 = _mm256_setzero_ps();
+ for (int k = 0; k < K; k++)
+ c0 = _mm256_fmadd_ps(_mm256_broadcast_ss(&a_row[k]),_mm256_load_ps(bp+k*NR),c0);
+ c0=_mm256_add_ps(c0,_mm256_loadu_ps(bias+n));
+ if(n+NR<=N){_mm256_storeu_ps(C+(size_t)m*N+n,c0);}
+ else{float t[8];_mm256_storeu_ps(t,c0);for(int j=0;j<N-n;j++)C[(size_t)m*N+n+j]=t[j];}
+ }
+ }
+#else
+ matmul_fp32(A, B_packed, C, M, K, N);
+ if (bias) for (int m=0;m<M;m++) for (int n=0;n<N;n++) C[m*N+n]+=bias[n];
+#endif
+}
+
+/* ============ Fused MatMul + Bias + GELU (single memory pass) ============ */
+/* Computes: C[m,n] = GELU(A[M,K] × B_packed[K,N] + bias[N])
+ * Bias and GELU applied in-register during store — saves 2 memory round-trips.
+ * Uses A&S 7.1.26 erf approximation, same as gelu_fp32. */
+#ifdef __AVX2__
+static inline __m256 _gelu_ymm(__m256 v) {
+ const __m256 v_inv_sqrt2 = _mm256_set1_ps(0.7071067811865476f);
+ const __m256 v_half = _mm256_set1_ps(0.5f);
+ const __m256 v_one = _mm256_set1_ps(1.0f);
+ const __m256 v_sign_mask = _mm256_set1_ps(-0.0f);
+ __m256 arg = _mm256_mul_ps(v, v_inv_sqrt2);
+ __m256 ax = _mm256_andnot_ps(v_sign_mask, arg);
+ __m256 sign = _mm256_and_ps(arg, v_sign_mask);
+ __m256 t = _mm256_div_ps(v_one, _mm256_fmadd_ps(_mm256_set1_ps(0.3275911f), ax, v_one));
+ __m256 exp_val = _mm256_exp_ps(_mm256_sub_ps(_mm256_setzero_ps(), _mm256_mul_ps(ax, ax)));
+ __m256 poly = _mm256_fmadd_ps(_mm256_set1_ps(1.061405429f), t, _mm256_set1_ps(-1.453152027f));
+ poly = _mm256_fmadd_ps(poly, t, _mm256_set1_ps(1.421413741f));
+ poly = _mm256_fmadd_ps(poly, t, _mm256_set1_ps(-0.284496736f));
+ poly = _mm256_fmadd_ps(poly, t, _mm256_set1_ps(0.254829592f));
+ poly = _mm256_mul_ps(poly, t);
+ __m256 erf_val = _mm256_xor_ps(_mm256_fnmadd_ps(poly, exp_val, v_one), sign);
+ return _mm256_mul_ps(_mm256_mul_ps(v_half, v), _mm256_add_ps(v_one, erf_val));
+}
+#endif
+
+void matmul_bias_gelu_packed(const float* A, const float* B_packed, const float* bias,
+ float* C, int M, int K, int N) {
+#ifdef __AVX2__
+ int NR = 8;
+ int n_panels = (N + NR - 1) / NR;
+ int m = 0;
+ for (; m + 4 <= M; m += 4) {
+ int p = 0;
+ for (; p + 2 <= n_panels; p += 2) {
+ int n = p * NR;
+ const float* bp0 = B_packed + (size_t)p * K * NR;
+ const float* bp1 = bp0 + (size_t)K * NR;
+ __m256 c00=_mm256_setzero_ps(),c01=_mm256_setzero_ps();
+ __m256 c10=_mm256_setzero_ps(),c11=_mm256_setzero_ps();
+ __m256 c20=_mm256_setzero_ps(),c21=_mm256_setzero_ps();
+ __m256 c30=_mm256_setzero_ps(),c31=_mm256_setzero_ps();
+ for (int k=0;k<K;k++){
+ __m256 b0=_mm256_load_ps(bp0+k*NR),b1=_mm256_load_ps(bp1+k*NR);
+ __m256 a0=_mm256_broadcast_ss(&A[(m+0)*K+k]);
+ __m256 a1=_mm256_broadcast_ss(&A[(m+1)*K+k]);
+ __m256 a2=_mm256_broadcast_ss(&A[(m+2)*K+k]);
+ __m256 a3=_mm256_broadcast_ss(&A[(m+3)*K+k]);
+ c00=_mm256_fmadd_ps(a0,b0,c00);c01=_mm256_fmadd_ps(a0,b1,c01);
+ c10=_mm256_fmadd_ps(a1,b0,c10);c11=_mm256_fmadd_ps(a1,b1,c11);
+ c20=_mm256_fmadd_ps(a2,b0,c20);c21=_mm256_fmadd_ps(a2,b1,c21);
+ c30=_mm256_fmadd_ps(a3,b0,c30);c31=_mm256_fmadd_ps(a3,b1,c31);
+ }
+ /* Fused: add bias + GELU in registers before store */
+ __m256 bb0=_mm256_loadu_ps(bias+n), bb1=_mm256_loadu_ps(bias+n+8);
+ c00=_gelu_ymm(_mm256_add_ps(c00,bb0)); c01=_gelu_ymm(_mm256_add_ps(c01,bb1));
+ c10=_gelu_ymm(_mm256_add_ps(c10,bb0)); c11=_gelu_ymm(_mm256_add_ps(c11,bb1));
+ c20=_gelu_ymm(_mm256_add_ps(c20,bb0)); c21=_gelu_ymm(_mm256_add_ps(c21,bb1));
+ c30=_gelu_ymm(_mm256_add_ps(c30,bb0)); c31=_gelu_ymm(_mm256_add_ps(c31,bb1));
+ if(n+16<=N){
+ _mm256_storeu_ps(C+(m+0)*N+n,c00);_mm256_storeu_ps(C+(m+0)*N+n+8,c01);
+ _mm256_storeu_ps(C+(m+1)*N+n,c10);_mm256_storeu_ps(C+(m+1)*N+n+8,c11);
+ _mm256_storeu_ps(C+(m+2)*N+n,c20);_mm256_storeu_ps(C+(m+2)*N+n+8,c21);
+ _mm256_storeu_ps(C+(m+3)*N+n,c30);_mm256_storeu_ps(C+(m+3)*N+n+8,c31);
+ } else {
+ _mm256_storeu_ps(C+(m+0)*N+n,c00);_mm256_storeu_ps(C+(m+1)*N+n,c10);
+ _mm256_storeu_ps(C+(m+2)*N+n,c20);_mm256_storeu_ps(C+(m+3)*N+n,c30);
+ int nr=N-n-8;if(nr>0){float t[4][8];
+ _mm256_storeu_ps(t[0],c01);_mm256_storeu_ps(t[1],c11);
+ _mm256_storeu_ps(t[2],c21);_mm256_storeu_ps(t[3],c31);
+ for(int i=0;i<4;i++)for(int j=0;j<nr;j++)C[(m+i)*N+n+8+j]=t[i][j];}
+ }
+ }
+ for(;p<n_panels;p++){
+ int n=p*NR;
+ const float* bp=B_packed+(size_t)p*K*NR;
+ __m256 c0=_mm256_setzero_ps(),c1=_mm256_setzero_ps();
+ __m256 c2=_mm256_setzero_ps(),c3=_mm256_setzero_ps();
+ for(int k=0;k<K;k++){
+ __m256 b=_mm256_load_ps(bp+k*NR);
+ c0=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+0)*K+k]),b,c0);
+ c1=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+1)*K+k]),b,c1);
+ c2=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+2)*K+k]),b,c2);
+ c3=_mm256_fmadd_ps(_mm256_broadcast_ss(&A[(m+3)*K+k]),b,c3);
+ }
+ __m256 bb=_mm256_loadu_ps(bias+n);
+ c0=_gelu_ymm(_mm256_add_ps(c0,bb));c1=_gelu_ymm(_mm256_add_ps(c1,bb));
+ c2=_gelu_ymm(_mm256_add_ps(c2,bb));c3=_gelu_ymm(_mm256_add_ps(c3,bb));
+ if(n+NR<=N){
+ _mm256_storeu_ps(C+(m+0)*N+n,c0);_mm256_storeu_ps(C+(m+1)*N+n,c1);
+ _mm256_storeu_ps(C+(m+2)*N+n,c2);_mm256_storeu_ps(C+(m+3)*N+n,c3);
+ } else {float t[4][8];
+ _mm256_storeu_ps(t[0],c0);_mm256_storeu_ps(t[1],c1);
+ _mm256_storeu_ps(t[2],c2);_mm256_storeu_ps(t[3],c3);
+ int nr=N-n;for(int i=0;i<4;i++)for(int j=0;j<nr;j++)C[(m+i)*N+n+j]=t[i][j];}
+ }
+ }
+ for(;m<M;m++){
+ const float* a_row=A+(size_t)m*K;
+ for(int p=0;p<n_panels;p++){
+ int n=p*NR;
+ const float* bp=B_packed+(size_t)p*K*NR;
+ __m256 c0=_mm256_setzero_ps();
+ for(int k=0;k<K;k++)
+ c0=_mm256_fmadd_ps(_mm256_broadcast_ss(&a_row[k]),_mm256_load_ps(bp+k*NR),c0);
+ c0=_gelu_ymm(_mm256_add_ps(c0,_mm256_loadu_ps(bias+n)));
+ if(n+NR<=N)_mm256_storeu_ps(C+(size_t)m*N+n,c0);
+ else{float t[8];_mm256_storeu_ps(t,c0);for(int j=0;j<N-n;j++)C[(size_t)m*N+n+j]=t[j];}
+ }
+ }
+#else
+ matmul_fp32(A, B_packed, C, M, K, N);
+ for(int i=0;i<M*N;i++){float v=C[i]+bias[i%N];C[i]=0.5f*v*(1.0f+erff(v*0.7071067811865476f));}
+#endif
+}
+
+/* ============ MatMul + Add (bias) ============ */
+void matmul_bias_fp32(const float* A, const float* B, const float* bias,
+ float* C, int M, int K, int N) {
+ matmul_fp32(A, B, C, M, K, N);
+ if (bias) {
+ for (int m = 0; m < M; m++)
+ for (int n = 0; n < N; n++)
+ C[(size_t)m * N + n] += bias[n];
+ }
+}
+
+/* ============ L2 Normalize ============ */
+/* Normalize each row to unit L2 norm, with clipping */
+void l2_normalize_fp32(float* x, int N, int C, float min_norm) {
+ for (int n = 0; n < N; n++) {
+ float* row = x + (size_t)n * C;
+ float norm_sq = 0;
+ for (int c = 0; c < C; c++) norm_sq += row[c] * row[c];
+ float norm = sqrtf(norm_sq);
+ if (norm < min_norm) norm = min_norm;
+ float inv = 1.0f / norm;
+ for (int c = 0; c < C; c++) row[c] *= inv;
+ }
+}
+
+/* ============ Adaptive Average Pool ============ */
+/* Pool spatial dims H×W → 1×1, for [N, C, H, W] layout */
+void adaptive_avg_pool_fp32(const float* x, int C, int H, int W, float* out) {
+ int HW = H * W;
+ float inv = 1.0f / HW;
+ for (int c = 0; c < C; c++) {
+ float sum = 0;
+ for (int hw = 0; hw < HW; hw++)
+ sum += x[(size_t)c * HW + hw];
+ out[c] = sum * inv;
+ }
+}
+
+/* ============ Depthwise Conv NxN (generalized) ============ */
+/* Supports arbitrary kernel size (3,5,7,9), stride 1, pad=K/2 */
+/* DW Conv NxN on HWC layout — AVX2 optimized for C multiple of 8 */
+void depthwise_conv_nxn_hwc_fp32(
+ const float* in, int H, int W, int C,
+ const float* weights, /* [C, K, K] */
+ const float* bias,
+ int K,
+ float* out)
+{
+ int pad = K / 2;
+
+ /* Weights assumed pre-transposed to [K*K, C] layout */
+ int KK = K * K;
+ const float* w_t = weights;
+
+ for (int oy = 0; oy < H; oy++) {
+ for (int ox = 0; ox < W; ox++) {
+ float* o = out + ((size_t)oy * W + ox) * C;
+
+ /* Init with bias */
+ int c = 0;
+#ifdef __AVX512F__
+ for (; c + 16 <= C; c += 16)
+ _mm512_storeu_ps(o + c, bias ? _mm512_loadu_ps(bias + c) : _mm512_setzero_ps());
+#endif
+#ifdef __AVX2__
+ for (; c + 8 <= C; c += 8)
+ _mm256_storeu_ps(o + c, bias ? _mm256_loadu_ps(bias + c) : _mm256_setzero_ps());
+#endif
+ for (; c < C; c++) o[c] = bias ? bias[c] : 0;
+
+ /* Accumulate kernel */
+ for (int ky = 0; ky < K; ky++) {
+ int iy = oy - pad + ky;
+ if (iy < 0 || iy >= H) continue;
+ for (int kx = 0; kx < K; kx++) {
+ int ix = ox - pad + kx;
+ if (ix < 0 || ix >= W) continue;
+ const float* inp = in + ((size_t)iy * W + ix) * C;
+ int ki = ky * K + kx;
+ c = 0;
+#ifdef __AVX512F__
+ for (; c + 16 <= C; c += 16) {
+ __m512 vi = _mm512_loadu_ps(inp + c);
+ __m512 vw = _mm512_loadu_ps(w_t + ki * C + c);
+ _mm512_storeu_ps(o + c, _mm512_fmadd_ps(vi, vw, _mm512_loadu_ps(o + c)));
+ }
+#endif
+#ifdef __AVX2__
+ for (; c + 8 <= C; c += 8) {
+ __m256 vi = _mm256_loadu_ps(inp + c);
+ int ki2 = ky * K + kx;
+ __m256 vw = _mm256_loadu_ps(w_t + ki2 * C + c);
+ _mm256_storeu_ps(o + c, _mm256_fmadd_ps(vi, vw, _mm256_loadu_ps(o + c)));
+ }
+#endif
+ for (; c < C; c++) {
+ o[c] += inp[c] * w_t[(ky * K + kx) * C + c];
+ }
+ }
+ }
+ }
+ }
+ /* w_t is pre-transposed, no free needed */
+}
+
+void depthwise_conv_nxn_fp32(
+ const float* in, int H, int W, int C,
+ const float* weights, /* [C, 1, K, K] */
+ const float* bias,
+ int K, /* kernel size */
+ float* out)
+{
+ int pad = K / 2;
+ int OH = H, OW = W;
+
+ /* Channel-first: each channel is independent spatial conv */
+ for (int c = 0; c < C; c++) {
+ const float* in_c = in + (size_t)c * H * W;
+ const float* w_c = weights + (size_t)c * K * K;
+ float* out_c = out + (size_t)c * OH * OW;
+ float b = bias ? bias[c] : 0;
+
+ for (int oy = 0; oy < OH; oy++) {
+ for (int ox = 0; ox < OW; ox++) {
+ float sum = b;
+ for (int ky = 0; ky < K; ky++) {
+ int iy = oy - pad + ky;
+ if (iy < 0 || iy >= H) continue;
+ for (int kx = 0; kx < K; kx++) {
+ int ix = ox - pad + kx;
+ if (ix < 0 || ix >= W) continue;
+ sum += in_c[(size_t)iy * W + ix] * w_c[(size_t)ky * K + kx];
+ }
+ }
+ out_c[(size_t)oy * OW + ox] = sum;
+ }
+ }
+ }
+}
diff --git a/src/weight_crypto.c b/src/weight_crypto.c
new file mode 100644
index 0000000..cbf4edc
--- /dev/null
+++ b/src/weight_crypto.c
@@ -0,0 +1,317 @@
+/*
+ * weight_crypto.c — AES-256-CTR encryption for model weights.
+ *
+ * Uses a minimal AES implementation (no OpenSSL dependency).
+ * Key derivation: SHA-256(machine_id + salt) → AES-256 key.
+ * Machine ID: combination of CPU info + hostname for hardware binding.
+ *
+ * Usage:
+ * Encrypt: weight_encrypt("weights.bin", "weights.enc", key)
+ * Decrypt: weight_decrypt_inplace(data, size, key)
+ */
+
+#include <stdint.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _WIN32
+#include <windows.h>
+#endif
+
+/* ============ Minimal AES-256 (no dependency) ============ */
+
+static const uint8_t sbox[256] = {
+ 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
+ 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
+ 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
+ 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
+ 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
+ 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
+ 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
+ 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
+ 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
+ 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
+ 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
+ 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
+ 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
+ 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
+ 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
+ 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
+};
+
+static const uint8_t rcon[11] = {0,1,2,4,8,16,32,64,128,27,54};
+
+static void aes256_key_expand(const uint8_t key[32], uint8_t rkeys[240]) {
+ memcpy(rkeys, key, 32);
+ uint8_t tmp[4];
+ for (int i = 8; i < 60; i++) {
+ memcpy(tmp, rkeys + (i-1)*4, 4);
+ if (i % 8 == 0) {
+ uint8_t t = tmp[0];
+ tmp[0] = sbox[tmp[1]] ^ rcon[i/8];
+ tmp[1] = sbox[tmp[2]];
+ tmp[2] = sbox[tmp[3]];
+ tmp[3] = sbox[t];
+ } else if (i % 8 == 4) {
+ for (int j = 0; j < 4; j++) tmp[j] = sbox[tmp[j]];
+ }
+ for (int j = 0; j < 4; j++)
+ rkeys[i*4+j] = rkeys[(i-8)*4+j] ^ tmp[j];
+ }
+}
+
+static void aes256_encrypt_block(const uint8_t rkeys[240], const uint8_t in[16], uint8_t out[16]) {
+ uint8_t s[16];
+ memcpy(s, in, 16);
+ /* AddRoundKey 0 */
+ for (int i = 0; i < 16; i++) s[i] ^= rkeys[i];
+ /* Rounds 1-13 */
+ for (int r = 1; r < 14; r++) {
+ uint8_t t[16];
+ /* SubBytes */
+ for (int i = 0; i < 16; i++) t[i] = sbox[s[i]];
+ /* ShiftRows */
+ s[0]=t[0]; s[1]=t[5]; s[2]=t[10]; s[3]=t[15];
+ s[4]=t[4]; s[5]=t[9]; s[6]=t[14]; s[7]=t[3];
+ s[8]=t[8]; s[9]=t[13]; s[10]=t[2]; s[11]=t[7];
+ s[12]=t[12]; s[13]=t[1]; s[14]=t[6]; s[15]=t[11];
+ /* MixColumns (skip for last round) */
+ if (r < 13) {
+ for (int c = 0; c < 4; c++) {
+ uint8_t a[4]; memcpy(a, s+c*4, 4);
+ uint8_t h[4];
+ for (int i = 0; i < 4; i++) h[i] = (a[i] & 0x80) ? (a[i]<<1)^0x1b : a[i]<<1;
+ s[c*4+0] = h[0]^h[1]^a[1]^a[2]^a[3];
+ s[c*4+1] = a[0]^h[1]^h[2]^a[2]^a[3];
+ s[c*4+2] = a[0]^a[1]^h[2]^h[3]^a[3];
+ s[c*4+3] = h[0]^a[0]^a[1]^a[2]^h[3];
+ }
+ }
+ /* AddRoundKey */
+ for (int i = 0; i < 16; i++) s[i] ^= rkeys[r*16+i];
+ }
+ /* Final round (no MixColumns) */
+ uint8_t t[16];
+ for (int i = 0; i < 16; i++) t[i] = sbox[s[i]];
+ s[0]=t[0]; s[1]=t[5]; s[2]=t[10]; s[3]=t[15];
+ s[4]=t[4]; s[5]=t[9]; s[6]=t[14]; s[7]=t[3];
+ s[8]=t[8]; s[9]=t[13]; s[10]=t[2]; s[11]=t[7];
+ s[12]=t[12]; s[13]=t[1]; s[14]=t[6]; s[15]=t[11];
+ for (int i = 0; i < 16; i++) out[i] = s[i] ^ rkeys[14*16+i];
+}
+
+/* ============ AES-256-CTR mode ============ */
+
+static void aes256_ctr(const uint8_t key[32], const uint8_t nonce[16],
+ uint8_t* data, size_t len) {
+ uint8_t rkeys[240];
+ aes256_key_expand(key, rkeys);
+
+ uint8_t ctr[16], keystream[16];
+ memcpy(ctr, nonce, 16);
+
+ for (size_t i = 0; i < len; i += 16) {
+ aes256_encrypt_block(rkeys, ctr, keystream);
+ size_t block_len = (len - i < 16) ? len - i : 16;
+ for (size_t j = 0; j < block_len; j++)
+ data[i + j] ^= keystream[j];
+ /* Increment counter */
+ for (int k = 15; k >= 0; k--) {
+ if (++ctr[k]) break;
+ }
+ }
+}
+
+/* ============ SHA-256 (minimal, for key derivation) ============ */
+
+static const uint32_t sha256_k[64] = {
+ 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
+ 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
+ 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
+ 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
+ 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
+ 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
+ 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
+ 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
+};
+
+#define RR(x,n) (((x)>>(n))|((x)<<(32-(n))))
+#define CH(x,y,z) (((x)&(y))^((~(x))&(z)))
+#define MAJ(x,y,z) (((x)&(y))^((x)&(z))^((y)&(z)))
+#define EP0(x) (RR(x,2)^RR(x,13)^RR(x,22))
+#define EP1(x) (RR(x,6)^RR(x,11)^RR(x,25))
+#define SIG0(x) (RR(x,7)^RR(x,18)^((x)>>3))
+#define SIG1(x) (RR(x,17)^RR(x,19)^((x)>>10))
+
+void sha256(const uint8_t* data, size_t len, uint8_t hash[32]) {
+ uint32_t h[8] = {0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
+ 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19};
+ /* Padding */
+ size_t padded_len = ((len + 9 + 63) / 64) * 64;
+ uint8_t* msg = (uint8_t*)calloc(padded_len, 1);
+ memcpy(msg, data, len);
+ msg[len] = 0x80;
+ uint64_t bitlen = len * 8;
+ for (int i = 0; i < 8; i++) msg[padded_len - 1 - i] = (uint8_t)(bitlen >> (i * 8));
+
+ for (size_t chunk = 0; chunk < padded_len; chunk += 64) {
+ uint32_t w[64];
+ for (int i = 0; i < 16; i++)
+ w[i] = (msg[chunk+i*4]<<24)|(msg[chunk+i*4+1]<<16)|(msg[chunk+i*4+2]<<8)|msg[chunk+i*4+3];
+ for (int i = 16; i < 64; i++)
+ w[i] = SIG1(w[i-2]) + w[i-7] + SIG0(w[i-15]) + w[i-16];
+ uint32_t a=h[0],b=h[1],c=h[2],d=h[3],e=h[4],f=h[5],g=h[6],hh=h[7];
+ for (int i = 0; i < 64; i++) {
+ uint32_t t1 = hh + EP1(e) + CH(e,f,g) + sha256_k[i] + w[i];
+ uint32_t t2 = EP0(a) + MAJ(a,b,c);
+ hh=g; g=f; f=e; e=d+t1; d=c; c=b; b=a; a=t1+t2;
+ }
+ h[0]+=a; h[1]+=b; h[2]+=c; h[3]+=d; h[4]+=e; h[5]+=f; h[6]+=g; h[7]+=hh;
+ }
+ free(msg);
+ for (int i = 0; i < 8; i++) {
+ hash[i*4] = h[i]>>24; hash[i*4+1] = h[i]>>16; hash[i*4+2] = h[i]>>8; hash[i*4+3] = h[i];
+ }
+}
+
+/* ============ Hardware ID ============ */
+
+static void get_machine_id(char* buf, int maxlen) {
+ /* Combine hostname + CPU info for hardware binding */
+ buf[0] = 0;
+#ifdef _WIN32
+ char hostname[256] = "unknown";
+ DWORD sz = sizeof(hostname);
+ GetComputerNameA(hostname, &sz);
+ snprintf(buf, maxlen, "%s", hostname);
+#else
+ FILE* f;
+ /* Hostname */
+ f = fopen("/etc/hostname", "r");
+ if (f) { fgets(buf, maxlen, f); fclose(f); buf[strcspn(buf,"\n")] = 0; }
+ /* CPU ID from /proc/cpuinfo */
+ f = fopen("/proc/cpuinfo", "r");
+ if (f) {
+ char line[256];
+ while (fgets(line, sizeof(line), f)) {
+ if (strstr(line, "model name")) {
+ strncat(buf, line, maxlen - strlen(buf) - 1);
+ break;
+ }
+ }
+ fclose(f);
+ }
+#endif
+}
+
+/* ============ Public API ============ */
+
+/* Derive AES-256 key from license string + machine hardware */
+void derive_key(const char* license, uint8_t key[32]) {
+ char machine_id[512] = {0};
+ get_machine_id(machine_id, sizeof(machine_id));
+
+ /* key = SHA-256(license + "|" + machine_id) */
+ size_t lic_len = strlen(license);
+ size_t mid_len = strlen(machine_id);
+ size_t total = lic_len + 1 + mid_len;
+ uint8_t* combined = (uint8_t*)malloc(total);
+ memcpy(combined, license, lic_len);
+ combined[lic_len] = '|';
+ memcpy(combined + lic_len + 1, machine_id, mid_len);
+ sha256(combined, total, key);
+ free(combined);
+}
+
+/* Encrypt weight file in-place (adds 16-byte nonce header) */
+int weight_encrypt_file(const char* input, const char* output, const char* license) {
+ uint8_t key[32];
+ derive_key(license, key);
+
+ FILE* fin = fopen(input, "rb");
+ if (!fin) return -1;
+ fseek(fin, 0, SEEK_END);
+ size_t len = ftell(fin);
+ fseek(fin, 0, SEEK_SET);
+ uint8_t* data = (uint8_t*)malloc(len);
+ fread(data, 1, len, fin);
+ fclose(fin);
+
+ /* Generate nonce from weight data hash (take first 16 bytes of SHA-256) */
+ uint8_t nonce_hash[32];
+ sha256(data, len > 1024 ? 1024 : len, nonce_hash);
+ uint8_t nonce[16];
+ memcpy(nonce, nonce_hash, 16);
+
+ /* Encrypt */
+ aes256_ctr(key, nonce, data, len);
+
+ /* Write: nonce (16) + encrypted data */
+ FILE* fout = fopen(output, "wb");
+ if (!fout) { free(data); return -1; }
+ fwrite("EFXE", 1, 4, fout); /* magic: EFXE = EdgeFace eXtended Encrypted */
+ fwrite(nonce, 1, 16, fout);
+ fwrite(data, 1, len, fout);
+ fclose(fout);
+ free(data);
+ return 0;
+}
+
+/* Decrypt weight data in-place (data starts after 20-byte header: 4 magic + 16 nonce) */
+int weight_decrypt_inplace(uint8_t* raw, size_t raw_size, const char* license) {
+ if (raw_size < 20 || memcmp(raw, "EFXE", 4) != 0) return -1;
+
+ uint8_t key[32];
+ derive_key(license, key);
+
+ uint8_t* nonce = raw + 4;
+ uint8_t* data = raw + 20;
+ size_t data_len = raw_size - 20;
+
+ aes256_ctr(key, nonce, data, data_len);
+
+ /* Verify decryption by checking for EFXS magic in decrypted data */
+ if (memcmp(data, "EFXS", 4) != 0) {
+ /* Wrong key — re-encrypt to restore original state */
+ aes256_ctr(key, nonce, data, data_len);
+ return -2; /* invalid license */
+ }
+
+ return 0;
+}
+
+/* ============ CLI tool ============ */
+
+#ifdef WEIGHT_CRYPTO_MAIN
+int main(int argc, char** argv) {
+ if (argc < 4) {
+ fprintf(stderr, "Usage:\n");
+ fprintf(stderr, " Encrypt: %s encrypt input.bin output.enc LICENSE_KEY\n", argv[0]);
+ fprintf(stderr, " Test: %s test encrypted.enc LICENSE_KEY\n", argv[0]);
+ return 1;
+ }
+
+ if (strcmp(argv[1], "encrypt") == 0 && argc >= 5) {
+ int r = weight_encrypt_file(argv[2], argv[3], argv[4]);
+ if (r == 0) printf("Encrypted: %s -> %s\n", argv[2], argv[3]);
+ else fprintf(stderr, "Error: %d\n", r);
+ return r;
+ }
+
+ if (strcmp(argv[1], "test") == 0 && argc >= 4) {
+ FILE* f = fopen(argv[2], "rb");
+ if (!f) { fprintf(stderr, "Cannot open %s\n", argv[2]); return 1; }
+ fseek(f, 0, SEEK_END); size_t sz = ftell(f); fseek(f, 0, SEEK_SET);
+ uint8_t* data = malloc(sz); fread(data, 1, sz, f); fclose(f);
+ int r = weight_decrypt_inplace(data, sz, argv[3]);
+ if (r == 0) printf("OK: decryption successful, EFXS magic verified\n");
+ else if (r == -2) printf("FAIL: wrong license key for this machine\n");
+ else printf("FAIL: not an encrypted file\n");
+ free(data);
+ return r == 0 ? 0 : 1;
+ }
+
+ fprintf(stderr, "Unknown command: %s\n", argv[1]);
+ return 1;
+}
+#endif