{"slug": "llm-asm-pure-x86-64-assembly-for-llm-inference-and-training", "title": "Llm.asm – Pure x86-64 Assembly for LLM Inference and Training", "summary": "A developer published llm.asm, a set of three LLM projects written entirely in x86-64 NASM assembly with zero C, C++, Rust, libc or libm dependencies, totaling 17,252 lines of hand-written assembly. The flagship 14,712-byte static Linux binary runs Qwen/Qwen3-0.6B at 126.8 tok/s decode on 40 threads (20.7 tok/s on 1 thread), which the author reports as 18% to 36% faster than llama.cpp CPU Q8_0 across 1 to 40 threads on an AMD EPYC 7642, with 0.99965 cosine similarity and 64/64 exact greedy tokens versus PyTorch FP32. The set also includes a 24,252-byte bare-metal Qwen3-0.6B OS booting in 74-94 ms at up to 136.6 tok/s under KVM and a 32,944-byte FP32 Mini-GPT trainer reaching 27,662 train tok/s with 1.0000000000 cosine across all 21 gradient tensors against PyTorch CPU.", "body_md": "**Three complete LLM projects written in 100% pure x86-64 NASM assembly.**\nZero C, zero C++, zero Rust, zero libc, zero libm, zero runtime dependencies.\n\nAssembled 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).\n\n| Project | Binary | Size | Deps | Key Numbers | \n|---|---|---|---|---|\n| **[01-qwen3-inference/](https://github.com/alesha-pro/llm.asm/blob/main/01-qwen3-inference)** | `build/asm-llm` | **14,712 B***(14,008 B `FAST_Q8=0`)* | **0** | Pure x86-64 NASM 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. | \n| **[02-baremetal-os/](https://github.com/alesha-pro/llm.asm/blob/main/02-baremetal-os)** | `build/asm-llm-os.elf` | **24,252 B***(23,612 B `FAST_Q8=0`)* | **0** | Pure x86-64 NASM 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. | \n| **[03-minigpt-train/](https://github.com/alesha-pro/llm.asm/blob/main/03-minigpt-train)** | `build/asm-gpt-train` | **32,944 B** | **0** | Pure x86-64 NASM 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. | \n| **[04-ring1-kernel-surgeon/](https://github.com/alesha-pro/llm.asm/blob/main/04-ring1-kernel-surgeon)** | `04-ring1-kernel-surgeon/build/surgeon.elf` | **75,424 B** | **0***(freestanding NASM + zero-libc C)* | Bare-metal Type-1 AMD SVM hypervisor ( `Ring -1` ) running beneath unmodified Linux`5.15` (`Ring 0` ) with an embedded**MiniCPM5-2B `Q4_K_M`** engine across 24 LAPIC SMP cores, NPT memory isolation, live`efifb` HUD, static x86-64 patch validator, and single-level KVM verifier RL.**97.54% pass@1** (`119/122` unseen test scenarios,`0%` dangerous continues) vs**16.39%** base. | \n\nMeasured 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:\n\n| 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`)** | \n|---|---|---|---|---|---|\n| **1** | 7.18 tok/s | 16.63 tok/s | **20.70 tok/s** | **1.24x (+24.5%)** | **23.67 tok/s** | \n| **4** | 28.12 tok/s | 51.08 tok/s | **69.24 tok/s** | **1.36x (+35.6%)** | **78.89 tok/s** | \n| **8** | 53.09 tok/s | 80.79 tok/s | **103.64 tok/s** | **1.28x (+28.3%)** | **118.08 tok/s** | \n| **16** | 77.50 tok/s | 103.03 tok/s | **121.86 tok/s** | **1.18x (+18.3%)** | **134.94 tok/s** | \n| **24** | 91.88 tok/s | 104.11 tok/s | **123.72 tok/s** | **1.19x (+18.8%)** | **132.90 tok/s** | \n| **32** | 96.63 tok/s | 103.82 tok/s | **122.51 tok/s** | **1.18x (+18.0%)** | **133.75 tok/s** | \n| **40** | 98.50 tok/s | 105.08 tok/s | **125.86 tok/s***(peak 126.81)* | **1.20x (+19.8%)** | — | \n\n*(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.)*\n\n```\n╭──────────────────────────────────────────────────────────────────────────────╮\n│ asm-gpt-train │ 100% Pure x86-64 Assembly (Zero libc, AVX2+FMA)              │\n│ L=6 D=192 H=6 FF=512 V=65 │ params=2681664 │ B=16 T=128 │ threads=20         │\n├──────────────────────────────────────────────────────────────────────────────┤\n│ Loss Curve (0..400)    ⣿⣿⣿ train   ◆ val    best_val=1.8399                  │\n│ 4.34 ┤◆   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·  │\n│      │⡇                                                                      │\n│ 3.61 ┤⢱   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·  │\n│      │ ⢱                                                                     │\n│ 2.87 ┤· ⠣⣀·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·  │\n│      │    ⠑⠢⠤⣀◆                                                              │\n│ 2.14 ┤·   ·   ·⠉⠉⠑⠒⠒⠢⠤⠤◆⠤⣀⣀⣀⡀⣀⣀◆  ·   · ◆ ·   ·   ·   ·   ·   ·   ·   ·   ·  │\n│      │                      ⠈  ⠉⠉⠉⠊⠉⠊⠒⠊⠒⠊⠒⠔⠒⠢⠤⠤⠔⠢◆⠤⠤⠤⢄⣀⣀⢄◆⣀⣀⣀⣀⡀⣀⣀⢀◆⡀ ⡀⢀   ⣀◆ │\n│ 1.40 ┤·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ⠈  ⠁⠁⠈⠉⠈⠁⠉⠉⠉·⠈ │\n│      └step 0 ───────────────────────── 200 ────────────────────────── 400    │\n├──────────────────────────────────────────────────────────────────────────────┤\n│ Step 400/400 [████████████████████████████] 100% │ elapsed 35.2s             │\n│ loss=1.6604  val=1.8399  best=1.8399  gnorm=0.53  lr=0.000200  25470 tok/s   │\n├─ Live Sample (step 400) ─────────────────────────────────────────────────────┤\n│ ROMEO:                                                                       │\n│ Nay, to lond, in if as my kears, some with death.                            │\n│                                                                              │\n│ DUKE VINCENTIO:                                                              │\n╰──────────────────────────────────────────────────────────────────────────────╯\n```\n\nClone the repo and build everything with `make all`:\n\n```\ngit clone https://github.com/alesha-pro/llm.asm.git\ncd llm.asm\nmake all\n# Export compact .asmbin v2 (FP16 block scales, 613.66 MiB; or --scale-dtype fp32 for legacy v1)\npython3 scripts/export_weights.py --model-dir models/qwen3-0.6b-bf16 --out models/qwen3-0.6b-q8_0.asmbin --scale-dtype fp16\n# Build with FAST_Q8=1 (default: INT8xINT8 AVX2 + parallel GQA) or FAST_Q8=0 (exact FP32 activations)\nmake inference FAST_Q8=1\n./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\n# Or start an interactive multi-turn chat preserving the KV-cache across turns:\n./build/asm-llm -m models/qwen3-0.6b-q8_0.asmbin --chat -t 16\n```\n\nFull step-by-step setup, model download, CLI flags, and benchmarks: **[01-qwen3-inference/README.md](https://github.com/alesha-pro/llm.asm/blob/main/01-qwen3-inference/README.md)**.\n\n```\nmake os FAST_Q8=1\nmake os-run MODEL=models/qwen3-0.6b-q8_0.asmbin SMP=16\n# Or build a bootable BIOS+UEFI ISO for QEMU / Proxmox VE:\nmake os-iso MODEL=models/qwen3-0.6b-q8_0.asmbin\n```\n\nFull QEMU KVM, bootable ISO, and 0 GB disk Proxmox VE deployment guide: **[02-baremetal-os/README.md](https://github.com/alesha-pro/llm.asm/blob/main/02-baremetal-os/README.md)**.\n\nZero Python required to train or run inference:\n\n```\nmkdir -p data checkpoints && curl -fsSL https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt -o data/tinyshakespeare.txt\nmake train\n./build/asm-gpt-train --data data/tinyshakespeare.txt --steps 400 --seq 128 -t 16 --save checkpoints/shakespeare.ckpt\n```\n\nFull training, live Braille TUI, checkpoint chat loop, and PyTorch gradient check guide: **[03-minigpt-train/README.md](https://github.com/alesha-pro/llm.asm/blob/main/03-minigpt-train/README.md)**.\n\n```\ncd 04-ring1-kernel-surgeon\nmake hv                                # Build 75 KB freestanding Ring -1 AMD SVM hypervisor (surgeon.elf)\npython3 verifier/kvm_verifier.py --selftest\n```\n\nFull architecture, QEMU nested-SVM + VNC demo, SFT/GRPO training, and KVM verifier guide: **[04-ring1-kernel-surgeon/README.md](https://github.com/alesha-pro/llm.asm/blob/main/04-ring1-kernel-surgeon/README.md)**.\n\n```\nllm.asm/\n├── LICENSE                        # MIT License\n├── Makefile                       # Single build file: inference, os, os-iso, train, all, check\n├── README.md                      # You are here\n├── assets/\n│   ├── baremetal-vga.png          # QEMU KVM 80x25 VGA text-mode capture (EPYC 7642, 16 cores)\n│   └── proxmox-vm250-vga.png      # Real Proxmox VE 0 GB disk VM capture (Xeon E5-2670 v3, 12 cores)\n├── shared/                        # Pure x86-64 NASM core reused across phases (3,857 lines)\n│   ├── constants.inc              # Linux syscalls, .asmbin v1/v2 header, runtime context offsets\n│   ├── syscalls.asm               # Raw Linux syscalls + string/number formatting helpers\n│   ├── math.asm                   # AVX2/SSE2 expf, sincosf, FP64 RoPE, RMSNorm, Softmax, SiLU, argmax, top-p\n│   ├── matmul.asm                 # FAST_Q8=1 INT8xINT8 AVX2+F16C & FAST_Q8=0 Q8_0xFP32 matmul, dequant, dot, saxpy\n│   ├── threads.asm                # Zero-libc Linux clone() + hybrid spin/futex thread pool (matmul + GQA attn)\n│   ├── tokenizer.asm              # Fibonacci-hashed BPE encoder, UTF-8 decoder, Qwen3 chat template\n│   └── transformer.asm            # Full 28-layer Qwen3 forward pass (v1/v2 auto-detect, contiguous KV, parallel GQA)\n├── 01-qwen3-inference/            # Phase 1: 14 KB static Linux ELF inference engine + --chat (1,251 lines)\n│   ├── README.md\n│   ├── main.asm\n│   └── test_math.asm\n├── 02-baremetal-os/               # Phase 2: 24 KB bare-metal bootable LLM OS (4,167 lines)\n│   ├── README.md\n│   ├── boot.asm                   # Multiboot 1 -> 4-level paging -> Long Mode -> AVX2/FMA -> IDT\n│   ├── drivers.asm                # COM1 115200, 80x25 Color VGA, PS/2 keyboard, PIT+RDTSC, ACPI poweroff\n│   ├── kernel.asm                 # Kernel entrypoint, CPUID banner, cmdline parser, multi-turn chat REPL\n│   ├── linker.ld                  # Bare-metal linker script at 0x00100000\n│   ├── os_constants.inc           # Hardware, Multiboot 1, Local APIC, and SMP constants\n│   ├── runtime.asm                # Multiboot mmap bump allocator + bare-metal formatting runtime\n│   └── smp.asm                    # ACPI MADT + 16->32->64 AP trampoline + INIT-SIPI-SIPI spin-barrier\n├── 03-minigpt-train/              # Phase 3: 32 KB Mini-GPT trainer + inference engine (7,977 lines)\n│   ├── README.md\n│   ├── train_constants.inc        # Training context offsets, SGEMM flags, .gptckpt format\n│   ├── sgemm.asm                  # Thread pool + register-blocked 6x16 AVX2+FMA FP32 SGEMM (NN/TN/NT)\n│   ├── kernels.asm                # Forward/backward RMSNorm, RoPE, Causal MHA, SwiGLU, CE, AdamW, PRNG\n│   ├── model.asm                  # Arena layout, deterministic init, full fwd/bwd pass, sampler\n│   ├── tui.asm                    # ioctl(TCGETS) TTY detect + flicker-free 80x24 ANSI/Braille TUI\n│   └── main.asm                   # CLI, auto char-vocab, 90/10 split, .gptckpt I/O, train/sample loop\n├── 04-ring1-kernel-surgeon/       # Phase 4: Ring -1 AMD SVM hypervisor + MiniCPM5-2B live kernel patcher\n│   ├── README.md\n│   ├── ARCHITECTURE.md            # Physical memory map, NPT isolation, SVM intercepts\n│   ├── Makefile                   # Builds surgeon.elf, surgeon_crash.ko, initramfs, UEFI ISO\n│   ├── hv/                        # Bare-metal Ring -1 hypervisor (NASM + freestanding zero-libc C)\n│   ├── guest/                     # Ring 0 fault-injection test module (crash_mod) & KVM verifier module (bench_mod)\n│   ├── dataset/                   # 48-pilot & 600-scenario corpus + DeepSeek distillation script\n│   ├── verifier/                  # 3-tier single-level QEMU/KVM + Capstone safety verifier\n│   ├── training/                  # MiniCPM5-2B LoRA SFT, KVM-verified GRPO, eval, TensorBoard logger\n│   ├── dashboard/                 # Live FastAPI training & verifier telemetry dashboard\n│   └── scripts/                   # Initramfs/ISO builders, QEMU/VNC demos, GGUF/.r1m packers\n└── scripts/\n    ├── export_weights.py          # Offline HuggingFace Qwen3-0.6B -> .asmbin (Q8_0) converter\n    ├── mkiso.sh                   # Bootable BIOS+UEFI hybrid GRUB Multiboot 1 ISO builder\n    ├── test_math.py               # Automated SIMD & math kernel unit test driver\n    ├── verify_ref.py              # Independent NumPy Q8_0 + PyTorch FP32 parity harness\n    ├── verify_os.py               # Phase 2 parity, SMP determinism, KVM benchmark & VGA capture suite\n    └── verify_train_ref.py        # Phase 3 per-tensor PyTorch CPU grad-check & AdamW trajectory suite\n```\n\n- **CPU:** x86-64 with**AVX2 + FMA + F16C** (Intel Haswell / AMD Excavator or newer).\n- **Build tools:**`nasm` and GNU`binutils` (`ld` ,`objcopy` ).\n\n```\nsudo apt install nasm binutils\n```\n\n- **Phase 1 & 3 runtime:** Any Linux x86-64 kernel. Zero shared libraries (`readelf -d` reports no dynamic section).\n- **Phase 2 runtime (optional):**`qemu-system-x86_64` with KVM, or any x86-64 hypervisor/bare-metal machine (Proxmox VE, VirtualBox, real hardware). Building bootable ISOs uses`grub-mkrescue` (`grub-pc-bin` ,`grub-efi-amd64-bin` ,`mtools` ,`xorriso` ).\n- **Offline tooling (optional):**`python3` +`numpy` only for one-time`Qwen3-0.6B``.asmbin` export and reference verification (`torch` +`transformers` only if running PyTorch parity checks).\n\nEvery phase is built on the same engineering rules: no runtime libraries, deterministic parallel partitioning, and numerical verification against independent Python/PyTorch references.\n\n- **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` .\n- **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` .\n- **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).\n- **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` .\n- **Phase 4 verification (`04-ring1-kernel-surgeon/`):** MiniCPM5-2B GRPO achieves**` 97.54%` pass@1 (`119/122`)** on unseen held-out fault scenarios (` 16.39%` base) with**`0%` dangerous continues** under the 3-tier QEMU/KVM verifier, and runs end-to-end inside Ring`-1` (`75 KB`` surgeon.elf` , 24 LAPIC SMP cores, 2 GiB read-only NVDIMM unmapped in AMD NPT) to live-patch`#PF` /`#DE` /`#UD` , delegate`extable` , and freeze`lock_held` faults.\n\nSee each project's README for full tables, memory layouts, and reproduction steps:\n\n- [01-qwen3-inference/README.md](https://github.com/alesha-pro/llm.asm/blob/main/01-qwen3-inference/README.md)\n- [02-baremetal-os/README.md](https://github.com/alesha-pro/llm.asm/blob/main/02-baremetal-os/README.md)\n- [03-minigpt-train/README.md](https://github.com/alesha-pro/llm.asm/blob/main/03-minigpt-train/README.md)\n- [04-ring1-kernel-surgeon/README.md](https://github.com/alesha-pro/llm.asm/blob/main/04-ring1-kernel-surgeon/README.md)\n\nMIT License. See [LICENSE](https://github.com/alesha-pro/llm.asm/blob/main/LICENSE).", "url": "https://wpnews.pro/news/llm-asm-pure-x86-64-assembly-for-llm-inference-and-training", "canonical_source": "https://github.com/alesha-pro/llm.asm", "published_at": "2026-11-28 03:39:41+00:00", "updated_at": "2026-11-28 04:13:14.749940+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-infrastructure", "ai-research", "ai-tools"], "entities": ["llm.asm", "Qwen3-0.6B", "llama.cpp", "PyTorch", "AMD EPYC 7642", "Mini-GPT", "NASM", "MiniCPM5-2B"], "also_reported_by": [], "takeaway": "A hand-written AVX2+FMA+F16C assembly GEMV engine with Q8_0 weights and FP16 scales (FAST_Q8=1) decoded Qwen3-0.6B at 20.70 tok/s on 1 thread and 125.86 tok/s on 40 threads, 1.18x to 1.36x llama.cpp's Q8_0 CPU throughput on the same AMD EPYC 7642.", "recommendation": {"advice": "If you run CPU-only LLM decode, implement the GEMV path in AVX2+FMA with F16C scale handling and Q8_0 weights; the source measured 1.18x-1.36x over llama.cpp at 1-40 threads.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/llm-asm-pure-x86-64-assembly-for-llm-inference-and-training", "markdown": "https://wpnews.pro/news/llm-asm-pure-x86-64-assembly-for-llm-inference-and-training.md", "text": "https://wpnews.pro/news/llm-asm-pure-x86-64-assembly-for-llm-inference-and-training.txt", "jsonld": "https://wpnews.pro/news/llm-asm-pure-x86-64-assembly-for-llm-inference-and-training.jsonld"}}