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.

16.9 KB
Raw Blame
#!/usr/bin/env python3
"""
Parallel QEMU KVM Ring-3 Validator for Zero-App Ephemeral OS (160x120 v1 ABI).
Used by:
  1. Stage 2.2 compact golden-app verification
  2. DeepSeek API dataset generation & #PF repair filtering
  3. Stage 2.3 GRPO reward function (zeroapp_research.md §5)
"""

import concurrent.futures
import json
import os
import re
import socket
import subprocess
import tempfile
import threading
import time
from dataclasses import dataclass, asdict
from typing import Optional, List, Dict, Any

try:
    from PIL import Image
except ImportError:
    Image = None


EXC_NAMES = {
    0: "#DE", 1: "#DB", 3: "#BP", 4: "#OF", 5: "#BR", 6: "#UD",
    7: "#NM", 8: "#DF", 10: "#TS", 11: "#NP", 12: "#SS", 13: "#GP", 14: "#PF",
}


@dataclass
class EvalResult:
    status: str                  # ok | asm_err | fault | timeout | abi_err | infra_err
    reward: float
    passed: bool
    insns: int = 0
    code_bytes: int = 0
    frames: int = 0
    early_exit: int = 0
    nonbg0: int = 0
    nonbg_last: int = 0
    colors: int = 0
    diff015: int = 0
    diff1530: int = 0
    diff30last: int = 0
    hlast_idle: str = ""
    hlast_active: str = ""
    input_reactive: bool = False
    animated: bool = False
    elapsed_ms: int = 0
    err_line: int = 0
    err_msg: str = ""
    fault_vec: int = -1
    fault_name: str = ""
    fault_rip: str = ""
    fault_cr2: str = ""
    fault_err: str = ""
    fault_frame: int = -1
    png_path: str = ""


