In partnership with

❝

What actually beats llama.cpp is a sign trick in an AVX2 integer instruction, a scale format that saves 35.5 MiB of memory traffic per token, and a thread pool that never makes a syscall while it is busy.

SnackOnAI Engineering | Senior AI Systems Researcher | Technical Deep Dive | November 26, 2026

Found this useful?
A tip keeps the deep-dives free for everyone.
$0 of $10,000 · 0 supporters
$1,000 Silver
$5,000 Gold
$10,000 Platinum
Other amount

Promise and Fence

The promise: by the end of this issue you will know why a hand-written NASM engine decodes Qwen3-0.6B 18% to 36% faster than llama.cpp on the same CPU, what the trick inside its INT8 kernel is, and exactly where that lead flips into a 3.8× loss.

The fence: this is not an argument for writing production inference in assembly, and not a llama.cpp takedown. I cloned alesha-pro/llm.asm at commit 48feccb (Nov 25, 2026), assembled it, reproduced the 14,712 byte binary, passed every math unit test, and trained the pure-assembly GPT on TinyShakespeare. I could not run Qwen3 inference itself, because Hugging Face is unreachable from my sandbox. All Qwen3 throughput numbers are the author's, measured on an AMD EPYC 7642, plus arithmetic I show.

What It Actually Does

Three programs, zero libraries, all hand-written x86-64 NASM, about 17,200 lines in total, MIT licensed, by Alexey Fateev:

Phase

Binary

What it is

Inference

14,712 B static ELF

Runs Qwen/Qwen3-0.6B in Q8_0: BPE tokenizer, chat template, GQA, QK-norm, RoPE, SwiGLU, KV-cache chat REPL

Bare-metal OS

24,252 B Multiboot kernel

Same model with no operating system: boots in 74 to 94 ms to a VGA chat prompt, uses every core via ACPI and SIPI, needs 0 GB of disk

Mini-GPT trainer

32,944 B static ELF

FP32 GPT with a full analytical backward pass, AdamW and a live Braille TUI, gradient checked against PyTorch to a cosine of 1.0000000000

No libc, no libm, no dynamic linker. expf, sincosf, RMSNorm, softmax, the BPE merge table, the thread pool and the AP core trampoline are all written by hand. The only Python is an offline exporter that converts the Hugging Face safetensors to a .asmbin file once.

The Architecture, Unpacked

Follow the bytes, not the instructions: each decoded token streams all 614 MiB of weights through the kernel at the bottom. Everything above it exists to keep that stream full.

Three decisions matter more than the language choice.

1. A file format built for the memory bus. Every row stores K int8 weights followed by K/32 FP16 scales, padded to a multiple of 64 bytes. Switching the scales from FP32 (v1, 649.18 MiB) to FP16 (v2, 613.66 MiB) cuts 35.5 MiB of DRAM traffic from every token. Fused QKV and gate+up layouts mean one thread-pool barrier per pair of projections instead of three.

2. Integer math on both sides. FAST_Q8=0 keeps activations in FP32 and decodes at 7.18 tok/s on one thread. FAST_Q8=1 quantizes each activation vector to int8 once, then does int8 × int8 dot products: 20.70 tok/s, 2.88× faster, and the 64 greedy tokens still match PyTorch FP32 exactly.

3. Determinism as a design rule. Rows are split with a ceiling-balanced static formula and each worker owns its slice, so the output is bit-identical from 1 to 40 threads. That is why the author can claim exact parity at every thread count, something most engines don't promise.

The Code, Annotated

The integer dot product (real code, shared/matmul.asm, one of two block pairs)

