读见

GitHub - alesha-pro/llm.asm:完全使用 x86-64 NASM 汇编实现 Qwen3-0.6B 推理(12 KB)、裸机可启动 OS(22 KB),以及带实时盲文 TUI 的 Mini-GPT 从零训练器(32 KB)。100% 纯汇编,零 C、零 libc、零依赖。

原题GitHub - alesha-pro/llm.asm: 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.

约 9 分钟约 2,025 字原文英文已翻译

推荐理由适合想拆分推理程序与模型权重占用的读者,用这个小实现定位最基本的推理流程,再理解常用运行时多提供了什么。

读前速览

5 个要点

llm.asm 是一个 100% 纯 x86-64 NASM 汇编项目,实现了 Qwen3-0.6B 推理(14KB)、裸机可启动 OS(24KB)和 Mini-GPT 训练器(32KB),没有任何运行时依赖,CPU 推理速度比 llama.cpp 快 18-36%。

  1. 三个完整的 LLM 项目均以 100% 纯 x86-64 NASM 汇编实现,且没有运行时依赖

    所有数学内核、GEMM 引擎、分词器和线程功能均由手写汇编实现,总计 17,252 行;推理、裸机 OS、训练和内核修补项目均不依赖 C、C++、Rust、libc 或 libm。

  2. Qwen3-0.6B 推理在 1-40 个线程下的 CPU 解码速度比 llama.cpp 快 18-36%

    在 AMD EPYC 7642 上使用相同模型和精度进行基准测试时,llm.asm(14.7KB)在 40T 下达到 126.8 tok/s,而 llama.cpp 为 105.08 tok/s。FAST_Q8=1 使用 INT8xINT8 AVX2 和并行 GQA 注意力,在不同线程数下比 llama.cpp 快 +18% 到 +36%。

  3. 裸机 OS 可在 74-94ms 内直接从硬件启动 Qwen3-0.6B,在 KVM EPYC 上达到 134.9 tok/s

    这个 24KB 的可启动 OS 实现了 Multiboot 1 -> Long Mode -> AVX2/FMA/F16C -> ACPI/APIC SMP;在 16 个 vCPU 的 KVM EPYC 上达到 134.9 tok/s,在真实的 Proxmox Xeon E5-2670 v3 上达到 55.4 tok/s,无需磁盘空间。经 5 个测试提示词和多轮 KV-cache 验证,生成的 token 完全一致。

  4. Mini-GPT 训练器在全部 21 个梯度张量上与 PyTorch 的余弦匹配度达到 1.0000000000

    这个 32KB 的训练器使用寄存器分块的 6x16 AVX2+FMA SGEMM、完整的解析反向传播、解耦式 AdamW 和实时 80x24 盲文 TUI;在 TinyShakespeare 上 4 分钟内达到 27,662 train tok/s,并将 val_loss 从 4.19 降至 1.51,且梯度变化轨迹通过验证。

  5. Ring -1 虚拟机监控程序在未见过的故障场景中达到 97.54% pass@1,危险继续执行率为 0%

    这个 75KB 的 AMD SVM 虚拟机监控程序运行在未经修改的 Linux 5.15 下,搭载 MiniCPM5-2B 引擎,覆盖 24 个 LAPIC 核心,并提供 NPT 内存隔离和实时 KVM 验证器;在包含 600 个场景的语料库中达到 119/122 pass@1,而基线为 16.39%。

完整摘要

llm.asm 展示了三个完全使用 x86-64 NASM 汇编实现的完整 LLM 项目,不依赖 C、C++、Rust、libc 或其他运行时组件。项目包括:(1) 仅 14KB 的 Qwen3-0.6B 推理引擎,在 40T 下解码速度达到 126.8 tok/s,比 llama.cpp CPU 快 18-36%;(2) 仅 24KB 的裸机可启动 OS,可直接在硬件上启动 Qwen3-0.6B,在 KVM EPYC 上达到 134.9 tok/s;(3) 仅 32KB 的 Mini-GPT 训练器,配备实时 80x24 盲文 TUI,训练速度达到 27,662 train tok/s,与 PyTorch 的余弦梯度匹配度为 1.0000000000;(4) 仅 75KB、用于内核修补的 Ring -1 AMD SVM 虚拟机监控程序。所有实现均通过 PyTorch 参考实现验证,具备位精确的确定性;数学内核(expf、sincosf、RMSNorm、RoPE、SiLU、Softmax)、AVX2+FMA+F16C GEMM/GEMV 引擎、BPE 分词器和线程池均由手写汇编实现。