class QemuSlot:
    """One persistent lightweight QEMU KVM 128 MiB VM slot with COM1 + optional QMP."""

    def __init__(self, kernel_path: str, slot_id: int, enable_qmp: bool = False):
        self.kernel_path = kernel_path
        self.slot_id = slot_id
        self.enable_qmp = enable_qmp
        self.tmpdir = tempfile.mkdtemp(prefix=f"zapp_slot{slot_id}_")
        self.ser_sock_path = os.path.join(self.tmpdir, "serial.sock")
        self.qmp_sock_path = os.path.join(self.tmpdir, "qmp.sock")
        self.proc: Optional[subprocess.Popen] = None
        self.ser: Optional[socket.socket] = None
        self.qmp: Optional[socket.socket] = None
        self.ser_buf = ""
        self.qmp_buf = b""
        self.lock = threading.Lock()
        self.start()

    def start(self):
        self.stop()
        for p in (self.ser_sock_path, self.qmp_sock_path):
            if os.path.exists(p):
                os.remove(p)
        cmd = [
            "qemu-system-x86_64",
            "-enable-kvm", "-cpu", "host",
            "-m", "128M", "-smp", "1",
            "-vga", "std", "-display", "none",
            "-serial", f"unix:{self.ser_sock_path},server,nowait",
            "-kernel", self.kernel_path,
        ]
        if self.enable_qmp:
            cmd += ["-qmp", f"unix:{self.qmp_sock_path},server,nowait"]
        self.proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        self.ser = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.ser.settimeout(0.25)
        for _ in range(80):
            try:
                self.ser.connect(self.ser_sock_path)
                break
            except OSError:
                time.sleep(0.03)
        self.ser_buf = ""
        self._read_until("zero-app> ", timeout=8.0)

        if self.enable_qmp:
            self.qmp = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.qmp.settimeout(5.0)
            for _ in range(80):
                try:
                    self.qmp.connect(self.qmp_sock_path)
                    break
                except OSError:
                    time.sleep(0.03)
            self.qmp_buf = b""
            self._qmp_recv()
            self._qmp_cmd("qmp_capabilities")

    def _qmp_recv(self):
        while b"\n" not in self.qmp_buf:
            chunk = self.qmp.recv(4096)
            if not chunk:
                raise EOFError("QMP closed")
            self.qmp_buf += chunk
        line, self.qmp_buf = self.qmp_buf.split(b"\n", 1)
        return json.loads(line.decode("utf-8"))

    def _qmp_cmd(self, execute: str, arguments=None):
        req = {"execute": execute}
        if arguments is not None:
            req["arguments"] = arguments
        self.qmp.sendall((json.dumps(req) + "\n").encode("utf-8"))
        while True:
            msg = self._qmp_recv()
            if "event" in msg:
                continue
            return msg.get("return")

    def screendump_png(self, out_png: str):
        assert self.enable_qmp and Image is not None
        ppm = os.path.join(self.tmpdir, "shot.ppm")
        self._qmp_cmd("screendump", {"filename": ppm})
        img = Image.open(ppm).convert("RGB")
        # Crop to the 960x720 scaled 160x120 viewport (32..992, 40..760) OR keep full 1024x768?
        # Keep full 1024x768 with HUD bar — looks awesome on dashboard!
        img.save(out_png)
        os.remove(ppm)

    def _read_until(self, needle: str, timeout: float = 8.0) -> str:
        t0 = time.time()
        while time.time() - t0 < timeout:
            idx = self.ser_buf.find(needle)
            if idx != -1:
                end = idx + len(needle)
                chunk = self.ser_buf[:end]
                self.ser_buf = self.ser_buf[end:]
                return chunk
            try:
                data = self.ser.recv(8192)
                if data:
                    self.ser_buf += data.decode("utf-8", errors="replace")
                else:
                    raise EOFError("QEMU serial closed")
            except socket.timeout:
                pass
        raise TimeoutError(f"Timeout waiting for {needle!r}; buf={self.ser_buf[-300:]!r}")

    def run_eval160(self, src: str, n_frames: int, tape_hex: str, blit: int = 0) -> Dict[str, Any]:
        cmd_line = f"eval160 {n_frames} {blit} {tape_hex}\n"
        self.ser.sendall(cmd_line.encode("utf-8"))
        self._read_until("EVAL_READY\n", timeout=5.0)
        clean_lines = [ln.rstrip("\r") for ln in src.splitlines() if ln.strip() != "END"]
        payload = "\n".join(clean_lines) + "\nEND\n"
        # Send in 256-byte chunks so 16-byte COM1 FIFO never overruns!
        data = payload.encode("utf-8")
        for off in range(0, len(data), 128):
            self.ser.sendall(data[off:off + 128])
            time.sleep(0.001)
        out = self._read_until("zero-app> ", timeout=12.0)
        for line in out.splitlines():
            line = line.strip()
            if line.startswith("EVAL_OK "):
                kv = dict(re.findall(r"(\w+)=([^\s]+)", line[8:]))
                return {"type": "ok", **{k: (int(v) if v.isdigit() else v) for k, v in kv.items()}}
            if line.startswith("EVAL_ERR asm "):
                m = re.match(r"EVAL_ERR asm line=(\d+) msg=(.*)", line)
                return {"type": "asm_err", "line": int(m.group(1)) if m else 0, "msg": m.group(2) if m else line}
            if line.startswith("EVAL_ERR abi_exit="):
                kv = dict(re.findall(r"(\w+)=([^\s]+)", line))
                return {"type": "abi_err", "abi_exit": int(kv.get("abi_exit", -1)), "frame": int(kv.get("frame", -1))}
            if line.startswith("EVAL_FAULT "):
                kv = dict(re.findall(r"(\w+)=([^\s]+)", line[11:]))
                vec = int(kv.get("vec", -1))
                return {
                    "type": "fault",
                    "vec": vec,
                    "name": EXC_NAMES.get(vec, f"#EXC{vec}"),
                    "rip": kv.get("rip", ""),
                    "line": int(kv.get("line", 0)),
                    "cr2": kv.get("cr2", ""),
                    "err": kv.get("err", ""),
                    "frame": int(kv.get("frame", -1)),
                }
            if line.startswith("EVAL_TIMEOUT "):
                kv = dict(re.findall(r"(\w+)=([^\s]+)", line[13:]))
                return {
                    "type": "timeout",
                    "rip": kv.get("rip", ""),
                    "line": int(kv.get("line", 0)),
                    "frame": int(kv.get("frame", -1)),
                    "ms": int(kv.get("ms", 0)),
                }
        return {"type": "infra_err", "msg": out[-200:]}

    def stop(self):
        for s in (self.ser, self.qmp):
            if s:
                try:
                    s.close()
                except Exception:
                    pass
        self.ser = None
        self.qmp = None
        if self.proc and self.proc.poll() is None:
            self.proc.terminate()
            try:
                self.proc.wait(timeout=2)
            except subprocess.TimeoutExpired:
                self.proc.kill()
        self.proc = None

    def cleanup(self):
        self.stop()
        for f in os.listdir(self.tmpdir):
            try:
                os.remove(os.path.join(self.tmpdir, f))
            except OSError:
                pass
        try:
            os.rmdir(self.tmpdir)
        except OSError:
            pass


