Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

Add FAST_Q8=1 INT8xINT8 AVX2+F16C kernel, .asmbin v2 FP16 scales, and parallel GQA attention

Alexey Fateev48feccbfd57c
diff --git a/01-qwen3-inference/README.md b/01-qwen3-inference/README.md
index 00d94e8..86b9bf5 100644
--- a/01-qwen3-inference/README.md
+++ b/01-qwen3-inference/README.md
@@ -1,18 +1,18 @@
-# Phase 1: Qwen3-0.6B Inference in a 13 KB Pure x86-64 ELF
+# Phase 1: Qwen3-0.6B Inference in a 14 KB Pure x86-64 ELF
A complete inference engine for **Qwen/Qwen3-0.6B** written in **100% pure x86-64 NASM assembly** for Linux.
-- **13,528 bytes** stripped static ELF executable (`.text` = 10,990 B, `.rodata` = 1,943 B).
+- **14,712 bytes** stripped static ELF executable (`FAST_Q8=1`, default) or **14,008 bytes** (`FAST_Q8=0`, legacy FP32-activation mode).
- **Zero runtime dependencies:** no `gcc`, no `libc`, no `libm`, no dynamic linker, no `.so` files.
- **Full Qwen3 architecture:** GQA (`16Q / 8KV`, `head_dim = 128`), per-head QK-Norm (`RMSNorm` on Q and K before RoPE), split-half NeoX RoPE (`rope_theta = 1e6`), SwiGLU MLP, tied embeddings / LM head, persistent multi-turn KV-cache (`--chat`), greedy and temperature/top-p sampling.
- **Built-in BPE tokenizer in assembly:** Fibonacci-hashed open-addressing merge table (`524,288` slots, 100% token-exact match with HuggingFace `AutoTokenizer`), UTF-8 prompt encoding (English, Cyrillic, code, numbers), Qwen3 chat template (default no-think and `--think` reasoning mode), and raw `write()` streaming to stdout.
-- **AVX2 + FMA Q8_0 x FP32 matmul + zero-libc thread pool:** 4-row unrolled AVX2/FMA kernel, fused QKV and gate+up projections, and a raw Linux `clone()` + `futex()` thread pool with cache-line-isolated completion slots. **105.4 tok/s** peak decode and **154.3 tok/s** peak prefill on AMD EPYC 7642, bit-exact across `1T..47T`.
+- **`FAST_Q8=1` INT8xINT8 AVX2 + F16C engine + zero-libc thread pool:** quantizes activations to Q8_0 once per matmul, runs a 1-row sequential 4-block (`128B`) `vpabsb`+`vpsignb`+`vpmaddubsw`+`vpmaddwd` kernel with monotonic next-row prefetch, auto-detects `.asmbin` v2 FP16 scales (`vcvtph2ps`) and legacy v1 FP32 scales, runs parallel GQA attention over a contiguous head-major KV-cache, and synchronizes workers via a hybrid spin-then-futex lock-free thread pool (`0%` idle CPU in `--chat`). **126.8 tok/s** peak decode (**20.7 tok/s** 1T) on AMD EPYC 7642 — **+18% to +36% faster than `llama.cpp` CPU (`Q8_0`) across `1..40T`**, bit-exact across all thread counts.
---
## Prerequisites
-- Linux x86-64 CPU with **AVX2 + FMA**.
+- Linux x86-64 CPU with **AVX2 + FMA + F16C** (Intel Haswell / AMD Excavator or newer; no AVX-512 or VNNI required).
- Build tools:
```bash
sudo apt install nasm binutils
@@ -41,27 +41,41 @@ hf download Qwen/Qwen3-0.6B \
### 2. Export Weights to `.asmbin` (Q8_0)
-Convert the BF16 safetensors and `tokenizer.json` into a single 64-byte aligned, directly `mmap()`-able `.asmbin` file (`649.18 MiB`):
+Convert the BF16 safetensors and `tokenizer.json` into a single 64-byte aligned, directly `mmap()`-able `.asmbin` file:
```bash
+# Compact v2 format with IEEE-754 FP16 block scales (default, 613.66 MiB — saves ~35.5 MiB/tok RAM bandwidth)
python3 scripts/export_weights.py \
--model-dir models/qwen3-0.6b-bf16 \
- --out models/qwen3-0.6b-q8_0.asmbin
+ --out models/qwen3-0.6b-q8_0.asmbin \
+ --scale-dtype fp16
+
+# Legacy v1 format with FP32 block scales (649.18 MiB)
+python3 scripts/export_weights.py \
+ --model-dir models/qwen3-0.6b-bf16 \
+ --out models/qwen3-0.6b-q8_0-fp32s.asmbin \
+ --scale-dtype fp32
```
-### 3. Build the 13 KB Pure x86-64 Binary
+Both formats are auto-detected at load time (`model_init`) by `HDR_VERSION` / `HDR_FLAGS` in both `FAST_Q8=1` and `FAST_Q8=0` builds.
-From the repository root:
+### 3. Build the 14 KB Pure x86-64 Binary
+
+From the repository root, choose the compile-time `FAST_Q8` mode (`FAST_Q8=1` is the default):
```bash
-make inference test-math
+# Default fast path: INT8xINT8 AVX2+F16C matmul + parallel GQA attention + contiguous KV-cache (14,712 B)
+make inference test-math FAST_Q8=1
make check
+
+# Legacy reference path: exact Q8_0 x FP32 activations (14,008 B)
+make inference test-math FAST_Q8=0
```
-Expected ELF inspection output:
+Expected ELF inspection output (`FAST_Q8=1`):
```text
--rwxr-xr-x 1 user user 13528 build/asm-llm
+-rwxr-xr-x 1 user user 14712 build/asm-llm
build/asm-llm: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped
There is no dynamic section in this file.
```
@@ -114,16 +128,16 @@ There is no dynamic section in this file.
---
-## `.asmbin` Binary Format (Version 1)
+## `.asmbin` Binary Format (v2 FP16 Scales & v1 FP32 Scales)
Designed for zero-copy `mmap()` with **64-byte alignment** for every section, matrix, and row:
-- **Header (128 bytes):** magic `"ASML"`, version `1`, model dimensions (`dim=1024`, `hidden_dim=3072`, `n_layers=28`, `n_heads=16`, `n_kv_heads=8`, `head_dim=128`, `vocab_size=151936`, `rms_norm_eps=1e-6`, `rope_theta=1e6`, EOS tokens `151645`/`151643`), hash table mask, flags, and 64-byte aligned section offsets.
+- **Header (128 bytes):** magic `"ASML"`, version `2` (FP16 scales, `HDR_FLAG_FP16_SCALES = 4`) or `1` (legacy FP32 scales), model dimensions (`dim=1024`, `hidden_dim=3072`, `n_layers=28`, `n_heads=16`, `n_kv_heads=8`, `head_dim=128`, `vocab_size=151936`, `rms_norm_eps=1e-6`, `rope_theta=1e6`, EOS tokens `151645`/`151643`), hash table mask, flags, and 64-byte aligned section offsets.
- **Tokenizer section (~9.5 MiB):** `byte_to_tok[256]`, `tok_offsets[vocab_size+1]`, raw UTF-8 `tok_bytes` pool (`976,309` B), and a pre-built `524,288`-slot open-addressing merge table (`151,387` merges, load factor `0.289`, avg probe `1.20`).
-- **Tied Embeddings / LM Head (`[151936, 1024]` Q8_0):** verified bit-identical in BF16 (`max_diff = 0.0`), stored once (`166.92 MiB`).
-- **28 Transformer Layers (`stride = 17,703,936 B` each):** 4 FP32 norm vectors (`input_layernorm`, `q_norm`, `k_norm`, `post_attention_layernorm`) followed by 7 per-row split Q8_0 matrices (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`). Contiguous layout allows fused QKV (`[4096, 1024]`) and gate+up (`[6144, 1024]`) matmuls in a single thread-pool barrier.
-- **Per-row split Q8_0:** each row of `K` weights stores `[K int8 in -127..127][K/32 fp32 scales]`. For `K in {1024, 2048, 3072}`, row strides are `{1152, 2304, 3456}` bytes, all exact multiples of 64 bytes.
-- **Total size:** `680,718,528` bytes (`649.18 MiB`) vs `1.40 GiB` BF16 safetensors.
+- **Tied Embeddings / LM Head (`[151936, 1024]` Q8_0):** verified bit-identical in BF16 (`max_diff = 0.0`), stored once (`157.65 MiB` in v2 / `166.92 MiB` in v1).
+- **28 Transformer Layers (`stride = 16,720,896 B` v2 / `17,703,936 B` v1):** 4 FP32 norm vectors (`input_layernorm`, `q_norm`, `k_norm`, `post_attention_layernorm`) followed by 7 per-row split Q8_0 matrices (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`). Contiguous layout allows fused QKV (`[4096, 1024]`) and gate+up (`[6144, 1024]`) matmuls in a single thread-pool barrier.
+- **Per-row split Q8_0:** each row of `K` weights stores `[K int8 in -127..127][K/32 scales]`. For `K in {1024, 2048, 3072}`, row strides are `{1088, 2176, 3264}` B in v2 (`--scale-dtype fp16`) and `{1152, 2304, 3456}` B in v1 (`--scale-dtype fp32`) — all exact multiples of 64 bytes.
+- **Total size:** `643,469,504` bytes (`613.66 MiB`) in v2 (`680,718,528` B / `649.18 MiB` in v1) vs `1.40 GiB` BF16 safetensors.
---
@@ -143,7 +157,8 @@ python3 scripts/test_math.py build/test_math
| `init_rope_freqs` (FP64) | Max abs error (`theta=1e6`, 64 freqs) | `4.366e-14` | `< 1e-12` |
| `rmsnorm_avx2` | Max abs error (`n=128`) | `2.056e-07` | `< 1e-6` |
| `silu_mul_avx2` | Max rel error (`[-150, +150]`, overflow-free) | `6.774e-08` | `< 1e-6` |
-| `matmul_q8_0_range` | Max abs error (`8x64` Q8_0 x FP32) | `9.537e-07` | `< 1e-5` |
+| `matmul_q8_0_range` (`FAST_Q8=1`, v1/v2) | Max abs error vs exact Q8_0xQ8_0 ref | `9.537e-07` / `5.960e-07` | `< 1e-5` |
+| `matmul_q8_0_range` (`FAST_Q8=0`, v1/v2) | Max abs error vs exact Q8_0xFP32 ref | `9.537e-07` / `9.537e-07` | `< 1e-5` |
### 2. End-to-End Logits & 64-Token Greedy Parity
@@ -155,34 +170,34 @@ python3 scripts/verify_ref.py \
--threads 16
```
-Prompt: `"Explain the difference between L1, L2, and L3 CPU caches and why cache locality matters."` (`34` prompt tokens, `64` generated tokens):
+Prompt: `"Explain the difference between L1, L2, and L3 CPU caches and why cache locality matters."` (`34` prompt tokens, `64` generated tokens, `.asmbin` v2 FP16 scales):
| Comparison | Tokenizer Match | `max_abs_diff` | `mean_abs_diff` | `cosine_similarity` | Greedy Match |
|---|---|---:|---:|---:|---|
-| **`build/asm-llm` vs Python `.asmbin` Q8_0 ref** | **Exact (34/34)** | **`0.0000167`** | **`0.0000030`** | **`1.000000000`** | **64/64 tokens (100%)** |
-| Python `.asmbin` Q8_0 vs PyTorch FP32 `Qwen3-0.6B` | **Exact (34/34)** | `0.427719` | `0.075629` | `0.9998471` | **64/64 tokens (100%)** |
+| **`asm-llm` (`FAST_Q8=1`, INT8xINT8) vs PyTorch FP32** | **Exact (34/34)** | `0.603448` | `0.099726` | **`0.9996517`** | **64/64 tokens (100%)** |
+| **`asm-llm` (`FAST_Q8=1`, INT8xINT8) vs Python v2 Q8_0 ref** | **Exact (34/34)** | `0.583087` | `0.121621` | **`0.9996510`** | **64/64 tokens (100%)** |
+| **`asm-llm` (`FAST_Q8=0`, Q8_0xFP32) vs Python v2 Q8_0 ref** | **Exact (34/34)** | **`0.0000153`** | **`0.0000024`** | **`1.000000000`** | **64/64 tokens (100%)** |
+| Python `.asmbin` v2 (FP16 scales) vs PyTorch FP32 | **Exact (34/34)** | `0.452851` | `0.080212` | `0.9998394` | **64/64 tokens (100%)** |
-All three implementations (PyTorch FP32, Python Q8_0 reference, and the 12 KB assembly ELF) produce the exact same 64 greedy tokens.
+All configurations (PyTorch FP32, Python Q8_0 reference, `FAST_Q8=0`, and `FAST_Q8=1`) produce the exact same 64 greedy tokens, and outputs are bit-for-bit identical across `1..40` threads.
---
-## Benchmarks (AMD EPYC 7642, 47C Online, 256 MiB L3, DDR4)
+## Benchmarks: `llm.asm` vs `llama.cpp` CPU (`Q8_0`, AMD EPYC 7642)
-37 prompt tokens, 64 generated tokens, greedy decoding (`-n 64`), verified bit-for-bit identical across all thread counts:
+Head-to-head decode comparison on **AMD EPYC 7642** (47C online, 256 MiB L3, DDR4, CPU-only `-ngl 0`), `Qwen3-0.6B Q8_0`, `34` prompt tokens / `64` generated tokens, `3`-run mean (greedy, bit-for-bit identical across all thread counts):
-| Threads | Prefill (ms) | Prefill (`tok/s`) | Decode (ms) | Decode (`tok/s`) | Speedup vs 1T (Decode) | Determinism |
+| Threads | `asm-llm` `FAST_Q8=0` (v1 FP32s) | `llama.cpp` `llama-bench -ngl 0` (`Q8_0`) | **`asm-llm` `FAST_Q8=1` (v2 FP16s)** | **Speedup vs `FAST_Q8=0`** | **vs `llama.cpp`** | Determinism |
|---:|---:|---:|---:|---:|---:|---|
-| 1 | 3133.09 | 11.81 | 7910.50 | 7.96 | 1.00x | Baseline (64/64) |
-| 4 | 933.82 | 39.62 | 2330.10 | 27.04 | 3.40x | Exact match |
-| 8 | 461.59 | 80.16 | 1134.25 | 55.54 | 6.98x | Exact match |
-| 12 | 370.08 | 99.98 | 914.84 | 68.86 | 8.65x | Exact match |
-| 16 | 318.88 | 116.03 | 796.55 | 79.09 | 9.94x | Exact match |
-| 24 | 271.67 | 136.20 | 673.23 | 93.58 | 11.76x | Exact match |
-| 32 | 251.00 | 147.41 | 636.52 | 98.98 | 12.43x | Exact match |
-| **40** | **243.91** | **151.70** | **628.88** | **100.18** | **12.59x** | **Exact match** |
-| 47 | 265.49 | 139.36 | 730.02 | 86.30 | 10.84x | Exact match |
-
-Peak throughput observed on shorter live prompts at `-t 32`: **154.28 tok/s prefill** and **105.39 tok/s decode**.
+| 1 | 7.18 tok/s | 16.63 ± 0.04 tok/s | **20.70 tok/s** | **2.88x** | **1.24x (+24.5%)** | Exact (64/64) |
+| 4 | 28.12 tok/s | 51.08 ± 0.31 tok/s | **69.24 tok/s** | **2.46x** | **1.36x (+35.6%)** | Exact (64/64) |
+| 8 | 53.09 tok/s | 80.79 ± 0.68 tok/s | **103.64 tok/s** | **1.95x** | **1.28x (+28.3%)** | Exact (64/64) |
+| 16 | 77.50 tok/s | 103.03 ± 0.09 tok/s | **121.86 tok/s** | **1.57x** | **1.18x (+18.3%)** | Exact (64/64) |
+| 24 | 91.88 tok/s | 104.11 ± 0.18 tok/s | **123.72 tok/s** | **1.35x** | **1.19x (+18.8%)** | Exact (64/64) |
+| 32 | 96.63 tok/s | 103.82 ± 0.64 tok/s | **122.51 tok/s** | **1.27x** | **1.18x (+18.0%)** | Exact (64/64) |
+| **40** | **98.50 tok/s** | **105.08 ± 0.08 tok/s** | **125.86 tok/s** *(peak 126.81)* | **1.28x** | **1.20x (+19.8%)** | **Exact (64/64)** |
+
+*(Prefill note: `llama-bench` `pp34` uses batched GEMM (`56..1113 tok/s`), while `asm-llm` runs token-by-token GEMV (`26.7..160.8 tok/s` prefill at `1..40T`).)*
---
diff --git a/01-qwen3-inference/test_math.asm b/01-qwen3-inference/test_math.asm
index a7feb6d..825add9 100644
--- a/01-qwen3-inference/test_math.asm
+++ b/01-qwen3-inference/test_math.asm
@@ -7,9 +7,10 @@
; to stdout:
; stdin : [64 floats for exp] [64 floats for sincos] [128 floats x + 128 floats w for rmsnorm]
; [64 floats gate + 64 floats up for silu_mul]
-; [64 floats x_vec + 8x64 Q8_0 rows (8*72=576 bytes) for matmul]
+; [64 floats x_vec + 8x64 Q8_0 v1 fp32-scale rows (8*72=576B)
+; + 8x64 Q8_0 v2 fp16-scale rows (8*68=544B)]
; stdout: [64 exp_out] [64 sin_out] [64 cos_out] [64 rope_inv_freq f64 (512B)]
-; [128 rmsnorm_out] [64 silu_out] [8 matmul_out]
+; [128 rmsnorm_out] [64 silu_out] [8 matmul_v1_out] [8 matmul_v2_out]
; ============================================================================
bits 64
@@ -17,7 +18,11 @@ default rel
%include "constants.inc"
-%define IN_TOTAL_BYTES (2304 + 576)
+%ifndef FAST_Q8
+%define FAST_Q8 1
+%endif
+
+%define IN_TOTAL_BYTES (2304 + 576 + 544)
extern sys_write_all
extern sys_exit_group
@@ -26,6 +31,10 @@ extern fast_sincosf
extern init_rope_freqs
extern rmsnorm_avx2
extern silu_mul_avx2
+extern matmul_set_fp16
+%if FAST_Q8
+extern quantize_x_q8_0
+%endif
extern matmul_q8_0_range
section .text
@@ -115,7 +124,14 @@ _start:
mov rdx, 64
call silu_mul_avx2
- ; 6. matmul_q8_0_range Q8_0 x F32 (8 rows x 64 cols)
+ ; 6. matmul_q8_0_range (8 rows x 64 cols): v1 fp32 scales + v2 fp16 scales
+%if FAST_Q8
+ lea rdi, [rel in_mm_x]
+ mov rsi, 64
+ call quantize_x_q8_0
+%endif
+ xor edi, edi
+ call matmul_set_fp16
lea rdi, [rel in_mm_w]
lea rsi, [rel in_mm_x]
lea rdx, [rel out_mm]
@@ -124,6 +140,16 @@ _start:
mov r9, 8 ; r1 = 8
call matmul_q8_0_range
+ mov edi, 1
+ call matmul_set_fp16
+ lea rdi, [rel in_mm_w16]
+ lea rsi, [rel in_mm_x]
+ lea rdx, [rel out_mm16]
+ mov rcx, 64 ; K
+ xor r8d, r8d ; r0 = 0
+ mov r9, 8 ; r1 = 8
+ call matmul_q8_0_range
+
; Write all outputs to stdout
mov edi, 1
lea rsi, [rel out_exp]
@@ -157,7 +183,12 @@ _start:
mov edi, 1
lea rsi, [rel out_mm]
- mov edx, 32 ; 8 f32
+ mov edx, 32 ; 8 f32 (v1 fp32 scales)
+ call sys_write_all
+
+ mov edi, 1
+ lea rsi, [rel out_mm16]
+ mov edx, 32 ; 8 f32 (v2 fp16 scales)
call sys_write_all
xor edi, edi
@@ -178,7 +209,8 @@ in_rms_w: resb 512 ; 128 f32
in_gate: resb 256 ; 64 f32
in_up: resb 256 ; 64 f32
in_mm_x: resb 256 ; 64 f32
-in_mm_w: resb 576
+in_mm_w: resb 576 ; 8 * (64 + 8) v1 fp32 scales
+in_mm_w16: resb 544 ; 8 * (64 + 4) v2 fp16 scales
alignb 64
out_exp: resb 256
@@ -187,3 +219,4 @@ out_cos: resb 256
out_rope: resb 512
out_rms: resb 512
out_mm: resb 32
+out_mm16: resb 32
diff --git a/02-baremetal-os/README.md b/02-baremetal-os/README.md
index 791f960..8887779 100644
--- a/02-baremetal-os/README.md
+++ b/02-baremetal-os/README.md
@@ -1,11 +1,11 @@
-# Phase 2: Bare-Metal Bootable Qwen3-0.6B OS in 23 KB of Pure Assembly
+# Phase 2: Bare-Metal Bootable Qwen3-0.6B OS in 24 KB of Pure Assembly
A standalone bootable x86-64 operating system that runs **Qwen/Qwen3-0.6B** directly on hardware or KVM with **no Linux, no Windows, no C, no Rust, and no libc**.
-- **23,132 bytes** stripped static Multiboot 1 kernel (`build/asm-llm-os.elf`, `.text` = 16,119 B, `.rodata` = 2,676 B, `.bss` = 2.1 MiB `NOBITS`, zero dynamic dependencies).
-- **85 ms cold boot** to interactive `asm-llm>` multi-turn chat with persistent KV-cache across turns, all SMP cores online, and the 649 MiB model bound zero-copy from physical RAM.
+- **24,252 bytes** stripped static Multiboot 1 kernel (`FAST_Q8=1`, default: `.text` = 17,143 B, `.rodata` = 2,772 B, `.bss` = 2.1 MiB `NOBITS`, zero dynamic dependencies), or **23,612 bytes** (`FAST_Q8=0`, legacy Q8_0xFP32).
+- **74–94 ms cold boot** to interactive `asm-llm>` multi-turn chat with persistent KV-cache across turns, all SMP cores online, and the `.asmbin` v2 (`614 MiB` FP16 scales) or v1 (`649 MiB` FP32 scales) model bound zero-copy from physical RAM on 2 MiB huge pages.
- **100% token-exact and byte-for-byte parity** with [Phase 1](../01-qwen3-inference/) across `1..32` vCPUs.
-- **100.1 tok/s** decode on QEMU KVM (AMD EPYC 7642, 32 vCPUs) and **55.4 tok/s** live on a **0 GB disk Proxmox VE VM** (Intel Xeon E5-2670 v3, 12 cores).
+- **134.9 tok/s** decode on QEMU KVM (AMD EPYC 7642, 16 vCPUs; **23.7 tok/s** at 1 vCPU, **118.1 tok/s** at 8 vCPUs, **136.6 tok/s** peak) and **55.4 tok/s** live on a **0 GB disk Proxmox VE VM** (Intel Xeon E5-2670 v3, 12 cores).
![Bare-Metal Qwen3-0.6B OS VGA Console](../assets/baremetal-vga.png)
@@ -17,7 +17,7 @@ A standalone bootable x86-64 operating system that runs **Qwen/Qwen3-0.6B** dire
## Prerequisites
-- x86-64 CPU with **AVX2 + FMA**.
+- x86-64 CPU with **AVX2 + FMA + F16C**.
- Core build & QEMU KVM:
```bash
sudo apt install nasm binutils qemu-system-x86
@@ -26,23 +26,23 @@ A standalone bootable x86-64 operating system that runs **Qwen/Qwen3-0.6B** dire
```bash
sudo apt install grub-pc-bin grub-efi-amd64-bin grub-common mtools xorriso
```
-- An exported `models/qwen3-0.6b-q8_0.asmbin` file (see [Phase 1 setup](../01-qwen3-inference/README.md#1-download-qwenqwen3-06b)).
+- An exported `models/qwen3-0.6b-q8_0.asmbin` file (`--scale-dtype fp16` v2 recommended, or legacy v1 `--scale-dtype fp32`; see [Phase 1 setup](../01-qwen3-inference/README.md#1-download-qwenqwen3-06b)).
---
## Build
-From the repository root:
+From the repository root (`FAST_Q8=1` is enabled by default; pass `FAST_Q8=0` for legacy FP32-activation mode):
```bash
-make os
+make os FAST_Q8=1
make os-check
```
-Expected output:
+Expected output (`FAST_Q8=1`):
```text
--rwxr-xr-x 1 user user 23132 build/asm-llm-os.elf
+-rwxr-xr-x 1 user user 24252 build/asm-llm-os.elf
build/asm-llm-os.elf: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, stripped
There is no dynamic section in this file.
```
@@ -181,11 +181,11 @@ Pass via QEMU `-append "..."`, `make os-run CMDLINE='...'`, or `make os-iso CMDL
## Architecture Overview
-Phase 2 compiles the exact same `shared/math.asm`, `shared/matmul.asm`, `shared/tokenizer.asm`, and `shared/transformer.asm` with `-DBARE_METAL` and pairs them with 4,058 lines of bare-metal OS code:
+Phase 2 compiles the exact same `shared/math.asm`, `shared/matmul.asm`, `shared/tokenizer.asm`, and `shared/transformer.asm` with `-DBARE_METAL -DFAST_Q8=$(FAST_Q8)` and pairs them with 4,167 lines of bare-metal OS code:
-- **Boot & Long Mode (`boot.asm`, `linker.ld`):** verifies Multiboot 1 magic (`0x2BADB002`), zeroes `.bss`, builds 4-level 2 MiB huge-page identity tables covering `0..4 GiB` (with `0xFE000000..0xFFFFFFFF` marked Strong Uncacheable for Local APIC MMIO), enters 64-bit Long Mode, installs a 32-entry exception IDT, verifies `XSAVE + AVX + AVX2 + FMA` via CPUID, and initializes `CR0`/`CR4`/`XCR0=7`/`MXCSR`.
-- **Zero-Copy Weights & Physical Arena (`runtime.asm`):** binds the `.asmbin` Multiboot module directly at its physical address (validating `"ASML"` magic) and carves the 449 MiB KV-cache + scratch arena from the largest usable Multiboot memory-map region, zeroing it with AVX2.
-- **Bare-Metal SMP (`smp.asm`):** parses ACPI RSDP -> RSDT/XSDT -> MADT (`"APIC"`) with a Local APIC broadcast fallback, installs a position-independent 16->32->64-bit trampoline at `0x8000`, wakes all AP cores via Local APIC `INIT-SIPI-SIPI`, enables AVX2/FMA/MXCSR identically on every core, and synchronizes `matmul_q8_0` with a lock-free cache-line-isolated spin-barrier.
+- **Boot & Long Mode (`boot.asm`, `linker.ld`):** verifies Multiboot 1 magic (`0x2BADB002`), zeroes `.bss`, builds 4-level 2 MiB huge-page identity tables covering `0..4 GiB` (with `0xFE000000..0xFFFFFFFF` marked Strong Uncacheable for Local APIC MMIO), enters 64-bit Long Mode, installs a 32-entry exception IDT, verifies `XSAVE + AVX + AVX2 + FMA + F16C` via CPUID, and initializes `CR0`/`CR4`/`XCR0=7`/`MXCSR`.
+- **Zero-Copy Weights & Physical Arena (`runtime.asm`):** binds the `.asmbin` (v2 FP16 scales or v1 FP32 scales) Multiboot module directly at its physical address (validating `"ASML"` magic) and carves the 449 MiB KV-cache + scratch arena from the largest usable Multiboot memory-map region, zeroing it with AVX2.
+- **Bare-Metal SMP (`smp.asm`):** parses ACPI RSDP -> RSDT/XSDT -> MADT (`"APIC"`) with a Local APIC broadcast fallback, installs a position-independent 16->32->64-bit trampoline at `0x8000`, wakes all AP cores via Local APIC `INIT-SIPI-SIPI`, enables AVX2/FMA/MXCSR identically on every core, and dispatches both `matmul_q8_0` and `gqa_attn_range` (`FAST_Q8=1`) with a lock-free cache-line-isolated spin-barrier.
- **Hardware Drivers (`drivers.asm`):**
- **COM1 Serial (`0x3F8`, 115200 8N1):** raw UTF-8 TX and RX.
- **80x25 Color VGA (`0xB8000`):** colored boot banner, hardware scrolling, batched CRTC cursor updates, and UTF-8 decoding with Cyrillic-to-ASCII fallback on VGA while streaming raw UTF-8 to COM1.
@@ -205,16 +205,18 @@ python3 scripts/verify_os.py --model models/qwen3-0.6b-q8_0.asmbin --run-dir run
All 5 parity prompts (English technical, English concise, Russian UTF-8, arithmetic word problem, `--think` mode) match Phase 1 (`build/asm-llm`) **100% exact** in prompt tokens, generated tokens, and raw UTF-8 bytes.
-### KVM SMP Scaling (AMD EPYC 7642, 34 prompt tok, 64 gen tok, greedy)
+### KVM SMP Scaling (`FAST_Q8=1`, `.asmbin` v2 FP16 Scales, AMD EPYC 7642, 34 prompt tok, 64 gen tok, greedy)
| vCPUs (KVM) | SMP Online | Boot Ready (ms) | Boot -> 1st Tok (ms) | Prefill (ms) | Prefill (`tok/s`) | Decode (ms) | Decode (`tok/s`) | Parity vs Phase 1 |
|---:|---|---:|---:|---:|---:|---:|---:|---|
-| 1 | 1/1 | 73.57 | 3448.23 | 3358.45 | 10.12 | 8818.57 | 7.14 | **Exact (64/64)** |
-| 4 | 4/4 | 86.60 | 986.89 | 884.18 | 38.45 | 2306.86 | 27.31 | **Exact (64/64)** |
-| 8 | 8/8 | 87.43 | 516.81 | 413.25 | 82.27 | 1128.06 | 55.85 | **Exact (64/64)** |
-| 16 | 16/16 | 84.01 | 383.02 | 282.84 | 120.21 | 780.31 | 80.74 | **Exact (64/64)** |
-| 24 | 24/24 | 98.27 | 347.75 | 233.37 | **145.69** | 674.30 | 93.43 | **Exact (64/64)** |
-| **32** | **32/32** | **94.88** | **359.37** | **248.34** | **136.91** | **632.28** | **99.64** *(peak 100.10)* | **Exact (64/64)** |
+| 1 | 1/1 | 73.47 | 1161.48 | 1071.98 | 31.72 | 2685.04 | **23.46** *(peak 23.67)* | **Exact (64/64)** |
+| 4 | 4/4 | 84.10 | 425.11 | 324.82 | 104.67 | 805.95 | **78.17** *(peak 78.89)* | **Exact (64/64)** |
+| 8 | 8/8 | 84.54 | 316.71 | 215.93 | 157.46 | 529.53 | **118.97** | **Exact (64/64)** |
+| **16** | **16/16** | **84.88** | **312.87** | **211.89** | **160.46** | **466.88** | **134.94** *(peak 136.63)* | **Exact (64/64)** |
+| 24 | 24/24 | 94.27 | 288.75 | 178.32 | **190.67** | 473.44 | **133.07** | **Exact (64/64)** |
+| 32 | 32/32 | 89.84 | 313.82 | 203.53 | 167.05 | 475.72 | **132.43** *(peak 133.75)* | **Exact (64/64)** |
+
+*(Because `boot.asm` identity-maps guest RAM with 2 MiB huge pages, the bare-metal kernel avoids 4 KiB page-table walks across the 614 MiB model and outperforms both Linux `mmap()` Phase 1 and `llama.cpp` CPU `Q8_0` at every thread count.)*
### Live Proxmox VE VM (Intel Xeon E5-2670 v3, 12 Cores, 2 GiB RAM, 0 GB Disk, BIOS GRUB ISO)
diff --git a/02-baremetal-os/boot.asm b/02-baremetal-os/boot.asm
index 7b1b774..9034434 100644
--- a/02-baremetal-os/boot.asm
+++ b/02-baremetal-os/boot.asm
@@ -193,8 +193,8 @@ check_cpu_features:
push rbx
mov eax, 1
cpuid
- ; ECX: bit 12 (FMA), bit 26 (XSAVE), bit 28 (AVX)
- mov edx, (1 << 12) | (1 << 26) | (1 << 28)
+ ; ECX: bit 12 (FMA), bit 26 (XSAVE), bit 28 (AVX), bit 29 (F16C)
+ mov edx, (1 << 12) | (1 << 26) | (1 << 28) | (1 << 29)
and ecx, edx
cmp ecx, edx
jne .no
diff --git a/02-baremetal-os/smp.asm b/02-baremetal-os/smp.asm
index 2d58735..e155ac4 100644
--- a/02-baremetal-os/smp.asm
+++ b/02-baremetal-os/smp.asm
@@ -13,6 +13,10 @@ default rel
%include "constants.inc"
%include "os_constants.inc"
+%ifndef FAST_Q8
+%define FAST_Q8 1
+%endif
+
extern pml4_table
extern gdt64_ptr
extern idt64_ptr
@@ -20,12 +24,19 @@ extern enable_avx_fpu
extern pit_delay_us
extern timer_ns
extern matmul_q8_0_range
+%if FAST_Q8
+extern quantize_x_q8_0
+extern gqa_attn_range
+%endif
section .text
global smp_init
global tp_shutdown
global tp_matmul_q8_0
+%if FAST_Q8
+global tp_gqa_attn
+%endif
global g_smp_total_cpus
global g_smp_online_cpus
global g_smp_apic_base
@@ -551,8 +562,27 @@ ap_entry64:
cmp r12, r8
jae .job_done
- ; Deterministic 4-row-aligned slice [r0, r1) for tid = r12
+ ; Deterministic balanced row/head slice [r0, r1) for tid = r12
mov rcx, [rel tp_M]
+%if FAST_Q8
+ lea r9, [r8 - 1] ; N - 1
+ mov rax, rcx
+ imul rax, r12
+ add rax, r9
+ xor edx, edx
+ div r8
+ mov r14, rax ; r0
+
+ lea rax, [r12 + 1]
+ cmp rax, r8
+ je .last_slice
+ imul rax, rcx
+ add rax, r9
+ xor edx, edx
+ div r8
+ mov r15, rax ; r1
+ jmp .run_slice
+%else
mov r9, rcx
shr r9, 2 ; blocks4 = M / 4
@@ -572,6 +602,7 @@ ap_entry64:
shl rax, 2
mov r15, rax ; r1
jmp .run_slice
+%endif
.last_slice:
mov r15, rcx ; r1 = M
@@ -583,9 +614,20 @@ ap_entry64:
mov rsi, [rel tp_x]
mov rdx, [rel tp_out]
mov rcx, [rel tp_K]
+%if FAST_Q8
+ test rcx, rcx
+ jz .run_attn
+%endif
mov r8, r14 ; r0
mov r9, r15 ; r1
call matmul_q8_0_range
+ jmp .job_done
+%if FAST_Q8
+.run_attn:
+ mov rcx, r14 ; h0
+ mov r8, r15 ; h1
+ call gqa_attn_range
+%endif
.job_done:
; Lock-free TSO release store to this core's private 64B cache line
@@ -616,6 +658,22 @@ tp_shutdown:
; Exact same ABI and 4-row-aligned partitioning as Phase 1 src/threads.asm!
; ----------------------------------------------------------------------------
tp_matmul_q8_0:
+%if FAST_Q8
+ ; Quantize input vector x[0..K-1] to Q8_0 ONCE before waking AP cores
+ push rdi
+ push rsi
+ push rdx
+ push rcx
+ push r8
+ mov rdi, rsi ; x
+ mov rsi, r8 ; K
+ call quantize_x_q8_0
+ pop r8
+ pop rcx
+ pop rdx
+ pop rsi
+ pop rdi
+%endif
mov rax, [rel tp_n_threads]
cmp rax, 1
jle .single_thread
@@ -636,12 +694,19 @@ tp_matmul_q8_0:
lock xadd dword [rel tp_gen], r12d
inc r12d ; r12d = new_gen
+.run_bsp_slice:
; Run BSP's own slice (tid = 0)
mov rax, [rel tp_M]
+%if FAST_Q8
+ lea rax, [rax + rbx - 1]
+ xor edx, edx
+ div rbx ; r1 for tid = 0: ceil(M / N)
+%else
shr rax, 2 ; blocks4
xor edx, edx
div rbx
shl rax, 2 ; r1 for tid = 0
+%endif
test rax, rax
jz .wait_workers
@@ -649,9 +714,20 @@ tp_matmul_q8_0:
mov rsi, [rel tp_x]
mov rdx, [rel tp_out]
mov rcx, [rel tp_K]
+%if FAST_Q8
+ test rcx, rcx
+ jz .bsp_attn
+%endif
xor r8d, r8d ; r0 = 0
mov r9, rax ; r1
call matmul_q8_0_range
+ jmp .wait_workers
+%if FAST_Q8
+.bsp_attn:
+ xor ecx, ecx ; h0 = 0
+ mov r8, rax ; h1
+ call gqa_attn_range
+%endif
.wait_workers:
; Spin-wait for each worker tid = 1 .. n_threads - 1
@@ -684,6 +760,39 @@ tp_matmul_q8_0:
xor r8d, r8d ; r0 = 0
jmp matmul_q8_0_range
+%if FAST_Q8
+; ----------------------------------------------------------------------------
+; void tp_gqa_attn(uint64 layer_kv_base, uint64 pos, uint64 scale_gqa_packed,
+; uint64 n_heads)
+; Dispatches GQA attention across SMP AP cores (tp_K = 0 signals attn job).
+; ----------------------------------------------------------------------------
+tp_gqa_attn:
+ mov rax, [rel tp_n_threads]
+ cmp rax, 1
+ jle .attn_single
+
+ push rbx
+ push r12
+ sub rsp, 8
+ mov rbx, rax
+
+ mov [rel tp_W], rdi
+ mov [rel tp_x], rsi
+ mov [rel tp_out], rdx
+ mov [rel tp_M], rcx
+ mov qword [rel tp_K], 0
+
+ mov r12d, 1
+ lock xadd dword [rel tp_gen], r12d
+ inc r12d
+ jmp tp_matmul_q8_0.run_bsp_slice
+
+.attn_single:
+ mov r8, rcx ; h1 = n_heads
+ xor ecx, ecx ; h0 = 0
+ jmp gqa_attn_range
+%endif
+
; ============================================================================
; Position-Independent 16-bit -> 32-bit -> 64-bit AP Trampoline (copied to 0x8000)
; ZERO relocations inside this block — all offsets evaluated at assembly time!
diff --git a/Makefile b/Makefile
index 444a486..4ae546d 100644
--- a/Makefile
+++ b/Makefile
@@ -5,16 +5,20 @@ OBJCOPY := objcopy
LDFLAGS := --gc-sections -s -z noexecstack -z noseparate-code
BUILD := build
-# Portable defaults (override on CLI, e.g. make os-iso MODEL=path/to/model.asmbin)
+# Portable defaults (override on CLI, e.g. make inference FAST_Q8=0)
+FAST_Q8 ?= 1
MODEL ?= models/qwen3-0.6b-q8_0.asmbin
DATA ?= data/tinyshakespeare.txt
SMP ?= 16
RAM ?= 2G
CMDLINE ?=
+# Stamp file tracks FAST_Q8 compile-time toggle so toggling rebuilds cleanly
+FAST_Q8_STAMP := $(BUILD)/.fast_q8_$(FAST_Q8)
+
# --- Shared x86-64 NASM modules ---
SHARED_DIR := shared
-AFLAGS := -f elf64 -I$(SHARED_DIR)/
+AFLAGS := -f elf64 -DFAST_Q8=$(FAST_Q8) -I$(SHARED_DIR)/
# --- Phase 1: Qwen3-0.6B Linux Inference Engine (12 KB static ELF) ---
P1_DIR := 01-qwen3-inference
@@ -43,7 +47,7 @@ OS_BUILD := $(BUILD)/os
OS_ELF64 := $(OS_BUILD)/asm-llm-os.elf64
OS_ELF := $(BUILD)/asm-llm-os.elf
OS_ISO := $(BUILD)/asm-llm-os.iso
-OS_AFLAGS := -f elf64 -DBARE_METAL -I$(SHARED_DIR)/ -I$(P2_DIR)/
+OS_AFLAGS := -f elf64 -DBARE_METAL -DFAST_Q8=$(FAST_Q8) -I$(SHARED_DIR)/ -I$(P2_DIR)/
OS_LDFLAGS := -m elf_x86_64 -T $(P2_DIR)/linker.ld --gc-sections -s -z max-page-size=0x1000 -z noexecstack
OS_OBJS := \
@@ -84,13 +88,16 @@ test-math: $(TEST)
$(BUILD):
mkdir -p $(BUILD)
-$(BUILD)/%.o: $(SHARED_DIR)/%.asm $(SHARED_DIR)/constants.inc | $(BUILD)
+$(FAST_Q8_STAMP): | $(BUILD)
+ rm -f $(BUILD)/.fast_q8_* && touch $@
+
+$(BUILD)/%.o: $(SHARED_DIR)/%.asm $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(BUILD)
$(NASM) $(AFLAGS) $< -o $@
$(BUILD)/main.o: $(P1_DIR)/main.asm $(SHARED_DIR)/constants.inc | $(BUILD)
$(NASM) $(AFLAGS) $< -o $@
-$(BUILD)/test_math.o: $(P1_DIR)/test_math.asm $(SHARED_DIR)/constants.inc | $(BUILD)
+$(BUILD)/test_math.o: $(P1_DIR)/test_math.asm $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(BUILD)
$(NASM) $(AFLAGS) $< -o $@
$(TARGET): $(P1_OBJS)
@@ -109,19 +116,19 @@ check: $(TARGET)
$(OS_BUILD):
mkdir -p $(OS_BUILD)
-$(OS_BUILD)/%.o: $(P2_DIR)/%.asm $(P2_DIR)/os_constants.inc $(SHARED_DIR)/constants.inc | $(OS_BUILD)
+$(OS_BUILD)/%.o: $(P2_DIR)/%.asm $(P2_DIR)/os_constants.inc $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
$(OS_BUILD)/math.o: $(SHARED_DIR)/math.asm | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
-$(OS_BUILD)/matmul.o: $(SHARED_DIR)/matmul.asm | $(OS_BUILD)
+$(OS_BUILD)/matmul.o: $(SHARED_DIR)/matmul.asm $(FAST_Q8_STAMP) | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
$(OS_BUILD)/tokenizer.o: $(SHARED_DIR)/tokenizer.asm $(SHARED_DIR)/constants.inc | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
-$(OS_BUILD)/transformer.o: $(SHARED_DIR)/transformer.asm $(SHARED_DIR)/constants.inc | $(OS_BUILD)
+$(OS_BUILD)/transformer.o: $(SHARED_DIR)/transformer.asm $(SHARED_DIR)/constants.inc $(FAST_Q8_STAMP) | $(OS_BUILD)
$(NASM) $(OS_AFLAGS) $< -o $@
$(OS_ELF64): $(OS_OBJS) $(P2_DIR)/linker.ld
diff --git a/README.md b/README.md
index 3cc9886..aef47dc 100644
--- a/README.md
+++ b/README.md
@@ -3,15 +3,33 @@
**Three complete LLM projects written in 100% pure x86-64 NASM assembly.**
Zero C, zero C++, zero Rust, zero libc, zero libm, zero runtime dependencies.
-Assembled directly with `nasm` and linked with `ld`. Every math kernel (`expf`, `sincosf`, `RMSNorm`, `RoPE`, `SiLU`, `Softmax`), AVX2+FMA GEMM/GEMV engine, BPE tokenizer, `clone()`/`futex()` thread pool, bare-metal SMP kernel, analytical backward pass, AdamW optimizer, and live Unicode Braille TUI is hand-written x86-64 assembly (`16,275` lines total across all three projects).
+Assembled directly with `nasm` and linked with `ld`. Every math kernel (`expf`, `sincosf`, `RMSNorm`, `RoPE`, `SiLU`, `Softmax`), AVX2+FMA+F16C GEMM/GEMV engine, BPE tokenizer, `clone()`/`futex()` thread pool, bare-metal SMP kernel, analytical backward pass, AdamW optimizer, and live Unicode Braille TUI is hand-written x86-64 assembly (`17,252` lines total across all three projects).
## The Trilogy
| Project | Binary | Size | Deps | Key Numbers |
|---|---|---:|---:|---|
-| **[01-qwen3-inference/](01-qwen3-inference/)** | `build/asm-llm` | **13,528 B** | **0** | Static Linux ELF running `Qwen/Qwen3-0.6B` (Q8_0, built-in BPE tokenizer, GQA + QK-Norm + RoPE + SwiGLU, single-shot & `--chat` multi-turn KV-cache REPL). **105.4 tok/s** peak decode, **`1.000000000`** cosine vs Q8_0 ref, **64/64** exact greedy token match vs PyTorch FP32. |
-| **[02-baremetal-os/](02-baremetal-os/)** | `build/asm-llm-os.elf` | **23,132 B** | **0** | Bootable bare-metal `Qwen3-0.6B` OS with no Linux or Windows. Multiboot 1 -> Long Mode -> AVX2/FMA -> ACPI/APIC SMP -> VGA + PS/2 + COM1 multi-turn KV-cache chat (`/clear`, `/think`, `/bench`). **85 ms** boot, **100.1 tok/s** KVM EPYC, **55.4 tok/s** live on Proxmox Xeon E5-2670 v3 with **0 GB** disk. |
-| **[03-minigpt-train/](03-minigpt-train/)** | `build/asm-gpt-train` | **32,752 B** | **0** | From-scratch FP32 Mini-GPT trainer and sampler. Register-blocked `6x16` AVX2+FMA SGEMM, full analytical backward pass (**`1.0000000000`** cosine across all 21 gradient tensors vs PyTorch CPU), decoupled AdamW, **27,662 train tok/s**, live 80x24 Braille TUI, `val_loss 4.19 -> 1.51` on TinyShakespeare in 4 min. |
+| **[01-qwen3-inference/](01-qwen3-inference/)** | `build/asm-llm` | **14,712 B** *(14,008 B `FAST_Q8=0`)* | **0** | Static Linux ELF running `Qwen/Qwen3-0.6B` (Q8_0, built-in BPE tokenizer, GQA + QK-Norm + RoPE + SwiGLU, single-shot & `--chat` multi-turn KV-cache REPL). **`FAST_Q8=1` (default):** **126.8 tok/s** decode at 40T (**20.7 tok/s** at 1T), **+18% to +36% faster than `llama.cpp` CPU (`Q8_0`) across 1..40T**, **`0.99965`** cosine & **64/64** exact greedy tokens vs PyTorch FP32. |
+| **[02-baremetal-os/](02-baremetal-os/)** | `build/asm-llm-os.elf` | **24,252 B** *(23,612 B `FAST_Q8=0`)* | **0** | Bootable bare-metal `Qwen3-0.6B` OS with no Linux or Windows. Multiboot 1 -> Long Mode -> AVX2/FMA/F16C -> ACPI/APIC SMP -> VGA + PS/2 + COM1 multi-turn KV-cache chat (`/clear`, `/think`, `/bench`). **74–94 ms** boot, **134.9 tok/s** KVM EPYC (**23.7 tok/s** 1 vCPU, **136.6 tok/s** peak), **55.4 tok/s** live on Proxmox Xeon E5-2670 v3 with **0 GB** disk. |
+| **[03-minigpt-train/](03-minigpt-train/)** | `build/asm-gpt-train` | **32,944 B** | **0** | From-scratch FP32 Mini-GPT trainer and sampler. Register-blocked `6x16` AVX2+FMA SGEMM, full analytical backward pass (**`1.0000000000`** cosine across all 21 gradient tensors vs PyTorch CPU), decoupled AdamW, **27,662 train tok/s**, live 80x24 Braille TUI, `val_loss 4.19 -> 1.51` on TinyShakespeare in 4 min. |
+
+---
+
+## Head-to-Head CPU Decode Benchmark: `llm.asm` vs `llama.cpp` (`Qwen3-0.6B Q8_0`)
+
+Measured on the same machine (**AMD EPYC 7642**, 47C online, 256 MiB L3, DDR4, CPU-only `-ngl 0`), same model (`Qwen3-0.6B Q8_0`: `613.66 MiB` `.asmbin` v2 FP16-scale vs `604.15 MiB` GGUF `Q8_0`), `34` prompt tokens / `64` generated tokens, `3`-run average:
+
+| Threads | `llm.asm` (`FAST_Q8=0`, FP32 act) | `llama.cpp` (`Q8_0`, `-ngl 0`) | **`llm.asm` (`FAST_Q8=1`, 14.7 KB)** | **vs `llama.cpp`** | **Bare-Metal OS KVM (`FAST_Q8=1`)** |
+|---:|---:|---:|---:|---:|---:|
+| **1** | 7.18 tok/s | 16.63 tok/s | **20.70 tok/s** | **1.24x (+24.5%)** | **23.67 tok/s** |
+| **4** | 28.12 tok/s | 51.08 tok/s | **69.24 tok/s** | **1.36x (+35.6%)** | **78.89 tok/s** |
+| **8** | 53.09 tok/s | 80.79 tok/s | **103.64 tok/s** | **1.28x (+28.3%)** | **118.08 tok/s** |
+| **16** | 77.50 tok/s | 103.03 tok/s | **121.86 tok/s** | **1.18x (+18.3%)** | **134.94 tok/s** |
+| **24** | 91.88 tok/s | 104.11 tok/s | **123.72 tok/s** | **1.19x (+18.8%)** | **132.90 tok/s** |
+| **32** | 96.63 tok/s | 103.82 tok/s | **122.51 tok/s** | **1.18x (+18.0%)** | **133.75 tok/s** |
+| **40** | 98.50 tok/s | 105.08 tok/s | **125.86 tok/s** *(peak 126.81)* | **1.20x (+19.8%)** | — |
+
+*(Note: `llama.cpp` uses batched GEMM for prompt prefill `pp34`, whereas `llm.asm` runs token-by-token GEMV. For autoregressive decode `tg64`, `llm.asm` (`FAST_Q8=1`) combines INT8xINT8 AVX2 `vpmaddubsw`/`vpmaddwd`, `.asmbin` v2 FP16 block scales (`F16C vcvtph2ps`), monotonic next-row prefetch, contiguous head-major KV-cache, and parallel GQA attention — beating `llama.cpp` by +18%..+36% across 1..40 threads while producing bit-exact deterministic outputs across all thread counts. The bare-metal OS gains another ~10% from 2 MiB huge-page identity mapping.)*
---
@@ -66,11 +84,13 @@ cd llm.asm
make all
```
-### 1. Run Qwen3-0.6B Inference in 13 KB (`01-qwen3-inference/`)
+### 1. Run Qwen3-0.6B Inference in 14 KB (`01-qwen3-inference/`)
```bash
-python3 scripts/export_weights.py --model-dir models/qwen3-0.6b-bf16 --out models/qwen3-0.6b-q8_0.asmbin
-make inference
+# Export compact .asmbin v2 (FP16 block scales, 613.66 MiB; or --scale-dtype fp32 for legacy v1)
+python3 scripts/export_weights.py --model-dir models/qwen3-0.6b-bf16 --out models/qwen3-0.6b-q8_0.asmbin --scale-dtype fp16
+# Build with FAST_Q8=1 (default: INT8xINT8 AVX2 + parallel GQA) or FAST_Q8=0 (exact FP32 activations)
+make inference FAST_Q8=1
./build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin -p "Explain how a CPU cache works in 3 concise sentences." -n 128 -t 16
# Or start an interactive multi-turn chat preserving the KV-cache across turns:
./build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin --chat -t 16
@@ -78,10 +98,10 @@ make inference
Full step-by-step setup, model download, CLI flags, and benchmarks: **[01-qwen3-inference/README.md](01-qwen3-inference/README.md)**.
-### 2. Boot Bare-Metal Qwen3-0.6B OS in 23 KB (`02-baremetal-os/`)
+### 2. Boot Bare-Metal Qwen3-0.6B OS in 24 KB (`02-baremetal-os/`)
```bash
-make os
+make os FAST_Q8=1
make os-run MODEL=models/qwen3-0.6b-q8_0.asmbin SMP=16
# Or build a bootable BIOS+UEFI ISO for QEMU / Proxmox VE:
make os-iso MODEL=models/qwen3-0.6b-q8_0.asmbin
@@ -113,19 +133,19 @@ llm.asm/
├── assets/
│ ├── baremetal-vga.png # QEMU KVM 80x25 VGA text-mode capture (EPYC 7642, 16 cores)
│ └── proxmox-vm250-vga.png # Real Proxmox VE 0 GB disk VM capture (Xeon E5-2670 v3, 12 cores)
-├── shared/ # Pure x86-64 NASM core reused across phases (3,022 lines)
-│ ├── constants.inc # Linux syscalls, .asmbin header, runtime context offsets
+├── shared/ # Pure x86-64 NASM core reused across phases (3,857 lines)
+│ ├── constants.inc # Linux syscalls, .asmbin v1/v2 header, runtime context offsets
│ ├── syscalls.asm # Raw Linux syscalls + string/number formatting helpers
-│ ├── math.asm # AVX2/SSE2 expf, sincosf, FP64 RoPE, RMSNorm, Softmax, SiLU, top-p
-│ ├── matmul.asm # 4-row unrolled AVX2+FMA Q8_0 x FP32 matmul, dequant, dot, saxpy
-│ ├── threads.asm # Zero-libc Linux clone() + futex() lock-free thread pool
+│ ├── math.asm # AVX2/SSE2 expf, sincosf, FP64 RoPE, RMSNorm, Softmax, SiLU, argmax, top-p
+│ ├── matmul.asm # FAST_Q8=1 INT8xINT8 AVX2+F16C & FAST_Q8=0 Q8_0xFP32 matmul, dequant, dot, saxpy
+│ ├── threads.asm # Zero-libc Linux clone() + hybrid spin/futex thread pool (matmul + GQA attn)
│ ├── tokenizer.asm # Fibonacci-hashed BPE encoder, UTF-8 decoder, Qwen3 chat template
-│ └── transformer.asm # Full 28-layer Qwen3 forward pass (mmap & bare-metal zero-copy)
-├── 01-qwen3-inference/ # Phase 1: 13 KB static Linux ELF inference engine + --chat (1,218 lines)
+│ └── transformer.asm # Full 28-layer Qwen3 forward pass (v1/v2 auto-detect, contiguous KV, parallel GQA)
+├── 01-qwen3-inference/ # Phase 1: 14 KB static Linux ELF inference engine + --chat (1,251 lines)
│ ├── README.md
│ ├── main.asm
│ └── test_math.asm
-├── 02-baremetal-os/ # Phase 2: 23 KB bare-metal bootable LLM OS (4,058 lines)
+├── 02-baremetal-os/ # Phase 2: 24 KB bare-metal bootable LLM OS (4,167 lines)
│ ├── README.md
│ ├── boot.asm # Multiboot 1 -> 4-level paging -> Long Mode -> AVX2/FMA -> IDT
│ ├── drivers.asm # COM1 115200, 80x25 Color VGA, PS/2 keyboard, PIT+RDTSC, ACPI poweroff
@@ -155,7 +175,7 @@ llm.asm/
## System Requirements
-- **CPU:** x86-64 with **AVX2 + FMA** (Intel Haswell / AMD Excavator or newer).
+- **CPU:** x86-64 with **AVX2 + FMA + F16C** (Intel Haswell / AMD Excavator or newer).
- **Build tools:** `nasm` and GNU `binutils` (`ld`, `objcopy`).
```bash
sudo apt install nasm binutils
@@ -171,8 +191,8 @@ llm.asm/
Every phase is built on the same engineering rules: no runtime libraries, deterministic parallel partitioning, and numerical verification against independent Python/PyTorch references.
- **Shared assembly core (`shared/`):** Phase 2 compiles the exact same `math.asm`, `matmul.asm`, `tokenizer.asm`, and `transformer.asm` with `-DBARE_METAL` (swapping Linux `mmap`/`clone`/`write` for physical Multiboot modules, APIC spin-barriers, and VGA+COM1 drivers). Phase 3 reuses `syscalls.asm` and `math.asm`.
-- **Phase 1 verification:** All 7 math/SIMD kernels pass unit tests within `1e-7..1e-6` (`init_rope_freqs` FP64 `< 5e-14`). Full `Qwen3-0.6B` logits match the Python Q8_0 reference with `cosine = 1.000000000` (`max_abs_diff = 1.67e-5`) and match PyTorch FP32 for **64/64 greedy tokens**. Deterministic from `1T` to `47T`.
-- **Phase 2 verification:** **100% token-exact and byte-for-byte identical** to Phase 1 across 5 test prompts (English, Russian UTF-8, arithmetic, `--think` mode) and across `1..32` KVM vCPUs. Verified on both QEMU KVM (AMD EPYC 7642) and a real Proxmox VE VM (Intel Xeon E5-2670 v3, 0 GB disk, BIOS GRUB ISO).
+- **Phase 1 verification:** All math/SIMD kernels pass unit tests within `1e-7..1e-6` (`init_rope_freqs` FP64 `< 5e-14`) for both `FAST_Q8=1` and `FAST_Q8=0` across v1 FP32 and v2 FP16 scale formats. `FAST_Q8=1` matches PyTorch FP32 `Qwen3-0.6B` with `cosine = 0.9996517` and **64/64 exact greedy tokens** (`FAST_Q8=0` matches the Python Q8_0 reference with `cosine = 1.000000000`). Bit-exact deterministic from `1T` to `40T`.
+- **Phase 2 verification:** **100% token-exact and byte-for-byte identical** to Phase 1 across 5 test prompts (English, Russian UTF-8, arithmetic, `--think` mode), multi-turn KV-cache recall + `/clear`, and across `1..32` KVM vCPUs (`134.9 tok/s` at 16 vCPUs). Verified on both QEMU KVM (AMD EPYC 7642) and a real Proxmox VE VM (Intel Xeon E5-2670 v3, 0 GB disk, BIOS GRUB ISO).
- **Phase 3 verification:** Verified against PyTorch FP32 CPU on all **21 parameter tensors** (`worst max_abs_diff = 3.35e-8`, `min cosine_sim = 1.0000000000`), 10-step AdamW + cosine LR + grad-clip trajectory (`max_loss_diff = 4.77e-7`), and bit-exact determinism across `1T`, `8T`, and `16T`.
See each project's README for full tables, memory layouts, and reproduction steps:
diff --git a/scripts/export_weights.py b/scripts/export_weights.py
index 8798049..33e8681 100644
--- a/scripts/export_weights.py
+++ b/scripts/export_weights.py
@@ -5,9 +5,11 @@ Export Qwen3-0.6B (BF16 safetensors + tokenizer.json) into a compact,
Weight format: Per-row split Q8_0 (block size = 32, symmetric int8 in [-127, 127]):
Each row of K elements (K multiple of 32) is stored as:
- [K bytes of int8 quantized weights] [K/32 * 4 bytes of fp32 block scales]
- For Qwen3-0.6B (K in {1024, 2048, 3072}), every row stride is an exact
- multiple of 64 bytes (1152, 2304, 3456), ensuring 32-byte aligned AVX2 loads.
+ - v2 (--scale-dtype fp16, default): [K int8 weights][K/32 * 2B fp16 scales]
+ For Qwen3-0.6B (K in {1024, 2048, 3072}), row strides are {1088, 2176, 3264} B.
+ - v1 (--scale-dtype fp32): [K int8 weights][K/32 * 4B fp32 scales]
+ For Qwen3-0.6B (K in {1024, 2048, 3072}), row strides are {1152, 2304, 3456} B.
+ Every row stride is an exact multiple of 64 bytes, ensuring 32-byte aligned AVX2 loads.
"""
import argparse
@@ -18,7 +20,11 @@ import time
import numpy as np
MAGIC = b"ASML"
-VERSION = 1
+VERSION_V1 = 1
+VERSION_V2 = 2
+FLAG_TIED_EMB = 1
+FLAG_QK_NORM = 2
+FLAG_FP16_SCALES = 4
HEADER_SIZE = 128
TOK_HEADER_SIZE = 64
HT_BITS = 19
@@ -82,7 +88,7 @@ def read_tensor_f32(f, hdr, data_offset: int, name: str) -> np.ndarray:
raise ValueError(f"Unsupported dtype {dtype} for tensor {name}")
-def quantize_matrix_q8_0_row_split(w: np.ndarray) -> bytes:
+def quantize_matrix_q8_0_row_split(w: np.ndarray, scale_dtype: str = "fp16") -> bytes:
"""Quantize [M, K] float32 matrix into per-row split Q8_0 bytes."""
assert w.ndim == 2
M, K = w.shape
@@ -90,14 +96,25 @@ def quantize_matrix_q8_0_row_split(w: np.ndarray) -> bytes:
nb = K // 32
blocks = w.reshape(M, nb, 32).astype(np.float32, copy=False)
amax = np.max(np.abs(blocks), axis=2) # [M, nb]
- scale = np.where(amax > 0.0, amax / np.float32(127.0), np.float32(0.0)).astype(np.float32)
- inv_scale = np.where(scale > 0.0, np.float32(1.0) / scale, np.float32(0.0)).astype(np.float32)
- q = np.clip(np.rint(blocks * inv_scale[:, :, None]), -127, 127).astype(np.int8)
+ scale_f32 = np.where(amax > 0.0, amax / np.float32(127.0), np.float32(0.0)).astype(np.float32)
+ if scale_dtype == "fp16":
+ scale_f16 = scale_f32.astype(np.float16)
+ scale_eff = scale_f16.astype(np.float32)
+ inv_scale = np.where(scale_eff > 0.0, np.float32(1.0) / scale_eff, np.float32(0.0)).astype(np.float32)
+ q = np.clip(np.rint(blocks * inv_scale[:, :, None]), -127, 127).astype(np.int8)
+ s_bytes = scale_f16.astype("<f2").view(np.uint8).reshape(M, nb * 2)
+ scale_bytes_per_block = 2
+ elif scale_dtype == "fp32":
+ inv_scale = np.where(scale_f32 > 0.0, np.float32(1.0) / scale_f32, np.float32(0.0)).astype(np.float32)
+ q = np.clip(np.rint(blocks * inv_scale[:, :, None]), -127, 127).astype(np.int8)
+ s_bytes = scale_f32.astype("<f4").view(np.uint8).reshape(M, nb * 4)
+ scale_bytes_per_block = 4
+ else:
+ raise ValueError(f"Unsupported scale_dtype: {scale_dtype}")
q_flat = q.reshape(M, K) # [M, K] int8
- s_bytes = scale.view(np.uint8).reshape(M, nb * 4) # [M, nb*4] uint8
- # Pack each row contiguously: [K int8][nb*4 scale bytes]
+ # Pack each row contiguously: [K int8][nb*scale_bytes_per_block scale bytes]
row_packed = np.concatenate([q_flat.view(np.uint8), s_bytes], axis=1)
- assert row_packed.shape == (M, K + nb * 4)
+ assert row_packed.shape == (M, K + nb * scale_bytes_per_block)
return row_packed.tobytes()
@@ -203,8 +220,10 @@ def build_tokenizer_blob(tok_json_path: str, vocab_size: int) -> bytes:
return bytes(buf)
-def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096):
+def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_dtype: str = "fp16"):
t0 = time.time()
+ use_fp16 = scale_dtype == "fp16"
+ version = VERSION_V2 if use_fp16 else VERSION_V1
with open(os.path.join(model_dir, "config.json"), "r") as f:
cfg = json.load(f)
@@ -244,8 +263,8 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096):
assert max_diff == 0.0, f"tie_word_embeddings=True but diff={max_diff}"
print("Verified embed_tokens == lm_head exact (max_diff=0.0)")
del lmh
- print(f"Quantizing embed_tokens {emb.shape} -> Q8_0...")
- out.write(quantize_matrix_q8_0_row_split(emb))
+ print(f"Quantizing embed_tokens {emb.shape} -> Q8_0 (scale_dtype={scale_dtype}, v{version})...")
+ out.write(quantize_matrix_q8_0_row_split(emb, scale_dtype=scale_dtype))
del emb
# 3. Transformer layers (fixed 64-byte aligned stride)
@@ -285,7 +304,7 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096):
pad64(out)
mat = read_tensor_f32(sf, hdr, data_offset, name)
assert mat.shape == expected_shape, f"{name}: got {mat.shape}, expected {expected_shape}"
- out.write(quantize_matrix_q8_0_row_split(mat))
+ out.write(quantize_matrix_q8_0_row_split(mat, scale_dtype=scale_dtype))
layer_end = pad64(out)
this_stride = layer_end - layer_start
@@ -305,13 +324,13 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096):
file_size = pad64(out)
# Write 128-byte header
- flags = (1 if tie_emb else 0) | 2 # bit0=tied_emb, bit1=qk_norm
+ flags = (FLAG_TIED_EMB if tie_emb else 0) | FLAG_QK_NORM | (FLAG_FP16_SCALES if use_fp16 else 0)
eos_1 = 151645 # <|im_end|>
eos_2 = 151643 # <|endoftext|>
header = struct.pack(
"<4sIIIIIIIIIffIIIIQQQQQQ16s",
MAGIC,
- VERSION,
+ version,
dim,
hidden_dim,
n_layers,
@@ -340,6 +359,7 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096):
dt = time.time() - t0
print(f"\nExport complete: {out_path}")
+ print(f" Format : .asmbin v{version} (scale_dtype={scale_dtype}, flags=0x{flags:x})")
print(f" Total size : {file_size:,} bytes ({file_size / (1024**2):.2f} MiB)")
print(f" off_tokenizer: {off_tokenizer:,}")
print(f" off_embed : {off_embed:,}")
@@ -353,8 +373,9 @@ def main():
ap.add_argument("--model-dir", default="models/qwen3-0.6b-bf16", help="Directory containing Qwen3-0.6B config.json, model.safetensors, tokenizer.json")
ap.add_argument("--out", default="models/qwen3-0.6b-q8_0.asmbin", help="Output .asmbin path")
ap.add_argument("--max-seq-len", type=int, default=4096)
+ ap.add_argument("--scale-dtype", choices=["fp16", "fp32"], default="fp16", help="Per-block Q8_0 scale dtype (fp16 -> v2 compact, fp32 -> v1 legacy)")
args = ap.parse_args()
- export_model(args.model_dir, args.out, args.max_seq_len)
+ export_model(args.model_dir, args.out, args.max_seq_len, scale_dtype=args.scale_dtype)
if __name__ == "__main__":
diff --git a/scripts/test_math.py b/scripts/test_math.py
index b78ff6a..2d5b3fa 100644
--- a/scripts/test_math.py
+++ b/scripts/test_math.py
@@ -34,13 +34,18 @@ def main():
])
in_up = rng.normal(0.0, 2.0, size=64).astype(np.float32)
- # 5. matmul Q8_0 x Q8_0 (8 rows x 64 cols)
+ # 5. matmul Q8_0 (8 rows x 64 cols): v1 fp32 scales + v2 fp16 scales
in_mm_x = rng.normal(0.0, 1.5, size=64).astype(np.float32)
w_f32 = rng.normal(0.0, 0.5, size=(8, 64)).astype(np.float32)
wb = w_f32.reshape(8, 2, 32)
ws = (np.max(np.abs(wb), axis=2) / np.float32(127.0)).astype(np.float32)
wq = np.clip(np.rint(wb / ws[:, :, None]), -127, 127).astype(np.int8)
- in_mm_w = np.concatenate([wq.reshape(8, 64).view(np.uint8), ws.view(np.uint8).reshape(8, 8)], axis=1).tobytes()
+ in_mm_w = np.concatenate([wq.reshape(8, 64).view(np.uint8), ws.astype("<f4").view(np.uint8).reshape(8, 8)], axis=1).tobytes()
+
+ ws16 = ws.astype(np.float16)
+ ws16_f32 = ws16.astype(np.float32)
+ wq16 = np.clip(np.rint(wb / ws16_f32[:, :, None]), -127, 127).astype(np.int8)
+ in_mm_w16 = np.concatenate([wq16.reshape(8, 64).view(np.uint8), ws16.astype("<f2").view(np.uint8).reshape(8, 4)], axis=1).tobytes()
payload = (
in_exp.tobytes()
@@ -51,6 +56,7 @@ def main():
+ in_up.tobytes()
+ in_mm_x.tobytes()
+ in_mm_w
+ + in_mm_w16
)
proc = subprocess.run([bin_path], input=payload, capture_output=True, check=True)
@@ -71,6 +77,7 @@ def main():
out_rms = take("<f4", 128)
out_silu = take("<f4", 64)
out_mm = take("<f4", 8)
+ out_mm16 = take("<f4", 8)
assert off == len(raw), f"Extra output bytes: {len(raw) - off}"
# References
@@ -96,16 +103,36 @@ def main():
rel_silu = np.max(np.abs(out_silu.astype(np.float64) - ref_silu) / np.maximum(np.abs(ref_silu), 1.0))
xb = in_mm_x.reshape(2, 32).astype(np.float32)
- ref_mm = np.sum(np.einsum("mnb,nb->mn", wq.astype(np.float32), xb) * ws, axis=1).astype(np.float32)
- err_mm = np.max(np.abs(out_mm - ref_mm))
-
+ ref_mm_f32 = np.sum(np.einsum("mnb,nb->mn", wq.astype(np.float32), xb) * ws, axis=1).astype(np.float32)
+ ref_mm16_f32 = np.sum(np.einsum("mnb,nb->mn", wq16.astype(np.float32), xb) * ws16_f32, axis=1).astype(np.float32)
+
+ # Exact Q8_0 x Q8_0 reference for FAST_Q8=1 builds
+ x_amax = np.max(np.abs(xb), axis=1)
+ xs = (x_amax * np.float32(1.0 / 127.0)).astype(np.float32)
+ x_inv = np.where(x_amax > 0.0, np.float32(127.0) / x_amax, np.float32(0.0)).astype(np.float32)
+ xq = np.clip(np.rint(xb * x_inv[:, None]), -127, 127).astype(np.int8)
+ ref_mm_q8 = np.sum(np.einsum("mnb,nb->mn", wq.astype(np.int32), xq.astype(np.int32)).astype(np.float32) * (ws * xs[None, :]), axis=1).astype(np.float32)
+ ref_mm16_q8 = np.sum(np.einsum("mnb,nb->mn", wq16.astype(np.int32), xq.astype(np.int32)).astype(np.float32) * (ws16_f32 * xs[None, :]), axis=1).astype(np.float32)
+
+ err_mm_f32 = float(np.max(np.abs(out_mm - ref_mm_f32)))
+ err_mm_q8 = float(np.max(np.abs(out_mm - ref_mm_q8)))
+ err_mm16_f32 = float(np.max(np.abs(out_mm16 - ref_mm16_f32)))
+ err_mm16_q8 = float(np.max(np.abs(out_mm16 - ref_mm16_q8)))
+
+ fast_mode = err_mm_q8 < err_mm_f32
+ mode_str = "FAST_Q8=1 (Q8_0xQ8_0)" if fast_mode else "FAST_Q8=0 (Q8_0xFP32)"
+ err_mm = err_mm_q8 if fast_mode else err_mm_f32
+ err_mm16 = err_mm16_q8 if fast_mode else err_mm16_f32
+
+ print(f"Detected matmul mode: {mode_str}")
print(f"fast_expf_avx2 max_rel_err = {rel_exp:.3e} (target < 1e-6)")
print(f"fast_sincosf sin max_abs_err = {err_sin:.3e} (target < 1e-6)")
print(f"fast_sincosf cos max_abs_err = {err_cos:.3e} (target < 1e-6)")
print(f"init_rope_freqs max_abs_err = {err_rope:.3e} (target < 1e-12)")
print(f"rmsnorm_avx2 max_abs_err = {err_rms:.3e} (target < 1e-6)")
print(f"silu_mul_avx2 max_rel_err = {rel_silu:.3e} (target < 1e-6)")
- print(f"matmul_q8_0 max_abs_err = {err_mm:.3e} (target < 1e-5)")
+ print(f"matmul_q8_0 v1 max_abs_err = {err_mm:.3e} (target < 1e-5, vs FP32={err_mm_f32:.3e})")
+ print(f"matmul_q8_0 v2 max_abs_err = {err_mm16:.3e} (target < 1e-5, vs FP32={err_mm16_f32:.3e})")
assert rel_exp < 1e-6, f"expf error too high: {rel_exp}"
assert err_sin < 1e-6, f"sinf error too high: {err_sin}"
@@ -113,7 +140,8 @@ def main():
assert err_rope < 1e-12, f"rope freq error too high: {err_rope}"
assert err_rms < 1e-6, f"rmsnorm error too high: {err_rms}"
assert rel_silu < 1e-6, f"silu error too high: {rel_silu}"
- assert err_mm < 1e-5, f"matmul error too high: {err_mm}"
+ assert err_mm < 1e-5, f"matmul v1 error too high: {err_mm}"
+ assert err_mm16 < 1e-5, f"matmul v2 error too high: {err_mm16}"
print("\nALL PURE-ASM MATH & SIMD KERNEL UNIT TESTS PASSED!")
diff --git a/scripts/verify_ref.py b/scripts/verify_ref.py
index 46508e6..0f1af5d 100644
--- a/scripts/verify_ref.py
+++ b/scripts/verify_ref.py
@@ -34,7 +34,7 @@ class AsmBinModel:
hdr = struct.unpack_from("<4sIIIIIIIIIffIIIIQQQQQQ", self.buf, 0)
assert hdr[0] == b"ASML", f"Bad magic: {hdr[0]}"
- assert hdr[1] == 1, f"Bad version: {hdr[1]}"
+ assert hdr[1] in (1, 2), f"Bad version: {hdr[1]}"
(
self.magic,
self.version,
@@ -60,6 +60,8 @@ class AsmBinModel:
self.file_size,
) = hdr
+ self.fp16_scales = bool(self.flags & 4) or (self.version >= 2)
+ self.scale_bytes = 2 if self.fp16_scales else 4
self.q_dim = self.n_heads * self.head_dim
self.kv_dim = self.n_kv_heads * self.head_dim
self._load_tokenizer()
@@ -91,12 +93,15 @@ class AsmBinModel:
def _view_q8_0(self, offset: int, rows: int, cols: int):
nb = cols // 32
- row_stride = cols + nb * 4
+ row_stride = cols + nb * self.scale_bytes
raw = np.frombuffer(self.buf, dtype=np.uint8, count=rows * row_stride, offset=offset).reshape(
rows, row_stride
)
q = raw[:, :cols].view(np.int8)
- s = np.ascontiguousarray(raw[:, cols:]).view("<f4").reshape(rows, nb)
+ if self.fp16_scales:
+ s = np.ascontiguousarray(raw[:, cols:]).view("<f2").reshape(rows, nb).astype(np.float32)
+ else:
+ s = np.ascontiguousarray(raw[:, cols:]).view("<f4").reshape(rows, nb)
return q, s
def _load_weights(self):
@@ -118,7 +123,7 @@ class AsmBinModel:
nonlocal pos
pos = align64(pos)
mat = self._view_q8_0(pos, rows, cols)
- pos += rows * (cols + (cols // 32) * 4)
+ pos += rows * (cols + (cols // 32) * self.scale_bytes)
return mat
self.layers.append(
@@ -328,6 +333,8 @@ def main():
print(f" gen ids : {ref_gen}")
print(f" decoded : {model.decode(ref_gen)!r}")
+ pt_logits = None
+ pt_gen_clean = None
if args.compare_pt:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
@@ -420,6 +427,21 @@ def main():
print(f" cosine_similarity: {cos:.9f}")
print(f" top10_match : {top10_asm == top10_ref} (asm={top10_asm[:5]}, ref={top10_ref[:5]})")
print(f" greedy_match : {exact_gen} ({match_cnt}/{len(ref_gen)} tokens)")
+ if pt_logits is not None and pt_gen_clean is not None:
+ p_max_d, p_mean_d, p_cos = metrics(asm_logits, pt_logits)
+ p_prefix = 0
+ for a, b in zip(asm_gen_ids or [], pt_gen_clean):
+ if a == b:
+ p_prefix += 1
+ else:
+ break
+ p_match = sum(1 for a, b in zip(asm_gen_ids or [], pt_gen_clean) if a == b)
+ print(f"\n[Pure x86-64 asm-llm vs PyTorch FP32]")
+ print(f" max_abs_diff : {p_max_d:.6f}")
+ print(f" mean_abs_diff : {p_mean_d:.6f}")
+ print(f" cosine_similarity: {p_cos:.7f}")
+ print(f" top1_match : {int(np.argmax(asm_logits)) == int(np.argmax(pt_logits))}")
+ print(f" greedy_prefix : {p_prefix}/{min(len(asm_gen_ids or []), len(pt_gen_clean))} tokens (pos_match={p_match}/{len(pt_gen_clean)})")
print(f" asm stdout : {proc.stdout!r}")
print(f" asm stderr :\n{proc.stderr.strip()}")
if not exact_gen:
diff --git a/shared/constants.inc b/shared/constants.inc
index d73502c..e82809c 100644
--- a/shared/constants.inc
+++ b/shared/constants.inc
@@ -41,6 +41,10 @@
; --- .asmbin Header Offsets (128 bytes) ---
%define ASMBIN_MAGIC 0x4C4D5341 ; "ASML"
%define ASMBIN_VERSION 1
+%define ASMBIN_VERSION_V2 2
+%define HDR_FLAG_TIED_EMB 1
+%define HDR_FLAG_QK_NORM 2
+%define HDR_FLAG_FP16_SCALES 4
%define HDR_MAGIC 0
%define HDR_VERSION 4
@@ -148,4 +152,6 @@
%define CTX_BUF_PROMPT 344
%define CTX_BUF_GEN 352
%define CTX_BUF_PROBS 360
+%define CTX_FP16_SCALES 368 ; uint32: 0 = v1 fp32 scales, 1 = v2 fp16 scales
+%define CTX_SCALE_SHIFT 372 ; uint32: 3 = fp32 (K>>3), 4 = fp16 (K>>4)
%define CTX_SIZE 384
diff --git a/shared/math.asm b/shared/math.asm
index 0a9702c..e507863 100644
--- a/shared/math.asm
+++ b/shared/math.asm
@@ -590,12 +590,64 @@ vec_add_avx2:
; ----------------------------------------------------------------------------
; uint64 argmax_f32(const float *x, uint64 n)
; rdi = x, rsi = n -> rax = index of maximum float (first index on tie)
+; 8-wide AVX2 scan with exact first-index tie-breaking.
; ----------------------------------------------------------------------------
argmax_f32:
+ cmp rsi, 8
+ jb .scalar_init
+
+ sub rsp, 64 ; 32B vals + 32B idxs
+ vmovups ymm0, [rdi] ; best_vals = x[0..7]
+ vmovdqa ymm1, [rel i_iota8] ; best_idxs = [0..7]
+ vpbroadcastd ymm3, [rel i_eight] ; step = [8..8]
+ vpaddd ymm2, ymm1, ymm3 ; cur_idxs = [8..15]
+ mov rcx, 8
+ mov rdx, rsi
+ and rdx, -8 ; n8 = n & ~7
+.v_lp:
+ cmp rcx, rdx
+ jae .v_red
+ vmovups ymm4, [rdi + rcx*4]
+ vcmpps ymm5, ymm4, ymm0, 14 ; _CMP_GT_OS: strict > preserves first index
+ vblendvps ymm0, ymm0, ymm4, ymm5
+ vblendvps ymm1, ymm1, ymm2, ymm5
+ vpaddd ymm2, ymm2, ymm3
+ add rcx, 8
+ jmp .v_lp
+
+.v_red:
+ vmovups [rsp], ymm0
+ vmovdqu [rsp + 32], ymm1
+ vmovss xmm0, [rsp] ; best_val
+ mov eax, [rsp + 32] ; best_idx (zero-extended)
+ mov r8d, 1
+.red8:
+ cmp r8d, 8
+ jae .v_tail
+ vmovss xmm1, [rsp + r8*4]
+ mov r9d, [rsp + 32 + r8*4]
+ vucomiss xmm1, xmm0
+ ja .take8
+ jb .next8
+ ; Tie: keep smaller index
+ cmp r9, rax
+ jae .next8
+.take8:
+ vmovss xmm0, xmm1, xmm1
+ mov rax, r9
+.next8:
+ inc r8d
+ jmp .red8
+
+.v_tail:
+ add rsp, 64
+ jmp .tail_lp
+
+.scalar_init:
xor eax, eax ; best_idx = 0
vmovss xmm0, [rdi] ; best_val = x[0]
mov rcx, 1
-.lp:
+.tail_lp:
cmp rcx, rsi
jae .done
vmovss xmm1, [rdi + rcx*4]
@@ -605,7 +657,7 @@ argmax_f32:
mov rax, rcx
.next:
inc rcx
- jmp .lp
+ jmp .tail_lp
.done:
ret
@@ -756,6 +808,8 @@ sample_top_p:
section .rodata
align 32
+i_iota8: dd 0, 1, 2, 3, 4, 5, 6, 7
+i_eight: dd 8
; Float32 constants
f_one: dd 1.0
f_exp_hi: dd 88.3762626647949
diff --git a/shared/matmul.asm b/shared/matmul.asm
index a698db6..28ff2fd 100644
--- a/shared/matmul.asm
+++ b/shared/matmul.asm
@@ -1,12 +1,28 @@
; ============================================================================
-; matmul.asm — High-throughput AVX2 + FMA Q8_0 x F32 kernels (zero libc)
+; matmul.asm — High-throughput AVX2 + FMA + F16C Q8_0 matmul kernels (zero libc)
;
; Weight layout (per-row split Q8_0, block size = 32, int8 in [-127, 127]):
-; row_stride = K + (K / 32) * 4 = K + (K >> 3) bytes
-; [row + 0 .. row + K - 1] : K int8 weights (32-byte aligned!)
-; [row + K .. row + row_stride - 1]: K/32 fp32 block scales (4-byte aligned!)
+; v2 (FP16 scales, HDR_FLAG_FP16_SCALES):
+; row_stride = K + (K / 32) * 2 = K + (K >> 4) bytes
+; [row + 0 .. row + K - 1] : K int8 weights
+; [row + K .. row + row_stride - 1]: K/32 IEEE-754 fp16 block scales
+; v1 (FP32 scales, legacy):
+; row_stride = K + (K / 32) * 4 = K + (K >> 3) bytes
+; [row + 0 .. row + K - 1] : K int8 weights
+; [row + K .. row + row_stride - 1]: K/32 fp32 block scales
+;
+; Compile-time modes:
+; FAST_Q8=1 (default): Q8_0 x Q8_0 INT8xINT8 AVX2 (vpabsb + vpsignb +
+; vpmaddubsw + vpmaddwd + vcvtdq2ps + vfmadd231ps),
+; 1-row sequential 4-block (128B) unrolled with
+; next-row software prefetch for max DRAM streaming BW.
+; Auto-detects v1 (fp32) and v2 (fp16) scales.
+; FAST_Q8=0 (legacy) : Q8_0 x FP32 AVX2+FMA exact FP32-activation matmul,
+; auto-detects v1 (fp32) and v2 (fp16) scales.
;
; Functions:
+; matmul_set_fp16 : (uint64 is_fp16)
+; quantize_x_q8_0 : (const float *x, uint64 K) [FAST_Q8=1]
; dequant_row_q8_0 : (const void *row_ptr, float *out, uint64 K)
; matmul_q8_0_range : (const void *W, const float *x, float *out,
; uint64 K, uint64 r0, uint64 r1)
@@ -17,26 +33,62 @@
bits 64
default rel
+%ifndef FAST_Q8
+%define FAST_Q8 1
+%endif
+
+%ifndef Q8_PREFETCH
+%define Q8_PREFETCH prefetcht0
+%endif
+
+%define Q8_MAX_K 16384
+
section .text
+global matmul_set_fp16
+%if FAST_Q8
+global quantize_x_q8_0
+%endif
global dequant_row_q8_0
global matmul_q8_0_range
global dot_f32_avx2
global saxpy_f32_avx2
+; ----------------------------------------------------------------------------
+; void matmul_set_fp16(uint64 is_fp16)
+; rdi = 0 for v1 FP32 scales, non-zero for v2 FP16 scales
+; ----------------------------------------------------------------------------
+matmul_set_fp16:
+ xor eax, eax
+ test rdi, rdi
+ setnz al
+ mov [rel g_fp16_scales], eax
+ ret
+
; ----------------------------------------------------------------------------
; void dequant_row_q8_0(const void *row_ptr, float *out, uint64 K)
-; rdi = row_ptr ([K int8][K/32 fp32]), rsi = out, rdx = K (multiple of 32)
+; rdi = row_ptr, rsi = out, rdx = K (multiple of 32)
+; Auto-detects v1 FP32 vs v2 FP16 scales via g_fp16_scales.
; ----------------------------------------------------------------------------
dequant_row_q8_0:
lea r8, [rdi + rdx] ; scales_ptr = row_ptr + K
mov rcx, rdx
shr rcx, 5 ; nb = K / 32
+ mov r11d, [rel g_fp16_scales]
xor eax, eax ; b = 0
.lp:
cmp rax, rcx
jae .done
- vbroadcastss ymm4, [r8 + rax*4] ; scale[b]
+ test r11d, r11d
+ jnz .sc_f16
+ vbroadcastss ymm4, [r8 + rax*4] ; v1 fp32 scale[b]
+ jmp .sc_ok
+.sc_f16:
+ movzx r10d, word [r8 + rax*2] ; v2 fp16 scale[b]
+ vmovd xmm4, r10d
+ vcvtph2ps xmm4, xmm4
+ vbroadcastss ymm4, xmm4
+.sc_ok:
mov r9, rax
shl r9, 5 ; b * 32 (q offset)
mov r10, rax
@@ -64,17 +116,153 @@ dequant_row_q8_0:
.done:
ret
+%if FAST_Q8
+; ----------------------------------------------------------------------------
+; void quantize_x_q8_0(const float *x, uint64 K)
+; rdi = x (f32), rsi = K (multiple of 32, <= Q8_MAX_K)
+; Quantizes x into Q8_0 blocks of 32 ONCE before matmul dispatch:
+; q8_xq[0..K-1] : int8 in [-127, 127] (32-byte aligned, fits in L1D!)
+; q8_xs[0..K/32] : float32 scale = max_abs / 127.0f
+; ----------------------------------------------------------------------------
+quantize_x_q8_0:
+ mov rcx, rsi
+ shr rcx, 5 ; nb = K / 32
+ lea r9, [rel q8_xq]
+ lea r10, [rel q8_xs]
+
+ vpbroadcastd ymm12, [rel q8_abs_mask]
+ vmovss xmm13, [rel q8_inv_127]
+ vmovss xmm14, [rel q8_f127]
+ vxorps xmm15, xmm15, xmm15
+ vmovdqa ymm11, [rel q8_pack_perm]
+ vpbroadcastb ymm10, [rel q8_min_i8]
+
+ xor eax, eax ; b = 0
+ xor r8d, r8d ; x byte offset (b * 128)
+ xor edx, edx ; xq byte offset (b * 32)
+.qlp:
+ cmp rax, rcx
+ jae .qdone
+
+ vmovups ymm0, [rdi + r8]
+ vmovups ymm1, [rdi + r8 + 32]
+ vmovups ymm2, [rdi + r8 + 64]
+ vmovups ymm3, [rdi + r8 + 96]
+
+ vandps ymm4, ymm0, ymm12
+ vandps ymm5, ymm1, ymm12
+ vandps ymm6, ymm2, ymm12
+ vandps ymm7, ymm3, ymm12
+ vmaxps ymm4, ymm4, ymm5
+ vmaxps ymm6, ymm6, ymm7
+ vmaxps ymm4, ymm4, ymm6
+
+ vextractf128 xmm5, ymm4, 1
+ vmaxps xmm4, xmm4, xmm5
+ vshufps xmm5, xmm4, xmm4, 0x0E
+ vmaxps xmm4, xmm4, xmm5
+ vshufps xmm5, xmm4, xmm4, 0x01
+ vmaxss xmm4, xmm4, xmm5 ; xmm4 = max_abs
+
+ vmulss xmm5, xmm4, xmm13 ; scale_x = max_abs / 127.0f
+ vmovss [r10 + rax*4], xmm5
+
+ vxorps xmm6, xmm6, xmm6 ; inv_scale = 0.0f if max_abs == 0
+ vucomiss xmm4, xmm15
+ jbe .qinv_ok
+ vdivss xmm6, xmm14, xmm4 ; inv_scale = 127.0f / max_abs
+.qinv_ok:
+ vbroadcastss ymm6, xmm6
+
+ vmulps ymm0, ymm0, ymm6
+ vmulps ymm1, ymm1, ymm6
+ vmulps ymm2, ymm2, ymm6
+ vmulps ymm3, ymm3, ymm6
+
+ vcvtps2dq ymm0, ymm0
+ vcvtps2dq ymm1, ymm1
+ vcvtps2dq ymm2, ymm2
+ vcvtps2dq ymm3, ymm3
+
+ vpackssdw ymm0, ymm0, ymm1
+ vpackssdw ymm2, ymm2, ymm3
+ vpacksswb ymm0, ymm0, ymm2
+ vpermd ymm0, ymm11, ymm0 ; restore exact linear [0..31] byte order
+ vpmaxsb ymm0, ymm0, ymm10 ; clamp >= -127 (prevents -128 overflow)
+
+ vmovdqa [r9 + rdx], ymm0 ; q8_xq[b*32 .. b*32+31]
+
+ add r8, 128
+ add rdx, 32
+ inc rax
+ jmp .qlp
+.qdone:
+ ret
+
+; Macro: 1-row x 4-block (128 bytes = 2 cache lines) INT8xINT8 AVX2 body.
+; Preconditions:
+; rax = w (current row), r8 = s_cur = w + K (scales of current row)
+; r11 = q8_xq, rbx = byte offset into weights (multiple of 128)
+; ymm0..ymm3 = 4 independent f32 accumulators (hides FMA latency!)
+; ymm12 = [s0*xs0, s1*xs1, s2*xs2, s3*xs3] duplicated in both 128b lanes
+; ymm15 = 16x int16(1)
+; Prefetching [r8 + rbx] (= [w + K + rbx]) streams monotonically across both
+; the current row's scales and the entire next row without jumping pages or
+; resetting the CPU's L1/L2 hardware stream prefetcher.
+%macro INT8_1ROW_4BLK 0
+ Q8_PREFETCH [r8 + rbx]
+ Q8_PREFETCH [r8 + rbx + 64]
+
+ ; Blocks 0 & 1 (+0, +32)
+ vmovdqa ymm4, [r11 + rbx]
+ vmovdqa ymm10, [r11 + rbx + 32]
+ vpabsb ymm5, ymm4
+ vpabsb ymm11, ymm10
+ vmovdqu ymm6, [rax + rbx]
+ vmovdqu ymm7, [rax + rbx + 32]
+ vpsignb ymm6, ymm6, ymm4
+ vpsignb ymm7, ymm7, ymm10
+ vpmaddubsw ymm6, ymm5, ymm6
+ vpmaddubsw ymm7, ymm11, ymm7
+ vpmaddwd ymm6, ymm6, ymm15
+ vpmaddwd ymm7, ymm7, ymm15
+ vcvtdq2ps ymm6, ymm6
+ vcvtdq2ps ymm7, ymm7
+ vpermilps ymm8, ymm12, 0x00
+ vpermilps ymm9, ymm12, 0x55
+ vfmadd231ps ymm0, ymm6, ymm8
+ vfmadd231ps ymm1, ymm7, ymm9
+
+ ; Blocks 2 & 3 (+64, +96)
+ vmovdqa ymm4, [r11 + rbx + 64]
+ vmovdqa ymm10, [r11 + rbx + 96]
+ vpabsb ymm5, ymm4
+ vpabsb ymm11, ymm10
+ vmovdqu ymm6, [rax + rbx + 64]
+ vmovdqu ymm7, [rax + rbx + 96]
+ vpsignb ymm6, ymm6, ymm4
+ vpsignb ymm7, ymm7, ymm10
+ vpmaddubsw ymm6, ymm5, ymm6
+ vpmaddubsw ymm7, ymm11, ymm7
+ vpmaddwd ymm6, ymm6, ymm15
+ vpmaddwd ymm7, ymm7, ymm15
+ vcvtdq2ps ymm6, ymm6
+ vcvtdq2ps ymm7, ymm7
+ vpermilps ymm8, ymm12, 0xAA
+ vpermilps ymm9, ymm12, 0xFF
+ vfmadd231ps ymm2, ymm6, ymm8
+ vfmadd231ps ymm3, ymm7, ymm9
+%endmacro
+
; ----------------------------------------------------------------------------
; void matmul_q8_0_range(const void *W, const float *x, float *out,
; uint64 K, uint64 r0, uint64 r1)
-; rdi = W, rsi = x (f32), rdx = out (f32), rcx = K, r8 = r0, r9 = r1
-;
-; 4-row unrolled AVX2 + FMA Q8_0 x FP32 matrix-vector multiplication:
-; - Full FP32 activations (zero activation quantization noise or rounding cliffs!)
-; - Loads x[b*32 .. b*32+31] ONCE per block and reuses across 4 rows
-; - Interleaves 2 rows at a time across ymm8..ymm15 to hide convert+FMA latency
-; - ZERO stack accesses inside inner block loop
-; - Bit-for-bit identical across any thread count (1T..64T)
+; FAST_Q8=1: 1-row sequential 4-block (128B) unrolled AVX2 + FMA + F16C
+; INT8xINT8 kernel with monotonic next-row software prefetch.
+; - Linear row-by-row memory traversal maximizes DRAM/L2 streaming BW
+; - 4 independent FP32 accumulators saturate Zen2/Haswell FMA & int pipes
+; - Zero stack accesses inside row/block loops
+; - 100% bit-for-bit identical per row for ANY partitioning (1T..64T)
; ----------------------------------------------------------------------------
matmul_q8_0_range:
push rbx
@@ -83,40 +271,229 @@ matmul_q8_0_range:
push r13
push r14
push r15
- sub rsp, 40
- ; Stack locals (touched only once per 4 rows):
- ; [rsp + 0] = out_ptr (advances by 16 per 4 rows)
- ; [rsp + 8] = rows_left (r1 - r0)
- ; [rsp + 16] = row_stride = K + (K >> 3)
- ; [rsp + 24] = stride4 = 4 * row_stride
- ; [rsp + 32] = base_w_cur (advances by stride4)
+
+ mov rsi, r9
+ sub rsi, r8 ; rsi = rows_left = r1 - r0
+ jle .exit
+
+ lea rdx, [rdx + r8 * 4] ; rdx = out_ptr = out + r0 * 4
+ vpbroadcastw ymm15, [rel q8_one16] ; 16x int16(1)
+ lea r11, [rel q8_xq]
+ lea rbp, [rel q8_xs]
+ mov r15, rcx ; r15 = K
+ mov r13, rcx
+ and r13, -128 ; r13 = K_128 = K & ~127
+
+ cmp dword [rel g_fp16_scales], 0
+ jne .fast_fp16
+
+ ; ========================================================================
+ ; FAST_Q8=1, v1 FP32 scales: row_stride = K + (K >> 3)
+ ; ========================================================================
+ mov r14, rcx
+ shr r14, 3
+ add r14, rcx ; r14 = row_stride
+ mov rax, r8
+ imul rax, r14
+ add rax, rdi ; rax = w_cur = W + r0 * row_stride
+
+align 16
+.row_f32:
+ lea r12, [rax + r14] ; r12 = w_next
+ lea r8, [rax + r15] ; r8 = s_cur (fp32)
+
+ vxorps ymm0, ymm0, ymm0
+ vxorps ymm1, ymm1, ymm1
+ vxorps ymm2, ymm2, ymm2
+ vxorps ymm3, ymm3, ymm3
+ xor ebx, ebx ; b_q: 0, 128, ...
+ xor r9d, r9d ; b_s: 0, 16, ... (fp32 scale & xs offset)
+ test r13, r13
+ jz .tail_f32
+
+align 16
+.blk4_f32:
+ vmovups xmm12, [r8 + r9] ; 4x fp32 scale_w
+ vmulps xmm12, xmm12, [rbp + r9] ; * 4x fp32 scale_x
+ vinsertf128 ymm12, ymm12, xmm12, 1
+
+ INT8_1ROW_4BLK
+
+ add rbx, 128
+ add r9, 16
+ cmp rbx, r13
+ jb .blk4_f32
+
+.tail_f32:
+ cmp rbx, r15
+ jae .red_f32
+ vmovdqa ymm4, [r11 + rbx]
+ vpabsb ymm5, ymm4
+ vmovdqu ymm6, [rax + rbx]
+ vpsignb ymm6, ymm6, ymm4
+ vpmaddubsw ymm6, ymm5, ymm6
+ vpmaddwd ymm6, ymm6, ymm15
+ vcvtdq2ps ymm6, ymm6
+ vmovss xmm8, [r8 + r9]
+ vmulss xmm8, xmm8, [rbp + r9]
+ vbroadcastss ymm8, xmm8
+ vfmadd231ps ymm0, ymm6, ymm8
+ add rbx, 32
+ add r9, 4
+ jmp .tail_f32
+
+.red_f32:
+ vaddps ymm0, ymm0, ymm1
+ vaddps ymm2, ymm2, ymm3
+ vaddps ymm0, ymm0, ymm2
+ vhaddps ymm0, ymm0, ymm0
+ vhaddps ymm0, ymm0, ymm0
+ vextractf128 xmm1, ymm0, 1
+ vaddss xmm0, xmm0, xmm1
+ vmovss [rdx], xmm0
+ add rdx, 4
+ mov rax, r12
+ dec rsi
+ jnz .row_f32
+ jmp .exit
+
+ ; ========================================================================
+ ; FAST_Q8=1, v2 FP16 scales: row_stride = K + (K >> 4)
+ ; ========================================================================
+.fast_fp16:
+ mov r14, rcx
+ shr r14, 4
+ add r14, rcx ; r14 = row_stride
+ mov rax, r8
+ imul rax, r14
+ add rax, rdi ; rax = w_cur = W + r0 * row_stride
+
+align 16
+.row_f16:
+ lea r12, [rax + r14] ; r12 = w_next
+ lea r8, [rax + r15] ; r8 = s_cur (fp16)
+
+ vxorps ymm0, ymm0, ymm0
+ vxorps ymm1, ymm1, ymm1
+ vxorps ymm2, ymm2, ymm2
+ vxorps ymm3, ymm3, ymm3
+ xor ebx, ebx ; b_q: 0, 128, ...
+ xor r9d, r9d ; b_s: 0, 8, ... (fp16 scale offset; xs = r9*2)
+ test r13, r13
+ jz .tail_f16
+
+align 16
+.blk4_f16:
+ vmovq xmm12, qword [r8 + r9] ; 4x fp16 scale_w
+ vcvtph2ps xmm12, xmm12 ; -> 4x fp32
+ vmulps xmm12, xmm12, [rbp + r9*2] ; * 4x fp32 scale_x
+ vinsertf128 ymm12, ymm12, xmm12, 1
+
+ INT8_1ROW_4BLK
+
+ add rbx, 128
+ add r9, 8
+ cmp rbx, r13
+ jb .blk4_f16
+
+.tail_f16:
+ cmp rbx, r15
+ jae .red_f16
+ vmovdqa ymm4, [r11 + rbx]
+ vpabsb ymm5, ymm4
+ vmovdqu ymm6, [rax + rbx]
+ vpsignb ymm6, ymm6, ymm4
+ vpmaddubsw ymm6, ymm5, ymm6
+ vpmaddwd ymm6, ymm6, ymm15
+ vcvtdq2ps ymm6, ymm6
+ movzx ecx, word [r8 + r9]
+ vmovd xmm8, ecx
+ vcvtph2ps xmm8, xmm8
+ vmulss xmm8, xmm8, [rbp + r9*2]
+ vbroadcastss ymm8, xmm8
+ vfmadd231ps ymm0, ymm6, ymm8
+ add rbx, 32
+ add r9, 2
+ jmp .tail_f16
+
+.red_f16:
+ vaddps ymm0, ymm0, ymm1
+ vaddps ymm2, ymm2, ymm3
+ vaddps ymm0, ymm0, ymm2
+ vhaddps ymm0, ymm0, ymm0
+ vhaddps ymm0, ymm0, ymm0
+ vextractf128 xmm1, ymm0, 1
+ vaddss xmm0, xmm0, xmm1
+ vmovss [rdx], xmm0
+ add rdx, 4
+ mov rax, r12
+ dec rsi
+ jnz .row_f16
+
+.exit:
+ pop r15
+ pop r14
+ pop r13
+ pop r12
+ pop rbp
+ pop rbx
+ ret
+
+%else
+; ----------------------------------------------------------------------------
+; void matmul_q8_0_range(const void *W, const float *x, float *out,
+; uint64 K, uint64 r0, uint64 r1)
+; FAST_Q8=0 (legacy): 4-row unrolled AVX2 + FMA Q8_0 x FP32 matmul.
+; Full FP32 activations (zero activation quantization noise).
+; Auto-detects v1 FP32 scales vs v2 FP16 scales via g_fp16_scales.
+; ----------------------------------------------------------------------------
+matmul_q8_0_range:
+ push rbx
+ push rbp
+ push r12
+ push r13
+ push r14
+ push r15
+ sub rsp, 48
+ ; [rsp + 0] = out_ptr
+ ; [rsp + 8] = rows_left (r1 - r0)
+ ; [rsp + 16] = row_stride
+ ; [rsp + 24] = stride4
+ ; [rsp + 32] = base_w_cur
+ ; [rsp + 40] = is_fp16 (0 or 1)
mov rax, r9
sub rax, r8 ; rows_left = r1 - r0
jle .exit
mov [rsp + 8], rax
- ; row_stride = K + (K >> 3)
+ mov ebp, [rel g_fp16_scales]
+ mov [rsp + 40], rbp
+
+ ; row_stride = K + (K >> (is_fp16 ? 4 : 3))
mov rbx, rcx
+ test ebp, ebp
+ jnz .stride_f16
shr rbx, 3
+ jmp .stride_done
+.stride_f16:
+ shr rbx, 4
+.stride_done:
add rbx, rcx
- mov [rsp + 16], rbx ; row_stride
- lea rbp, [rbx * 4]
- mov [rsp + 24], rbp ; 4 * row_stride
+ mov [rsp + 16], rbx
+ lea rax, [rbx * 4]
+ mov [rsp + 24], rax
- ; out_ptr = out + r0 * 4
lea rdx, [rdx + r8 * 4]
mov [rsp + 0], rdx
- ; base_w_cur = W + r0 * row_stride
mov rax, r8
imul rax, rbx
add rdi, rax
mov [rsp + 32], rdi
- ; Persistent registers across all row groups
mov r11, rsi ; x_ptr (float*)
- mov r15, rcx ; K (byte limit for b_q)
+ mov r15, rcx ; K
.row4_lp:
cmp qword [rsp + 8], 4
@@ -128,22 +505,22 @@ matmul_q8_0_range:
lea rdx, [rcx + rbx] ; w2
lea rsi, [rdx + rbx] ; w3
- lea rdi, [rax + r15] ; s0 = w0 + K
- lea r8, [rcx + r15] ; s1 = w1 + K
- lea r9, [rdx + r15] ; s2 = w2 + K
- lea r10, [rsi + r15] ; s3 = w3 + K
+ lea rdi, [rax + r15] ; s0
+ lea r8, [rcx + r15] ; s1
+ lea r9, [rdx + r15] ; s2
+ lea r10, [rsi + r15] ; s3
- vxorps ymm0, ymm0, ymm0 ; acc0
- vxorps ymm1, ymm1, ymm1 ; acc1
- vxorps ymm2, ymm2, ymm2 ; acc2
- vxorps ymm3, ymm3, ymm3 ; acc3
+ vxorps ymm0, ymm0, ymm0
+ vxorps ymm1, ymm1, ymm1
+ vxorps ymm2, ymm2, ymm2
+ vxorps ymm3, ymm3, ymm3
- xor r12d, r12d ; b_x = 0, 128, ..., K*4 - 128
- xor r13d, r13d ; b_q = 0, 32, ..., K - 32
- xor r14d, r14d ; b_s = 0, 4, ..., K/8 - 4
+ xor r12d, r12d ; b_x = 0, 128, ...
+ xor r13d, r13d ; b_q = 0, 32, ...
+ xor r14d, r14d ; b_idx = 0, 1, 2, ... (block index)
+ mov ebp, [rsp + 40] ; is_fp16
.blk4_lp:
- ; Load 32 FP32 activations ONCE (reused across all 4 rows!)
vmovups ymm4, [r11 + r12]
vmovups ymm5, [r11 + r12 + 32]
vmovups ymm6, [r11 + r12 + 64]
@@ -178,8 +555,21 @@ matmul_q8_0_range:
vfmadd231ps ymm8, ymm11, ymm7
vfmadd231ps ymm12, ymm15, ymm7
- vbroadcastss ymm9, dword [rdi + r14]
- vbroadcastss ymm13, dword [r8 + r14]
+ test ebp, ebp
+ jnz .s01_f16
+ vbroadcastss ymm9, dword [rdi + r14*4]
+ vbroadcastss ymm13, dword [r8 + r14*4]
+ jmp .s01_ok
+.s01_f16:
+ movzx ebx, word [rdi + r14*2]
+ vmovd xmm9, ebx
+ vcvtph2ps xmm9, xmm9
+ vbroadcastss ymm9, xmm9
+ movzx ebx, word [r8 + r14*2]
+ vmovd xmm13, ebx
+ vcvtph2ps xmm13, xmm13
+ vbroadcastss ymm13, xmm13
+.s01_ok:
vfmadd231ps ymm0, ymm8, ymm9
vfmadd231ps ymm1, ymm12, ymm13
@@ -212,18 +602,30 @@ matmul_q8_0_range:
vfmadd231ps ymm8, ymm11, ymm7
vfmadd231ps ymm12, ymm15, ymm7
- vbroadcastss ymm9, dword [r9 + r14]
- vbroadcastss ymm13, dword [r10 + r14]
+ test ebp, ebp
+ jnz .s23_f16
+ vbroadcastss ymm9, dword [r9 + r14*4]
+ vbroadcastss ymm13, dword [r10 + r14*4]
+ jmp .s23_ok
+.s23_f16:
+ movzx ebx, word [r9 + r14*2]
+ vmovd xmm9, ebx
+ vcvtph2ps xmm9, xmm9
+ vbroadcastss ymm9, xmm9
+ movzx ebx, word [r10 + r14*2]
+ vmovd xmm13, ebx
+ vcvtph2ps xmm13, xmm13
+ vbroadcastss ymm13, xmm13
+.s23_ok:
vfmadd231ps ymm2, ymm8, ymm9
vfmadd231ps ymm3, ymm12, ymm13
add r12, 128
add r13, 32
- add r14, 4
+ inc r14
cmp r13, r15
jb .blk4_lp
- ; Horizontal sum of 4 accumulators (ymm0..ymm3 -> 4 floats in xmm0)
vhaddps ymm0, ymm0, ymm1
vhaddps ymm2, ymm2, ymm3
vhaddps ymm0, ymm0, ymm2
@@ -235,22 +637,22 @@ matmul_q8_0_range:
add rax, 16
mov [rsp + 0], rax
- mov rax, [rsp + 24] ; stride4
+ mov rax, [rsp + 24]
add [rsp + 32], rax
sub qword [rsp + 8], 4
jmp .row4_lp
- ; Tail loop for 1..3 remaining rows
.row1_check:
cmp qword [rsp + 8], 0
je .exit
.row1_lp:
- mov rax, [rsp + 32] ; w0
- lea rdi, [rax + r15] ; s0
+ mov rax, [rsp + 32]
+ lea rdi, [rax + r15]
vxorps ymm0, ymm0, ymm0
xor r12d, r12d
xor r13d, r13d
xor r14d, r14d
+ mov ebp, [rsp + 40]
.blk1_lp:
vpmovsxbd ymm8, qword [rax + r13]
vpmovsxbd ymm9, qword [rax + r13 + 8]
@@ -264,19 +666,28 @@ matmul_q8_0_range:
vfmadd231ps ymm8, ymm9, [r11 + r12 + 32]
vfmadd231ps ymm8, ymm10, [r11 + r12 + 64]
vfmadd231ps ymm8, ymm11, [r11 + r12 + 96]
- vbroadcastss ymm12, dword [rdi + r14]
+ test ebp, ebp
+ jnz .s1_f16
+ vbroadcastss ymm12, dword [rdi + r14*4]
+ jmp .s1_ok
+.s1_f16:
+ movzx ebx, word [rdi + r14*2]
+ vmovd xmm12, ebx
+ vcvtph2ps xmm12, xmm12
+ vbroadcastss ymm12, xmm12
+.s1_ok:
vfmadd231ps ymm0, ymm8, ymm12
add r12, 128
add r13, 32
- add r14, 4
+ inc r14
cmp r13, r15
jb .blk1_lp
+ vhaddps ymm0, ymm0, ymm0
+ vhaddps ymm0, ymm0, ymm0
vextractf128 xmm1, ymm0, 1
- vaddps xmm0, xmm0, xmm1
- vhaddps xmm0, xmm0, xmm0
- vhaddps xmm0, xmm0, xmm0
+ vaddss xmm0, xmm0, xmm1
mov rax, [rsp + 0]
vmovss [rax], xmm0
add rax, 4
@@ -287,7 +698,7 @@ matmul_q8_0_range:
jnz .row1_lp
.exit:
- add rsp, 40
+ add rsp, 48
pop r15
pop r14
pop r13
@@ -295,6 +706,7 @@ matmul_q8_0_range:
pop rbp
pop rbx
ret
+%endif
; ----------------------------------------------------------------------------
; float dot_f32_avx2(const float *a, const float *b, uint64 n) -> xmm0
@@ -358,3 +770,24 @@ saxpy_f32_avx2:
jmp .lp
.done:
ret
+
+%if FAST_Q8
+section .rodata
+align 32
+q8_pack_perm: dd 0, 4, 1, 5, 2, 6, 3, 7
+q8_abs_mask: dd 0x7FFFFFFF
+q8_f127: dd 127.0
+q8_inv_127: dd 0.007874015748031496 ; 1.0f / 127.0f
+q8_one16: dw 1
+q8_min_i8: db -127
+%endif
+
+section .bss
+alignb 64
+g_fp16_scales: resd 1
+%if FAST_Q8
+alignb 64
+q8_xq: resb Q8_MAX_K
+alignb 64
+q8_xs: resb (Q8_MAX_K / 32) * 4
+%endif
diff --git a/shared/threads.asm b/shared/threads.asm
index d778494..ffd9b52 100644
--- a/shared/threads.asm
+++ b/shared/threads.asm
@@ -18,16 +18,27 @@ default rel
%include "constants.inc"
+%ifndef FAST_Q8
+%define FAST_Q8 1
+%endif
+
%define SPIN_LIMIT 200000
extern sys_mmap_anon
extern matmul_q8_0_range
+%if FAST_Q8
+extern quantize_x_q8_0
+extern gqa_attn_range
+%endif
section .text
global tp_init
global tp_shutdown
global tp_matmul_q8_0
+%if FAST_Q8
+global tp_gqa_attn
+%endif
; ----------------------------------------------------------------------------
; void tp_init(uint64 n_threads)
@@ -144,9 +155,30 @@ tp_init:
jne .worker_exit
mov r13d, eax ; latch new generation
- ; Deterministic 4-row-aligned slice [r0, r1) for tid = r12
+ ; Deterministic balanced row/head slice [r0, r1) for tid = r12
mov rcx, [rel tp_M]
mov r8, [rel tp_n_threads]
+%if FAST_Q8
+ ; Ceiling-balanced partitioning: r0 = (tid*M + N - 1) / N, r1 = ((tid+1)*M + N - 1) / N
+ ; Guarantees tid=0 always gets work first and 1-row/1-head balance across 1..64T.
+ lea r9, [r8 - 1] ; N - 1
+ mov rax, rcx
+ imul rax, r12
+ add rax, r9
+ xor edx, edx
+ div r8
+ mov r14, rax ; r0
+
+ lea rax, [r12 + 1]
+ cmp rax, r8
+ je .last_slice
+ imul rax, rcx
+ add rax, r9
+ xor edx, edx
+ div r8
+ mov r15, rax ; r1
+ jmp .run_slice
+%else
mov r9, rcx
shr r9, 2 ; blocks4 = M / 4
@@ -166,6 +198,7 @@ tp_init:
shl rax, 2
mov r15, rax ; r1
jmp .run_slice
+%endif
.last_slice:
mov r15, rcx ; r1 = M
@@ -177,9 +210,20 @@ tp_init:
mov rsi, [rel tp_x]
mov rdx, [rel tp_out]
mov rcx, [rel tp_K]
+%if FAST_Q8
+ test rcx, rcx
+ jz .run_attn
+%endif
mov r8, r14 ; r0
mov r9, r15 ; r1
call matmul_q8_0_range
+ jmp .job_done
+%if FAST_Q8
+.run_attn:
+ mov rcx, r14 ; h0
+ mov r8, r15 ; h1
+ call gqa_attn_range
+%endif
.job_done:
; Lock-free TSO release store to worker's private 64B cache line!
@@ -219,6 +263,22 @@ tp_shutdown:
; rdi = W, rsi = x (f32), rdx = out (f32), rcx = M, r8 = K
; ----------------------------------------------------------------------------
tp_matmul_q8_0:
+%if FAST_Q8
+ ; Quantize input vector x[0..K-1] to Q8_0 ONCE for all worker threads
+ push rdi
+ push rsi
+ push rdx
+ push rcx
+ push r8
+ mov rdi, rsi ; x
+ mov rsi, r8 ; K
+ call quantize_x_q8_0
+ pop r8
+ pop rcx
+ pop rdx
+ pop rsi
+ pop rdi
+%endif
mov rax, [rel tp_n_threads]
cmp rax, 1
jle .single_thread
@@ -252,10 +312,16 @@ tp_matmul_q8_0:
.run_main_slice:
mov rax, [rel tp_M]
+%if FAST_Q8
+ lea rax, [rax + rbx - 1]
+ xor edx, edx
+ div rbx ; r1 for tid = 0: ceil(M / N)
+%else
shr rax, 2 ; blocks4
xor edx, edx
div rbx
shl rax, 2 ; r1 for tid = 0
+%endif
test rax, rax
jz .wait_workers
@@ -263,9 +329,20 @@ tp_matmul_q8_0:
mov rsi, [rel tp_x]
mov rdx, [rel tp_out]
mov rcx, [rel tp_K]
+%if FAST_Q8
+ test rcx, rcx
+ jz .main_attn
+%endif
xor r8d, r8d ; r0 = 0
mov r9, rax ; r1
call matmul_q8_0_range
+ jmp .wait_workers
+%if FAST_Q8
+.main_attn:
+ xor ecx, ecx ; h0 = 0
+ mov r8, rax ; h1
+ call gqa_attn_range
+%endif
.wait_workers:
; Wait for each worker tid = 1 .. n_threads-1 to store new_gen in its cache line
@@ -298,6 +375,50 @@ tp_matmul_q8_0:
xor r8d, r8d ; r0 = 0
jmp matmul_q8_0_range
+%if FAST_Q8
+; ----------------------------------------------------------------------------
+; void tp_gqa_attn(uint64 layer_kv_base, uint64 pos, uint64 scale_gqa_packed,
+; uint64 n_heads)
+; Dispatches GQA attention across the thread pool (tp_K = 0 signals attn job).
+; ----------------------------------------------------------------------------
+tp_gqa_attn:
+ mov rax, [rel tp_n_threads]
+ cmp rax, 1
+ jle .attn_single
+
+ push rbx
+ push r12
+ sub rsp, 8
+ mov rbx, rax
+
+ mov [rel tp_W], rdi
+ mov [rel tp_x], rsi
+ mov [rel tp_out], rdx
+ mov [rel tp_M], rcx
+ mov qword [rel tp_K], 0 ; K == 0 -> gqa_attn_range job
+
+ mov r12d, 1
+ lock xadd dword [rel tp_gen], r12d
+ inc r12d
+
+ cmp dword [rel tp_waiters], 0
+ je tp_matmul_q8_0.run_main_slice
+ lea rdi, [rel tp_gen]
+ mov esi, FUTEX_WAKE_PRIVATE
+ mov edx, FUTEX_WAKE_ALL
+ xor r10d, r10d
+ xor r8d, r8d
+ xor r9d, r9d
+ mov eax, SYS_futex
+ syscall
+ jmp tp_matmul_q8_0.run_main_slice
+
+.attn_single:
+ mov r8, rcx ; h1 = n_heads
+ xor ecx, ecx ; h0 = 0
+ jmp gqa_attn_range
+%endif
+
section .bss
alignb 64
tp_gen: resd 1
diff --git a/shared/transformer.asm b/shared/transformer.asm
index 0d35bdf..ca37711 100644
--- a/shared/transformer.asm
+++ b/shared/transformer.asm
@@ -14,6 +14,10 @@ default rel
%include "constants.inc"
+%ifndef FAST_Q8
+%define FAST_Q8 1
+%endif
+
%ifndef BARE_METAL
extern sys_openat_ro
extern sys_close
@@ -31,11 +35,15 @@ extern softmax_avx2
extern silu_mul_avx2
extern vec_add_avx2
+extern matmul_set_fp16
extern dequant_row_q8_0
extern dot_f32_avx2
extern saxpy_f32_avx2
extern tp_matmul_q8_0
+%if FAST_Q8
+extern tp_gqa_attn
+%endif
section .text
@@ -43,6 +51,9 @@ global g_ctx
global model_init
global model_free
global transformer_forward
+%if FAST_Q8
+global gqa_attn_range
+%endif
; Helper macro: align reg up to 64 bytes
%macro ALIGN64 1
@@ -100,11 +111,28 @@ model_init:
js .err_mmap
%endif
- ; Verify header magic and version
+ ; Verify header magic and version (v1 fp32 scales or v2 fp16 scales)
cmp dword [r15 + HDR_MAGIC], ASMBIN_MAGIC
jne .err_bad_hdr
- cmp dword [r15 + HDR_VERSION], ASMBIN_VERSION
+ mov eax, [r15 + HDR_VERSION]
+ cmp eax, ASMBIN_VERSION
+ je .ver_ok
+ cmp eax, ASMBIN_VERSION_V2
jne .err_bad_hdr
+.ver_ok:
+ xor ecx, ecx
+ test dword [r15 + HDR_FLAGS], HDR_FLAG_FP16_SCALES
+ setnz cl
+ cmp eax, ASMBIN_VERSION_V2
+ jb .store_scale_mode
+ mov ecx, 1
+.store_scale_mode:
+ mov [rbx + CTX_FP16_SCALES], ecx
+ mov edx, 3
+ add edx, ecx ; 3 for fp32 (K>>3), 4 for fp16 (K>>4)
+ mov [rbx + CTX_SCALE_SHIFT], edx
+ mov edi, ecx
+ call matmul_set_fp16
mov [rbx + CTX_MMAP_BASE], r15
mov [rbx + CTX_MMAP_SIZE], r14
@@ -209,8 +237,9 @@ model_init:
shl rax, 2 ; q_dim * 4
ALLOC_BUF CTX_BUF_ATT_OUT, rax
- mov rax, [rbx + CTX_MAX_SEQ]
- shl rax, 2 ; max_seq * 4
+ mov rax, [rbx + CTX_N_HEADS]
+ imul rax, [rbx + CTX_MAX_SEQ]
+ shl rax, 2 ; n_heads * max_seq * 4 (private per-head scores)
ALLOC_BUF CTX_BUF_ATT_SCR, rax
; Place buf_gate and buf_up CONTIGUOUSLY so gate+up execute in ONE fused matmul!
@@ -388,10 +417,11 @@ transformer_forward:
; 1. Embedding lookup: dequantize row token_id of embed_tokens into buf_x
mov rax, [rbx + CTX_DIM]
- mov rcx, rax
- shr rcx, 3
- add rcx, rax ; emb_row_stride = dim + dim/8
- imul rdi, rcx
+ mov ecx, [rbx + CTX_SCALE_SHIFT]
+ mov rdx, rax
+ shr rdx, cl
+ add rdx, rax ; emb_row_stride = dim + (dim >> scale_shift)
+ imul rdi, rdx
add rdi, [rbx + CTX_EMB_PTR]
mov rsi, [rbx + CTX_BUF_X]
mov rdx, rax ; dim
@@ -433,12 +463,12 @@ transformer_forward:
shl rcx, 2
add rax, rcx
- ; Helper: row_stride(K) = K + K/8
- ; dim_stride = dim + dim/8
+ ; Helper: row_stride(K) = K + (K >> scale_shift) [3 for v1 fp32, 4 for v2 fp16]
+ mov ecx, [rbx + CTX_SCALE_SHIFT]
mov r12, [rbx + CTX_DIM]
mov r13, r12
- shr r13, 3
- add r12, r13 ; r12 = dim_stride (1152)
+ shr r13, cl
+ add r12, r13 ; r12 = dim_stride (1152 v1 / 1088 v2)
ALIGN64 rax
mov [rsp + 56], rax ; q_proj [q_dim, dim]
@@ -458,12 +488,13 @@ transformer_forward:
ALIGN64 rax
mov [rsp + 80], rax ; o_proj [dim, q_dim]
- mov rcx, [rbx + CTX_Q_DIM]
- mov rdx, rcx
- shr rdx, 3
- add rcx, rdx ; q_dim_stride (2304)
- imul rcx, [rbx + CTX_DIM]
- add rax, rcx
+ mov ecx, [rbx + CTX_SCALE_SHIFT]
+ mov r13, [rbx + CTX_Q_DIM]
+ mov rdx, r13
+ shr rdx, cl
+ add r13, rdx ; q_dim_stride (2304 v1 / 2176 v2)
+ imul r13, [rbx + CTX_DIM]
+ add rax, r13
ALIGN64 rax
mov [rsp + 88], rax ; gate_proj [hidden_dim, dim]
@@ -540,7 +571,7 @@ transformer_forward:
mov r8, [rbx + CTX_HEAD_DIM]
call rope_apply_avx2
- ; --- 3e. Store K, V at cache[l, pos] ---
+ ; --- 3e. Store K, V at contiguous cache[l, kv_h, pos, head_dim] ---
; layer_kv_base_bytes = l * max_seq * kv_dim * 4
mov rax, [rsp + 16] ; l
imul rax, [rbx + CTX_MAX_SEQ]
@@ -548,7 +579,54 @@ transformer_forward:
shl rax, 2
mov [rsp + 120], rax
- ; pos_offset = pos * kv_dim * 4
+%if FAST_Q8
+ ; Head-major contiguous KV layout: cache[l, kv_h, pos, head_dim]
+ ; Eliminates 4KB L1D set aliasing & TLB thrashing across timesteps!
+ mov r14, [rbx + CTX_HEAD_DIM]
+ shl r14, 2 ; head_bytes (512)
+ mov r15, [rbx + CTX_MAX_SEQ]
+ imul r15, r14 ; kv_head_stride = max_seq * head_bytes
+ mov rcx, [rsp + 0] ; pos
+ imul rcx, r14 ; pos_off = pos * head_bytes
+ add rax, rcx ; layer_kv_base + pos_off
+
+ mov rdi, [rbx + CTX_BUF_K_CACHE]
+ add rdi, rax
+ mov rdx, [rbx + CTX_BUF_V_CACHE]
+ add rdx, rax
+ mov rsi, [rbx + CTX_BUF_K]
+ mov r8, [rbx + CTX_BUF_V]
+ mov r12, [rbx + CTX_N_KV_HEADS]
+.kv_head_lp:
+ xor r9d, r9d
+.kv_copy_lp:
+ cmp r9, r14
+ jae .kv_head_next
+ vmovups ymm0, [rsi + r9]
+ vmovups ymm1, [r8 + r9]
+ vmovups [rdi + r9], ymm0
+ vmovups [rdx + r9], ymm1
+ add r9, 32
+ jmp .kv_copy_lp
+.kv_head_next:
+ add rsi, r14
+ add r8, r14
+ add rdi, r15
+ add rdx, r15
+ dec r12
+ jnz .kv_head_lp
+
+ ; --- 3f. Parallel GQA Attention over heads h = 0 .. n_heads - 1 ---
+ mov rdi, [rsp + 120] ; layer_kv_base
+ mov rsi, [rsp + 0] ; pos
+ mov edx, [rsp + 116] ; gqa_ratio (upper 32 bits)
+ shl rdx, 32
+ mov eax, [rsp + 112] ; att_scale float32 bits (lower 32 bits)
+ or rdx, rax
+ mov rcx, [rbx + CTX_N_HEADS]
+ call tp_gqa_attn
+%else
+ ; Legacy layout: cache[l, pos, kv_h, head_dim]
mov rcx, [rsp + 0] ; pos
imul rcx, [rbx + CTX_KV_DIM]
shl rcx, 2
@@ -672,6 +750,7 @@ transformer_forward:
.head_next:
inc r12
jmp .head_lp
+%endif
.att_done:
; --- 3g. Output projection + residual: buf_x += o_proj @ buf_att_out ---
@@ -755,6 +834,148 @@ transformer_forward:
pop rbx
ret
+%if FAST_Q8
+; ----------------------------------------------------------------------------
+; void gqa_attn_range(uint64 layer_kv_base, uint64 pos, uint64 scale_gqa_packed,
+; uint64 h0, uint64 h1)
+; rdi = layer_kv_base, rsi = pos, rdx = (gqa_ratio << 32) | att_scale_bits,
+; rcx = h0, r8 = h1
+; Thread-safe parallel GQA attention over contiguous cache[l, kv_h, pos, hd].
+; ----------------------------------------------------------------------------
+gqa_attn_range:
+ push rbx
+ push rbp
+ push r12
+ push r13
+ push r14
+ push r15
+ sub rsp, 40 ; 6 pushes(48) + 40 + ret(8) = 96 (16B aligned)
+ ; [rsp + 0] = layer_kv_base
+ ; [rsp + 8] = pos
+ ; [rsp + 16] = att_scale (f32)
+ ; [rsp + 20] = gqa_ratio (u32)
+ ; [rsp + 24] = h1
+ ; [rsp + 32] = kv_head_stride (max_seq * head_dim * 4)
+
+ mov [rsp + 0], rdi
+ mov [rsp + 8], rsi
+ mov [rsp + 16], edx ; att_scale bits
+ shr rdx, 32
+ mov [rsp + 20], edx ; gqa_ratio
+ mov [rsp + 24], r8 ; h1
+
+ lea rbx, [rel g_ctx]
+ mov rbp, [rbx + CTX_HEAD_DIM]
+ shl rbp, 2 ; rbp = head_bytes (step per t = 512B contiguous!)
+ mov rax, [rbx + CTX_MAX_SEQ]
+ imul rax, rbp
+ mov [rsp + 32], rax ; kv_head_stride
+
+ mov r12, rcx ; h = h0
+.h_lp:
+ cmp r12, [rsp + 24]
+ jae .h_done
+
+ ; kv_h = h / gqa_ratio; r13 = layer_kv_base + kv_h * kv_head_stride
+ mov eax, r12d
+ xor edx, edx
+ div dword [rsp + 20]
+ imul rax, [rsp + 32]
+ add rax, [rsp + 0]
+ mov r13, rax
+
+ ; q_head = buf_q + h * head_bytes
+ mov rax, r12
+ imul rax, rbp
+ mov r14, [rbx + CTX_BUF_Q]
+ add r14, rax
+
+ ; Private score buffer scr_h = buf_att_scr + h * max_seq * 4
+ mov r11, r12
+ imul r11, [rbx + CTX_MAX_SEQ]
+ shl r11, 2
+ add r11, [rbx + CTX_BUF_ATT_SCR]
+
+ ; Scores[0..pos]: dot(q_head, k_cache[l, kv_h, t]) * att_scale
+ mov r15, [rbx + CTX_BUF_K_CACHE]
+ add r15, r13
+ xor ecx, ecx
+.sc_lp:
+ cmp rcx, [rsp + 8]
+ ja .sc_done
+ push rcx
+ push r11
+ mov rdi, r14
+ mov rsi, r15
+ mov rdx, [rbx + CTX_HEAD_DIM]
+ call dot_f32_avx2
+ pop r11
+ pop rcx
+ vmulss xmm0, xmm0, [rsp + 16]
+ vmovss [r11 + rcx*4], xmm0
+ add r15, rbp ; contiguous +512B!
+ inc rcx
+ jmp .sc_lp
+
+.sc_done:
+ push r11
+ sub rsp, 8 ; 16B align
+ mov rdi, r11
+ mov rsi, [rsp + 24] ; pos (rsp+8 + 16 = rsp+24)
+ inc rsi
+ call softmax_avx2
+ add rsp, 8
+ pop r11
+
+ ; Zero att_head = buf_att_out + h * head_bytes
+ mov rax, r12
+ imul rax, rbp
+ mov r14, [rbx + CTX_BUF_ATT_OUT]
+ add r14, rax
+ vxorps ymm0, ymm0, ymm0
+ xor eax, eax
+.z_lp:
+ cmp rax, rbp
+ jae .v_acc
+ vmovups [r14 + rax], ymm0
+ add rax, 32
+ jmp .z_lp
+
+.v_acc:
+ mov r15, [rbx + CTX_BUF_V_CACHE]
+ add r15, r13
+ xor ecx, ecx
+.v_lp:
+ cmp rcx, [rsp + 8]
+ ja .h_next
+ vmovss xmm0, [r11 + rcx*4]
+ push rcx
+ push r11
+ mov rdi, r14
+ mov rsi, r15
+ mov rdx, [rbx + CTX_HEAD_DIM]
+ call saxpy_f32_avx2
+ pop r11
+ pop rcx
+ add r15, rbp ; contiguous +512B!
+ inc rcx
+ jmp .v_lp
+
+.h_next:
+ inc r12
+ jmp .h_lp
+
+.h_done:
+ add rsp, 40
+ pop r15
+ pop r14
+ pop r13
+ pop r12
+ pop rbp
+ pop rbx
+ ret
+%endif
+
section .rodata
align 4
t_one: dd 1.0