目录 · 15 节

查看原文

三个完整的 LLM 项目,100% 使用纯 x86-64 NASM 汇编编写。零 C、零 C++、零 Rust、零 libc、零 libm,也没有任何运行时依赖。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.

直接使用 nasm 汇编,并通过 ld 链接。所有数学内核(expf、sincosf、RMSNorm、RoPE、SiLU、Softmax)、AVX2+FMA+F16C GEMM/GEMV 引擎、BPE 分词器、基于 clone()/futex() 的线程池、裸机 SMP 内核、解析式反向传播、AdamW 优化器,以及实时 Unicode 盲文 TUI,全部都是手工编写的 x86-64 汇编(这三个项目合计 17,252 行)。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 Projects

Project Binary Size Deps Key Numbers
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.
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.
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.
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.

CPU 解码正面对比基准测试:llm.asm 与 llama.cpp(Qwen3-0.6B Q8_0)Head-to-Head CPU Decode Benchmark: llm.asm vs llama.cpp (Qwen3-0.6B Q8_0)

在同一台机器上测得(AMD EPYC 7642,47 个核心在线,256 MiB L3 缓存,DDR4,仅使用 CPU,-ngl 0),使用同一模型(Qwen3-0.6B Q8_0:.asmbin v2 FP16-scale 为 613.66 MiB,GGUF Q8_0 为 604.15 MiB),输入 34 个提示词元、生成 64 个词元,取 3 次运行的平均值: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%) —

(注意:llama.cpp 在提示词预填充 pp34 阶段使用批量 GEMM,而 llm.asm 则逐 token 运行 GEMV。在自回归解码 tg64 阶段,llm.asm(FAST_Q8=1)结合了 INT8xINT8 AVX2 vpmaddubsw/vpmaddwd、.asmbin v2 FP16 块缩放因子(F16C vcvtph2ps)、单调递增的下一行预取、连续的 head-major KV 缓存以及并行 GQA 注意力;在 1 到 40 个线程的情况下,性能比 llama.cpp 高出 +18%..+36%,同时在所有线程数下都能生成逐位完全一致的确定性输出。裸机 OS 通过 2 MiB 大页恒等映射,性能又提升了约 10%。)(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.)


实时输出与视觉证明Live Output & Visual Proof

阶段 2:在裸机上直接启动 Qwen3-0.6B(QEMU KVM,16 个 vCPU)Phase 2: Booting Qwen3-0.6B Directly on Bare Metal (QEMU KVM, 16 vCPUs)

Bare-Metal Qwen3-0.6B OS VGA Console

阶段 2:在 Proxmox VE 虚拟机上上线运行(0 GB 磁盘、Intel Xeon E5-2670 v3、12 核)Phase 2: Running Live on a Proxmox VE VM (0 GB Disk, Intel Xeon E5-2670 v3, 12 Cores)

Running on Real Proxmox VE VM (0 GB Disk, Intel Xeon KVM)

阶段 3:纯汇编实时 80×24 UTF-8 盲文 TUI(build/asm-gpt-train)Phase 3: Pure-Assembly Live 80x24 UTF-8 Braille TUI (build/asm-gpt-train)