# Default paired tapes (60 frames): idle (all 0) vs active (diverse L/R/U/D/Action inputs!)
DEFAULT_IDLE_TAPE = "00" * 60
DEFAULT_ACTIVE_TAPE = (
    "00" * 4 + "02" * 12 + "10" * 10 + "04" * 10 + "01" * 12 + "08" * 6 + "12" * 6
)


def compute_reward(r_idle: Dict[str, Any], r_act: Optional[Dict[str, Any]], require_animation: bool = False) -> EvalResult:
    t = r_idle["type"]
    if t == "asm_err":
        return EvalResult(status="asm_err", reward=-1.0, passed=False, err_line=r_idle["line"], err_msg=r_idle["msg"])
    if t == "fault":
        return EvalResult(
            status="fault", reward=-0.5, passed=False,
            fault_vec=r_idle["vec"], fault_name=r_idle["name"], fault_rip=r_idle["rip"],
            err_line=r_idle["line"], fault_cr2=r_idle["cr2"], fault_err=r_idle["err"], fault_frame=r_idle["frame"],
        )
    if t == "timeout":
        return EvalResult(
            status="timeout", reward=-0.5, passed=False,
            fault_rip=r_idle["rip"], err_line=r_idle["line"], fault_frame=r_idle["frame"], elapsed_ms=r_idle["ms"],
        )
    if t == "abi_err":
        return EvalResult(status="abi_err", reward=-0.5, passed=False, err_msg=f"abi_exit={r_idle['abi_exit']}", fault_frame=r_idle["frame"])
    if t != "ok":
        return EvalResult(status="infra_err", reward=0.0, passed=False, err_msg=str(r_idle))

    if r_act is not None and r_act["type"] != "ok":
        # Crashed or timed out under user input!
        res = compute_reward(r_act, None)
        res.insns = r_idle.get("insns", 0)
        res.code_bytes = r_idle.get("bytes", 0)
        return res

    src_r = r_act if r_act else r_idle
    nonbg0 = src_r["nonbg0"]
    nonbg_last = src_r["nonbg_last"]
    colors = src_r["colors"]
    diff_sum = src_r["diff015"] + src_r["diff1530"] + src_r["diff30last"]
    animated = diff_sum > 0
    h_idle = str(r_idle["hlast"])
    h_act = str(src_r["hlast"])
    reactive = (r_act is not None) and (h_idle != h_act)

    # GRPO reward decomposition (zeroapp_research.md §5):
    #   +0.10 compiles & runs 60 frames cleanly
    #   +0.20 draws visible content (nonbg_last >= 32)
    #   +0.20 multi-color visuals (colors >= 2; +0.10 if colors == 1)
    #   +0.20 dynamic motion across frames (animated) OR full-screen visual coverage (>4000 px)
    #   +0.30 paired input sensitivity (idle hash != active hash)
    rew = 0.10
    if nonbg_last >= 32:
        rew += 0.20
    if colors >= 2:
        rew += 0.20
    elif colors == 1 and nonbg_last >= 32:
        rew += 0.10
    if animated or (not require_animation and nonbg_last >= 4000):
        rew += 0.20
    if reactive:
        rew += 0.30

    if src_r.get('insns', 0) <= 0:
        return EvalResult(status='asm_err', reward=-1.0, passed=False, err_msg='zero instructions')
    passed = (nonbg_last >= 32) and (colors >= 2) and reactive and (animated or not require_animation)
    return EvalResult(
        status="ok",
        reward=round(rew, 4),
        passed=passed,
        insns=src_r["insns"],
        code_bytes=src_r["bytes"],
        frames=src_r["frames"],
        early_exit=src_r["exit"],
        nonbg0=nonbg0,
        nonbg_last=nonbg_last,
        colors=colors,
        diff015=src_r["diff015"],
        diff1530=src_r["diff1530"],
        diff30last=src_r["diff30last"],
        hlast_idle=h_idle,
        hlast_active=h_act,
        input_reactive=reactive,
        animated=animated,
        elapsed_ms=r_idle["ms"] + (r_act["ms"] if r_act else 0),
    )