; Q8_0 weights: int8 in [-127, 127], never -128.  x_q8: activations quantized once.
; Goal: 32 signed×signed int8 products per block, summed, scaled, accumulated in fp32.
    Q8_PREFETCH [r8 + rbx]          ; prefetch scales of this row, then the NEXT row,
    Q8_PREFETCH [r8 + rbx + 64]     ; walking forward so the HW stream prefetcher never resets

    vmovdqa    ymm4,  [r11 + rbx]       ; 32 int8 activations (block 0)
    vpabsb     ymm5,  ymm4              ; |x|  → now UNSIGNED bytes
    vmovdqu    ymm6,  [rax + rbx]       ; 32 int8 weights
    vpsignb    ymm6,  ymm6, ymm4        ; w · sign(x)  ← THIS is the trick
    ; vpmaddubsw only multiplies UNSIGNED × SIGNED bytes. |x| · (w·sign(x)) = x·w,
    ; so moving x's sign onto w turns a signed×signed product into the shape the
    ; instruction accepts, with no widening to int16 first.
    vpmaddubsw ymm6,  ymm5, ymm6        ; pairwise u8×s8 → int16, SATURATING
    ; Saturation is safe only because Q8_0 clamps to ±127: 127·127·2 = 32,258 < 32,767.
    ; A single -128 could overflow here. The exporter's clamp is a correctness rule.
    vpmaddwd   ymm6,  ymm6, ymm15       ; × int16(1): sum pairs again → 8 × int32
    vcvtdq2ps  ymm6,  ymm6              ; int32 → fp32
    vpermilps  ymm8,  ymm12, 0x00       ; broadcast (w_scale · x_scale) for block 0
    vfmadd231ps ymm0, ymm6, ymm8        ; acc0 += partial · scale
    ; Four independent accumulators (ymm0..ymm3), one per block, hide the
    ; 4-cycle FMA latency. A single accumulator would stall on itself.

The vpabsb + vpsignb pair is the classic llama.cpp-era AVX2 idiom, but here it sits in a loop with zero stack traffic, 128 bytes per iteration and a prefetch pattern designed around one CPU's stream prefetcher. That specificity is the speedup.

The thread pool that never syscalls while hot (real code, shared/threads.asm)

.worker_wait:
    mov     ecx, SPIN_LIMIT             ; 200,000 iterations of pause ≈ tens of µs
.spin_lp:
    mov     eax, [rel tp_gen]           ; generation counter bumped by the main thread
    cmp     eax, r13d                   ; new job since my last one?
    jne     .got_job                    ; yes: no kernel involvement at all
    pause                               ; be polite to the sibling hyperthread
    dec     ecx
    jnz     .spin_lp
    ; Between tokens the next matmul arrives within microseconds, so spinning
    ; wins. In --chat while the user types, spinning would burn 100% of every
    ; core, so after the budget runs out the worker sleeps in the kernel.
    lock inc dword [rel tp_waiters]     ; announce "I might sleep" BEFORE re-checking
    mov     eax, [rel tp_gen]
    cmp     eax, r13d                   ; Dekker-style re-check closes the lost-wakeup race
    jne     .unwait
    lea     rdi, [rel tp_gen]
    mov     esi, FUTEX_WAIT_PRIVATE
    mov     edx, r13d                   ; sleep only if tp_gen still == my_gen
    mov     eax, SYS_futex
    syscall                             ; ← THIS is the trick: futex only when idle

A decode step on Qwen3-0.6B crosses about 140 thread-pool barriers (five per layer across 28 layers, plus the LM head). Paying a futex wake on each one would cost more than the math on small matrices. Spin-then-sleep gives zero syscalls during generation and 0% idle CPU at the prompt.

Verification arithmetic (mine)

weights_v2 = 643_469_504                      # bytes, from the README format spec
print(weights_v2 * 126.8 / 1e9)               # 81.6 GB/s streamed at peak decode
print(604.15 * 2**20 * 105.08 / 1e9)          # 66.6 GB/s for llama.cpp at 40 threads
print(8 * 25.6)                               # 204.8 GB/s: EPYC 7642, 8 × DDR4-3200

kv_per_tok = 28 * 2 * 8 * 128 * 4             # layers·(K,V)·kv_heads·head_dim·fp32
print(kv_per_tok, kv_per_tok * 2048 / 2**20)  # 229,376 B/token, 448 MiB at ctx 2048

# Long prompt: 2,000-token prefill + 200-token answer, peak rates from the README
print(2000/160.8 + 200/125.86)                # llm.asm   ≈ 14.0 s
print(2000/1113  + 200/105.08)                # llama.cpp ≈  3.7 s