╭──────────────────────────────────────────────────────────────────────────────╮
│ asm-gpt-train │ 100% Pure x86-64 Assembly (Zero libc, AVX2+FMA)              │
│ L=6 D=192 H=6 FF=512 V=65 │ params=2681664 │ B=16 T=128 │ threads=20         │
├──────────────────────────────────────────────────────────────────────────────┤
│ Loss Curve (0..400)    ⣿⣿⣿ train   ◆ val    best_val=1.8399                  │
│ 4.34 ┤◆   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·  │
│      │⡇                                                                      │
│ 3.61 ┤⢱   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·  │
│      │ ⢱                                                                     │
│ 2.87 ┤· ⠣⣀·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·  │
│      │    ⠑⠢⠤⣀◆                                                              │
│ 2.14 ┤·   ·   ·⠉⠉⠑⠒⠒⠢⠤⠤◆⠤⣀⣀⣀⡀⣀⣀◆  ·   · ◆ ·   ·   ·   ·   ·   ·   ·   ·   ·  │
│      │                      ⠈  ⠉⠉⠉⠊⠉⠊⠒⠊⠒⠊⠒⠔⠒⠢⠤⠤⠔⠢◆⠤⠤⠤⢄⣀⣀⢄◆⣀⣀⣀⣀⡀⣀⣀⢀◆⡀ ⡀⢀   ⣀◆ │
│ 1.40 ┤·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ·   ⠈  ⠁⠁⠈⠉⠈⠁⠉⠉⠉·⠈ │
│      └step 0 ───────────────────────── 200 ────────────────────────── 400    │
├──────────────────────────────────────────────────────────────────────────────┤
│ Step 400/400 [████████████████████████████] 100% │ elapsed 35.2s             │
│ loss=1.6604  val=1.8399  best=1.8399  gnorm=0.53  lr=0.000200  25470 tok/s   │
├─ Live Sample (step 400) ─────────────────────────────────────────────────────┤
│ ROMEO:                                                                       │
│ Nay, to lond, in if as my kears, some with death.                            │
│                                                                              │
│ DUKE VINCENTIO:                                                              │
╰──────────────────────────────────────────────────────────────────────────────╯

快速入门Quick Start

克隆代码仓库并使用 make all 构建所有内容:Clone the repo and build everything with make all:

git clone https://github.com/alesha-pro/llm.asm.git
cd llm.asm
make all

