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.

7.8 KB
Raw Blame
#!/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())