class QemuValidatorPool:
    def __init__(self, kernel_path: str, n_workers: int = 8, enable_qmp: bool = False):
        self.slots = [QemuSlot(kernel_path, i, enable_qmp=enable_qmp) for i in range(n_workers)]
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=n_workers)
        self._rr = 0
        self._rr_lock = threading.Lock()

    def _eval_on_slot(self, slot: QemuSlot, src: str, n_frames: int, idle_tape: str, active_tape: str, png_path: Optional[str]) -> EvalResult:
        if not src or not src.strip():
            return EvalResult(status="asm_err", reward=-1.0, passed=False, err_line=1, err_msg="empty program")
        with slot.lock:
            for attempt in range(2):
                try:
                    r_idle = slot.run_eval160(src, n_frames, idle_tape, blit=0)
                    r_act = None
                    if r_idle["type"] == "ok":
                        r_act = slot.run_eval160(src, n_frames, active_tape, blit=1 if png_path else 0)
                        if png_path and r_act["type"] == "ok" and slot.enable_qmp:
                            slot.screendump_png(png_path)
                    res = compute_reward(r_idle, r_act)
                    if png_path and os.path.exists(png_path):
                        res.png_path = png_path
                    return res
                except Exception as e:
                    slot.start()
                    if attempt == 1:
                        return EvalResult(status="infra_err", reward=0.0, passed=False, err_msg=str(e))
            return EvalResult(status="infra_err", reward=0.0, passed=False, err_msg="retry exhausted")

    def evaluate_batch(self, items: List[Dict[str, Any]]) -> List[EvalResult]:
        futs = []
        for idx, it in enumerate(items):
            slot = self.slots[idx % len(self.slots)]
            futs.append(self.executor.submit(
                self._eval_on_slot,
                slot,
                it["src"],
                it.get("n_frames", 60),
                it.get("idle_tape", DEFAULT_IDLE_TAPE),
                it.get("active_tape", DEFAULT_ACTIVE_TAPE),
                it.get("png_path"),
            ))
        return [f.result() for f in futs]

    def close(self):
        self.executor.shutdown(wait=True)
        for s in self.slots:
            s.cleanup()


if __name__ == "__main__":
    import argparse
    from tokenizers import Tokenizer

    ap = argparse.ArgumentParser()
    ap.add_argument("--kernel", default="build/zero-app-os.elf")
    ap.add_argument("--tokenizer", default="/mnt/ssd/models/minicpm5-2b/bf16/tokenizer.json")
    ap.add_argument("--run-dir", required=True)
    args = ap.parse_args()
    os.makedirs(args.run_dir, exist_ok=True)

    tok = Tokenizer.from_file(args.tokenizer)
    apps = ["mandelbrot", "falling_sand", "snake", "arkanoid"]
    pool = QemuValidatorPool(args.kernel, n_workers=4, enable_qmp=True)
    try:
        items = []
        tapes = {
            "mandelbrot": "02" * 10 + "00" * 50,
            "falling_sand": "10" * 20 + "02" * 10 + "10" * 15 + "00" * 15,
            "snake": "00" * 20 + "04" * 20 + "00" * 20,
            "arkanoid": "02" * 20 + "01" * 20 + "02" * 20,
        }
        for name in apps:
            src = open(f"apps160/{name}.uasm").read()
            items.append({
                "src": src,
                "n_frames": 60,
                "idle_tape": DEFAULT_IDLE_TAPE,
                "active_tape": tapes[name],
                "png_path": os.path.join(args.run_dir, f"{name}_160x120_6x.png"),
            })
        t0 = time.time()
        results = pool.evaluate_batch(items)
        wall = time.time() - t0

        summary = {}
        print(f"\n=== STAGE 2.2 COMPACT 160x120 GOLDEN APPS (4 parallel KVM VMs in {wall:.2f}s) ===")
        print(f"{'App':<14} {'Lines':>5} {'Insns':>5} {'Bytes':>5} {'Tok(CPM5)':>9} {'Q4_K_M s':>8} {'Status':>7} {'Rew':>5} {'React':>5} {'Anim':>5} {'Cols':>4}")
        for name, it, res in zip(apps, items, results):
            n_lines = len([l for l in it["src"].splitlines() if l.strip()])
            n_tok = len(tok.encode(it["src"], add_special_tokens=False).ids)
            est_q4 = n_tok / 48.0  # ~47.6-50.0 tok/s on EPYC 32T Q4_K_M
            print(f"{name:<14} {n_lines:>5} {res.insns:>5} {res.code_bytes:>5} {n_tok:>9} {est_q4:>7.1f}s {res.status:>7} {res.reward:>5.2f} {str(res.input_reactive):>5} {str(res.animated):>5} {res.colors:>4}")
            summary[name] = {"lines": n_lines, "tokens_minicpm5": n_tok, "est_epyc_q4km_s": round(est_q4, 1), **asdict(res)}
            assert res.passed, f"Golden app {name} did not pass: {res}"

        with open(os.path.join(args.run_dir, "golden160_summary.json"), "w") as f:
            json.dump(summary, f, indent=2)
        print(f"\nALL 4 COMPACT 160x120 GOLDEN APPS PASSED! Summary: {args.run_dir}/golden160_summary.json")
    finally:
        pool.close()