Skip to content

Fast local LLM inference on plain CPUs. No GPU, 8 GB of RAM. OpenAI-compatible server.

256-bit kernels for CPUs without AVX-512; fix portable start-up on those CPUs (#76)

0xaron81e97c34547f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 292f980..16960fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,25 @@ All notable changes to openset-llm. Dates are YYYY-MM-DD.
## Unreleased
+Added
+
+- 256-bit kernels for the ternary weights on CPUs without AVX-512 (AVX2, and AVX-VNNI where the CPU has it): Intel
+ Core, 12th gen and newer included, and AMD Zen 1 to 3. `./install.sh` and `--portable` builds pick them by
+ themselves; before, these CPUs ran the fork's own kernel. Measured on Ice Lake server VMs with AVX-512 disabled:
+ plain decoding 6.1–7.7 tok/s, 3.5× the old path and 0.7× of the AVX-512 path; prompt reading
+ 6.7× the old path. Speculation stays off by default on these CPUs (it speeds up code and JSON and slows down prose);
+ `./serve --spec` turns it on and drafts 2 tokens ahead there. AVX-512 machines are unchanged. See "CPUs without AVX-512" in the README.
+- `scripts/verify-dispatch.sh` checks the 256-bit kernels too (alone, inside the AVX-512 build, and in the build for
+ AVX-512 CPUs without VNNI); `tests/` gained a kernel test against a scalar reference.
+
+Fixed
+
+- In 0.2.0 and earlier, a `--portable` build could not start on a CPU without AVX-512; the Docker image and
+ `--bin-url` binaries are made from that build. Fixed in this release. Found and checked under emulated Haswell and
+ Alder Lake CPUs.
+
+Thank you to everyone who told us openset-llm was slow on laptops and desktops without AVX-512. This change is for you.
+
## 0.2.0 (2026-11-26)
Added
diff --git a/README.md b/README.md
index 262d8b5..52a03fe 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
<p align="center">
<img alt="Licence: MIT" src="https://img.shields.io/badge/licence-MIT-blue">
- <img alt="Platform: Linux x86-64, AVX-512" src="https://img.shields.io/badge/platform-Linux%20x86--64%20%C2%B7%20AVX--512-lightgrey">
+ <img alt="Platform: Linux x86-64, AVX-512 or AVX2" src="https://img.shields.io/badge/platform-Linux%20x86--64%20%C2%B7%20AVX--512%20or%20AVX2-lightgrey">
<img alt="API: OpenAI-compatible" src="https://img.shields.io/badge/API-OpenAI--compatible-brightgreen">
<img alt="GPU: none" src="https://img.shields.io/badge/GPU-none-black">
<img alt="RAM: 8 GB" src="https://img.shields.io/badge/RAM-8%20GB-black">
@@ -27,7 +27,7 @@
git clone https://github.com/opensetlabs/openset-llm && cd openset-llm && ./start
```
-<p align="center"><sub>Linux (or WSL2), a CPU with AVX-512, 8 GB of RAM. The first run builds the engine and downloads the model (~7.3 GB), then opens a chat page. <a href="#quick-start">Details</a></sub></p>
+<p align="center"><sub>Linux (or WSL2), an x86-64 CPU with AVX-512 (fastest) or AVX2, 8 GB of RAM. The first run builds the engine and downloads the model (~7.3 GB), then opens a chat page. <a href="#quick-start">Details</a></sub></p>
An LLM is not a sealed box. It is a stack of parts you can rewrite: matmul kernels, decoding, attention, caches. People
already rewire single neurons to change what a model does; we rewired the machinery underneath to change where it runs.
@@ -54,16 +54,17 @@ The race above in full: [▶ 45 s video](demo/race.mp4).
openset-llm is an inference engine for ordinary CPUs; more models and more hardware will follow. Today it runs
Qwen3.8-27B, as PrismML's ternary [Bonsai-2-27B](https://huggingface.co/prism-ml/Ternary-Bonsai-2-27B-gguf)
-(5.95 GB), on x86 CPUs with AVX-512. It is a set of new kernels and runtime patches on PrismML's llama.cpp fork, and it
+(5.95 GB), on x86 CPUs: fastest with AVX-512, and on our 256-bit kernels where the CPU only has AVX2. It is a set of new kernels and runtime patches on PrismML's llama.cpp fork, and it
serves an OpenAI-compatible API, so the clients and agents you already use work unchanged.
Its sibling, [openset-tts](https://github.com/opensetlabs/openset-tts), does the same for speech: Qwen3-TTS faster than real time on the same kind of box.
## Quick start
**To chat with it (no code).** You need a Linux PC, or Windows with WSL2, with 8 GB of RAM free for it (16 GB in the
-machine is comfortable; on Windows WSL2 must be given 8 GB, see [Run it locally](#run-it-locally)) and a processor with
-AVX-512: Intel Xeon Ice Lake or newer, or AMD Zen 4 or newer. Intel Core 12th gen and later do not have it and get a
-much slower fallback ([check yours](#which-cpus-get-the-fast-path)). It builds from source, so it needs git, cmake and
+machine is comfortable; on Windows WSL2 must be given 8 GB, see [Run it locally](#run-it-locally)) and an x86-64
+processor. The speeds on this page need AVX-512: Intel Xeon Ice Lake or newer, or AMD Zen 4 or newer. A CPU with AVX2
+but no AVX-512 (Intel Core 12th gen and newer, older Core, AMD Zen 1 to 3) runs on our 256-bit kernels
+([what was measured, and how to run it](#cpus-without-avx-512)). It builds from source, so it needs git, cmake and
a C++ compiler; on Ubuntu or Debian: `sudo apt install -y build-essential cmake git`.
```sh
@@ -71,7 +72,7 @@ git clone https://github.com/opensetlabs/openset-llm && cd openset-llm
./start
```
-Want to check your CPU (AVX-512 fast path) and free RAM before downloading the ~7.3 GB model? Run:
+Want to check your CPU (which kernels it will get) and free RAM before downloading the ~7.3 GB model? Run:
```sh
./install.sh --check
@@ -219,7 +220,8 @@ tg128 box medians, Ice Lake: openset-llm 9.6–10.8, ik_llama `-rtr 1` 4.4–4.7
## Which CPUs get the fast path
`./install.sh --check` prints the path your machine will get. The build picks it at compile time (default, `-march=native`)
-or at start-up (`--portable`, one binary for all x86-64). A CPU without the fast path still runs, on the fork's own kernel.
+or at start-up (`--portable`, one binary for all x86-64). A CPU without AVX-512 runs on the 256-bit kernels (AVX2, with
+AVX-VNNI where the CPU has it); one without AVX2 still runs, on the fork's own kernel.
| CPU | ISA | Path | Status |
|---|---|---|---|
@@ -228,11 +230,80 @@ or at start-up (`--portable`, one binary for all x86-64). A CPU without the fast
| AMD EPYC Zen 5 (9005) | AVX-512 VNNI + VBMI | full | **measured** (EPYC 9275F, 8 vCPU / 16 GB, 3 boxes, one prompt, 2026-11-06): `./serve` 35–36 tok/s, 3.0× ik_llama `-rtr`, 4.1× PrismML; plain ~22 tok/s |
| AMD Ryzen 7000 / 9000 | AVX-512 VNNI + VBMI | full | same cores as the EPYC rows |
| Intel Xeon Cascade Lake / Cooper Lake | AVX-512 VNNI, no VBMI | partial | this build decodes at 0.67–0.82× the full path (measured on Ice Lake / Zen 4 boxes) |
-| Intel Skylake-SP / Skylake-X | AVX-512, no VNNI | fallback: fork's kernel | untested |
-| Intel Core 12th gen and newer, most laptops | AVX2 only | fallback: fork's kernel | this build decodes 4.8–5.7× slower than the full path (measured on Ice Lake boxes) |
+| Intel Skylake-SP / Skylake-X | AVX-512, no VNNI | 256-bit kernels | starts and gives the same replies (checked with the build for this class on an Ice Lake box); speed not measured on such a CPU |
+| Intel Core 12th gen and newer (Alder / Raptor / Meteor / Arrow Lake) | AVX2 + AVX-VNNI | 256-bit kernels, VNNI dot product | not measured on such a CPU; the kernels were checked bit-exact, and the engine gave the same reply, under an emulated Alder Lake |
+| Intel Core before 12th gen without AVX-512, AMD Zen 1 to 3 (Ryzen 1000–5000, EPYC 7001–7003) | AVX2 | 256-bit kernels | **measured on Ice Lake server VMs with AVX-512 disabled** ([table](#cpus-without-avx-512)): 6.1–7.7 tok/s plain decoding, 3.5× the fork's own kernel on the same box, 0.7× of the AVX-512 path |
| ARM64 Linux (Graviton, Ampere, Raspberry Pi 5) | NEON | fallback: fork's kernel | builds; untested |
| Apple Silicon | — | not supported by `install.sh`: use PrismML's Metal build | — |
+### CPUs without AVX-512
+
+A CPU with AVX2 but no AVX-512 gets 256-bit kernels for the ternary weights (AVX2, and AVX-VNNI where the CPU has
+it) instead of the fork's own kernel. `./install.sh` and `./install.sh --portable` pick them by themselves.
+
+**This release also fixes a start-up bug.** In 0.2.0 and earlier, a `--portable` build could not start on a CPU
+without AVX-512, and the Docker image and `--bin-url` binaries are made from that build. Found and checked under
+emulated Haswell and Alder Lake CPUs.
+
+Thank you to everyone who told us openset-llm was slow on laptops and desktops without AVX-512. This change is for you.
+
+**How to run it.** The commands are the quick start's; on a machine with AVX2 and no AVX-512 they do this:
+
+```sh
+./install.sh --check # prints "Path: AVX2, no AVX-512: the 256-bit kernels ..."
+./install.sh # builds for this CPU, downloads and prepares the model
+./serve # plain decoding: the default without AVX-512
+./serve --spec # speculative decoding on, drafting 2 tokens ahead
+./bench/quick.sh --plain --spec # measures ./serve, ./serve --no-spec and ./serve --spec on this machine
+```
+
+To see which kernels a machine will get before cloning anything:
+
+```sh
+f=$(grep -m1 '^flags' /proc/cpuinfo); case "$f" in *avx512vbmi*avx512_vnni*|*avx512_vnni*avx512vbmi*) echo "fast path";; *avx512_vnni*) echo "partial fast path (AVX-512 without VBMI)";; *avx2*) echo "256-bit kernels (AVX2)";; *) echo "generic fallback: slow";; esac
+```
+
+**Measured on Ice Lake server VMs with AVX-512 disabled (the binary holds no AVX-512 instruction).** The engine was
+built for a Haswell-class CPU and run on 4 cloud VMs with 8 vCPU / 8 GB, 3 rounds each, every engine in every
+round, same model file.
+
+| Same box, AVX2-only builds, `llama-bench`, 8 threads | plain decoding tok/s (128 tokens) | prompt reading tok/s (512 tokens) |
+|---|---|---|
+| **openset-llm, 256-bit kernels** | **6.1–7.7** | **14.5–17.8** |
+| openset-llm before this change (the fork's own kernel) | 1.7–1.9 | 2.1–2.7 |
+| ik_llama.cpp `-rtr` (`13cffc0`) | 3.9–5.0 | 14–21 |
+| PrismML llama.cpp (`prism-b12178`, 2026-11-24) | 2.4–3.0 | 3.9–5.1 |
+| for reference: openset-llm with AVX-512 on the same box | 8.0–9.7 | 37–49 |
+
+Medians per box, range over the boxes. Plain decoding is 3.5× the fork's own kernel, 1.5× ik_llama.cpp and
+2.2× PrismML's current fork on the same box, and 0.7× of our AVX-512 path; prompt reading is 6.7×
+the fork's own kernel, level with ik_llama.cpp (0.93×) and 0.38× of the AVX-512 path.
+
+`./serve` on this path decodes at 5.8–7.2 tok/s on the benchmark prompts (plain decoding: speculation is off by default
+without AVX-512), 3.5× the same requests on the fork's own kernel. `./serve --spec` turns speculation on and drafts 2
+tokens ahead there: 7.2–8.7 tok/s on the benchmark prompts, 1.27× plain decoding [1.01, 1.78]. On a broader set of 128
+prompts it is 1.11× overall: 1.19–1.43× on code, JSON, maths and tool calls, and 0.91–0.99× on prose, translation and
+summaries, which is why it is not the default.
+
+Replies: greedy replies equal the AVX-512 path's (plain decoding) on 18 of the 24 benchmark prompts at 128 tokens; the other 6
+part at a token where the model's two best candidates are within 0.04 nats of each other. The kernels themselves
+give bit-identical results on both paths; the rest of the engine runs at 256 bits there, and near-ties can fall
+the other way. WikiText-2 perplexity is 7.5689 on this path against 7.5702 on the AVX-512 path (each ± 0.21).
+Memory on 8 GB: at the default 4k context the server holds 5.9 GiB after a ~3k-token prompt with 1.5 GiB still available
+(the AVX-512 path with plain decoding: 6.2 and 1.2 GiB); with `--spec` 6.5 GiB and 0.9 GiB (the AVX-512 default: 7.2 and
+0.2 GiB); at `--ctx 8192` 6.1 GiB and 1.3 GiB after a ~7k-token prompt. One 8 GB box, one run each.
+
+Not measured: a CPU without AVX-512 (AMD Zen 1 to 3, Intel Core); laptop and desktop memory configurations; CPUs
+with performance and efficiency cores; the AVX-VNNI kernels at speed (the test VMs do not have AVX-VNNI, so an
+emulator ran them, for correctness). If you run it on such a machine, please post the block that
+`./bench/quick.sh --plain --spec` prints as a "Measurement on my machine" issue.
+
+**What is next**
+
+- We are making this path faster.
+- Measurements on real AVX2-only desktop and laptop chips come next, and we will publish the numbers here.
+- Phones are the next target we are working on.
+
## Memory budget (8 GB machine)
| What | Size |
@@ -269,7 +340,8 @@ or at start-up (`--portable`, one binary for all x86-64). A CPU without the fast
A patch set on PrismML's llama.cpp fork (pinned at `e3de715`), applied by `install.sh`:
-- **New AVX-512 kernels for the ternary weights**, for generating and for reading prompts.
+- **New kernels for the ternary weights**, for generating and for reading prompts: AVX-512, and 256-bit (AVX2 /
+ AVX-VNNI) for CPUs without it.
- **Speculative decoding with the model's own multi-token-prediction head** (published by unsloth, grafted on at
install): the engine drafts a few tokens ahead and the full model checks every one.
- **A fused attention kernel** that keeps long contexts fast.
@@ -338,7 +410,7 @@ read once, kept on disk, and loaded by every stream that needs it.
**Which path will I get?** (Linux or WSL; no clone needed)
```sh
-f=$(grep -m1 '^flags' /proc/cpuinfo); case "$f" in *avx512vbmi*avx512_vnni*|*avx512_vnni*avx512vbmi*) echo "fast path";; *avx512_vnni*) echo "partial fast path (AVX-512 without VBMI)";; *avx2*) echo "fallback: AVX2, runs ~5x slower";; *) echo "generic fallback: slow";; esac
+f=$(grep -m1 '^flags' /proc/cpuinfo); case "$f" in *avx512vbmi*avx512_vnni*|*avx512_vnni*avx512vbmi*) echo "fast path";; *avx512_vnni*) echo "partial fast path (AVX-512 without VBMI)";; *avx2*) echo "256-bit kernels (AVX2)";; *) echo "generic fallback: slow";; esac
```
Inside a clone, `./install.sh --check` says the same and checks your RAM.
@@ -372,9 +444,9 @@ memory=10GB
```
Then, in the Ubuntu shell, run the Linux one-liner above. Clone into your Linux home (`~`), not `/mnt/c`: reading the
-model through `/mnt/c` is much slower. Most laptop CPUs (Intel 12th gen and newer) get the AVX2 fallback.
+model through `/mnt/c` is much slower. Most laptop CPUs (Intel 12th gen and newer) have no AVX-512 and get the 256-bit kernels.
-**Mac.** Our fast path is x86 AVX-512 only. On Apple Silicon, use PrismML's own build of their fork with Metal
+**Mac.** Our kernels are x86 only (AVX-512 and AVX2). On Apple Silicon, use PrismML's own build of their fork with Metal
([PrismML-Eng/llama.cpp](https://github.com/PrismML-Eng/llama.cpp)), which is much faster there than any CPU path.
Intel Macs are not supported by `install.sh`.
@@ -387,7 +459,8 @@ curl http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/jso
## In the cloud
-- **Any Linux VM or container host** with 8 vCPU / 8 GB and AVX-512: the Linux recipe or the Docker image above.
+- **Any Linux VM or container host** with 8 vCPU / 8 GB: the Linux recipe or the Docker image above (AVX-512 for the
+ speeds on this page; AVX2-only hosts such as AMD Zen 2 / Zen 3 instances run on the 256-bit kernels).
- **Prebuilt binaries:** `./install.sh --bin-url <tarball>` skips the build (tarballs come from `scripts/package.sh`).
A tarball runs on the Linux distribution it was built on or a newer one, so build it on the oldest one you want to
support; `install.sh` checks that it starts before it downloads the model.
@@ -395,7 +468,8 @@ curl http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/jso
## Limits
- **Hardware:** the fast path needs x86 with AVX-512 VNNI + VBMI (table above). Measured on Intel Ice Lake, AMD Zen 4
- and Zen 5. The 8 vCPU of our Ice Lake test boxes behave like 8 physical cores; a typical cloud 8 vCPU (AWS / GCP / Azure) is 4 cores, so
+ and Zen 5. The AVX2 path was measured on Ice Lake server VMs with AVX-512 disabled, and its AVX-VNNI variant was
+ checked under an emulator ([CPUs without AVX-512](#cpus-without-avx-512)). The 8 vCPU of our Ice Lake test boxes behave like 8 physical cores; a typical cloud 8 vCPU (AWS / GCP / Azure) is 4 cores, so
expect lower absolute speed there.
- **8 GB is the floor:** 4k context by default; above 4k on < 12 GB, `serve` uses plain decoding (above 8k with `--kv8`,
12k with `--kv6`, 16k with `--kv5`). The compact caches are experimental and were measured on one CPU class.
diff --git a/bench/quick.sh b/bench/quick.sh
index 23ab43a..46c3ea1 100755
--- a/bench/quick.sh
+++ b/bench/quick.sh
@@ -4,16 +4,18 @@
#
# ./bench/quick.sh # default settings (what ./serve runs), 6 prompts x 128 tokens, greedy
# ./bench/quick.sh --plain # also measure plain decoding (./serve --no-spec)
+# ./bench/quick.sh --spec # also measure ./serve --spec (speculation where ./serve turns it off by itself,
+# # for example on a CPU without AVX-512)
# ./bench/quick.sh --prompts 12 --tokens 256 --port 8191 --threads N
#
# It starts its own server on a spare port, so stop a running ./serve first on an 8 GB machine (two do not fit).
set -euo pipefail
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
-PORT=8191; NP=6; NTOK=128; PLAIN=0; THREADS=
+PORT=8191; NP=6; NTOK=128; PLAIN=0; SPECARM=0; THREADS=
while [ $# -gt 0 ]; do case $1 in
- --plain) PLAIN=1 ;; --prompts) NP=$2; shift ;; --tokens) NTOK=$2; shift ;; --port) PORT=$2; shift ;;
+ --plain) PLAIN=1 ;; --spec) SPECARM=1 ;; --prompts) NP=$2; shift ;; --tokens) NTOK=$2; shift ;; --port) PORT=$2; shift ;;
--threads) THREADS=$2; shift ;;
- -h|--help) sed -n 2,9p "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
+ -h|--help) sed -n 2,11p "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
*) echo "unknown option: $1" >&2; exit 2 ;; esac; shift; done
command -v python3 >/dev/null || { echo "python3 is needed" >&2; exit 1; }
PREFIX=${OPENSET_LLM_HOME:-$HOME/.openset-llm}
@@ -63,7 +65,7 @@ PY
cpu=$(grep -m1 'model name' /proc/cpuinfo | cut -d: -f2 | sed 's/^ //')
flags=" $(grep -m1 '^flags' /proc/cpuinfo | cut -d: -f2) "
-simd=; for f in avx2 avx512f avx512bw avx512_vnni avx512vbmi; do case "$flags" in *" $f "*) simd="$simd $f" ;; esac; done
+simd=; for f in avx2 avx_vnni avx512f avx512bw avx512_vnni avx512vbmi; do case "$flags" in *" $f "*) simd="$simd $f" ;; esac; done
cores=$(lscpu 2>/dev/null | awk -F: '/^Core\(s\) per socket/ {c=$2} /^Socket\(s\)/ {s=$2} END {if (c && s) print c * s}')
ram=$(awk '/^MemTotal:/ {printf "%.1f", $2 / 1048576}' /proc/meminfo)
commit=$(git -C "$HERE" rev-parse --short HEAD 2>/dev/null || echo "no git checkout")
@@ -74,6 +76,9 @@ arm "./serve" > "$ROWS"
if [ "$PLAIN" = 1 ]; then
arm "./serve --no-spec" --no-spec >> "$ROWS"
fi
+if [ "$SPECARM" = 1 ]; then
+ arm "./serve --spec" --spec >> "$ROWS"
+fi
rows=$(cat "$ROWS")
cat <<OUT
diff --git a/bench/test_quick_failures.py b/bench/test_quick_failures.py
index 083e927..d393b2c 100644
--- a/bench/test_quick_failures.py
+++ b/bench/test_quick_failures.py
@@ -8,7 +8,7 @@ import unittest
class QuickBenchmarkTest(unittest.TestCase):
- def run_quick(self, failure, plain=False):
+ def run_quick(self, failure, plain=False, spec=False):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "bench").mkdir()
@@ -27,7 +27,7 @@ class QuickBenchmarkTest(unittest.TestCase):
script(root / "serve", 'echo $$ > "$TEST_ROOT/server.pid"\necho "serving on test (synthetic mode)"\nexec sleep 60\n')
env = dict(os.environ, TEST_ROOT=str(root), TMPDIR=str(root), OPENSET_LLM_HOME=str(root / "home"),
PATH=str(root / "commands") + os.pathsep + os.environ["PATH"])
- proc = subprocess.Popen(["bash", str(root / "bench/quick.sh")] + (["--plain"] if plain else []),
+ proc = subprocess.Popen(["bash", str(root / "bench/quick.sh")] + (["--plain"] if plain else []) + (["--spec"] if spec else []),
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, start_new_session=True)
try:
@@ -54,6 +54,11 @@ class QuickBenchmarkTest(unittest.TestCase):
self.assertEqual(code, 0, stderr)
self.assertEqual(stdout.count("| synthetic result |"), 2)
+ def test_speculation_arm_adds_a_third_row(self):
+ code, stdout, stderr = self.run_quick(False, plain=True, spec=True)
+ self.assertEqual(code, 0, stderr)
+ self.assertEqual(stdout.count("| synthetic result |"), 3)
+
if __name__ == "__main__":
unittest.main()
diff --git a/install.sh b/install.sh
index c91862b..0dac664 100755
--- a/install.sh
+++ b/install.sh
@@ -2,7 +2,8 @@
# install.sh: build (or fetch) the engine and download the model. Then run ./serve.
#
# ./install.sh # CPU check, build for this machine, download + prepare the model
-# ./install.sh --portable # build one binary set for every x86-64 CPU (picks the best kernel at run time)
+# ./install.sh --portable # build one binary set for every x86-64 CPU (picks the best kernel at run time:
+# # AVX-512 where the CPU has it, the 256-bit AVX2 / AVX-VNNI kernels where it does not)
# ./install.sh --bin-url URL # fetch a prebuilt tarball (made by scripts/package.sh) instead of building
# ./install.sh --no-mtp # skip the speculative-decoding head (saves 1.4 GB of download; 1.4-1.9x slower)
# ./install.sh --check # only print what this machine will get, then exit
@@ -29,7 +30,7 @@ while [ $# -gt 0 ]; do
--no-mtp) MTP=0 ;;
--check) CHECK_ONLY=1 ;;
--model-only) MODEL_ONLY=1 ;;
- -h|--help) sed -n '2,11p' "$0"; exit 0 ;;
+ -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
*) echo "unknown option: $1" >&2; exit 2 ;;
esac
shift
@@ -49,8 +50,14 @@ cpu_path() {
echo "fast|AVX-512 VNNI + VBMI: full fast path"
elif has avx512f && has avx512bw && has avx512_vnni; then
echo "partial|AVX-512 VNNI without VBMI: partial fast path (slower than the full one)"
+ elif has avx512f && has avx2 && has fma && has f16c; then
+ echo "avx2|AVX-512 without VNNI: the 256-bit kernels (not measured on this CPU class)"
+ elif has avx2 && has fma && has f16c && has avx_vnni; then
+ echo "avx2|AVX2 + AVX-VNNI, no AVX-512: the 256-bit kernels (checked under an emulated CPU of this kind; not measured on one yet)"
+ elif has avx2 && has fma && has f16c; then
+ echo "avx2|AVX2, no AVX-512: the 256-bit kernels (0.7x of the AVX-512 path's plain decoding speed on an Ice Lake server with AVX-512 disabled)"
elif has avx2; then
- echo "fallback|AVX2 only: the fork's own ternary kernel. Same answers, but expect ~5x slower decode and much slower prompt reading"
+ echo "fallback|AVX2 without FMA: the fork's own ternary kernel. It will run, slowly"
else
echo "fallback|no AVX2: the generic kernel. It will run, slowly"
fi ;;
diff --git a/kernels/ptq1-avx2.inc b/kernels/ptq1-avx2.inc
new file mode 100644
index 0000000..aca4479
--- /dev/null
+++ b/kernels/ptq1-avx2.inc
@@ -0,0 +1,521 @@
+// ptq1-avx2: the PTQ1_0 ternary matmul for CPUs WITHOUT AVX-512. AVX2 + FMA + F16C only, plus AVX-VNNI (VEX vpdpbusd,
+// Intel Core 12th gen and newer, Zen 5) when the build has it.
+// A build without the AVX-512 kernels of ptq1-fast.inc runs this by default (GGML_PTQ1_AVX2=0 or GGML_PTQ1_FAST=0 = the
+// fork's own kernel). A build with them keeps them, and GGML_PTQ1_AVX2=1 selects this family instead (same-machine A/B).
+//
+// Decode without vpermb / vpmultishiftqb. A 16-bit word holds 10 trits as a base-3 number q < 3^10 = 59049, stored as
+// w = ceil(q * 65536 / 59049). Then (w * 9) >> 16 is the top base-9 digit (= two trits, 0..8) and w * 9 mod 65536 is the
+// encoding of the rest, so one decode stage is one vpmulhuw + one vpmullw per 16 words, both plain AVX2 (exact for every
+// q, checked exhaustively in tests/kernel_avx2.c). Two stages' words are packed to 32 bytes of digits with vpackuswb,
+// and two vpshufb (v % 3, v / 3) split each digit into its two trits, each landing as a full 32-byte code vector laid
+// out exactly as vpdpbusd wants it: lane l = row l, 4 consecutive k per lane. Per 64 trits: 2 vpmulhuw + 2 vpmullw +
+// 1 vpackuswb + 2 vpshufb = 7 uops on three ymm ports (Ice Lake and later run ymm ops on p0/p1/p5, zmm on two), vs the
+// 6-uop ptq1f_decode per 64 trits on two ports. Density 10 trits / 16 bits = 1.6 bpw, the same bytes as mode 4's
+// base-243 layout and 5 % fewer than the VBMI layout (1.684), so the repacked 27B is ~5.6 GB.
+//
+// Layout: panels of 8 rows (one ymm of int32 sums = 8 rows x 4 k). A panel is nck 64-byte chunks (32 words) then the
+// fp16 scales, 8 per 128-k group. Chunk c covers k in [40c, 40c + 40): word i (after the vpackuswb lane shuffle, see
+// ptq1a_wi) belongs to row i/4, j = i%4, and its stage s digit is trit(k = 40c + 8s + j) + 3 trit(k = 40c + 8s + 4 + j).
+// So stage s yields A = codes for k = 40c + 8s .. +3 and B = codes for 40c + 8s + 4 .. +7. k is padded to 160
+// (= lcm(40, 32)): a superblock of 4 chunks = 20 stages = 5 Q8_0 blocks, the flush points fixed at compile time.
+//
+// Dot product: vpdpbusd ymm (AVX-VNNI, or the EVEX form on an AVX-512 build) when available; otherwise vpmaddubsw +
+// vpaddw into an int16 accumulator per block (|pair sum| <= 508, |block sum| <= 8 x 508: no saturation) and one
+// vpmaddwd per block to widen. Either way every 32-k block sum is an exact int32, and the per-block float flush
+// (cvt, dx * dy, fma, in block order from 0) is the one ptq1v_panel / ptq1k4_tile do, so the outputs are bit-identical
+// to the AVX-512 paths (tests/kernel_avx2.c checks every path against a scalar reference).
+//
+// Paths (16 ymm registers, not 32, so the tiles are re-cut):
+// M = 1 ptq1a_panels: PTQ1A_NP panels interleaved per call (two weight streams per core, K5), 2 int chains each,
+// decode in registers, software prefetch PTQ1A_PF bytes ahead per stream.
+// M = 2..8 ptq1a_panels_m: one panel x 4 tokens per pass, decode and accumulators in registers (a speculation verify
+// batch, or the streams of --multi). GGML_PTQ1_AVX2_SMALLM=n moves the limit (0 = always ptq1a_gemm).
+// M > 8 ptq1a_gemm: K4's structure -- decode a k-chunk of PTQ1A_KC superblocks of 2 panels into an L1
+// buffer of code vectors once, then token tiles of PTQ1A_NT against it (per k-step: 2 code loads + NT
+// broadcasts + 2 NT dots, no table registers); the float accumulator of (token, 8 rows) is carried in dst
+// between chunks. The thread scheduling (shared quantize for M <= 8, dynamic panel chunks) is ptq1p_mul_mat's.
+#if defined(__AVX2__) && defined(__FMA__) && defined(__F16C__)
+#define PTQ1A_OK 1
+#include <immintrin.h>
+#include <pthread.h>
+#if defined(PTQ1A_FORCE_MADD) // test builds: the vpmaddubsw dot on a VNNI machine (identity of the two dots)
+#define PTQ1A_VNNI 0
+#elif defined(__AVXVNNI__)
+#define PTQ1A_VNNI 1
+#define PTQ1A_DPBUSD(acc, u, s) _mm256_dpbusd_avx_epi32((acc), (u), (s))
+#elif defined(__AVX512VNNI__) && defined(__AVX512VL__)
+#define PTQ1A_VNNI 1
+#define PTQ1A_DPBUSD(acc, u, s) _mm256_dpbusd_epi32((acc), (u), (s))
+#else
+#define PTQ1A_VNNI 0
+#endif
+
+#define PTQ1A_ROWS 8
+#define PTQ1A_KC_CHUNK 40 // k per 64-byte chunk
+#define PTQ1A_SB 4 // chunks per superblock (160 k = 5 Q8_0 blocks)
+#ifndef PTQ1A_NP
+#define PTQ1A_NP 2 // panels interleaved per M = 1 kernel call
+#endif
+#ifndef PTQ1A_PF
+#define PTQ1A_PF 1024 // M = 1 prefetch distance (bytes ahead per stream); 0 = none
+#endif
+#ifndef PTQ1A_NT
+#define PTQ1A_NT 4 // tokens per tile in ptq1a_gemm (2 panels x NT int accumulators + 2 codes + 1 bcast + 2 dxv <= 16 ymm)
+#endif
+#ifndef PTQ1A_KC
+#define PTQ1A_KC 8 // superblocks per k-chunk in ptq1a_gemm (2 panels x KC x 1280 B of codes in L1)
+#endif
+#ifndef PTQ1A_MB
+#define PTQ1A_MB 512 // tokens per token block (bounds the L2 activation chunk: MB x 160 KC bytes)
+#endif
+
+// the default: on where the AVX-512 kernels are not compiled in (the condition is ptq1-fast.inc's), off where they are
+#if defined(__AVX512F__) && defined(__AVX512BW__) && defined(__AVX512VNNI__)
+#define PTQ1A_DEFAULT 0
+#else
+#define PTQ1A_DEFAULT 1
+#endif
+static int ptq1a_on_cache = -1;
+static inline int ptq1a_on(void) {
+ if (ptq1a_on_cache < 0) {
+ const char * s = getenv("GGML_PTQ1_AVX2");
+ int on = s ? atoi(s) != 0 : PTQ1A_DEFAULT;
+#if PTQ1A_DEFAULT
+ const char * f = getenv("GGML_PTQ1_FAST"); // GGML_PTQ1_FAST=0 means the fork's own kernel on every build
+ if (f && atoi(f) == 0) on = 0;
+#endif
+ ptq1a_on_cache = on;
+ }
+ return ptq1a_on_cache;
+}
+
+// word index of output byte i after vpackuswb(lo = words 0..15, hi = words 16..31)
+static inline int ptq1a_wi(int i) { return i < 8 ? i : i < 16 ? i + 8 : i < 24 ? i - 8 : i; }
+
+static void ptq1a_init_entry(ptq1p_entry * e, const void * src, int64_t rows, int64_t k) {
+ e->src = src; e->rows = rows; e->k = k; e->nsb = 0; e->n36 = 0;
+ e->kpad = (k + PTQ1P_KPAD - 1) / PTQ1P_KPAD * PTQ1P_KPAD;
+ e->npanel = (rows + PTQ1A_ROWS - 1) / PTQ1A_ROWS;
+ e->nck = e->kpad / PTQ1A_KC_CHUNK;
+ e->ngp = (e->kpad + 127) / 128;
+ e->panel_stride = (e->nck * 64 + e->ngp * PTQ1A_ROWS * 2 + 63) / 64 * 64;
+}
+static inline int64_t ptq1a_data_bytes(const ptq1p_entry * e) { return e->nck * 64; }
+
+// codes: PTQ1A_ROWS rows of kpad trits {0,1,2} (row stride kpad) -> the panel's chunks at dst
+static void ptq1a_pack_codes(const uint8_t * codes, int64_t kpad, uint8_t * dst) {
+ for (int64_t c = 0; c < kpad / PTQ1A_KC_CHUNK; ++c)
+ for (int i = 0; i < 32; ++i) {
+ const int r = i / 4, j = i % 4;
+ uint32_t q = 0;
+ for (int s = 0; s < 5; ++s) {
+ const uint8_t * row = codes + r * kpad + c * PTQ1A_KC_CHUNK + 8 * s + j;
+ q = q * 9 + row[0] + 3 * row[4];
+ }
+ const uint16_t w = (uint16_t) (((uint64_t) q * 65536 + 59048) / 59049);
+ memcpy(dst + c * 64 + 2 * ptq1a_wi(i), &w, 2);
+ }
+}
+
+static void ptq1a_repack_panels(ptq1p_entry * e, int64_t p0, int64_t p1) {
+ const int64_t nb = e->k / 128;
+ uint8_t * codes = malloc((size_t) (PTQ1A_ROWS * e->kpad));
+ for (int64_t p = p0; p < p1; ++p) {
+ memset(codes, 1, (size_t) (PTQ1A_ROWS * e->kpad)); // trit 1 == weight 0
+ uint8_t * dst = e->packed + p * e->panel_stride;
+ ggml_half * sc = (ggml_half *) (dst + ptq1a_data_bytes(e));
+ memset(sc, 0, (size_t) (e->ngp * PTQ1A_ROWS * 2));
+ for (int r = 0; r < PTQ1A_ROWS; ++r) {
+ const int64_t row = p * PTQ1A_ROWS + r;
+ if (row >= e->rows) continue;
+ const block_ptq1_0 * src = (const block_ptq1_0 *) e->src + row * nb;
+ for (int64_t b = 0; b < nb; ++b) {
+ ptq1f_unpack_block(src + b, codes + r * e->kpad + b * 128);
+ sc[b * PTQ1A_ROWS + r] = src[b].d;
+ }
+ }
+ ptq1a_pack_codes(codes, e->kpad, dst);
+ }
+ free(codes);
+}
+
+// vpshufb tables, per 128-bit lane: digit v (0..8) -> v % 3 and v / 3. Constants, not a load-time constructor (a
+// --portable build loads every CPU variant of this library before it knows which one the CPU can run).
+static const uint8_t ptq1a_tab[2][32] __attribute__((aligned(32))) = {
+ { 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0 },
+ { 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0 }
+};
+
+// The Q8_0 quantizer of ptq1p_quantize_col_part_kp in AVX2: same q, same -sum(q), same fp16-rounded d per block.
+// roundf (half away from zero) is reproduced as trunc, then +-1 where |v - trunc(v)| >= 0.5 (exact in float).
+static void ptq1a_quantize_part(const float * x, int64_t k, int64_t kpad, uint8_t * out, int64_t b0, int64_t b1, int neg_asum) {
+ int8_t * q = (int8_t *) out;
+ float * dy = (float *) (out + kpad);
+ int32_t * asum = (int32_t *) (dy + kpad / 32);
+ if (b0 == 0) {
+ memset(q + k, 0, (size_t) (kpad - k));
+ for (int64_t b = k / 32; b < kpad / 32; ++b) { dy[b] = 0.0f; asum[b] = 0; }
+ }
+ const __m256 half = _mm256_set1_ps(0.5f), one = _mm256_set1_ps(1.0f), mone = _mm256_set1_ps(-1.0f), zero = _mm256_setzero_ps();
+ const __m256 absm = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));
+ const __m256i lanes = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7);
+ for (int64_t b = b0; b < b1; ++b) {
+ __m256 xv[4], am = zero;
+ for (int h = 0; h < 4; ++h) { xv[h] = _mm256_loadu_ps(x + b * 32 + 8 * h); am = _mm256_max_ps(am, _mm256_and_ps(xv[h], absm)); }
+ __m128 m4 = _mm_max_ps(_mm256_castps256_ps128(am), _mm256_extractf128_ps(am, 1));
+ m4 = _mm_max_ps(m4, _mm_movehl_ps(m4, m4)); m4 = _mm_max_ss(m4, _mm_shuffle_ps(m4, m4, 1));
+ const float amax = _mm_cvtss_f32(m4);
+ const float d = amax / ((1 << 7) - 1);
+ const float id = d ? 1.0f / d : 0.0f;
+ const __m256 idv = _mm256_set1_ps(id);
+ __m256i qi[4], sv = _mm256_setzero_si256();
+ for (int h = 0; h < 4; ++h) {
+ const __m256 v = _mm256_mul_ps(xv[h], idv);
+ const __m256 r = _mm256_round_ps(v, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC);
+ const __m256 away = _mm256_cmp_ps(_mm256_and_ps(_mm256_sub_ps(v, r), absm), half, _CMP_GE_OQ);
+ const __m256 sg = _mm256_blendv_ps(one, mone, _mm256_cmp_ps(v, zero, _CMP_LT_OQ));
+ qi[h] = _mm256_cvttps_epi32(_mm256_add_ps(r, _mm256_and_ps(away, sg)));
+ sv = _mm256_add_epi32(sv, qi[h]);
+ }
+ const __m256i p16a = _mm256_packs_epi32(qi[0], qi[1]), p16b = _mm256_packs_epi32(qi[2], qi[3]);
+ const __m256i p8 = _mm256_permutevar8x32_epi32(_mm256_packs_epi16(p16a, p16b), lanes);
+ _mm256_storeu_si256((__m256i *) (q + b * 32), p8);
+ __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(sv), _mm256_extracti128_si256(sv, 1));
+ s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0x4e)); s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xb1));
+ const int s = _mm_cvtsi128_si32(s4);
+ dy[b] = GGML_CPU_FP16_TO_FP32(GGML_CPU_FP32_TO_FP16(d));
+ asum[b] = neg_asum ? -s : s;
+ }
+}
+
+// ---- the dot-product step and the block flush, shared by the kernels below ---------------------------------------
+#if PTQ1A_VNNI
+#define PTQ1A_ACC_INIT(nas) (nas) // chain 0 starts at -sum(q)
+#define PTQ1A_DOT(acc, codes, bq) (acc) = PTQ1A_DPBUSD((acc), (codes), (bq))
+#define PTQ1A_SUM(a0, a1, nas) _mm256_add_epi32((a0), (a1))
+#else
+#define PTQ1A_ACC_INIT(nas) _mm256_setzero_si256()
+#define PTQ1A_DOT(acc, codes, bq) (acc) = _mm256_add_epi16((acc), _mm256_maddubs_epi16((codes), (bq)))
+#define PTQ1A_SUM(a0, a1, nas) _mm256_add_epi32(_mm256_add_epi32(_mm256_madd_epi16((a0), ones), _mm256_madd_epi16((a1), ones)), (nas))
+#endif
+#if PTQ1A_VNNI
+#define PTQ1A_SUM1(a, nas) (a)
+#else
+#define PTQ1A_SUM1(a, nas) _mm256_add_epi32(_mm256_madd_epi16((a), ones), (nas))
+#endif
+#define PTQ1A_FLUSH(accf, a0, a1, nas, dxv, dyb) (accf) = _mm256_fmadd_ps(_mm256_cvtepi32_ps(PTQ1A_SUM(a0, a1, nas)), _mm256_mul_ps((dxv), (dyb)), (accf))
+
+// one chunk's two word vectors at stage s: digits (packed), then the A and B code vectors
+#define PTQ1A_STAGE(w0, w1, s, A, B) do { \
+ const __m256i h0_ = _mm256_mulhi_epu16((w0), nine), h1_ = _mm256_mulhi_epu16((w1), nine); \
+ if ((s) < 4) { (w0) = _mm256_mullo_epi16((w0), nine); (w1) = _mm256_mullo_epi16((w1), nine); } \
+ const __m256i d_ = _mm256_packus_epi16(h0_, h1_); \
+ (A) = _mm256_shuffle_epi8(t0, d_); (B) = _mm256_shuffle_epi8(t1, d_); \
+ } while (0)
+#define PTQ1A_STAGE_DECL
+
+// M = 1: NP panels (panel, panel + stride, ...) x one token, chunk by chunk, each panel 2 int chains (A and B).
+// Per panel per 32-k block: 4 stages x (7 decode + 2 dot) + 3 flush uops, int sums exact, flush in block order.
+static inline __attribute__((always_inline)) void ptq1a_panel_np(
+ const ptq1p_entry * e, const uint8_t * panel, const uint8_t * acts, const int NP, const int PF, float * dst, int64_t row0) {
+ const int64_t kpad = e->kpad;
+ const int8_t * q = (const int8_t *) acts; const float * dy = (const float *) (acts + kpad); const int32_t * as = (const int32_t *) (dy + kpad / 32);
+ const __m256i nine = _mm256_set1_epi16(9), t0 = _mm256_load_si256((const __m256i *) ptq1a_tab[0]), t1 = _mm256_load_si256((const __m256i *) ptq1a_tab[1]);
+#if !PTQ1A_VNNI
+ const __m256i ones = _mm256_set1_epi16(1);
+#endif
+ const uint8_t * P[PTQ1A_NP]; const ggml_half * sc[PTQ1A_NP];
+ __m256 accf[PTQ1A_NP], dxv[PTQ1A_NP]; __m256i a0[PTQ1A_NP], a1[PTQ1A_NP];
+ for (int p = 0; p < NP; ++p) {
+ P[p] = panel + p * e->panel_stride; sc[p] = (const ggml_half *) (P[p] + ptq1a_data_bytes(e));
+ accf[p] = _mm256_setzero_ps(); dxv[p] = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *) sc[p]));
+ a0[p] = PTQ1A_ACC_INIT(_mm256_set1_epi32(as[0])); a1[p] = _mm256_setzero_si256();
+ }
+ for (int64_t sb = 0; sb < e->nck / PTQ1A_SB; ++sb) {
+ const int64_t c0 = sb * PTQ1A_SB, b0 = sb * 5;
+#pragma GCC unroll 4
+ for (int c = 0; c < PTQ1A_SB; ++c) {
+ for (int p = 0; p < NP; ++p) {
+ const uint8_t * ch = P[p] + (c0 + c) * 64;
+ if (PF) _mm_prefetch((const char *) ch + PF, _MM_HINT_T0);
+ __m256i w0 = _mm256_loadu_si256((const __m256i *) ch), w1 = _mm256_loadu_si256((const __m256i *) (ch + 32));
+ PTQ1A_STAGE_DECL
+#pragma GCC unroll 5
+ for (int s = 0; s < 5; ++s) {
+ __m256i A, B;
+ PTQ1A_STAGE(w0, w1, s, A, B);
+ const int64_t k0 = (c0 + c) * PTQ1A_KC_CHUNK + 8 * s;
+ PTQ1A_DOT(a0[p], A, _mm256_set1_epi32(*(const int32_t *) (q + k0)));
+ PTQ1A_DOT(a1[p], B, _mm256_set1_epi32(*(const int32_t *) (q + k0 + 4)));
+ if ((c * 5 + s) % 4 == 3) { // end of a 32-k block
+ const int64_t b = b0 + (c * 5 + s) / 4;
+ const __m256i nas = _mm256_set1_epi32(as[b]), nas1 = _mm256_set1_epi32(as[b + 1]);
+ PTQ1A_FLUSH(accf[p], a0[p], a1[p], nas, dxv[p], _mm256_set1_ps(dy[b]));
+ if (((b + 1) & 3) == 0) dxv[p] = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *) (sc[p] + ((b + 1) >> 2) * PTQ1A_ROWS)));
+ a0[p] = PTQ1A_ACC_INIT(nas1); a1[p] = _mm256_setzero_si256();
+ (void) nas; (void) nas1;
+ }
+ }
+ }
+ }
+ }
+ for (int p = 0; p < NP; ++p) {
+ const int64_t r0 = row0 + p * PTQ1A_ROWS;
+ const int64_t nr = (e->rows - r0) < PTQ1A_ROWS ? (e->rows - r0) : PTQ1A_ROWS;
+ if (nr <= 0) continue;
+ if (nr == PTQ1A_ROWS) _mm256_storeu_ps(dst + r0, accf[p]);
+ else { float tmp[8]; _mm256_storeu_ps(tmp, accf[p]); memcpy(dst + r0, tmp, (size_t) nr * 4); }
+ }
+}
+// panels [p0, p1) in groups of PTQ1A_NP, the rest one at a time
+static void ptq1a_panels(const ptq1p_entry * e, const uint8_t * acts, float * dst, int64_t p0, int64_t p1) {
+ int64_t p = p0;
+ for (; p + PTQ1A_NP <= p1; p += PTQ1A_NP) ptq1a_panel_np(e, e->packed + p * e->panel_stride, acts, PTQ1A_NP, PTQ1A_PF, dst, p * PTQ1A_ROWS);
+ for (; p < p1; ++p) ptq1a_panel_np(e, e->packed + p * e->panel_stride, acts, 1, PTQ1A_PF, dst, p * PTQ1A_ROWS);
+}
+
+// M = 2..8 (a speculation verify batch, the streams of --multi): one panel x NT <= 4 tokens, everything in registers. Each stage is decoded once
+// and every token adds its two dots to ONE integer accumulator (int16 form: a 32-k block is 8 pair sums of at most 508
+// per lane, no saturation), so a 4-token pass costs about twice a 1-token pass (through ptq1a_gemm it costs 4 times). Same exact int32
+// block sums and the same per-block flush as the kernels above and below: bit-identical to both.
+static inline __attribute__((always_inline)) void ptq1a_panel_nt(
+ const ptq1p_entry * e, const uint8_t * panel, const uint8_t * acts, size_t cb, const int NT, const int PF, float * dst, int64_t ld, int64_t row0) {
+ const int64_t kpad = e->kpad;
+ const int8_t * q[PTQ1A_NT]; const float * dy[PTQ1A_NT]; const int32_t * as[PTQ1A_NT];
+ for (int t = 0; t < NT; ++t) {
+ const uint8_t * base = acts + (size_t) t * cb;
+ q[t] = (const int8_t *) base; dy[t] = (const float *) (base + kpad); as[t] = (const int32_t *) (dy[t] + kpad / 32);
+ }
+ const __m256i nine = _mm256_set1_epi16(9), t0 = _mm256_load_si256((const __m256i *) ptq1a_tab[0]), t1 = _mm256_load_si256((const __m256i *) ptq1a_tab[1]);
+#if !PTQ1A_VNNI
+ const __m256i ones = _mm256_set1_epi16(1);
+#endif
+ const ggml_half * sc = (const ggml_half *) (panel + ptq1a_data_bytes(e));
+ __m256 accf[PTQ1A_NT]; __m256i acc[PTQ1A_NT];
+ __m256 dxv = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *) sc));
+ for (int t = 0; t < NT; ++t) { accf[t] = _mm256_setzero_ps(); acc[t] = PTQ1A_ACC_INIT(_mm256_set1_epi32(as[t][0])); }
+ for (int64_t sb = 0; sb < e->nck / PTQ1A_SB; ++sb) {
+ const int64_t c0 = sb * PTQ1A_SB, b0 = sb * 5;
+#pragma GCC unroll 4
+ for (int c = 0; c < PTQ1A_SB; ++c) {
+ const uint8_t * ch = panel + (c0 + c) * 64;
+ if (PF) _mm_prefetch((const char *) ch + PF, _MM_HINT_T0);
+ __m256i w0 = _mm256_loadu_si256((const __m256i *) ch), w1 = _mm256_loadu_si256((const __m256i *) (ch + 32));
+#pragma GCC unroll 5
+ for (int s = 0; s < 5; ++s) {
+ __m256i A, B;
+ PTQ1A_STAGE(w0, w1, s, A, B);
+ const int64_t k0 = (c0 + c) * PTQ1A_KC_CHUNK + 8 * s;
+ for (int t = 0; t < NT; ++t) {
+ PTQ1A_DOT(acc[t], A, _mm256_set1_epi32(*(const int32_t *) (q[t] + k0)));
+ PTQ1A_DOT(acc[t], B, _mm256_set1_epi32(*(const int32_t *) (q[t] + k0 + 4)));
+ }
+ if ((c * 5 + s) % 4 == 3) { // end of a 32-k block
+ const int64_t b = b0 + (c * 5 + s) / 4;
+ for (int t = 0; t < NT; ++t) {
+ const __m256i nas = _mm256_set1_epi32(as[t][b]);
+ accf[t] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(PTQ1A_SUM1(acc[t], nas)), _mm256_mul_ps(dxv, _mm256_set1_ps(dy[t][b])), accf[t]);
+ acc[t] = PTQ1A_ACC_INIT(_mm256_set1_epi32(as[t][b + 1]));
+ (void) nas;
+ }
+ if (((b + 1) & 3) == 0) dxv = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *) (sc + ((b + 1) >> 2) * PTQ1A_ROWS)));
+ }
+ }
+ }
+ }
+ const int64_t nr = (e->rows - row0) < PTQ1A_ROWS ? (e->rows - row0) : PTQ1A_ROWS;
+ for (int t = 0; t < NT; ++t) {
+ if (nr == PTQ1A_ROWS) _mm256_storeu_ps(dst + t * ld + row0, accf[t]);
+ else { float tmp[8]; _mm256_storeu_ps(tmp, accf[t]); memcpy(dst + t * ld + row0, tmp, (size_t) nr * 4); }
+ }
+}
+// panels [p0, p1) x m tokens in tiles of up to PTQ1A_NT (m <= 4 is one pass over each panel, 5..8 two)
+static void ptq1a_panels_m(const ptq1p_entry * e, const uint8_t * acts, size_t cb, int64_t m, int64_t p0, int64_t p1, float * dst, int64_t ld) {
+ for (int64_t p = p0; p < p1; ++p) {
+ const uint8_t * panel = e->packed + p * e->panel_stride;
+ for (int64_t t0 = 0; t0 < m; t0 += PTQ1A_NT) {
+ const uint8_t * a = acts + (size_t) t0 * cb; float * d = dst + t0 * ld;
+ switch (m - t0 < PTQ1A_NT ? (int) (m - t0) : PTQ1A_NT) {
+ case 1: ptq1a_panel_nt(e, panel, a, cb, 1, PTQ1A_PF, d, ld, p * PTQ1A_ROWS); break;
+ case 2: ptq1a_panel_nt(e, panel, a, cb, 2, PTQ1A_PF, d, ld, p * PTQ1A_ROWS); break;
+ case 3: ptq1a_panel_nt(e, panel, a, cb, 3, PTQ1A_PF, d, ld, p * PTQ1A_ROWS); break;
+ default: ptq1a_panel_nt(e, panel, a, cb, PTQ1A_NT, PTQ1A_PF, d, ld, p * PTQ1A_ROWS); break;
+ }
+ }
+ }
+}
+
+// one chunk (40 k) -> 10 code vectors: out[2s] = A (k = 40c + 8s..), out[2s + 1] = B
+static inline __attribute__((always_inline)) void ptq1a_decode_chunk(const uint8_t * ch, __m256i * out) {
+ const __m256i nine = _mm256_set1_epi16(9), t0 = _mm256_load_si256((const __m256i *) ptq1a_tab[0]), t1 = _mm256_load_si256((const __m256i *) ptq1a_tab[1]);
+ __m256i w0 = _mm256_loadu_si256((const __m256i *) ch), w1 = _mm256_loadu_si256((const __m256i *) (ch + 32));
+ PTQ1A_STAGE_DECL
+#pragma GCC unroll 5
+ for (int s = 0; s < 5; ++s) PTQ1A_STAGE(w0, w1, s, out[2 * s], out[2 * s + 1]);
+}
+
+// 2 panels x NT tokens x nblk blocks of decoded codes (codes[0..] panel 0, codes[cstride..] panel 1; 8 vectors per
+// block). q[t] points at the tokens' activations pre-offset to the chunk's first k; the float accumulator of (panel,
+// token) lives in dst[p] + t * ld (zeroed by first). msk[p]: row mask of a partial last panel (NULL = all 8 rows).
+static inline __attribute__((always_inline)) void ptq1a_tile(
+ const __m256i * codes, int cstride, int nblk, const ggml_half * const * sc, int64_t b0, const int np,
+ const int8_t * const * q, const float * const * dy, const int32_t * const * as,
+ float * const * dst, int64_t ld, const __m256i * const * msk, int first, const int NT) {
+#if !PTQ1A_VNNI
+ const __m256i ones = _mm256_set1_epi16(1);
+#endif
+ __m256i acc[2][PTQ1A_NT]; __m256 dxv[2];
+ for (int p = 0; p < 2; ++p) {
+ for (int t = 0; t < NT; ++t) acc[p][t] = PTQ1A_ACC_INIT(_mm256_set1_epi32(as[t][b0]));
+ dxv[p] = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *) (sc[p < np ? p : 0] + (b0 >> 2) * PTQ1A_ROWS)));
+ }
+ for (int b = 0; b < nblk; ++b) {
+#pragma GCC unroll 8
+ for (int s = 0; s < 8; ++s) {
+ const __m256i c0 = codes[8 * b + s], c1 = codes[cstride + 8 * b + s];
+ for (int t = 0; t < NT; ++t) {
+ const __m256i a = _mm256_set1_epi32(*(const int32_t *) (q[t] + 32 * b + 4 * s));
+ PTQ1A_DOT(acc[0][t], c0, a);
+ PTQ1A_DOT(acc[1][t], c1, a);
+ }
+ }
+ const int64_t gb = b0 + b;
+ for (int t = 0; t < NT; ++t) {
+ const __m256 dyv = _mm256_set1_ps(dy[t][gb]);
+ const __m256i nas = _mm256_set1_epi32(as[t][gb]), nas1 = _mm256_set1_epi32(as[t][gb + 1]);
+ for (int p = 0; p < np; ++p) {
+ float * d = dst[p] + t * ld;
+ __m256 accf = (first && b == 0) ? _mm256_setzero_ps() : (msk[p] ? _mm256_maskload_ps(d, *msk[p]) : _mm256_loadu_ps(d));
+ accf = _mm256_fmadd_ps(_mm256_cvtepi32_ps(PTQ1A_SUM1(acc[p][t], nas)), _mm256_mul_ps(dxv[p], dyv), accf);
+ if (msk[p]) _mm256_maskstore_ps(d, *msk[p], accf); else _mm256_storeu_ps(d, accf);
+ }
+ for (int p = 0; p < 2; ++p) acc[p][t] = PTQ1A_ACC_INIT(nas1);
+ (void) nas; (void) nas1;
+ }
+ if (((gb + 1) & 3) == 0) for (int p = 0; p < 2; ++p) dxv[p] = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *) (sc[p < np ? p : 0] + ((gb + 1) >> 2) * PTQ1A_ROWS)));
+ }
+}
+
+// panels [p0, p1) x all m tokens (M >= 2): per token block, per k-chunk of KC superblocks, per panel pair: decode the
+// pair's chunk into L1 once, prefetch the next pair's chunk, then token tiles of NT against it.
+static void ptq1a_gemm(const ptq1p_entry * e, const uint8_t * acts, size_t cb, int64_t m, int64_t p0, int64_t p1, float * dst, int64_t ld) {
+ const int KC = PTQ1A_KC, cstride = KC * PTQ1A_SB * 10;
+ __m256i codes[2 * PTQ1A_KC * PTQ1A_SB * 10] __attribute__((aligned(64)));
+ const int64_t kpad = e->kpad, nsbt = e->nck / PTQ1A_SB;
+ for (int64_t m0 = 0; m0 < m; m0 += PTQ1A_MB) {
+ const int64_t m1 = m0 + PTQ1A_MB < m ? m0 + PTQ1A_MB : m;
+ for (int64_t sb = 0; sb < nsbt; sb += KC) {
+ const int64_t sb1 = sb + KC < nsbt ? sb + KC : nsbt;
+ const int nblk = (int) ((sb1 - sb) * 5), nck = (int) ((sb1 - sb) * PTQ1A_SB);
+ const int64_t choff = sb * PTQ1A_SB * 64, s0 = sb * PTQ1A_SB * PTQ1A_KC_CHUNK, b0 = sb * 5;
+ for (int64_t p = p0; p < p1; p += 2) {
+ const int np = (int) (p1 - p < 2 ? p1 - p : 2);
+ const ggml_half * sc[2]; float * d[2]; __m256i mk[2]; const __m256i * msk[2];
+ for (int i = 0; i < np; ++i) {
+ const uint8_t * panel = e->packed + (p + i) * e->panel_stride;
+ for (int c = 0; c < nck; ++c) ptq1a_decode_chunk(panel + choff + c * 64, codes + i * cstride + c * 10);
+ sc[i] = (const ggml_half *) (panel + ptq1a_data_bytes(e));
+ const int64_t row0 = (p + i) * PTQ1A_ROWS;
+ const int nr = (int) ((e->rows - row0) < PTQ1A_ROWS ? (e->rows - row0) : PTQ1A_ROWS);
+ mk[i] = _mm256_setr_epi32(nr > 0 ? -1 : 0, nr > 1 ? -1 : 0, nr > 2 ? -1 : 0, nr > 3 ? -1 : 0, nr > 4 ? -1 : 0, nr > 5 ? -1 : 0, nr > 6 ? -1 : 0, nr > 7 ? -1 : 0);
+ msk[i] = nr == PTQ1A_ROWS ? NULL : &mk[i];
+ d[i] = dst + m0 * ld + row0;
+ }
+ for (int i = 0; i < np && p + np + i < p1; ++i) { // next pair's chunk: a cold DRAM/L3 read otherwise
+ const uint8_t * nxt = e->packed + (p + np + i) * e->panel_stride + choff;
+ for (int o = 0; o < nck * 64; o += 64) _mm_prefetch((const char *) nxt + o, _MM_HINT_T1);
+ }
+ for (int64_t t0 = m0; t0 < m1; t0 += PTQ1A_NT) {
+ const int nt = (int) (m1 - t0 < PTQ1A_NT ? m1 - t0 : PTQ1A_NT);
+ const int8_t * q[PTQ1A_NT]; const float * dy[PTQ1A_NT]; const int32_t * as[PTQ1A_NT]; float * dd[2];
+ for (int t = 0; t < nt; ++t) {
+ const uint8_t * base = acts + (size_t) (t0 + t) * cb;
+ q[t] = (const int8_t *) base + s0; dy[t] = (const float *) (base + kpad); as[t] = (const int32_t *) (dy[t] + kpad / 32);
+ }
+ for (int i = 0; i < np; ++i) dd[i] = d[i] + (t0 - m0) * ld;
+ switch (nt) {
+ case 1: ptq1a_tile(codes, cstride, nblk, sc, b0, np, q, dy, as, dd, ld, msk, sb == 0, 1); break;
+ case 2: ptq1a_tile(codes, cstride, nblk, sc, b0, np, q, dy, as, dd, ld, msk, sb == 0, 2); break;
+ case 3: ptq1a_tile(codes, cstride, nblk, sc, b0, np, q, dy, as, dd, ld, msk, sb == 0, 3); break;
+ default: ptq1a_tile(codes, cstride, nblk, sc, b0, np, q, dy, as, dd, ld, msk, sb == 0, PTQ1A_NT); break;
+ }
+ }
+ }
+ }
+ }
+}
+
+#ifndef PTQ1F_NO_GGML
+static ptq1p_entry * ptq1a_list = NULL;
+static pthread_mutex_t ptq1a_mu = PTHREAD_MUTEX_INITIALIZER;
+static int ptq1a_smallm_cache = -1;
+static inline int ptq1a_smallm(void) { // tokens per call up to which the in-register kernel runs
+ if (ptq1a_smallm_cache < 0) { const char * s = getenv("GGML_PTQ1_AVX2_SMALLM"); ptq1a_smallm_cache = s ? atoi(s) : 8; }
+ return ptq1a_smallm_cache;
+}
+static size_t ptq1a_wsize(const struct ggml_tensor * src0, const struct ggml_tensor * src1) { return ptq1p_col_bytes(src0->ne[0]) * (size_t) src1->ne[1] + 64; }
+
+// ptq1p_mul_mat's scheduling on the AVX2 kernels: lock-free entry lookup, first-use repack split across threads,
+// every thread quantizes a slice of every token's blocks for M <= 8 (one token per thread past that), one barrier,
+// then dynamic panel chunks (ggml_threadpool_chunk_add) for every M.
+static bool ptq1a_mul_mat(const struct ggml_compute_params * params, struct ggml_tensor * dst) {
+ const struct ggml_tensor * src0 = dst->src[0];
+ const struct ggml_tensor * src1 = dst->src[1];
+ const int ith = params->ith, nth = params->nth;
+ const int64_t k = src0->ne[0], rows = src0->ne[1], m = src1->ne[1];
+ ptq1p_entry * e = NULL;
+ for (ptq1p_entry * it = __atomic_load_n(&ptq1a_list, __ATOMIC_ACQUIRE); it; it = it->next) if (it->src == src0->data) { e = it; break; }
+ if (!e) {
+ ggml_barrier(params->threadpool);
+ if (ith == 0) {
+ ptq1p_entry * ne = calloc(1, sizeof(*ne));
+ ptq1a_init_entry(ne, src0->data, rows, k);
+ // + 64: the kernels load the scale vector of the group after the last one (and never use it)
+ ne->packed = aligned_alloc(64, (size_t) ((ne->panel_stride * ne->npanel + 63) / 64 * 64 + 64));
+ pthread_mutex_lock(&ptq1a_mu); ne->next = ptq1a_list; __atomic_store_n(&ptq1a_list, ne, __ATOMIC_RELEASE); pthread_mutex_unlock(&ptq1a_mu);
+ }
+ ggml_barrier(params->threadpool);
+ for (ptq1p_entry * it = __atomic_load_n(&ptq1a_list, __ATOMIC_ACQUIRE); it; it = it->next) if (it->src == src0->data) { e = it; break; }
+ const int64_t per = (e->npanel + nth - 1) / nth;
+ ptq1a_repack_panels(e, PTQ1F_MIN(e->npanel, ith * per), PTQ1F_MIN(e->npanel, (ith + 1) * per));
+ // GGML_PTQ1_DROP (ptq1-drop.h): the last thread to finish its panels gives the GGUF pages back
+ if (__atomic_add_fetch(&e->ndone, 1, __ATOMIC_ACQ_REL) == nth)
+ ptq1d_drop(src0->data, ggml_nbytes(src0), strcmp(src0->name, "x1_draft_head") == 0);
+ }
+ const size_t cb = ptq1p_col_bytes(k);
+ uint8_t * acts = (uint8_t *) (((uintptr_t) params->wdata + 63) & ~(uintptr_t) 63);
+ ggml_threadpool_chunk_set(params->threadpool, nth);
+ if (m <= PTQ1P_TB) {
+ const int64_t nb = k / 32, per = (nb + nth - 1) / nth;
+ for (int64_t t = 0; t < m; ++t)
+ ptq1a_quantize_part((const float *) ((const char *) src1->data + t * src1->nb[1]), k, e->kpad, acts + t * cb, PTQ1F_MIN(nb, ith * per), PTQ1F_MIN(nb, (ith + 1) * per), 1);
+ } else {
+ for (int64_t t = ith; t < m; t += nth)
+ ptq1a_quantize_part((const float *) ((const char *) src1->data + t * src1->nb[1]), k, e->kpad, acts + t * cb, 0, k / 32, 1);
+ }
+ ggml_barrier(params->threadpool);
+ float * out = (float *) dst->data; const int64_t ld = dst->nb[1] / sizeof(float);
+ if (m == 1) {
+ int64_t ch = PTQ1F_MIN(16, (e->npanel + 8 * nth - 1) / (8 * nth)); ch = (ch + 1) / 2 * 2; // whole panel pairs
+ const int64_t nch = (e->npanel + ch - 1) / ch;
+ for (int64_t c = ith; c < nch; c = ggml_threadpool_chunk_add(params->threadpool, 1))
+ ptq1a_panels(e, acts, out, c * ch, PTQ1F_MIN(e->npanel, (c + 1) * ch));
+ } else if (m <= ptq1a_smallm()) {
+ const int64_t ch = PTQ1F_MIN(8, (e->npanel + 8 * nth - 1) / (8 * nth));
+ const int64_t nch = (e->npanel + ch - 1) / ch;
+ for (int64_t c = ith; c < nch; c = ggml_threadpool_chunk_add(params->threadpool, 1))
+ ptq1a_panels_m(e, acts, cb, m, c * ch, PTQ1F_MIN(e->npanel, (c + 1) * ch), out, ld);
+ } else {
+ const int64_t ch = PTQ1F_MIN(16, ((e->npanel + 8 * nth - 1) / (8 * nth) + 1) / 2 * 2); // whole panel pairs
+ const int64_t nch = (e->npanel + ch - 1) / ch;
+ for (int64_t c = ith; c < nch; c = ggml_threadpool_chunk_add(params->threadpool, 1))
+ ptq1a_gemm(e, acts, cb, m, c * ch, PTQ1F_MIN(e->npanel, (c + 1) * ch), out, ld);
+ }
+ return true;
+}
+#endif
+#else
+#define PTQ1A_OK 0
+#endif
diff --git a/kernels/ptq1-fast.inc b/kernels/ptq1-fast.inc
index 662ea29..00572ae 100644
--- a/kernels/ptq1-fast.inc
+++ b/kernels/ptq1-fast.inc
@@ -16,6 +16,10 @@
// speculative verification amortize the decode instead of repeating it.
#include "ptq1-common.h"
#include "ptq1-drop.h"
+#ifndef PTQ1F_MIN
+#define PTQ1F_MIN(a, b) ((a) < (b) ? (a) : (b))
+#endif
+#include "ptq1-avx2.inc" // the 256-bit kernels: the default on a build without AVX-512, GGML_PTQ1_AVX2=1 on one with it
#if defined(__AVX512F__) && defined(__AVX512BW__) && defined(__AVX512VNNI__)
#include <immintrin.h>
@@ -77,6 +81,9 @@ static size_t ptq1p_col_bytes(int64_t k);
static size_t ptq1v_col_bytes(int64_t k);
#endif
static size_t ptq1f_wsize(const struct ggml_tensor * src0, const struct ggml_tensor * src1) {
+#if PTQ1A_OK
+ if (ptq1a_on()) return ptq1a_wsize(src0, src1);
+#endif
#if defined(__AVX512VBMI__)
if (ptq1f_mode() >= 5) return ptq1v_col_bytes(src0->ne[0]) * (size_t) src1->ne[1] + 64;
#endif
@@ -317,6 +324,9 @@ static bool ptq1f_mul_mat(const struct ggml_compute_params * params, struct ggml
const struct ggml_tensor * src0 = dst->src[0];
const struct ggml_tensor * src1 = dst->src[1];
if (!ptq1f_applies(src0, src1)) return false;
+#if PTQ1A_OK
+ if (ptq1a_on()) return ptq1a_mul_mat(params, dst);
+#endif
if (ptq1f_mode() >= 3) return ptq1p_mul_mat(params, dst);
const int ith = params->ith, nth = params->nth;
const int64_t k = src0->ne[0], rows = src0->ne[1], m = src1->ne[1];
@@ -360,9 +370,24 @@ static bool ptq1f_mul_mat(const struct ggml_compute_params * params, struct ggml
}
#endif
#else
+#if PTQ1A_OK && !defined(PTQ1F_NO_GGML)
+// no AVX-512 kernels in this build: the 256-bit kernels of ptq1-avx2.inc (AVX2, with AVX-VNNI when the build has it).
+// GGML_PTQ1_AVX2=0 or GGML_PTQ1_FAST=0 leaves the matmul to the fork's own kernel.
+static bool ptq1f_applies(const struct ggml_tensor * src0, const struct ggml_tensor * src1) {
+ return src0->type == GGML_TYPE_PTQ1_0 && src1->type == GGML_TYPE_F32 &&
+ src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] == 1 && src1->ne[3] == 1 &&
+ ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && src0->ne[0] % 128 == 0 && ptq1a_on();
+}
+static bool ptq1f_mul_mat(const struct ggml_compute_params * params, struct ggml_tensor * dst) {
+ if (!ptq1f_applies(dst->src[0], dst->src[1])) return false;
+ return ptq1a_mul_mat(params, dst);
+}
+static size_t ptq1f_wsize(const struct ggml_tensor * a, const struct ggml_tensor * b) { return ptq1a_wsize(a, b); }
+#else
static bool ptq1f_mul_mat(const struct ggml_compute_params * params, struct ggml_tensor * dst) { (void) params; (void) dst; return false; }
static size_t ptq1f_wsize(const struct ggml_tensor * a, const struct ggml_tensor * b) { (void) a; (void) b; return 0; }
static bool ptq1f_applies(const struct ggml_tensor * a, const struct ggml_tensor * b) { (void) a; (void) b; return false; }
+#endif
static inline int ptq1p_k7(void) { return 0; }
static const int ptq1p_k7_la = 0;
static void ptq1p_k7_spin(void) { }
diff --git a/kernels/ptq1-vbmi.inc b/kernels/ptq1-vbmi.inc
index b4c2e8b..a5f6b89 100644
--- a/kernels/ptq1-vbmi.inc
+++ b/kernels/ptq1-vbmi.inc
@@ -139,21 +139,58 @@ static void ptq1v_repack_panels(ptq1p_entry * e, int64_t p0, int64_t p1) {
// constant vectors: 0 ctrlA, 1 ctrlC, 2 ctrlD, 3-5 trit-n tables for 5-bit fields, 6-7 for 4-bit fields,
// 8 gather index for (C0, D0), 9 gather-append index from a C, 10 from a D
-static uint8_t ptq1v_tab[11][64] __attribute__((aligned(64)));
-__attribute__((constructor)) static void ptq1v_tab_init(void) {
- static const int pow3[3] = {1, 3, 9};
- for (int i = 0; i < 64; ++i) {
- const int j = i % 8;
- ptq1v_tab[0][i] = (uint8_t) (5 * j);
- ptq1v_tab[1][i] = (uint8_t) (j < 4 ? 40 + 5 * j : 60);
- ptq1v_tab[2][i] = (uint8_t) (j < 4 ? 60 : 40 + 5 * (j - 4));
- for (int n = 0; n < 3; ++n) ptq1v_tab[3 + n][i] = (uint8_t) ((i & 31) < 27 ? ((i & 31) / pow3[n]) % 3 : 0);
- for (int n = 0; n < 2; ++n) ptq1v_tab[6 + n][i] = (uint8_t) ((i & 15) < 9 ? ((i & 15) / pow3[n]) % 3 : 0);
- ptq1v_tab[8][i] = (uint8_t) (i < 8 ? 8 * j + 4 : 64 + 8 * j);
- ptq1v_tab[9][i] = (uint8_t) (64 + 8 * j + 4);
- ptq1v_tab[10][i] = (uint8_t) (64 + 8 * j);
- }
-}
+// Written out as constants (not filled in by a load-time constructor): a --portable build loads every CPU variant of
+// this library to ask whether it can run, and code that runs at load time in an AVX-512 variant is an illegal
+// instruction on a CPU without AVX-512. The formulas: i = byte, j = i % 8;
+// [0] 5j [1] j < 4 ? 40 + 5j : 60 [2] j < 4 ? 60 : 40 + 5(j - 4)
+// [3 + n] trit n of (i & 31) if < 27 else 0 [6 + n] trit n of (i & 15) if < 9 else 0
+// [8] i < 8 ? 8j + 4 : 64 + 8j [9] 64 + 8j + 4 [10] 64 + 8j (tests/test_kernel_tables.py recomputes them)
+static const uint8_t ptq1v_tab[11][64] __attribute__((aligned(64))) = {
+ { 0, 5, 10, 15, 20, 25, 30, 35, 0, 5, 10, 15, 20, 25, 30, 35,
+ 0, 5, 10, 15, 20, 25, 30, 35, 0, 5, 10, 15, 20, 25, 30, 35,
+ 0, 5, 10, 15, 20, 25, 30, 35, 0, 5, 10, 15, 20, 25, 30, 35,
+ 0, 5, 10, 15, 20, 25, 30, 35, 0, 5, 10, 15, 20, 25, 30, 35 },
+ { 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60,
+ 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60,
+ 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60,
+ 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60 },
+ { 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55,
+ 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55,
+ 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55,
+ 60, 60, 60, 60, 40, 45, 50, 55, 60, 60, 60, 60, 40, 45, 50, 55 },
+ { 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0,
+ 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0,
+ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0,
+ 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0 },
+ { 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2,
+ 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2,
+ 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0 },
+ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0 },
+ { 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0 },
+ { 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0 },
+ { 4, 12, 20, 28, 36, 44, 52, 60, 64, 72, 80, 88, 96, 104, 112, 120,
+ 64, 72, 80, 88, 96, 104, 112, 120, 64, 72, 80, 88, 96, 104, 112, 120,
+ 64, 72, 80, 88, 96, 104, 112, 120, 64, 72, 80, 88, 96, 104, 112, 120,
+ 64, 72, 80, 88, 96, 104, 112, 120, 64, 72, 80, 88, 96, 104, 112, 120 },
+ { 68, 76, 84, 92, 100, 108, 116, 124, 68, 76, 84, 92, 100, 108, 116, 124,
+ 68, 76, 84, 92, 100, 108, 116, 124, 68, 76, 84, 92, 100, 108, 116, 124,
+ 68, 76, 84, 92, 100, 108, 116, 124, 68, 76, 84, 92, 100, 108, 116, 124,
+ 68, 76, 84, 92, 100, 108, 116, 124, 68, 76, 84, 92, 100, 108, 116, 124 },
+ { 64, 72, 80, 88, 96, 104, 112, 120, 64, 72, 80, 88, 96, 104, 112, 120,
+ 64, 72, 80, 88, 96, 104, 112, 120, 64, 72, 80, 88, 96, 104, 112, 120,
+ 64, 72, 80, 88, 96, 104, 112, 120, 64, 72, 80, 88, 96, 104, 112, 120,
+ 64, 72, 80, 88, 96, 104, 112, 120, 64, 72, 80, 88, 96, 104, 112, 120 }
+};
// NT tokens x one panel; same accumulation and flush as ptq1p_panel. Fully unrolled over the steps of a
// superblock so every flush point is a compile-time constant.
diff --git a/patches/apply.sh b/patches/apply.sh
index e3e5dc1..2e7ab5a 100755
--- a/patches/apply.sh
+++ b/patches/apply.sh
@@ -1,7 +1,8 @@
#!/bin/sh
# Apply this repo's changes to a PrismML llama.cpp checkout at e3de715. Idempotent (resets the patched files first).
# sh patches/apply.sh <llama.cpp checkout>
-# 1. kernels/* -> ggml/src/ggml-cpu/ (the fast PTQ1_0 ternary matmul, the draft-layer kernel)
+# 1. kernels/* -> ggml/src/ggml-cpu/ (the fast PTQ1_0 ternary matmul: AVX-512 kernels, and 256-bit kernels for CPUs
+# without AVX-512; the draft-layer kernel)
# 2. 0001-*.patch: wires it into ggml_compute_forward_mul_mat; splits single-row GET_ROWS/CONCAT across threads.
# 3. 0002-*.patch: K6, fuses the decode graph's recurrent-state and norm/GLU/sign chains (bit-identical data moves).
# 4. 0003-*.patch: X1, faster MTP speculation cycle (GGML_X1 + X1_* env; all unset = 0002's behaviour).
@@ -21,7 +22,7 @@ set -eu
here=$(cd "$(dirname "$0")" && pwd)
src=${1:?usage: apply.sh <llama.cpp checkout>}
cp "$here"/../kernels/ptq1-common.h "$here"/../kernels/ptq1-drop.h "$here"/../kernels/ptq1-fast.inc "$here"/../kernels/ptq1-panel.inc \
- "$here"/../kernels/ptq1-vbmi.inc "$here"/../kernels/x1-q4k.inc "$here"/../kernels/attn-fast.inc "$here"/../kernels/kvq.h "$src/ggml/src/ggml-cpu/"
+ "$here"/../kernels/ptq1-vbmi.inc "$here"/../kernels/ptq1-avx2.inc "$here"/../kernels/x1-q4k.inc "$here"/../kernels/attn-fast.inc "$here"/../kernels/kvq.h "$src/ggml/src/ggml-cpu/"
git -C "$src" checkout -q -- ggml/src/ggml-cpu/ggml-cpu.c ggml/src/ggml-cpu/ops.cpp src/models/qwen35.cpp \
src/llama-context.cpp tools/server/server-context.cpp common/chat.h common/common.h common/arg.cpp ggml/include/ggml.h ggml/src/ggml.c
for p in "$here"/0*.patch; do
diff --git a/scripts/verify-dispatch.sh b/scripts/verify-dispatch.sh
index ad9b42e..148d6a6 100755
--- a/scripts/verify-dispatch.sh
+++ b/scripts/verify-dispatch.sh
@@ -4,8 +4,12 @@
# loader picks the best one the CPU supports. Hiding the better variants forces the slower paths on this machine.
# bash scripts/verify-dispatch.sh [n_predict] -> prints per-arm tok/s, which kernel loaded, output identity
# Arms: fast (icelake variant, defaults) | k6-off (GGML_K6=0) | fast-off (GGML_PTQ1_FAST=0) | avx512-novbmi (cascadelake) |
-# avx2 (haswell) | fast+MTP-3 (speculation vs plain) | X1 (serve's default env) vs MTP-3 on the fast, no-VBMI and AVX2
+# avx2 (haswell: the 256-bit kernels) | avx2-fork (haswell, GGML_PTQ1_AVX2=0: the fork's own kernel) |
+# avx512-novnni (skylakex: the 256-bit kernels in an AVX-512 build without VNNI) |
+# fast-256 (icelake, GGML_PTQ1_AVX2=1: the 256-bit kernels inside the AVX-512 build; must equal fast) |
+# fast+MTP-3 (speculation vs plain) | X1 (serve's default env) vs MTP-3 on the fast, no-VBMI and AVX2
# paths (X1 must not change any path's output)
+# The alderlake variant (AVX-VNNI) only loads on a CPU that has AVX-VNNI, so it is not an arm here.
set -uo pipefail
PREFIX=${OPENSET_LLM_HOME:-$HOME/.openset-llm}
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
@@ -48,12 +52,15 @@ run_arm() { # name bindir env spec
local tps; tps=$(sort -g "$W/tps-$name.txt" | awk '{a[NR]=$1} END {print a[int((NR+1)/2)]}')
printf '%-14s kernel=%-26s median decode %6.2f tok/s\n' "$name" "${kern:-?}" "$tps"
}
-FAST=$(mkbin icelake); NOVBMI=$(mkbin cascadelake); AVX2=$(mkbin haswell)
+FAST=$(mkbin icelake); NOVBMI=$(mkbin cascadelake); AVX2=$(mkbin haswell); NOVNNI=$(mkbin skylakex)
run_arm fast "$FAST" "" 0
run_arm k6-off "$FAST" "GGML_K6=0" 0
run_arm fast-off "$FAST" "GGML_PTQ1_FAST=0" 0
run_arm avx512-novbmi "$NOVBMI" "" 0
run_arm avx2 "$AVX2" "" 0
+run_arm avx2-fork "$AVX2" "GGML_PTQ1_AVX2=0" 0
+run_arm avx512-novnni "$NOVNNI" "" 0
+run_arm fast-256 "$FAST" "GGML_PTQ1_AVX2=1" 0
run_arm fast-mtp3 "$FAST" "" 1
run_arm fast-x1 "$FAST" "$X1ENV" 1
run_arm novbmi-mtp3 "$NOVBMI" "" 1
@@ -62,9 +69,13 @@ run_arm avx2-mtp3 "$AVX2" "" 1
run_arm avx2-x1 "$AVX2" "$X1ENV" 1
same() { paste -d'\n' "$W/out-$1.txt" "$W/out-$2.txt" | paste - - | awk -F'\t' '$1==$2' | wc -l; }
echo "== greedy identity vs 'fast' (${#PROMPTS[@]} prompts x $N tokens)"
-for a in k6-off fast-off avx512-novbmi avx2 fast-mtp3; do
+for a in k6-off fast-off avx512-novbmi fast-256 avx2 avx2-fork avx512-novnni fast-mtp3; do
printf '%-14s %d/%d identical\n' "$a" "$(same fast $a)" "${#PROMPTS[@]}"
done
+echo "== 256-bit kernels: fast-256 must be identical to fast (same kernel arithmetic). The avx2 arms are a different"
+echo " build (every other operation runs at 256 bits), so a few replies can part at a near-tie; they must agree with"
+echo " each other about as often as with fast"
+printf '%-14s %d/%d identical to avx2-fork\n' avx2 "$(same avx2 avx2-fork)" "${#PROMPTS[@]}"
echo "== X1 vs MTP-3 on the same path (must be identical)"
for p in fast novbmi avx2; do
printf '%-14s %d/%d identical\n' "$p-x1" "$(same $p-mtp3 $p-x1)" "${#PROMPTS[@]}"
diff --git a/serve b/serve
index 999afe8..5b780f6 100755
--- a/serve
+++ b/serve
@@ -9,7 +9,7 @@
# ./serve --no-spec # plain decoding (no speculation)
# ./serve --spec # keep speculation on where serve would turn it off: for lack of memory
# # (< 12 GB RAM: --ctx > 4096; > 8192 with --kv8; > 12288 with --kv6; > 16384 with --kv5)
-# # or on a CPU without AVX-512 VNNI
+# # or on a CPU without AVX-512 VNNI (AVX2 / AVX-VNNI: speculation speeds up code and JSON there and slows down prose)
# ./serve --think # let the model think before answering (much longer replies)
# ./serve --no-resume # turn off agent-loop resume (default on; saved prefix states live in $OPENSET_LLM_HOME/state)
# ./serve --kv6 | --kv5 # EXPERIMENTAL: 6- / 5-bit attention cache, 38 % / 32 % of the default cache; on 8 GB:
@@ -114,13 +114,22 @@ else
export LLAMA_RESUME=0 LLAMA_RESUME_DIR=
fi
[ "$FL128" = 1 ] && export GGML_PTQ1_FL128=${GGML_PTQ1_FL128:-1} GGML_PTQ1_K4=${GGML_PTQ1_K4:-2}
-# Without AVX-512 VNNI the engine runs on the fork's own kernel, and speculation is slower than plain decoding there
-# (measured 2026-11-12, AVX2 kernel: 1.2 vs 1.7 tok/s). With VNNI but no VBMI it still helps (7.8 vs 6.6), so it stays on.
-if [ "$SPEC" = 1 ] && [ "$MULTI" -lt 2 ] && [ "$SPEC_FORCE" = 0 ]; then
+# Without AVX-512 VNNI the engine runs on the 256-bit kernels (AVX2, AVX-VNNI where the CPU has it). Checking a draft
+# of 3 tokens costs about twice a single token there (1.1-1.2 times on the AVX-512 kernels), so speculation only pays
+# where the drafts are usually right:
+# measured with AVX-512 switched off on Ice Lake boxes (2026-11-26, 128 prompts of 10 kinds, drafting 2 tokens ahead):
+# 1.2-1.4x plain decoding on code, JSON, maths and tool calls, 0.9-1.0x on prose, translation and summaries (3 tokens
+# ahead: 0.8-0.85x there). So it stays off unless --spec asks for it, and --spec drafts 2 tokens ahead on these CPUs.
+# With AVX-512 VNNI but no VBMI it still helps (7.8 vs 6.6 tok/s), so it stays on.
+if [ "$SPEC" = 1 ] && [ "$MULTI" -lt 2 ]; then
case " $(grep -m1 '^flags' /proc/cpuinfo 2>/dev/null | cut -d: -f2) " in
*" avx512_vnni "*) ;;
- *) echo "note: this CPU has no AVX-512 VNNI: speculation off (it is slower than plain decoding here); --spec forces it" >&2
- SPEC=0 ;;
+ *) if [ "$SPEC_FORCE" = 0 ]; then
+ echo "note: this CPU has no AVX-512 VNNI: speculation off (on this kind of CPU it speeds up code and JSON and slows down prose); --spec forces it" >&2
+ SPEC=0
+ elif [ -z "$DEPTH" ] && [ "$ADAPT" = 0 ]; then
+ DEPTH=2 # drafting 2 tokens ahead instead of 3: the better depth on the 256-bit kernels (--spec-depth N overrides)
+ fi ;;
esac
fi
[ "$KV8" = 1 ] && [ "$KVQ" != 0 ] && { echo "choose one of --kv8, --kv6, --kv5" >&2; exit 2; }
diff --git a/tests/kernel_avx2.c b/tests/kernel_avx2.c
new file mode 100644
index 0000000..cf9b308
--- /dev/null
+++ b/tests/kernel_avx2.c
@@ -0,0 +1,138 @@
+// kernel_avx2.c: the 256-bit ternary kernels (kernels/ptq1-avx2.inc) against a scalar reference. Run by
+// tests/test_kernel_avx2.py, which compiles it once per dot-product variant the CPU can execute:
+// cc -O2 -mavx2 -mfma -mf16c [-mavxvnni | -mavx512f -mavx512bw -mavx512vl -mavx512vnni | -DPTQ1A_FORCE_MADD] -I kernels tests/kernel_avx2.c -lm
+// Checks, all bit-exact (max |diff| must be 0):
+// 1. the 16-bit word decode, every one of the 59049 values, with the two multiplies emulated in scalar code;
+// 2. the AVX2 activation quantizer = the scalar Q8_0 quantizer of ptq1-common.h, byte for byte;
+// 3. PTQ1_0 blocks -> panels -> M = 1 kernel (panel pairs and a single last panel, a partial last panel);
+// 4. the same through the M >= 2 kernels for 2..9 and 64 tokens (the verify and prompt paths).
+// The reference decodes the PTQ1_0 blocks with ptq1f_unpack_block and sums in the order the kernels promise:
+// exact int32 per 32-k block, one fma per block in block order.
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <math.h>
+#include <immintrin.h>
+typedef uint16_t ggml_half;
+typedef struct { uint8_t qs[24]; uint8_t qh[2]; ggml_half d; } block_ptq1_0;
+#define GGML_CPU_FP16_TO_FP32(h) _cvtsh_ss(h)
+#define GGML_CPU_FP32_TO_FP16(f) _cvtss_sh((f), 0)
+#define PTQ1F_NO_GGML
+#define PTQ1F_MIN(a, b) ((a) < (b) ? (a) : (b))
+#include "ptq1-common.h"
+#include "ptq1-avx2.inc"
+#if !PTQ1A_OK
+#error "needs -mavx2 -mfma -mf16c"
+#endif
+
+static uint64_t rng_s = 0x9E3779B97F4A7C15ull;
+static uint32_t rnd(void) { rng_s ^= rng_s << 13; rng_s ^= rng_s >> 7; rng_s ^= rng_s << 17; return (uint32_t) (rng_s >> 32); }
+static float rndf(void) { return (float) (rnd() & 0xffffff) / (float) 0x800000 - 1.0f; } // [-1, 1)
+
+static int check_words(void) {
+ int bad = 0;
+ for (uint32_t q = 0; q < 59049; ++q) {
+ uint32_t w = (uint32_t) (((uint64_t) q * 65536 + 59048) / 59049), rem = q;
+ if (w > 0xffff) { ++bad; continue; }
+ for (int s = 0; s < 5; ++s) {
+ const uint32_t d = (w * 9) >> 16; w = (w * 9) & 0xffff;
+ const uint32_t want = rem / 6561; rem = rem % 6561 * 9;
+ if (d != want) { ++bad; break; }
+ }
+ }
+ return bad;
+}
+
+static void random_block(block_ptq1_0 * b) {
+ uint8_t c5[5];
+ for (int m = 0; m < 24; ++m) { for (int n = 0; n < 5; ++n) c5[n] = (uint8_t) (rnd() % 3); b->qs[m] = ptq1f_pack5(c5); }
+ for (int h = 0; h < 2; ++h) { for (int n = 0; n < 4; ++n) c5[n] = (uint8_t) (rnd() % 3); c5[4] = 0; b->qh[h] = ptq1f_pack5(c5); }
+ b->d = GGML_CPU_FP32_TO_FP16(0.005f + 0.02f * (float) (rnd() % 1000) / 1000.0f);
+}
+
+// one output of the reference: row r of the weights x one quantized column (as[] holds -sum(q) per block)
+static float ref_row(const block_ptq1_0 * w, int64_t k, const uint8_t * acts, int64_t kpad) {
+ const int8_t * q = (const int8_t *) acts; const float * dy = (const float *) (acts + kpad);
+ const int32_t * as = (const int32_t *) (dy + kpad / 32);
+ uint8_t codes[128]; float accf = 0;
+ for (int64_t b = 0; b < kpad / 32; ++b) {
+ int32_t acc = 0; float dx = 0;
+ if (b * 32 < k) {
+ ptq1f_unpack_block(w + b / 4, codes);
+ for (int j = 0; j < 32; ++j) acc += (int32_t) codes[(b % 4) * 32 + j] * q[b * 32 + j];
+ dx = GGML_CPU_FP16_TO_FP32(w[b / 4].d);
+ }
+ accf = fmaf((float) (acc + as[b]), dx * dy[b], accf);
+ }
+ return accf;
+}
+
+static int run_case(int64_t rows, int64_t k, int64_t m) {
+ const int64_t nb = k / 128;
+ block_ptq1_0 * w = malloc((size_t) (rows * nb) * sizeof(*w));
+ for (int64_t i = 0; i < rows * nb; ++i) random_block(w + i);
+ ptq1p_entry e; memset(&e, 0, sizeof e);
+ ptq1a_init_entry(&e, w, rows, k);
+ e.packed = aligned_alloc(64, (size_t) ((e.panel_stride * e.npanel + 63) / 64 * 64 + 64));
+ ptq1a_repack_panels(&e, 0, e.npanel);
+ const size_t cb = ptq1p_col_bytes(k);
+ uint8_t * acts = aligned_alloc(64, (cb * (size_t) m + 63) / 64 * 64), * acts_ref = aligned_alloc(64, (cb + 63) / 64 * 64);
+ float * x = malloc((size_t) (k * m) * sizeof(float));
+ int bad = 0;
+ for (int64_t t = 0; t < m; ++t) {
+ const float amp = t % 3 == 0 ? 1.0f : t % 3 == 1 ? 37.5f : 1e-3f;
+ for (int64_t i = 0; i < k; ++i) x[t * k + i] = rndf() * amp;
+ if (t == 1) for (int64_t i = 0; i < 64 && i < k; ++i) x[t * k + i] = 0.0f; // all-zero blocks: d = 0
+ if (t == 2) for (int64_t i = 0; i < k; ++i) x[t * k + i] = (float) ((i * 7) % 255 - 127) * 0.5f; // exact .5 ties after scaling
+ ptq1a_quantize_part(x + t * k, k, e.kpad, acts + t * cb, 0, k / 32, 1);
+ memset(acts_ref, 0xAA, cb);
+ ptq1p_quantize_col_part_kp(x + t * k, k, e.kpad, acts_ref, 0, k / 32, 1);
+ if (memcmp(acts + t * cb, acts_ref, (size_t) (e.kpad + (e.kpad / 32) * 8)) != 0) { printf("FAIL quantizer rows=%lld k=%lld token %lld\n", (long long) rows, (long long) k, (long long) t); ++bad; }
+ }
+ float * ref = malloc((size_t) (rows * m) * sizeof(float)), * out = malloc((size_t) (rows * m + 8) * sizeof(float));
+ for (int64_t t = 0; t < m; ++t) for (int64_t r = 0; r < rows; ++r) ref[t * rows + r] = ref_row(w + r * nb, k, acts + t * cb, e.kpad);
+ // M = 1 kernel on every token's column, in two splits (pairs + single last panel; one panel at a time)
+ for (int split = 0; split < 2; ++split) {
+ for (int64_t i = 0; i < rows * m + 8; ++i) out[i] = NAN;
+ for (int64_t t = 0; t < m; ++t) {
+ if (split == 0) ptq1a_panels(&e, acts + t * cb, out + t * rows, 0, e.npanel);
+ else for (int64_t p = 0; p < e.npanel; ++p) ptq1a_panels(&e, acts + t * cb, out + t * rows, p, p + 1);
+ }
+ if (memcmp(out, ref, (size_t) (rows * m) * sizeof(float)) != 0) { printf("FAIL M=1 kernel rows=%lld k=%lld split %d\n", (long long) rows, (long long) k, split); ++bad; }
+ if (!isnan(out[rows * m])) { printf("FAIL M=1 kernel wrote past the last row\n"); ++bad; }
+ }
+ // M >= 2 kernel, panels in chunks of 2 (as the scheduler hands them out) and all at once
+ if (m >= 2) for (int split = 0; split < 2; ++split) {
+ for (int64_t i = 0; i < rows * m + 8; ++i) out[i] = NAN;
+ if (split == 0) ptq1a_gemm(&e, acts, cb, m, 0, e.npanel, out, rows);
+ else for (int64_t p = 0; p < e.npanel; p += 2) ptq1a_gemm(&e, acts, cb, m, p, PTQ1F_MIN(e.npanel, p + 2), out, rows);
+ if (memcmp(out, ref, (size_t) (rows * m) * sizeof(float)) != 0) {
+ float md = 0; for (int64_t i = 0; i < rows * m; ++i) md = fmaxf(md, fabsf(out[i] - ref[i]));
+ printf("FAIL M=%lld kernel rows=%lld k=%lld split %d max|diff| %g\n", (long long) m, (long long) rows, (long long) k, split, md); ++bad;
+ }
+ if (!isnan(out[rows * m])) { printf("FAIL M>=2 kernel wrote past the last row\n"); ++bad; }
+ }
+ // the in-register kernel for small batches (the scheduler uses it for 2..4 tokens; any M is valid)
+ if (m >= 2) {
+ for (int64_t i = 0; i < rows * m + 8; ++i) out[i] = NAN;
+ for (int64_t p = 0; p < e.npanel; p += 3) ptq1a_panels_m(&e, acts, cb, m, p, PTQ1F_MIN(e.npanel, p + 3), out, rows);
+ if (memcmp(out, ref, (size_t) (rows * m) * sizeof(float)) != 0) { printf("FAIL small-batch kernel M=%lld rows=%lld k=%lld\n", (long long) m, (long long) rows, (long long) k); ++bad; }
+ if (!isnan(out[rows * m])) { printf("FAIL small-batch kernel wrote past the last row\n"); ++bad; }
+ }
+ free(w); free(e.packed); free(acts); free(acts_ref); free(x); free(ref); free(out);
+ return bad;
+}
+
+int main(void) {
+ int bad = check_words();
+ if (bad) printf("FAIL word decode: %d of 59049 values\n", bad);
+ static const int64_t rows_k[][2] = { {8, 128}, {16, 640}, {21, 1152}, {40, 5120}, {3, 384}, {17, 2560} };
+ static const int64_t ms[] = { 1, 2, 3, 4, 5, 8, 9, 64 };
+ int cases = 0;
+ for (size_t i = 0; i < sizeof rows_k / sizeof rows_k[0]; ++i)
+ for (size_t j = 0; j < sizeof ms / sizeof ms[0]; ++j) { bad += run_case(rows_k[i][0], rows_k[i][1], ms[j]); ++cases; }
+ printf("dot=%s cases=%d failures=%d\n", PTQ1A_VNNI ? "vpdpbusd" : "vpmaddubsw", cases, bad);
+ return bad ? 1 : 0;
+}
diff --git a/tests/test_cpu_paths.py b/tests/test_cpu_paths.py
new file mode 100644
index 0000000..d13758a
--- /dev/null
+++ b/tests/test_cpu_paths.py
@@ -0,0 +1,117 @@
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+BASE = 'fpu sse sse2 ssse3 sse4_1 sse4_2 popcnt avx'
+AVX2 = BASE + ' fma f16c avx2 bmi2'
+CPUS = {
+ 'icelake': AVX2 + ' avx512f avx512dq avx512bw avx512vl avx512vbmi avx512_vnni',
+ 'cascadelake': AVX2 + ' avx512f avx512dq avx512bw avx512vl avx512_vnni',
+ 'skylakex': AVX2 + ' avx512f avx512dq avx512bw avx512vl',
+ 'alderlake': AVX2 + ' avx_vnni',
+ 'zen3': AVX2,
+ 'avx2-no-fma': BASE + ' avx2',
+ 'sandybridge': BASE,
+}
+
+
+class CpuPaths(unittest.TestCase):
+ """install.sh --check and serve read the CPU flags from /proc/cpuinfo; a grep in front of the real one answers
+ for that file, so every CPU class can be checked on any machine."""
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.work = Path(self.temp.name)
+ self.tools = self.work / 'tools'
+ self.tools.mkdir()
+ real = shutil.which('grep')
+ grep = self.tools / 'grep'
+ grep.write_text('#!/bin/bash\n'
+ 'for last; do :; done\n'
+ 'if [ "$last" = /proc/cpuinfo ]; then\n'
+ ' case " $* " in *"model name"*) echo "model name : Fixture CPU" ;; *) echo "flags : $FIXTURE_FLAGS" ;; esac\n'
+ ' exit 0\n'
+ 'fi\n'
+ f'exec {real} "$@"\n')
+ grep.chmod(0o755)
+ uname = self.tools / 'uname'
+ uname.write_text('#!/bin/sh\ncase "$1" in -m) echo x86_64 ;; -s) echo Linux ;; *) echo Linux ;; esac\n')
+ uname.chmod(0o755)
+ self.prefix = self.work / 'home'
+ (self.prefix / 'bin').mkdir(parents=True)
+ (self.prefix / 'models').mkdir()
+ (self.prefix / 'models/model.gguf').touch()
+ server = self.prefix / 'bin/llama-server'
+ server.write_text('#!/usr/bin/env python3\nimport json,sys\nprint(json.dumps(sys.argv[1:]))\n')
+ server.chmod(0o755)
+
+ def env(self, cpu):
+ return {**os.environ, 'OPENSET_LLM_HOME': str(self.prefix), 'FIXTURE_FLAGS': CPUS[cpu],
+ 'PATH': str(self.tools) + os.pathsep + os.environ['PATH']}
+
+ def check(self, cpu):
+ result = subprocess.run(['bash', str(ROOT / 'install.sh'), '--check'], env=self.env(cpu),
+ text=True, capture_output=True, timeout=15)
+ return result.stdout + result.stderr
+
+ def serve(self, cpu, *args):
+ return subprocess.run(['bash', str(ROOT / 'serve'), '--no-resume', *args], env=self.env(cpu),
+ text=True, capture_output=True, timeout=15)
+
+ def test_check_names_the_path_of_every_cpu_class(self):
+ self.assertIn('full fast path', self.check('icelake'))
+ self.assertIn('partial fast path', self.check('cascadelake'))
+ for cpu in ('alderlake', 'zen3', 'skylakex'):
+ out = self.check(cpu)
+ self.assertIn('256-bit kernels', out, cpu)
+ self.assertNotIn("fork's own", out, cpu)
+ self.assertIn('AVX-VNNI', self.check('alderlake'))
+ self.assertNotIn('AVX-VNNI', self.check('zen3'))
+ self.assertIn('without VNNI', self.check('skylakex'))
+ for cpu in ('avx2-no-fma', 'sandybridge'):
+ out = self.check(cpu)
+ self.assertNotIn('256-bit kernels', out, cpu)
+ self.assertIn('slowly', out, cpu)
+
+ def test_serve_keeps_speculation_on_only_with_avx512_vnni(self):
+ for cpu, on in (('icelake', True), ('cascadelake', True), ('alderlake', False), ('zen3', False), ('skylakex', False)):
+ result = self.serve(cpu)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ args = json.loads(result.stdout.strip().splitlines()[-1])
+ self.assertEqual('--spec-type' in args, on, cpu)
+ if not on:
+ self.assertIn('speculation off', result.stderr, cpu)
+ self.assertIn('--spec', result.stderr, cpu)
+
+ def draft_depth(self, cpu, *args):
+ result = self.serve(cpu, *args)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ argv = json.loads(result.stdout.strip().splitlines()[-1])
+ self.assertIn('--spec-type', argv)
+ return argv[argv.index('--spec-draft-n-max') + 1]
+
+ def test_serve_spec_flag_forces_speculation_without_avx512(self):
+ self.assertEqual(self.draft_depth('zen3', '--spec'), '2')
+ self.assertEqual(self.draft_depth('alderlake', '--spec'), '2')
+ self.assertEqual(self.draft_depth('zen3', '--spec', '--spec-depth', '3'), '3')
+
+ def test_draft_depth_with_avx512_is_unchanged(self):
+ self.assertEqual(self.draft_depth('icelake'), '3')
+ self.assertEqual(self.draft_depth('icelake', '--spec'), '3')
+
+ def test_compact_attention_caches_still_need_avx512(self):
+ for flag in ('--kv6', '--kv5'):
+ result = self.serve('alderlake', flag)
+ self.assertEqual(result.returncode, 2, flag)
+ self.assertIn('--kv8', result.stderr)
+ self.assertEqual(self.serve('alderlake', '--kv8').returncode, 0)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_kernel_avx2.py b/tests/test_kernel_avx2.py
new file mode 100644
index 0000000..f92ca3a
--- /dev/null
+++ b/tests/test_kernel_avx2.py
@@ -0,0 +1,58 @@
+from pathlib import Path
+import platform
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+BASE = ['-O2', '-mavx2', '-mfma', '-mf16c']
+# name -> (extra compiler flags, CPU flags the machine needs to run the result)
+VARIANTS = {
+ 'avx2': ([], ()), # the vpmaddubsw dot: any AVX2 CPU
+ 'avx2-forced': (['-DPTQ1A_FORCE_MADD'], ()), # same dot with the VNNI detection overridden
+ 'avx-vnni': (['-mavxvnni'], ('avx_vnni',)), # VEX vpdpbusd: Intel Core 12th gen and newer, Zen 5
+ 'avx512-vnni-256': (['-mavx512f', '-mavx512bw', '-mavx512vl', '-mavx512vnni'],
+ ('avx512f', 'avx512bw', 'avx512vl', 'avx512_vnni')), # the same kernels in an AVX-512 build
+}
+
+
+def cpu_flags():
+ try:
+ for line in Path('/proc/cpuinfo').read_text().splitlines():
+ if line.startswith('flags'):
+ return set(line.split(':', 1)[1].split())
+ except OSError:
+ pass
+ return set()
+
+
+class Avx2Kernel(unittest.TestCase):
+ def test_kernels_match_the_scalar_reference(self):
+ compiler = shutil.which('cc') or shutil.which('gcc') or shutil.which('clang')
+ flags = cpu_flags()
+ if platform.machine() not in ('x86_64', 'AMD64') or not compiler:
+ self.skipTest('needs an x86-64 C compiler')
+ if not {'avx2', 'fma', 'f16c'} <= flags:
+ self.skipTest('this CPU has no AVX2 + FMA + F16C')
+ ran = []
+ with tempfile.TemporaryDirectory() as tmp:
+ for name, (extra, needs) in VARIANTS.items():
+ if not set(needs) <= flags:
+ continue
+ exe = Path(tmp) / f'kernel-{name}'
+ build = subprocess.run([compiler, *BASE, *extra, '-I', str(ROOT / 'kernels'),
+ str(ROOT / 'tests/kernel_avx2.c'), '-o', str(exe), '-lm'],
+ capture_output=True, text=True)
+ self.assertEqual(build.returncode, 0, f'{name}: {build.stderr}')
+ run = subprocess.run([str(exe)], capture_output=True, text=True, timeout=300)
+ self.assertEqual(run.returncode, 0, f'{name}: {run.stdout}{run.stderr}')
+ self.assertIn('failures=0', run.stdout, name)
+ want = 'vpmaddubsw' if name.startswith('avx2') else 'vpdpbusd'
+ self.assertIn(f'dot={want}', run.stdout, name)
+ ran.append(name)
+ self.assertIn('avx2', ran)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_kernel_tables.py b/tests/test_kernel_tables.py
new file mode 100644
index 0000000..fe05078
--- /dev/null
+++ b/tests/test_kernel_tables.py
@@ -0,0 +1,43 @@
+from pathlib import Path
+import re
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def table(path, name):
+ """The rows of `static const uint8_t <name>[R][C] ... = { {..}, .. };` in a kernel source."""
+ text = (ROOT / path).read_text()
+ match = re.search(r'static const uint8_t ' + name + r'\[(\d+)\]\[(\d+)\][^=]*=\s*\{(.*?)\n\};', text, re.S)
+ assert match, f'{name} not found in {path}'
+ rows = [[int(v) for v in re.findall(r'\d+', row)] for row in re.findall(r'\{([^{}]*)\}', match.group(3))]
+ assert len(rows) == int(match.group(1)) and all(len(r) == int(match.group(2)) for r in rows)
+ return rows
+
+
+class KernelTables(unittest.TestCase):
+ def test_avx512_decode_tables(self):
+ rows = table('kernels/ptq1-vbmi.inc', 'ptq1v_tab')
+ for i in range(64):
+ j = i % 8
+ want = [5 * j, 40 + 5 * j if j < 4 else 60, 60 if j < 4 else 40 + 5 * (j - 4)]
+ want += [((i & 31) // p) % 3 if (i & 31) < 27 else 0 for p in (1, 3, 9)]
+ want += [((i & 15) // p) % 3 if (i & 15) < 9 else 0 for p in (1, 3)]
+ want += [8 * j + 4 if i < 8 else 64 + 8 * j, 64 + 8 * j + 4, 64 + 8 * j]
+ self.assertEqual([row[i] for row in rows], want, i)
+
+ def test_avx2_decode_tables(self):
+ rows = table('kernels/ptq1-avx2.inc', 'ptq1a_tab')
+ for i in range(32):
+ v = i & 15
+ self.assertEqual([rows[0][i], rows[1][i]], [v % 3, v // 3] if v < 9 else [0, 0], i)
+
+ def test_no_code_runs_when_a_cpu_variant_is_loaded(self):
+ # --portable: the loader opens every libggml-cpu-<variant>.so to ask for its score. A constructor in a variant
+ # built for AVX-512 runs AVX-512 code right there, and the process dies on a CPU without it.
+ for path in list((ROOT / 'kernels').iterdir()) + list((ROOT / 'patches').glob('*.patch')):
+ self.assertNotIn('__attribute__((constructor', path.read_text(), path.name)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_patch_failure.py b/tests/test_patch_failure.py
index f698b75..a6a42b1 100644
--- a/tests/test_patch_failure.py
+++ b/tests/test_patch_failure.py
@@ -17,7 +17,7 @@ class ApplyFailure(unittest.TestCase):
path.mkdir(parents=True)
shutil.copyfile(ROOT / 'patches/apply.sh', patches / 'apply.sh')
for name in ('ptq1-common.h', 'ptq1-drop.h', 'ptq1-fast.inc', 'ptq1-panel.inc',
- 'ptq1-vbmi.inc', 'x1-q4k.inc', 'attn-fast.inc', 'kvq.h'):
+ 'ptq1-vbmi.inc', 'ptq1-avx2.inc', 'x1-q4k.inc', 'attn-fast.inc', 'kvq.h'):
(kernels / name).touch()
paths = ('ggml/src/ggml-cpu/ggml-cpu.c', 'ggml/src/ggml-cpu/ops.cpp',
'src/models/qwen35.cpp', 'src/llama-context.cpp', 'tools/server/server-context.cpp',