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.
ci: build all phases and boot-test the OS in QEMU with KVM
Kevin Griffin16ef5ef1b2f6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..a5d60c1--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,137 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:+ inputs:+ run_1_7b:+ description: "Also run the Qwen3-1.7B smoke test (downloads ~4 GB, converts to a 1.8 GB .asmbin)"+ type: boolean+ default: false++concurrency:+ group: ci-${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++permissions:+ contents: read++jobs:+ # Pure toolchain check: every phase assembles and links. No model needed.+ build:+ name: build (all phases)+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v7+ - name: Install toolchain+ run: |+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends nasm binutils file+ - name: make all+ run: make all+ - name: make check-all+ run: make check-all+ - name: Kernel is a valid Multiboot 1 image+ run: |+ sudo apt-get install -y --no-install-recommends grub-common+ grub-file --is-x86-multiboot build/asm-llm-os.elf+ echo "multiboot header OK"++ # Boot the bare-metal OS in QEMU with KVM and check the serial output.+ # Default: Qwen3-0.6B. Qwen3-1.7B is added only for a manual workflow_dispatch run.+ smoke:+ name: QEMU smoke (Qwen3-${{ matrix.size }})+ runs-on: ubuntu-latest+ timeout-minutes: ${{ matrix.size == '1.7b' && 60 || 30 }}+ strategy:+ fail-fast: false+ matrix:+ size: ${{ fromJSON(inputs.run_1_7b && '["0.6b","1.7b"]' || '["0.6b"]') }}+ env:+ SIZE: ${{ matrix.size }}+ EXPECT_MODEL: ${{ matrix.size == '1.7b' && 'Qwen3-1.7B' || 'Qwen3-0.6B' }}+ RAM: ${{ matrix.size == '1.7b' && '4G' || '2G' }}+ MODEL: models/qwen3-${{ matrix.size }}-q8_0.asmbin+ steps:+ - uses: actions/checkout@v7++ - name: Install toolchain+ run: |+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends \+ nasm qemu-system-x86 python3-numpy \+ grub-common grub-pc-bin xorriso mtools++ - name: Build the OS kernel+ run: make os++ - name: Enable KVM+ run: |+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \+ | sudo tee /etc/udev/rules.d/99-kvm4all.rules+ sudo udevadm control --reload-rules+ sudo udevadm trigger --name-match=kvm+ ls -l /dev/kvm++ - name: Check CPU features (the kernel needs AVX2, FMA and F16C)+ run: |+ grep -m1 'model name' /proc/cpuinfo+ nproc+ missing=0+ for f in avx2 fma f16c; do+ if grep -m1 '^flags' /proc/cpuinfo | grep -qw "$f"; then+ echo "cpu flag $f: yes"+ else+ echo "::error::cpu flag $f: MISSING"+ missing=1+ fi+ done+ exit "$missing"++ - name: Restore converted model cache+ id: model-cache+ uses: actions/cache@v6+ with:+ path: ${{ env.MODEL }}+ # The pinned HF revision + SHA-256 hashes live in ci_fetch_model.sh,+ # so changing the model (or the converter) changes the key.+ key: asmbin-${{ matrix.size }}-${{ hashFiles('scripts/ci_fetch_model.sh', 'scripts/export_weights.py', 'scripts/merge_safetensors.py') }}++ - name: Fetch Qwen3 from Hugging Face and convert to .asmbin+ if: steps.model-cache.outputs.cache-hit != 'true'+ env:+ HF_TOKEN: ${{ secrets.HF_TOKEN }} # optional; anonymous download works+ run: scripts/ci_fetch_model.sh "$SIZE"++ - name: Banner test+ run: |+ mkdir -p build/ci-logs+ python3 scripts/test_qemu_boot.py banner --accel kvm \+ --model "$MODEL" --ram "$RAM" --expect-model "$EXPECT_MODEL" \+ --log "build/ci-logs/banner-$SIZE.log"++ - name: Generation test (batch prompt, 8 tokens)+ run: |+ python3 scripts/test_qemu_boot.py gen --accel kvm \+ --model "$MODEL" --ram "$RAM" --expect-model "$EXPECT_MODEL" \+ --expect-text assist --max-tokens 8 --min-decode-toks 1.0 \+ --log "build/ci-logs/gen-$SIZE.log"++ - name: Build the GRUB ISO and boot it+ if: matrix.size == '0.6b'+ run: |+ make os-iso MODEL="$MODEL"+ python3 scripts/test_qemu_boot.py banner --accel kvm \+ --iso build/asm-llm-os.iso --ram "$RAM" --expect-model "$EXPECT_MODEL" \+ --log "build/ci-logs/iso-banner-$SIZE.log"++ - name: Upload serial logs+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: serial-logs-${{ matrix.size }}+ path: build/ci-logs/+ if-no-files-found: ignorediff --git a/scripts/ci_fetch_model.sh b/scripts/ci_fetch_model.shnew file mode 100755index 0000000..6ec8a82--- /dev/null+++ b/scripts/ci_fetch_model.sh@@ -0,0 +1,79 @@+#!/usr/bin/env bash+# ============================================================================+# scripts/ci_fetch_model.sh — fetch an official Qwen3 checkpoint from Hugging+# Face (pinned revision, SHA-256 verified) and convert it to a Q8_0 .asmbin+# with this repo's own exporter (scripts/export_weights.py).+#+# usage: scripts/ci_fetch_model.sh 0.6b|1.7b+#+# The exporter consumes BF16 safetensors + tokenizer.json + config.json (not+# GGUF), so the official Qwen/Qwen3-* repos are used. Output:+# models/qwen3-0.6b-q8_0.asmbin or models/qwen3-1.7b-q8_0.asmbin+# Optional: set HF_TOKEN to avoid anonymous rate limits.+# Bumping a revision/hash below also changes the CI cache key.+# ============================================================================+set -euo pipefail++SIZE="${1:?usage: ci_fetch_model.sh 0.6b|1.7b}"+cd "$(dirname "$0")/.."++TOKENIZER_SHA=aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4++case "$SIZE" in+ 0.6b)+ REPO=Qwen/Qwen3-0.6B+ REV=c1899de289a04d12100db370d81485cdf75e47ca+ CONFIG_SHA=660db3b73d788119c04535e48cf9be5f55bc3100841a718637ae695b442f27dd+ SHARDS=(+ "model.safetensors f47f71177f32bcd101b7573ec9171e6a57f4f4d31148d38e382306f42996874b"+ )+ ;;+ 1.7b)+ REPO=Qwen/Qwen3-1.7B+ REV=70d244cc86ccca08cf5af4e1e306ecf908b1ad5e+ CONFIG_SHA=1ddb5b89ebc90dcb417a45c213d818577e65976454d29385c8f6140771d95197+ SHARDS=(+ "model-00001-of-00002.safetensors 169ad53ec313c3a34b06c0809216e4fc072cce444a5d4ff2b59690d064130ed5"+ "model-00002-of-00002.safetensors 912becff8d60672aa8628ef08c05898d9adf17c2ad4ae3caf99b065622fdeff9"+ )+ ;;+ *) echo "unknown size: $SIZE (want 0.6b or 1.7b)" >&2; exit 2 ;;+esac++DIR="models/qwen3-${SIZE}-bf16"+OUT="models/qwen3-${SIZE}-q8_0.asmbin"+mkdir -p "$DIR"++fetch() { # fetch <file> <sha256>+ local file="$1" sha="$2" dest="$DIR/$1"+ local url="https://huggingface.co/${REPO}/resolve/${REV}/${file}"+ local auth=()+ [[ -n "${HF_TOKEN:-}" ]] && auth=(-H "Authorization: Bearer ${HF_TOKEN}")+ if [[ -f "$dest" ]] && echo "${sha} ${dest}" | sha256sum -c --quiet - 2>/dev/null; then+ echo "[fetch] ${file}: already present, hash ok"+ return+ fi+ echo "[fetch] ${url}"+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 5 "${auth[@]}" -o "$dest" "$url"+ echo "${sha} ${dest}" | sha256sum -c -+}++fetch config.json "$CONFIG_SHA"+fetch tokenizer.json "$TOKENIZER_SHA"+for s in "${SHARDS[@]}"; do+ read -r file sha <<<"$s"+ fetch "$file" "$sha"+done++if [[ ${#SHARDS[@]} -gt 1 ]]; then+ files=()+ for s in "${SHARDS[@]}"; do files+=("$DIR/${s%% *}"); done+ python3 scripts/merge_safetensors.py "$DIR/model.safetensors.merged" "${files[@]}"+ rm -f "${files[@]}"+ mv "$DIR/model.safetensors.merged" "$DIR/model.safetensors"+fi++python3 scripts/export_weights.py --model-dir "$DIR" --out "$OUT" --scale-dtype fp16+rm -rf "$DIR" # free runner disk; the .asmbin is all the tests need+ls -l "$OUT"+sha256sum "$OUT"diff --git a/scripts/merge_safetensors.py b/scripts/merge_safetensors.pynew file mode 100755index 0000000..625ab17--- /dev/null+++ b/scripts/merge_safetensors.py@@ -0,0 +1,65 @@+#!/usr/bin/env python3+"""Merge sharded .safetensors files into one file.++scripts/export_weights.py reads a single model.safetensors. Qwen3-1.7B and+larger ship as several shards, so merge them first:++ python3 scripts/merge_safetensors.py OUT.safetensors SHARD1 SHARD2 ...++Tensors are copied byte-for-byte in chunks (low RAM); the header is rebuilt with+fresh data offsets.+"""+import json+import struct+import sys++CHUNK = 1 << 24+++def main() -> int:+ if len(sys.argv) < 3:+ print(__doc__, file=sys.stderr)+ return 2+ out_path, shards = sys.argv[1], sys.argv[2:]++ tensors = [] # (name, meta, shard_path, shard_data_base)+ for path in shards:+ with open(path, "rb") as f:+ (n,) = struct.unpack("<Q", f.read(8))+ header = json.loads(f.read(n))+ for name, meta in header.items():+ if name != "__metadata__":+ tensors.append((name, meta, path, 8 + n))++ out_header, off = {}, 0+ for name, meta, _, _ in tensors:+ start, end = meta["data_offsets"]+ out_header[name] = {+ "dtype": meta["dtype"],+ "shape": meta["shape"],+ "data_offsets": [off, off + end - start],+ }+ off += end - start+ hb = json.dumps(out_header).encode()+ hb += b" " * ((8 - len(hb) % 8) % 8)++ with open(out_path, "wb") as out:+ out.write(struct.pack("<Q", len(hb)))+ out.write(hb)+ for _, meta, path, base in tensors:+ start, end = meta["data_offsets"]+ with open(path, "rb") as f:+ f.seek(base + start)+ left = end - start+ while left:+ buf = f.read(min(left, CHUNK))+ if not buf:+ raise EOFError(f"truncated shard: {path}")+ out.write(buf)+ left -= len(buf)+ print(f"merged {len(tensors)} tensors, {off} bytes -> {out_path}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/test_qemu_boot.py b/scripts/test_qemu_boot.pynew file mode 100755index 0000000..c4e7880--- /dev/null+++ b/scripts/test_qemu_boot.py@@ -0,0 +1,187 @@+#!/usr/bin/env python3+"""+QEMU boot smoke test for the asm-llm bare-metal OS (Phase 2), driven over serial.++ banner : boot, wait for the first `asm-llm> ` prompt, check the banner.+ gen : boot with a batch prompt (prompt=... shutdown=1), check the banner,+ the generated text and the prefill/decode stats lines.++Boots either -kernel/-initrd (default) or a GRUB ISO (--iso). Uses KVM when+available (--accel kvm, -cpu host) or TCG (--accel tcg, -cpu max; very slow).++Examples:+ scripts/test_qemu_boot.py gen --model models/qwen3-0.6b-q8_0.asmbin \+ --expect-model Qwen3-0.6B --accel kvm --expect-text assist+ scripts/test_qemu_boot.py banner --iso build/asm-llm-os.iso --accel kvm++Exit status 0 = all assertions passed, 1 = assertion failed, 2 = usage/setup.+"""+import argparse+import os+import re+import select+import subprocess+import sys+import time++BANNER_RE = re.compile(+ rb"Model\s*:\s*(Qwen3-[0-9.]+B) (Q8_0) \((\d+) MiB @ (0x[0-9a-fA-F]+), (\d+)L, ctx=(\d+)\)"+)+CPU_RE = re.compile(rb"CPU\s*:\s*([^\r\n]*)")+SMP_RE = re.compile(rb"SMP\s*:\s*(\d+)/(\d+)\s+x86-64 cores online")+PREFILL_RE = re.compile(rb"\[asm-llm-os\] prefill:\s*(\d+) tok in ([0-9.]+) ms \(([0-9.]+) tok/s\)")+DECODE_RE = re.compile(+ rb"\[asm-llm-os\] decode\s*:\s*(\d+) tok in ([0-9.]+) ms \(([0-9.]+) tok/s, cores=(\d+)\)"+)+++def build_cmd(a):+ cpu = "host" if a.accel == "kvm" else "max"+ accel = ["-enable-kvm"] if a.accel == "kvm" else ["-accel", "tcg,thread=multi"]+ cmd = ["qemu-system-x86_64", *accel, "-cpu", cpu, "-m", a.ram, "-smp", str(a.smp)]+ if a.iso:+ cmd += ["-cdrom", a.iso, "-boot", "d"]+ else:+ cmd += ["-kernel", a.kernel, "-initrd", a.model]+ if a.mode == "gen":+ cmd += ["-append", f'prompt="{a.prompt}" max_tokens={a.max_tokens} think=0 shutdown=1']+ cmd += [+ "-display", "none", "-no-reboot",+ "-chardev", "stdio,id=s0,mux=on,signal=off",+ "-serial", "chardev:s0", "-mon", "chardev=s0",+ "-device", "isa-debug-exit,iobase=0x501,iosize=0x02",+ ]+ return cmd+++def run_qemu(cmd, goal, timeout):+ """Run QEMU, return (output bytes, goal_seen, exit code, elapsed)."""+ t0 = time.time()+ p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, bufsize=0)+ buf, seen = b"", False+ end = t0 + timeout+ while time.time() < end:+ r, _, _ = select.select([p.stdout], [], [], 0.5)+ if r:+ d = os.read(p.stdout.fileno(), 65536)+ if not d:+ break+ sys.stdout.buffer.write(d)+ sys.stdout.buffer.flush()+ buf += d+ if goal.search(buf):+ seen = True+ break+ elif p.poll() is not None:+ break+ if seen: # drain briefly: gen mode prints the stats lines just before poweroff+ drain_end = time.time() + 3+ while time.time() < drain_end:+ r, _, _ = select.select([p.stdout], [], [], 0.2)+ if r:+ d = os.read(p.stdout.fileno(), 65536)+ if not d:+ break+ sys.stdout.buffer.write(d)+ buf += d+ elif p.poll() is not None:+ break+ if p.poll() is None:+ p.kill()+ try:+ p.wait(timeout=10)+ except subprocess.TimeoutExpired:+ pass+ return buf, seen, p.returncode, time.time() - t0+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("mode", choices=["banner", "gen"])+ ap.add_argument("--kernel", default="build/asm-llm-os.elf")+ ap.add_argument("--model", default="models/qwen3-0.6b-q8_0.asmbin")+ ap.add_argument("--iso", help="boot this GRUB ISO instead of -kernel/-initrd (banner mode only)")+ ap.add_argument("--accel", choices=["kvm", "tcg"], default="kvm")+ ap.add_argument("--ram", default="2G")+ ap.add_argument("--smp", type=int, default=4)+ ap.add_argument("--timeout", type=int, default=0, help="seconds (default: 120 kvm / 3600 tcg)")+ ap.add_argument("--prompt", default="Hello")+ ap.add_argument("--max-tokens", type=int, default=8)+ ap.add_argument("--expect-model", help="e.g. Qwen3-0.6B (exact banner model name)")+ ap.add_argument("--expect-text", help="substring the generated reply must contain")+ ap.add_argument("--min-decode-toks", type=float, default=0.0, help="fail if decode tok/s is lower")+ ap.add_argument("--log", help="write raw serial output here")+ a = ap.parse_args()++ if a.iso and a.mode == "gen":+ ap.error("--iso supports banner mode only (the ISO's cmdline is fixed at build time)")+ for path in ([a.iso] if a.iso else [a.kernel, a.model]):+ if not os.path.isfile(path):+ print(f"error: missing file: {path}", file=sys.stderr)+ return 2+ if a.accel == "kvm" and not os.access("/dev/kvm", os.R_OK | os.W_OK):+ print("error: --accel kvm but /dev/kvm is not accessible", file=sys.stderr)+ return 2+ timeout = a.timeout or (120 if a.accel == "kvm" else 3600)++ cmd = build_cmd(a)+ print("CMD:", " ".join(cmd), flush=True)+ goal = re.compile(rb"asm-llm> " if a.mode == "banner" else rb"\[asm-llm-os\] boot\s*:")+ buf, seen, rc, elapsed = run_qemu(cmd, goal, timeout)+ if a.log:+ with open(a.log, "wb") as f:+ f.write(buf)++ failures = []++ def check(cond, msg):+ print(f"[test] {'PASS' if cond else 'FAIL'}: {msg}")+ if not cond:+ failures.append(msg)++ check(seen, f"reached {'prompt' if a.mode == 'banner' else 'end of generation'} within {timeout}s")+ m = BANNER_RE.search(buf)+ check(m is not None, "banner has `Model : Qwen3-<N>B Q8_0 (<MiB> MiB @ <addr>, <L>L, ctx=<N>)`")+ if m:+ name, _, mib, _, layers, ctx = m.groups()+ print(f"[test] banner: model={name.decode()} size={mib.decode()} MiB layers={layers.decode()} ctx={ctx.decode()}")+ if a.expect_model:+ check(name.decode() == a.expect_model,+ f"banner model is {a.expect_model} (got {name.decode()})")+ c = CPU_RE.search(buf)+ check(c is not None, "banner has a CPU line")+ if c:+ print(f"[test] cpu: {c.group(1).decode(errors='replace').strip()}")+ check(b"AVX2" in c.group(1), "CPU line reports AVX2")+ s = SMP_RE.search(buf)+ check(s is not None and s.group(1) == s.group(2) and int(s.group(1)) == a.smp,+ f"all {a.smp} cores online")++ if a.mode == "gen":+ pm = re.search(rb"Prompt: " + re.escape(a.prompt.encode()) + rb"[ \t]*\r?\n(.*?)\r?\n\[asm-llm-os\] prefill",+ buf, re.S)+ reply = pm.group(1).decode("utf-8", "replace").strip() if pm else ""+ print(f"[test] reply: {reply!r}")+ check(bool(reply), "model produced a non-empty reply")+ if a.expect_text:+ check(a.expect_text.lower() in reply.lower(), f"reply contains {a.expect_text!r}")+ pf, dc = PREFILL_RE.search(buf), DECODE_RE.search(buf)+ check(pf is not None, "prefill stats line present")+ check(dc is not None, "decode stats line present")+ if pf:+ print(f"[test] prefill: {pf.group(1).decode()} tok, {pf.group(3).decode()} tok/s")+ if dc:+ n, tps = int(dc.group(1)), float(dc.group(3))+ print(f"[test] decode : {n} tok, {tps} tok/s, cores={dc.group(4).decode()}")+ check(n == a.max_tokens, f"decoded exactly max_tokens={a.max_tokens} tokens (got {n})")+ if a.min_decode_toks:+ check(tps >= a.min_decode_toks, f"decode >= {a.min_decode_toks} tok/s (got {tps})")++ print(f"[test] elapsed={elapsed:.1f}s qemu_exit={rc}")+ print("[test] RESULT:", "FAIL" if failures else "OK")+ return 1 if failures else 0+++if __name__ == "__main__":+ sys.exit(main())