At peak, both engines use well under half of the socket's theoretical memory bandwidth, so the race is decided by kernel and synchronization quality, not by raw DRAM speed. The last two lines are where the story turns.

It In Action

Input: Explain how a CPU cache works in 3 concise sentences., run with -t 32 (author's sample run and Proxmox table).

Step

What happens

Number

Tokenize

Fibonacci-hashed BPE + Qwen3 chat template

25 prompt tokens

Prefill

25 tokens, one at a time through GEMV

154.28 tok/s → ≈162 ms

Decode

52 tokens, 614 MiB of weights streamed per token

103.40 tok/s → ≈503 ms

Bandwidth

643.5 MB × 103.4 tok/s

≈66.5 GB/s

Memory

weights + FP32 KV arena at ctx 2048

614 MiB + 448 MiB ≈ 1.04 GiB

Output

"A CPU cache is a small amount of memory used to store frequently accessed data and instructions…"

3 sentences

And what I could run myself (the trainer, on 2 vCPUs of a 2.1 GHz Xeon in my sandbox):

Step

Number

Build

make train → 32,944 B static ELF, identical to the README

Model

L=6, D=192, H=6, FF=512, vocab 65 → 2,681,664 params

Init

val_loss 4.1925 (ln 65 = 4.17, i.e. uniform guessing)

200 steps

101.08 s, 505 ms/step, 4,052 train tok/s

After

val_loss 2.0310, sample: "O I have seemings and that belistleme to and hoth fiar in spell of me"

Implied compute

6 × 2.68M × 4,052 ≈ 65 GFLOP/s on two cores, about half their nominal AVX2 FMA peak (my estimate)

Math tests

all 8 kernels pass, e.g. fast_expf_avx2 max rel err 1.394e-07

The author reports 27,662 tok/s on 24 EPYC threads and val_loss 1.51 after 4 minutes. My two-core run lands at about 2,000 tok/s per core, which is consistent with that.

Why This Design Works

Decode at batch 1 is a memory streaming problem. Each token reads every weight once and does about two FLOPs per weight. Whoever keeps the memory pipe fullest with the fewest stalls wins. llm.asm attacks exactly that: a smaller scale format, a 128-byte inner loop, prefetching shaped for the hardware prefetcher, and barriers that cost almost nothing.

One model, one ISA, no dispatch. llama.cpp supports dozens of architectures, quant types and backends, so its hot path carries dispatch, generality and graph scheduling. llm.asm supports one model on AVX2 + FMA + F16C. Every byte of its 14 KB is the hot path.

Bare metal removes the last tax. The OS build identity-maps RAM with 2 MiB pages, so walking 614 MiB of weights needs no 4 KiB page walks. Result: 134.94 vs 121.86 tok/s at 16 threads, about 11% faster than the same code under Linux.

What it trades away. Batched prefill, other models, other CPUs (no AVX-512, no ARM), quantized KV cache, long context (default 2,048) and any serving features. These are not omissions to fix later; they are the reasons it is fast.

Technical Moats

  1. End-to-end numerical verification. Every kernel is unit-tested against NumPy, the full model matches PyTorch FP32 with a cosine of 0.9996517 and 64/64 greedy tokens, and the trainer matches PyTorch gradients on all 21 tensors (worst max abs diff 3.35e-8). Writing assembly is the easy part. Proving it is right is the moat.

  2. Determinism across thread counts. Bit-exact output from 1 to 40 threads on two different hypervisors. Most engines quietly vary with thread count because of reduction order.

  3. A full systems stack in one head. Multiboot, long mode, page tables, ACPI MADT parsing, INIT-SIPI-SIPI, PS/2 and VGA drivers, plus a transformer and a trainer. The breadth needed to replicate all three phases is rare.

Contrarian Insights

1. The binary size is a vanity metric. 14,712 bytes of code drives 643,469,504 bytes of weights. The executable is about 0.002% of what gets touched per token. A 5 MB llama.cpp binary would not be slower because it is bigger; it is slower here because its kernels and scheduling are general. Credit the speed to memory engineering. Crediting it to "no libc" teaches the wrong lesson.

2. "Faster than llama.cpp" is a decode-only claim, and decode-only flips on real prompts. The README states it openly: llama.cpp prefill uses batched GEMM at 56 to 1,113 tok/s, while llm.asm feeds prompts one token at a time at 26.7 to 160.8 tok/s. For a 2,000-token RAG or agent prompt with a 200-token answer, using each engine's peak rates, llm.asm needs about 14.0 s and llama.cpp about 3.7 s, a 3.8× win for llama.cpp. Then there is the cache: llm.asm keeps KV in FP32 at 224 KiB per token. The 34 + 64 token benchmark never touches more than about 21 MiB of it. At a full 2,048-token context it is 448 MiB, read on every decode step, roughly 73% on top of the weight traffic. Expect the decode lead to shrink, and possibly vanish, as context grows (my estimate, not measured).

❝

Surprising Takeaway: the single most important line in the INT8 kernel is a constraint in the exporter, not an instruction. vpmaddubsw saturates at 32,767, and two products of 127 × 127 sum to 32,258. Allow one weight of -128 and pairs can overflow silently. The whole speedup rests on Q8_0's habit of clamping to ±127, a choice usually explained as "symmetry" that turns out to be an overflow guarantee.

TL;DR For Engineers

  • 14,712 B static NASM ELF runs Qwen3-0.6B Q8_0 at 20.70 tok/s on 1 thread and 126.8 tok/s peak on an EPYC 7642, 18% to 36% faster than llama.cpp on decode.

  • The win comes from INT8 × INT8 vpmaddubsw with a vpsignb sign trick, FP16 block scales (35.5 MiB less traffic per token), fused projections and a spin-then-futex pool.

  • Prefill is one token at a time: on a 2,000-token prompt, llama.cpp finishes about 3.8× sooner end to end.

  • FP32 KV cache costs 224 KiB/token, 448 MiB at the 2,048 default, untested by the short benchmark.

  • The bare-metal build adds about 11% from 2 MiB pages; the trainer matches PyTorch gradients exactly and ran at 4,052 tok/s on my two cores.

Explain It Like I'm New

Every time a chatbot writes a word, the computer has to read through the model's entire "memory," hundreds of millions of numbers, and do a little arithmetic on each one. For a small model like the one in this project, that is about 600 megabytes of reading for every single word. Most of the time, the computer is not thinking hard; it is waiting for data to arrive from memory.

Most AI software is built in layers, like a house built on a foundation built on bedrock: your program sits on libraries, which sit on the operating system, which talks to the hardware. Each layer is convenient but adds a bit of overhead.

This project removes the layers. One person wrote everything in assembly, the language closest to what the processor actually understands, so they control exactly how data moves. Imagine a delivery route planned street by street by someone who knows every traffic light, instead of a general-purpose navigation app.

The result is faster than a popular, well-tuned tool for producing words one at a time. It is slower at reading a long question before it starts answering, because it reads one word at a time instead of in batches.

That trade-off is the real lesson. AI speed is mostly about moving data efficiently, and knowing which part of the job you are optimizing.

See It In Action

  • Bare-metal Qwen3 boot capture (alesha-pro, repo asset): baremetal-vga.png. The VGA console of the 24 KB kernel chatting on QEMU KVM with 16 vCPUs, showing that there really is no OS underneath.

  • Diskless Proxmox VM capture (alesha-pro, repo asset): proxmox-vm250-vga.png. The same model on a 0 GB disk Xeon E5-2670 v3 VM at 55.4 tok/s, evidence that it runs outside the author's own box.

  • Phase 1 walkthrough (repo docs): 01-qwen3-inference/README.md. The .asmbin byte layout, the CLI and the full llama.cpp table with prefill caveats; the best ten minutes you can spend on CPU inference this month.

  • Phase 3 trainer and Braille TUI (repo docs): 03-minigpt-train/README.md. Loss curves, live samples at steps 300 to 1,200, and the PyTorch gradient check, so you can watch a model learn Shakespeare in pure assembly.

  • Qwen3-0.6B model card (Qwen): huggingface.co/Qwen/Qwen3-0.6B. The source architecture, with 28 layers, 16/8 GQA and tied embeddings, which this engine reproduces exactly.

Community Conversation

  • Alexey Fateev (alesha-pro), the author: llm.asm README. He publishes the prefill caveat right next to the headline win and documents bit-exact determinism. That candor is why the decode claim deserves to be taken seriously.

  • alesha-pro's llama.cpp benchmarking: depth-harness results. Context Studios lists his recipe for running Qwen3.6 27B Q4_K_M with llama.cpp on one RTX 3090 at 63.9 tok/s, so the comparison comes from someone who measures llama.cpp seriously, not from a skeptic.

  • herbert-rs (xigh): github.com/xigh/herbert-rs. A parallel effort, a from-scratch Rust inference engine that skips GGML and llama.cpp and writes all critical inner loops as hand-written x86-64 assembly (.S files). Hand-tuned kernels are becoming a trend, not a one-off.

  • llama.cpp maintainers' issue traffic (Weekly GitHub Report): buttondown.com. Recent reports include Qwen3-Next 80B CPU inference running about 5× slower than expected on consumer hardware. General engines carry real CPU performance debt, and that debt is exactly the gap a specialized engine exploits.

Specialization Beats Generality on Decode, Not on the Job

llm.asm is a superb piece of engineering and an honest one. It proves that on batch 1 CPU decode, a single-model engine that respects the memory bus can beat the most popular general engine by a fifth to a third. It also proves, in its own footnotes, that decode is not the whole job: prefill and long context are where the general engine's batched GEMM and compact cache earn their keep.

The lesson for teams shipping CPU inference is not "rewrite in assembly." It is "profile bytes per token, then specialize the hot path." The FP16 scales, the sign trick and the spin-then-futex pool are all portable to C or Rust in an afternoon. The 14 KB binary is the souvenir; the memory engineering is the takeaway.

References

  • Qwen Team, Qwen3 Technical Report (2025). arXiv:2505.09388

  • Loshchilov and Hutter, Decoupled Weight Decay Regularization (2017). arXiv:1711.05101

  • Dettmers et al., LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale (2022). arXiv:2208.07339

  • Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023). arXiv:2305.13245

  • Williams, Waterman and Patterson, Roofline: An Insightful Visual Performance Model for Multicore Architectures (2009). CACM