1. 在 14 KB 中运行 Qwen3-0.6B 推理(01-qwen3-inference/)1. Run Qwen3-0.6B Inference in 14 KB (01-qwen3-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

完整的分步设置说明、模型下载、命令行参数和基准测试:01-qwen3-inference/README.md。Full step-by-step setup, model download, CLI flags, and benchmarks: 01-qwen3-inference/README.md.

2. 在 24 KB 中启动裸机 Qwen3-0.6B 操作系统(02-baremetal-os/)2. Boot Bare-Metal Qwen3-0.6B OS in 24 KB (02-baremetal-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

完整的 QEMU KVM、可启动 ISO 和 0 GB 磁盘 Proxmox VE 部署指南:02-baremetal-os/README.md。Full QEMU KVM, bootable ISO, and 0 GB disk Proxmox VE deployment guide: 02-baremetal-os/README.md.

3. 在 32 KB 中从零开始训练 Mini-GPT(03-minigpt-train/)3. Train Mini-GPT from Scratch in 32 KB (03-minigpt-train/)

训练或运行推理无需使用 Python:Zero Python required to train or run inference:

mkdir -p data checkpoints && curl -fsSL https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt -o data/tinyshakespeare.txt
make train
./build/asm-gpt-train --data data/tinyshakespeare.txt --steps 400 --seq 128 -t 16 --save checkpoints/shakespeare.ckpt

完整训练、实时盲文 TUI、检查点聊天循环,以及 PyTorch 梯度检查指南:03-minigpt-train/README.md。Full training, live Braille TUI, checkpoint chat loop, and PyTorch gradient check guide: 03-minigpt-train/README.md.

4. 从 Ring -1 实时修补 Linux Ring 0 崩溃(04-ring1-kernel-surgeon/)4. Live-Patch Linux Ring 0 Crashes from Ring -1 (04-ring1-kernel-surgeon/)

cd 04-ring1-kernel-surgeon
make hv                                # Build 75 KB freestanding Ring -1 AMD SVM hypervisor (surgeon.elf)
python3 verifier/kvm_verifier.py --selftest

完整架构、QEMU nested-SVM + VNC 演示、SFT/GRPO 训练和 KVM 验证器指南:04-ring1-kernel-surgeon/README.md。Full architecture, QEMU nested-SVM + VNC demo, SFT/GRPO training, and KVM verifier guide: 04-ring1-kernel-surgeon/README.md.


仓库布局Repository Layout

llm.asm/
├── LICENSE                        # MIT License
├── Makefile                       # Single build file: inference, os, os-iso, train, all, check
├── README.md                      # You are here
├── 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,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, 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 (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: 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
│   ├── kernel.asm                 # Kernel entrypoint, CPUID banner, cmdline parser, multi-turn chat REPL
│   ├── linker.ld                  # Bare-metal linker script at 0x00100000
│   ├── os_constants.inc           # Hardware, Multiboot 1, Local APIC, and SMP constants
│   ├── runtime.asm                # Multiboot mmap bump allocator + bare-metal formatting runtime
│   └── smp.asm                    # ACPI MADT + 16->32->64 AP trampoline + INIT-SIPI-SIPI spin-barrier
├── 03-minigpt-train/              # Phase 3: 32 KB Mini-GPT trainer + inference engine (7,977 lines)
│   ├── README.md
│   ├── train_constants.inc        # Training context offsets, SGEMM flags, .gptckpt format
│   ├── sgemm.asm                  # Thread pool + register-blocked 6x16 AVX2+FMA FP32 SGEMM (NN/TN/NT)
│   ├── kernels.asm                # Forward/backward RMSNorm, RoPE, Causal MHA, SwiGLU, CE, AdamW, PRNG
│   ├── model.asm                  # Arena layout, deterministic init, full fwd/bwd pass, sampler
│   ├── tui.asm                    # ioctl(TCGETS) TTY detect + flicker-free 80x24 ANSI/Braille TUI
│   └── main.asm                   # CLI, auto char-vocab, 90/10 split, .gptckpt I/O, train/sample loop
├── 04-ring1-kernel-surgeon/       # Phase 4: Ring -1 AMD SVM hypervisor + MiniCPM5-2B live kernel patcher
│   ├── README.md
│   ├── ARCHITECTURE.md            # Physical memory map, NPT isolation, SVM intercepts
│   ├── Makefile                   # Builds surgeon.elf, surgeon_crash.ko, initramfs, UEFI ISO
│   ├── hv/                        # Bare-metal Ring -1 hypervisor (NASM + freestanding zero-libc C)
│   ├── guest/                     # Ring 0 fault-injection test module (crash_mod) & KVM verifier module (bench_mod)
│   ├── dataset/                   # 48-pilot & 600-scenario corpus + DeepSeek distillation script
│   ├── verifier/                  # 3-tier single-level QEMU/KVM + Capstone safety verifier
│   ├── training/                  # MiniCPM5-2B LoRA SFT, KVM-verified GRPO, eval, TensorBoard logger
│   ├── dashboard/                 # Live FastAPI training & verifier telemetry dashboard
│   └── scripts/                   # Initramfs/ISO builders, QEMU/VNC demos, GGUF/.r1m packers
└── scripts/
    ├── export_weights.py          # Offline HuggingFace Qwen3-0.6B -> .asmbin (Q8_0) converter
    ├── mkiso.sh                   # Bootable BIOS+UEFI hybrid GRUB Multiboot 1 ISO builder
    ├── test_math.py               # Automated SIMD & math kernel unit test driver
    ├── verify_ref.py              # Independent NumPy Q8_0 + PyTorch FP32 parity harness
    ├── verify_os.py               # Phase 2 parity, SMP determinism, KVM benchmark & VGA capture suite
    └── verify_train_ref.py        # Phase 3 per-tensor PyTorch CPU grad-check & AdamW trajectory suite

系统要求System Requirements

  • CPU:x86-64,支持 AVX2 + FMA + F16C(Intel Haswell / AMD Excavator 或更新型号)。
    CPU: x86-64 with AVX2 + FMA + F16C (Intel Haswell / AMD Excavator or newer).
  • Build tools: nasm and GNU binutils (ld, objcopy).
    sudo apt install nasm binutils
  • 阶段 1 和 3 运行时:任何 Linux x86-64 内核。零共享库(readelf -d 报告不存在动态段)。
    Phase 1 & 3 runtime: Any Linux x86-64 kernel. Zero shared libraries (readelf -d reports no dynamic section).
  • 阶段 2 运行环境(可选):qemu-system-x86_64 搭配 KVM,或任何 x86-64 虚拟机监控程序/裸机(Proxmox VE、VirtualBox、真实硬件)。构建可启动 ISO 需要使用 grub-mkrescue(grub-pc-bin、grub-efi-amd64-bin、mtools、xorriso)。
    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).
  • 离线工具(可选):仅需 python3 + numpy,用于一次性导出 Qwen3-0.6B .asmbin 并进行参考验证(仅在运行 PyTorch 一致性检查时才需要 torch + transformers)。
    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).

架构与验证总结Architecture & Verification Summary

每个阶段都遵循相同的工程规则:不使用运行时库、采用确定性的并行分区,并通过独立的 Python/PyTorch 参考实现进行数值验证。Every phase is built on the same engineering rules: no runtime libraries, deterministic parallel partitioning, and numerical verification against independent Python/PyTorch references.

  • 共享汇编核心(shared/):阶段 2 使用 -DBARE_METAL 编译完全相同的 math.asm、matmul.asm、tokenizer.asm 和 transformer.asm(将 Linux mmap/clone/write 替换为物理 Multiboot 模块、APIC 自旋屏障以及 VGA+COM1 驱动程序)。阶段 3 重用 syscalls.asm 和 math.asm。
    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.
  • 第 1 阶段验证:对于 FAST_Q8=1 和 FAST_Q8=0,在 v1 FP32 和 v2 FP16 scale 格式下,所有数学/SIMD 内核均通过单元测试,误差在 1e-7..1e-6 以内(init_rope_freqs FP64 < 5e-14)。FAST_Q8=1 与 PyTorch FP32 Qwen3-0.6B 的余弦相似度为 0.9996517,64/64 个贪心生成 token 完全一致(FAST_Q8=0 与 Python Q8_0 参考实现完全匹配,余弦相似度为 1.000000000)。从 1T 到 40T 均可实现位精确的确定性结果。
    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.
  • 第二阶段验证:在 5 个测试提示(英语、俄语 UTF-8、算术、--think 模式)中,输出 100% 逐 token 精确,且与第一阶段逐字节完全一致;还验证了多轮 KV-cache 回忆 + /clear,以及 1 至 32 个 KVM vCPU 的情况(16 个 vCPU 时为 134.9 tok/s)。已在 QEMU KVM(AMD EPYC 7642)和真实的 Proxmox VE 虚拟机(Intel Xeon E5-2670 v3、0 GB 磁盘、BIOS GRUB ISO)上完成验证。
    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).
  • 第 3 阶段验证:已针对 PyTorch FP32 CPU 验证全部 21 个参数张量(最差 max_abs_diff = 3.35e-8,最低 cosine_sim = 1.0000000000)、10 步 AdamW + 余弦 LR + 梯度裁剪训练轨迹(max_loss_diff = 4.77e-7),以及 1T、8T 和 16T 之间的位精确确定性。
    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.
  • 第 4 阶段验证(04-ring1-kernel-surgeon/):在三层 QEMU/KVM 验证器下,MiniCPM5-2B GRPO 在未见过的留出故障场景中达到 97.54% 的 pass@1(119/122)(基线为 16.39%),且危险继续执行率为 0%;它还在 Ring -1 内端到端运行(75 KB 的 surgeon.elf、24 个 LAPIC SMP 核心、在 AMD NPT 中取消映射的 2 GiB 只读 NVDIMM),可实时修补 #PF/#DE/#UD、委派 extable 处理,并冻结 lock_held 故障。
    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.