Summary

llm.asm runs Qwen3-0.6B from a 14,712 byte NASM binary, boots it on bare metal, and trains a GPT in pure assembly, all verified against PyTorch. Its 18% to 36% decode win over llama.cpp comes from memory engineering, not binary size, and it flips into a roughly 3.8× loss once prompts get long.

Sponsored Ad If you enjoy practical AI insights, check out SnackOnAI and support the newsletter by subscribing, sharing, and exploring our sponsored ad—it helps us keep building and delivering value 🚀

It's time to set up your holiday streaming campaign

Are you ready to reach holiday shoppers on CTV? For many streamers, the season is already underway.

Last year, according to Roku internal data, holiday content searches on Roku saw an 86% increase during October. And in November, those searches rise an average of 39% weekly. This surging holiday spirit is mirrored by consumer activity, as about half of Roku streamers shopped Black Friday and Cyber Monday deals in 2025.

Meeting those shoppers is easier than you might think. Begin with the seasonal outcome you hope to drive: awareness, online sales, leads, store visits, or another measurable goal. From there, define your audience, upload your creative, set the budget and campaign dates, and establish measurement before launching. You can even create a shoppable ad unit that lets streamers buy with a click of their remote.

Our holiday playbook offers a month-by-month guide to reaching shoppers during this all-important time of year.

First-time spenders get a $5,000 match on the first $5,000 spent with code BEEHIIV5K. Terms apply.

Another security questionnaire just landed. Sprinto collects the evidence, keeps controls current and answers questionnaires on demand, so engineers stay on the roadmap.

Recommended for you

View all
caret-right