请参阅各个项目的 README,了解完整表格、内存布局和复现步骤:See each project's README for full tables, memory layouts, and reproduction steps:


许可证License

MIT 许可证。请参阅 LICENSE。MIT License. See LICENSE.

值得记下

  1. 三个完整的 LLM 项目全部使用 100% 纯 x86-64 NASM 汇编编写。零 C、零 C++、零 Rust、零 libc、零 libm、零运行时依赖。
  2. llm.asm(FAST_Q8=1)结合了 INT8xINT8 AVX2 vpmaddubsw/vpmaddwd、.asmbin v2 FP16 块缩放(F16C vcvtph2ps)、单调递增的下一行预取、连续的 head-major KV-cache,以及并行 GQA 注意力,在 1..40 个线程范围内比 llama.cpp 快 +18%..+36%。
  3. 每个数学内核(expf、sincosf、RMSNorm、RoPE、SiLU、Softmax)、AVX2+FMA+F16C GEMM/GEMV 引擎、BPE 分词器、clone()/futex() 线程池、裸机 SMP 内核、解析反向传播、AdamW 优化器,以及实时 Unicode 盲文 TUI,全部由手写 x86-64 汇编实现(所有三个项目合计 17,252 行)。
  4. 第三阶段验证:与 PyTorch FP32 CPU 在全部 21 个参数张量上完成比对(最差 max_abs_diff = 3.35e-8,最低 cosine_sim = 1.0000000000);验证了 10 步 AdamW + cosine LR + grad-clip 训练轨迹(max_loss_diff = 4.77e-7),并确认在 1T、8T 和 16T 下结果位精确且确定。
  5. 裸机 OS 通过 2 MiB 大页恒等映射进一步提升了约 10% 的性能。

← 回到本期 · 第 18 条