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.

33.0 KB
Raw Blame
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""verify_train_np.py -- numpy-only (no PyTorch) verification of asm-gpt-train.

WHY THIS EXISTS / HOW IT DIFFERS FROM scripts/verify_train_ref.py
    scripts/verify_train_ref.py is the authoritative harness and uses a
    PyTorch FP32 CPU reference. Its own README notes it is "Optional, only
    if you want to run the PyTorch CPU gradient verification harness" and
    requires `pip install numpy torch`.

    This file is an independent, dependency-light companion:
      * requires numpy ONLY -- no torch, no autograd, no C++ extension.
        Runs on offline / air-gapped / CI boxes where a ~2 GB torch wheel
        is unavailable. numpy is already a dependency of the repo
        (scripts/export_weights.py imports it).
      * re-implements forward, analytic backward, grad-clip, AdamW and the
        LR schedule by hand in float64. It shares NO code path with
        PyTorch autograd, so agreement is evidence from a *different*
        kind of reference (hand-derived chain rule vs. autodiff).
      * adds RELATIVE error metrics (rel_rms / rel_l2) alongside the
        absolute max_abs used upstream. A pure max_abs gate on a flat
        90,560-element gradient vector is dominated by the largest
        entries; rel_rms is scale-free per tensor and catches a tensor
        that is wrong while small in absolute terms.

    It is NOT a replacement: it is a cross-check with an independent,
    much lighter trust root.

PURPOSE
    Layered numerical verification of a --dump-debug run:
      L1  step0 raw gradients      vs dump/step0_grads.bin
      L2  per-step loss and lr     vs dump/losses.bin, dump/lrs.bin
      L3  full k-step AdamW replay vs dump/final_weights.bin

METHOD (binding limitation -- read before quoting any number)
    --dump-debug exports ONLY init_weights, final_weights and step0 grads.
    Optimizer internal state (opt_m / opt_v) and the RNG stream are NOT
    exported. We therefore re-implement forward / analytic backward / grad
    clipping / AdamW / LR schedule from the assembly source (single source
    of truth) and replay all k steps starting from W0.

    This is an INDIRECT comparison. The numpy replica can itself introduce
    divergence, so results bound "the asm numerics are consistent with a
    faithful re-implementation of its own documented algorithm", NOT "the
    asm matches some external ground truth".

    Expected divergence sources, by design:
      - asm keeps activations/weights in f32 and accumulates matrix products
        in f32 AVX2 lanes; this replica uses f64 throughout.
      - asm uses fast_expf_avx2 (~2e-7 rel) and fast_sincos_f64 (<1e-13)
        approximations; this replica uses exact np.exp / np.cos.
    A healthy result is "small but nonzero divergence", not "zero".

PATHS
    Self-contained: no external path module. Nothing is hardcoded; every
    input path comes from the command line or is derived from this file.

USAGE
    # 1. point at the freshly built binary; this script runs it for you
    python3 scripts/verify-train-np/verify_train_np.py --bin build/asm-gpt-train \
            --data data/tinyshakespeare.txt

    # 2. or verify an already-produced dump directory (offline)
    python3 scripts/verify-train-np/verify_train_np.py --dump-dir /tmp/np_verify/run1

    # 3. quick pass with a shorter run
    python3 scripts/verify-train-np/verify_train_np.py --bin build/asm-gpt-train \
            --data data/tinyshakespeare.txt --steps 10 --keep-dump

    Exit code: 0 = all gates PASS, 1 = a gate FAILED, 2 = usage/IO error.
"""
import argparse
import json
import math
import subprocess
import sys
import tempfile
from pathlib import Path

import numpy as np

# --------------------------------------------------------------------------
# Path base (inlined; pathlib only; no third-party and no local helper module)
# --------------------------------------------------------------------------
_HERE = Path(__file__).resolve()

# Locate repository root (works from scripts/verify-train-np/ or scripts/).
REPO_ROOT = next(
    (p for p in _HERE.parents if (p / "Makefile").is_file()),
    _HERE.parents[2] if len(_HERE.parents) > 2 else _HERE.parent,
)

F32 = np.float32
F64 = np.float64


# --------------------------------------------------------------------------
# dump / meta readers  (layout taken from main.asm dump_* writers)
# --------------------------------------------------------------------------
def read_meta(path: Path) -> dict:
    """meta.bin: 8x u32 | u64 n_params | 5x f32 | u32 warmup   (64 bytes)."""
    raw = path.read_bytes()
    if len(raw) < 64:
        raise ValueError(f"meta.bin too short: {len(raw)}")
    u32 = np.frombuffer(raw, dtype="<u4", count=8, offset=0)
    n_params = int(np.frombuffer(raw, dtype="<u8", count=1, offset=32)[0])
    f32 = np.frombuffer(raw, dtype="<f4", count=5, offset=40)
    warmup = int(np.frombuffer(raw, dtype="<u4", count=1, offset=60)[0])
    return {
        "vocab": int(u32[0]),
        "dim": int(u32[1]),
        "layers": int(u32[2]),
        "heads": int(u32[3]),
        "hidden": int(u32[4]),
        "seq": int(u32[5]),
        "batch": int(u32[6]),
        "steps": int(u32[7]),
        "n_params": n_params,
        "lr_max": float(f32[0]),
        "wd": float(f32[1]),
        "clip": float(f32[2]),
        "rms_eps": float(f32[3]),
        "rope_theta": float(f32[4]),
        "warmup": warmup,
    }


def read_f32(path: Path, count: int) -> np.ndarray:
    raw = path.read_bytes()
    if len(raw) < count * 4:
        raise ValueError(f"{path.name}: expected >={count*4} bytes, got {len(raw)}")
    return np.frombuffer(raw, dtype="<f4", count=count).astype(F64)


def read_u32(path: Path, count: int) -> np.ndarray:
    raw = path.read_bytes()
    return np.frombuffer(raw, dtype="<u4", count=count).astype(np.int64)


# --------------------------------------------------------------------------
# Tensor slicing out of the flat parameter vector
#   global: tok_emb(V,D) | L x layer | final_ln(D) | lm_head(V,D)
#   layer : ln1(D) wq wk wv wo (D,D) ln2(D) wgate wup wdown (FF,D)
#   linear weights are stored [out][in]  =>  y = x @ W.T
# --------------------------------------------------------------------------
def slice_params(flat: np.ndarray, cfg: dict, *, dtype=F64) -> dict:
    V, D, L, FF = cfg["vocab"], cfg["dim"], cfg["layers"], cfg["hidden"]
    out = {}
    off = 0

    def take(n):
        nonlocal off
        seg = flat[off:off + n].astype(dtype)
        off += n
        return seg

    out["tok_emb"] = take(V * D).reshape(V, D)
    layers = []
    for _ in range(L):
        d = {}
        d["ln1"] = take(D)
        d["wq"] = take(D * D).reshape(D, D)
        d["wk"] = take(D * D).reshape(D, D)
        d["wv"] = take(D * D).reshape(D, D)
        d["wo"] = take(D * D).reshape(D, D)
        d["ln2"] = take(D)
        d["wgate"] = take(FF * D).reshape(FF, D)
        d["wup"] = take(FF * D).reshape(FF, D)
        d["wdown"] = take(D * FF).reshape(D, FF)
        layers.append(d)
    out["layers"] = layers
    out["final_ln"] = take(D)
    out["lm_head"] = take(V * D).reshape(V, D)

    if off != cfg["n_params"]:
        raise AssertionError(f"slice consumed {off} != n_params {cfg['n_params']}")
    return out


def flatten_params(params: dict, cfg: dict) -> np.ndarray:
    """Inverse of slice_params; ordering must match slice_params exactly."""
    parts = [params["tok_emb"].ravel()]
    for d in params["layers"]:
        for k in ("ln1", "wq", "wk", "wv", "wo", "ln2", "wgate", "wup", "wdown"):
            parts.append(d[k].ravel())
    parts.append(params["final_ln"].ravel())
    parts.append(params["lm_head"].ravel())
    flat = np.concatenate(parts)
    if flat.size != cfg["n_params"]:
        raise AssertionError(f"flatten size {flat.size} != {cfg['n_params']}")
    return flat


# Which flat spans get weight decay (model.asm:1471-1499).
# 2D weights: tok_emb, 4*D*D, 3*D*FF, lm_head.  1D RMSNorm gains: wd = 0.
def decay_mask(cfg: dict) -> np.ndarray:
    V, D, L, FF = cfg["vocab"], cfg["dim"], cfg["layers"], cfg["hidden"]
    n = cfg["n_params"]
    mask = np.zeros(n, dtype=bool)
    off = 0
    mask[off:off + V * D] = True
    off += V * D
    for _ in range(L):
        off += D                      # ln1  -> no decay
        mask[off:off + 4 * D * D] = True
        off += 4 * D * D
        off += D                      # ln2  -> no decay
        mask[off:off + 3 * D * FF] = True
        off += 3 * D * FF
    off += D                          # final_ln -> no decay
    mask[off:off + V * D] = True
    off += V * D
    assert off == n, (off, n)
    return mask


# --------------------------------------------------------------------------
# LR schedule (kernels.asm compute_lr, verified bit-exact vs dump/lrs.bin)
# --------------------------------------------------------------------------
def compute_lr(step: int, total: int, warmup: int, lr_max: float) -> float:
    if warmup > 0 and step < warmup:
        return lr_max * float(step + 1) / float(warmup)
    if total <= warmup or total <= 1:
        return lr_max
    prog = (step - warmup) / float(total - warmup)
    prog = min(1.0, max(0.0, prog))
    coeff = 0.5 * (1.0 + math.cos(math.pi * prog))
    return lr_max * (0.1 + 0.9 * coeff)


# --------------------------------------------------------------------------
# Building blocks
# --------------------------------------------------------------------------
def rmsnorm_fwd(x, w, eps):
    ms = np.mean(x * x, axis=-1, keepdims=True)
    inv = 1.0 / np.sqrt(ms + eps)
    y = x * inv * w
    return y, (x, inv, w, eps)


def rmsnorm_bwd(dy, cache):
    x, inv, w, eps = cache
    D = x.shape[-1]
    d_hat = dy * w
    # y_i = x_i * inv * w_i ;  inv = (mean(x^2)+eps)^-0.5
    d_inv = np.sum(d_hat * x, axis=-1, keepdims=True)
    dn = -0.5 * (inv ** 3) * d_inv          # d/dn of n^-0.5
    dx = d_hat * inv + 2.0 * x * dn / D
    dw = np.sum(dy * x * inv, axis=tuple(range(dy.ndim - 1)))
    return dx, dw


def silu(g):
    return g / (1.0 + np.exp(-g))


def dsilu(g):
    s = 1.0 / (1.0 + np.exp(-g))
    return s * (1.0 + g * (1.0 - s))


def rope_tables(seq, hd, theta):
    half = hd // 2
    i = np.arange(half, dtype=F64)
    inv_freq = theta ** (-2.0 * i / hd)
    pos = np.arange(seq, dtype=F64)[:, None]
    ang = pos * inv_freq[None, :]
    # (T, 1, half): right-aligns against (B,T,H,half) as
    # (1, T, 1, half) so the token axis lands on T, not on H.
    return np.cos(ang)[:, None, :], np.sin(ang)[:, None, :]


def rope_fwd(x, cos, sin):
    half = x.shape[-1] // 2
    x1, x2 = x[..., :half], x[..., half:]
    return np.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1)


def rope_bwd(dy, cos, sin):
    half = dy.shape[-1] // 2
    d1, d2 = dy[..., :half], dy[..., half:]
    return np.concatenate([d1 * cos + d2 * sin, -d1 * sin + d2 * cos], axis=-1)


# --------------------------------------------------------------------------
# Forward
# --------------------------------------------------------------------------
def forward(params, ids, cfg, cos_t, sin_t):
    V, D, H = cfg["vocab"], cfg["dim"], cfg["heads"]
    B, T = ids.shape
    FF = cfg["hidden"]
    hd = D // H
    scale = 1.0 / math.sqrt(hd)
    eps = cfg["rms_eps"]

    cache = {"ids": ids, "layers": []}
    x = params["tok_emb"][ids]                       # (B,T,D)
    cache["emb_out"] = x

    for d in params["layers"]:
        lc = {}
        ln1, c_ln1 = rmsnorm_fwd(x, d["ln1"], eps)
        lc["ln1"], lc["c_ln1"] = ln1, c_ln1
        lc["x_in"] = x

        q = ln1 @ d["wq"].T
        k = ln1 @ d["wk"].T
        v = ln1 @ d["wv"].T

        q = rope_fwd(q.reshape(B, T, H, hd), cos_t, sin_t)
        k = rope_fwd(k.reshape(B, T, H, hd), cos_t, sin_t)
        v4 = v.reshape(B, T, H, hd)

        q = q.transpose(0, 2, 1, 3)                  # (B,H,T,hd)
        k = k.transpose(0, 2, 1, 3)
        v4 = v4.transpose(0, 2, 1, 3)
        lc["q"], lc["k"], lc["v4"] = q, k, v4

        scores = (q @ k.transpose(0, 1, 3, 2)) * scale
        mask = np.triu(np.ones((T, T), dtype=bool), 1)
        scores = np.where(mask, -1e30, scores)
        m = scores.max(axis=-1, keepdims=True)
        e = np.exp(scores - m)
        p = e / e.sum(axis=-1, keepdims=True)
        lc["p"] = p

        att = p @ v4                                  # (B,H,T,hd)
        att = att.transpose(0, 2, 1, 3).reshape(B, T, D)
        lc["att"] = att

        att_out = att @ d["wo"].T
        x_mid = x + att_out
        lc["x_mid"], lc["att_out"] = x_mid, att_out

        ln2, c_ln2 = rmsnorm_fwd(x_mid, d["ln2"], eps)
        lc["ln2"], lc["c_ln2"] = ln2, c_ln2
        gate = ln2 @ d["wgate"].T
        up = ln2 @ d["wup"].T
        lc["gate"], lc["up"] = gate, up
        act = silu(gate) * up
        lc["act"] = act

        down = act @ d["wdown"].T
        x = x_mid + down
        lc["down"] = down
        cache["layers"].append(lc)

    lnf, c_lnf = rmsnorm_fwd(x, params["final_ln"], eps)
    cache["lnf"], cache["c_lnf"] = lnf, c_lnf
    logits = lnf @ params["lm_head"].T                # (B,T,V)
    cache["logits"] = logits
    cache["cos"], cache["sin"] = cos_t, sin_t
    return logits, cache


def ce_loss(logits, targets):
    B, T, V = logits.shape
    lt = logits.reshape(-1, V)
    y = targets.reshape(-1)
    mx = lt.max(axis=-1, keepdims=True)
    lp = lt - mx
    lse = np.log(np.exp(lp).sum(axis=-1, keepdims=True))
    logp = lp - lse
    n = B * T
    loss = -logp[np.arange(n), y].sum() / n
    d = np.exp(logp)
    d[np.arange(n), y] -= 1.0
    d /= n
    return loss, d.reshape(B, T, V)


# --------------------------------------------------------------------------
# Backward (analytic, mirroring the asm graph)
# --------------------------------------------------------------------------
def backward(params, cache, dlogits, cfg):
    D, H = cfg["dim"], cfg["heads"]
    B, T = cache["ids"].shape
    hd = D // H
    scale = 1.0 / math.sqrt(hd)
    grads = {"layers": []}
    dl = dlogits

    lnf = cache["lnf"]
    grads["lm_head"] = np.einsum("btv,btd->vd", dl, lnf)
    d_lnf = dl @ params["lm_head"]
    dx, grads["final_ln"] = rmsnorm_bwd(d_lnf, cache["c_lnf"])

    for li in range(len(params["layers"]) - 1, -1, -1):
        d = params["layers"][li]
        lc = cache["layers"][li]
        g = {}

        # x_out = x_mid + act @ wdown.T   ->   dx is d(x_out)
        g["wdown"] = np.einsum("btd,btf->df", dx, lc["act"])
        d_act = dx @ d["wdown"]

        gate, up = lc["gate"], lc["up"]
        d_gate = d_act * up * dsilu(gate)
        d_up = d_act * silu(gate)
        g["wgate"] = np.einsum("btf,btd->fd", d_gate, lc["ln2"])
        g["wup"] = np.einsum("btf,btd->fd", d_up, lc["ln2"])
        d_ln2 = d_gate @ d["wgate"] + d_up @ d["wup"]

        d_ln2_in, g["ln2"] = rmsnorm_bwd(d_ln2, lc["c_ln2"])
        d_xmid = dx + d_ln2_in

        g["wo"] = np.einsum("btd,bte->de", d_xmid, lc["att"])
        d_att = d_xmid @ d["wo"]

        d_att4 = d_att.reshape(B, T, H, hd).transpose(0, 2, 1, 3)   # (B,H,T,hd)
        p, v4, q, k = lc["p"], lc["v4"], lc["q"], lc["k"]

        dP = d_att4 @ v4.transpose(0, 1, 3, 2)
        dV = p.transpose(0, 1, 3, 2) @ d_att4
        d_scores = p * (dP - np.sum(dP * p, axis=-1, keepdims=True))
        dQ = (d_scores @ k) * scale
        dK = (d_scores.transpose(0, 1, 3, 2) @ q) * scale

        dQ = rope_bwd(dQ.transpose(0, 2, 1, 3), cache["cos"], cache["sin"])
        dK = rope_bwd(dK.transpose(0, 2, 1, 3), cache["cos"], cache["sin"])
        dV = dV.transpose(0, 2, 1, 3)

        dQ = dQ.reshape(B, T, D)
        dK = dK.reshape(B, T, D)
        dV = dV.reshape(B, T, D)

        g["wq"] = np.einsum("btd,bte->de", dQ, lc["ln1"])
        g["wk"] = np.einsum("btd,bte->de", dK, lc["ln1"])
        g["wv"] = np.einsum("btd,bte->de", dV, lc["ln1"])
        d_ln1 = dQ @ d["wq"] + dK @ d["wk"] + dV @ d["wv"]

        d_ln1_in, g["ln1"] = rmsnorm_bwd(d_ln1, lc["c_ln1"])
        dx = d_xmid + d_ln1_in

        grads["layers"].insert(0, g)

    g_emb = np.zeros_like(params["tok_emb"])
    np.add.at(g_emb, cache["ids"].reshape(-1), dx.reshape(-1, D))
    grads["tok_emb"] = g_emb
    return grads


def flatten_grads(grads, cfg):
    return flatten_params(grads, cfg)


# --------------------------------------------------------------------------
# Optimizer (kernels.asm tp_adamw_range / tp_grad_norm + model.asm spans)
# --------------------------------------------------------------------------
def grad_norm(flat_g):
    return float(np.sqrt(np.sum(flat_g.astype(F64) ** 2)))


def adamw_step(flat_p, flat_g, m, v, lr, wd, inv_bc1, inv_bc2, mask):
    decay = 1.0 - lr * wd
    flat_p = flat_p.copy()
    flat_p[mask] *= decay            # p *= (1 - lr*wd) on decayed spans
    m = 0.9 * m + 0.1 * flat_g
    v = 0.999 * v + 0.001 * (flat_g * flat_g)
    denom = np.sqrt(v * inv_bc2) + 1e-8
    flat_p -= (lr * inv_bc1) * (m / denom)
    return flat_p, m, v


# --------------------------------------------------------------------------
# Comparison helpers
# --------------------------------------------------------------------------
def cmp_stats(a, b):
    a = np.asarray(a, dtype=F64).ravel()
    b = np.asarray(b, dtype=F64).ravel()
    diff = a - b
    ad = np.abs(diff)
    nb = np.abs(b)
    denom = np.where(nb > 0, nb, 1.0)
    rel = ad / denom
    cos = float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-300))
    nrm_diff = float(np.linalg.norm(diff))
    nrm_ref = float(np.linalg.norm(b))
    rms_abs = float(np.sqrt(np.mean(diff ** 2)))

    # Per-element relative error is meaningless where the reference value is
    # ~0: a 1e-9 absolute error on a 2e-8 element reads as 5% "error" while
    # being pure float32 rounding.  Report scale-free measures, and a
    # per-element max restricted to elements whose magnitude is above the
    # float32 noise floor of this problem (|ref| > 1e-6).
    big = nb > 1e-6
    max_rel_big = float(rel[big].max()) if bool(big.any()) else 0.0

    return {
        "n": int(a.size),
        "max_abs": float(ad.max()),
        "max_rel": float(rel.max()),
        "max_rel_big": max_rel_big,
        "n_big": int(big.sum()),
        "mean_abs": float(ad.mean()),
        "rms_abs": rms_abs,
        # scale-free: the primary criterion
        "rel_rms": rms_abs / (float(nb.mean()) + 1e-300),
        "rel_l2": nrm_diff / (nrm_ref + 1e-300),
        "cosine": cos,
        "ref_abs_max": float(nb.max()),
        "ref_abs_mean": float(nb.mean()),
    }


LAYER_KEYS = ("ln1", "wq", "wk", "wv", "wo", "ln2", "wgate", "wup", "wdown")


def iter_named(params, cfg):
    yield "tok_emb", params["tok_emb"]
    for i, d in enumerate(params["layers"]):
        for k in LAYER_KEYS:
            yield f"L{i}.{k}", d[k]
    yield "final_ln", params["final_ln"]
    yield "lm_head", params["lm_head"]


def per_tensor_stats(got, ref, cfg):
    out = []
    got_map = dict(iter_named(got, cfg))
    ref_map = dict(iter_named(ref, cfg))
    for name, gv in got_map.items():
        out.append({"tensor": name, **cmp_stats(gv, ref_map[name])})
    return out


# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def run_asm_debug(binary: str, data: str, out_dir: Path, cfg: dict, threads: int):
    """Invoke the trainer to emit a --dump-debug directory. Mirrors upstream."""
    cmd = [
        binary,
        "--data", data,
        "--layers", str(cfg["layers"]),
        "--dim", str(cfg["dim"]),
        "--heads", str(cfg["heads"]),
        "--hidden", str(cfg["hidden"]),
        "--batch", str(cfg["batch"]),
        "--seq", str(cfg["seq"]),
        "--steps", str(cfg["steps"]),
        "--lr", str(cfg["lr"]),
        "--wd", str(cfg["wd"]),
        "--grad-clip", str(cfg["grad_clip"]),
        "--warmup", str(cfg["warmup"]),
        "--seed", str(cfg["seed"]),
        "-t", str(threads),
        "--eval-every", "0",
        "--sample-every", "0",
        "--plain",
        "--dump-debug", str(out_dir),
    ]
    out_dir.mkdir(parents=True, exist_ok=True)
    proc = subprocess.run(cmd, capture_output=True, text=True)
    (out_dir.parent / "trainer_stdout.txt").write_text(proc.stdout, encoding="utf-8")
    (out_dir.parent / "trainer_stderr.txt").write_text(proc.stderr, encoding="utf-8")
    if proc.returncode != 0:
        raise RuntimeError(
            f"trainer exited {proc.returncode}\n"
            f"--- stdout ---\n{proc.stdout[-2000:]}\n"
            f"--- stderr ---\n{proc.stderr[-2000:]}"
        )
    return proc


def main(argv=None):
    ap = argparse.ArgumentParser(
        description="numpy-only (no PyTorch) verification of asm-gpt-train")
    # --- same names/defaults as scripts/verify_train_ref.py, so the two
    # --- harnesses are interchangeable on the command line.
    ap.add_argument("--bin", default="build/asm-gpt-train",
                    help="path to asm-gpt-train (run to produce a dump)")
    ap.add_argument("--data", default="data/tinyshakespeare.txt")
    ap.add_argument("--layers", type=int, default=2)
    ap.add_argument("--dim", type=int, default=64)
    ap.add_argument("--heads", type=int, default=4)
    ap.add_argument("--hidden", type=int, default=128)
    ap.add_argument("--batch", type=int, default=2)
    ap.add_argument("--seq", type=int, default=16)
    ap.add_argument("--steps", type=int, default=10)
    ap.add_argument("--lr", type=float, default=1e-3)
    ap.add_argument("--wd", type=float, default=0.1)
    ap.add_argument("--grad-clip", type=float, default=1.0)
    ap.add_argument("--warmup", type=int, default=3)
    ap.add_argument("--seed", type=int, default=42)
    ap.add_argument("-t", "--threads", type=int, default=4)
    # --- this script's own knobs
    ap.add_argument("--dump-dir", default=None,
                    help="verify an existing dump dir instead of running --bin")
    ap.add_argument("--work-dir", default=None,
                    help="where to put the generated dump (default: temp dir)")
    ap.add_argument("--keep-dump", action="store_true",
                    help="keep the generated dump after verification")
    ap.add_argument("--json-out", default=None, help="write report json here")
    ap.add_argument("--quiet", action="store_true")
    args = ap.parse_args(argv)

    tmp_ctx = None
    if args.dump_dir:
        dump = Path(args.dump_dir)
        if not dump.is_dir():
            print(f"ERROR: dump dir not found: {dump}", file=sys.stderr)
            return 2
        work = dump.parent
    else:
        cfg_args = dict(
            layers=args.layers, dim=args.dim, heads=args.heads,
            hidden=args.hidden, batch=args.batch, seq=args.seq,
            steps=args.steps, lr=args.lr, wd=args.wd,
            grad_clip=args.grad_clip, warmup=args.warmup, seed=args.seed,
        )
        binary = Path(args.bin)
        if not binary.is_absolute():
            binary = (REPO_ROOT / binary)
        if not binary.exists():
            print(f"ERROR: binary not found: {binary}\n"
                  f"       build it first: make train", file=sys.stderr)
            return 2
        data = Path(args.data)
        if not data.is_absolute():
            data = (REPO_ROOT / data)
        if not data.exists():
            print(f"ERROR: data not found: {data}", file=sys.stderr)
            return 2

        if args.work_dir:
            work = Path(args.work_dir)
            work.mkdir(parents=True, exist_ok=True)
        else:
            tmp_ctx = tempfile.TemporaryDirectory(prefix="np_verify_")
            work = Path(tmp_ctx.name)
        dump = work / "dump"
        print(f"binary     : {binary}")
        print(f"data       : {data}")
        print(f"cfg        : " + " ".join(f"{k}={v}" for k, v in cfg_args.items())
              + f" -t {args.threads}")
        print(f"running trainer to produce dump -> {dump}")
        try:
            run_asm_debug(str(binary), str(data), dump, cfg_args, args.threads)
        except RuntimeError as e:
            print(f"ERROR: {e}", file=sys.stderr)
            return 2
        print("trainer rc : 0")

    try:
        return _verify(dump, work, args)
    finally:
        if tmp_ctx is not None:
            if args.keep_dump:
                import shutil as _sh
                dest = Path.cwd() / "np_verify_dump"
                _sh.copytree(work, dest, dirs_exist_ok=True)
                print(f"\ndump kept  : {dest}")
            tmp_ctx.cleanup()


def _verify(dump: Path, work: Path, args):
    cfg = read_meta(dump / "meta.bin")
    V, D, L, H, FF = cfg["vocab"], cfg["dim"], cfg["layers"], cfg["heads"], cfg["hidden"]
    T, B, steps = cfg["seq"], cfg["batch"], cfg["steps"]

    print(f"dump       : {dump}")
    print(f"cfg        : V={V} D={D} L={L} H={H} FF={FF} T={T} B={B} steps={steps}")
    print(f"hyper      : lr={cfg['lr_max']} wd={cfg['wd']} clip={cfg['clip']} "
          f"eps={cfg['rms_eps']:.3e} theta={cfg['rope_theta']} warmup={cfg['warmup']}")
    print(f"n_params   : {cfg['n_params']}")

    w0_flat = read_f32(dump / "init_weights.bin", cfg["n_params"])
    wf_flat = read_f32(dump / "final_weights.bin", cfg["n_params"])
    g0_flat = read_f32(dump / "step0_grads.bin", cfg["n_params"])
    ids = read_u32(dump / "batch_x.bin", B * T).reshape(B, T)
    tgt = read_u32(dump / "batch_y.bin", B * T).reshape(B, T)
    ref_losses = read_f32(dump / "losses.bin", steps)
    ref_lrs = read_f32(dump / "lrs.bin", steps)

    cos_t, sin_t = rope_tables(T, D // H, cfg["rope_theta"])
    mask = decay_mask(cfg)

    report = {
        "dump": str(dump),
        "config": {k: cfg[k] for k in (
            "vocab", "dim", "layers", "heads", "hidden", "seq", "batch",
            "steps", "lr_max", "wd", "clip", "rms_eps", "rope_theta",
            "warmup", "n_params")},
        "method": "full k-step replay",
        "comparison": "indirect",
        "caveat": ("numpy replica is float64 and uses libm exp/cos; the asm "
                   "uses fast_expf_avx2 (~2e-7) and fast_sincos_f64 (<1e-13). "
                   "Residual differences are expected and are NOT by "
                   "themselves evidence of an asm defect."),
        "dump_files": {p.name: p.stat().st_size for p in sorted(dump.glob("*.bin"))},
    }

    # ======================================================================
    # L1 -- step-0 raw gradients (exported BEFORE clip and AdamW)
    # ======================================================================
    print("\n=== L1  step-0 raw gradients (pre-clip, pre-AdamW) ===")
    params0 = slice_params(w0_flat, cfg)
    logits0, cache0 = forward(params0, ids, cfg, cos_t, sin_t)
    loss0, dlogits0 = ce_loss(logits0, tgt)
    g_np_flat = flatten_grads(backward(params0, cache0, dlogits0, cfg), cfg)

    l1_flat = cmp_stats(g_np_flat, g0_flat)
    l1_tensors = per_tensor_stats(
        slice_params(g_np_flat, cfg), slice_params(g0_flat, cfg), cfg)
    n_np = grad_norm(g_np_flat)
    n_ref = grad_norm(g0_flat.astype(F64))

    print("  loss(step0)   np=%.8f  asm=%.8f  |d|=%.3e"
          % (loss0, ref_losses[0], abs(loss0 - float(ref_losses[0]))))
    print("  grad ||.||2   np=%.8f  asm=%.8f  rel=%.3e"
          % (n_np, n_ref, abs(n_np - n_ref) / (n_ref + 1e-300)))
    print("  flat          max_abs=%.3e  rel_rms=%.3e  rel_l2=%.3e  cos=%.10f"
          % (l1_flat["max_abs"], l1_flat["rel_rms"], l1_flat["rel_l2"],
             l1_flat["cosine"]))
    print("  %-14s %11s %11s %11s %13s"
          % ("tensor", "max_abs", "rel_rms", "maxrelbig", "cosine"))
    for t in l1_tensors:
        print("  %-14s %11.3e %11.3e %11.3e %13.10f"
              % (t["tensor"], t["max_abs"], t["rel_rms"], t["max_rel_big"],
                 t["cosine"]))

    report["L1_step0_grads"] = {
        "loss_step0_np": float(loss0),
        "loss_step0_asm": float(ref_losses[0]),
        "gnorm_np": n_np,
        "gnorm_asm": n_ref,
        "flat": l1_flat,
        "per_tensor": l1_tensors,
    }

    # ======================================================================
    # L2 -- replay all steps; compare loss and lr trajectories
    # ======================================================================
    print("\n=== L2  %d-step replay: loss / lr trajectory ===" % steps)
    flat_p = w0_flat.astype(F64).copy()
    m = np.zeros_like(flat_p)
    v = np.zeros_like(flat_p)
    b1_pow, b2_pow = 1.0, 1.0
    losses_np, lrs_np, gnorms_np = [], [], []

    for step in range(steps):
        params = slice_params(flat_p, cfg)
        logits, cache = forward(params, ids, cfg, cos_t, sin_t)
        loss, dlogits = ce_loss(logits, tgt)
        losses_np.append(float(loss))

        lr = compute_lr(step, steps, cfg["warmup"], cfg["lr_max"])
        lrs_np.append(lr)

        flat_g = flatten_grads(backward(params, cache, dlogits, cfg), cfg)
        gn = grad_norm(flat_g)
        gnorms_np.append(gn)

        # asm order: norm -> clip -> bias-correction -> elementwise update
        if cfg["clip"] > 0.0:
            coef = cfg["clip"] / (gn + 1e-6)
            if coef < 1.0:
                flat_g = flat_g * coef

        b1_pow *= 0.9
        b2_pow *= 0.999
        inv_bc1 = 1.0 / (1.0 - b1_pow)
        inv_bc2 = 1.0 / (1.0 - b2_pow)

        flat_p, m, v = adamw_step(
            flat_p, flat_g, m, v, lr, cfg["wd"], inv_bc1, inv_bc2, mask)

    l2_loss = cmp_stats(losses_np, ref_losses)
    l2_lr = cmp_stats(lrs_np, ref_lrs)

    print("  %5s %14s %14s %10s" % ("step", "loss_np", "loss_asm", "|d|"))
    for i in range(steps):
        print("  %5d %14.8f %14.8f %10.2e"
              % (i, losses_np[i], float(ref_losses[i]),
                 abs(losses_np[i] - float(ref_losses[i]))))
    print("  loss: max_abs=%.3e  max_rel=%.3e  cos=%.10f"
          % (l2_loss["max_abs"], l2_loss["max_rel"], l2_loss["cosine"]))
    print("  lr  : max_abs=%.3e  max_rel=%.3e"
          % (l2_lr["max_abs"], l2_lr["max_rel"]))

    report["L2_trajectory"] = {
        "loss_np": losses_np,
        "loss_asm": [float(x) for x in ref_losses],
        "lr_np": lrs_np,
        "lr_asm": [float(x) for x in ref_lrs],
        "gnorm_np": gnorms_np,
        "loss_stats": l2_loss,
        "lr_stats": l2_lr,
    }
    # ======================================================================
    # L3 -- final weights after `steps` AdamW updates
    # ======================================================================
    print("\n=== L3  final weights after %d steps ===" % steps)
    l3_flat = cmp_stats(flat_p, wf_flat)
    l3_tensors = per_tensor_stats(
        slice_params(flat_p, cfg), slice_params(wf_flat, cfg), cfg)

    print("  flat          max_abs=%.3e  rel_rms=%.3e  rel_l2=%.3e  cos=%.10f"
          % (l3_flat["max_abs"], l3_flat["rel_rms"], l3_flat["rel_l2"],
             l3_flat["cosine"]))
    print("  %-14s %11s %11s %11s %13s"
          % ("tensor", "max_abs", "rel_rms", "maxrelbig", "cosine"))
    for t in l3_tensors:
        print("  %-14s %11.3e %11.3e %11.3e %13.10f"
              % (t["tensor"], t["max_abs"], t["rel_rms"], t["max_rel_big"],
                 t["cosine"]))

    report["L3_final_weights"] = {
        "flat": l3_flat,
        "per_tensor": l3_tensors,
    }

    # ======================================================================
    # Verdict -- layered, threshold-based, bounded wording
    # ======================================================================
    # Thresholds are loose on purpose: the replica is float64/libm while the
    # target is float32 with fast_expf/fast_sincos approximations.  These
    # gates detect *structural* divergence (wrong graph, wrong slicing,
    # wrong optimizer order), not ulp-level noise.
    gates = {
        # Threshold derivation (stated a priori, not tuned to the result):
        # float32 eps = 1.19e-7.  A 12-step chain plus fast_expf_avx2
        # (~2e-7 relative) puts the expected relative RMS error near 1e-6.
        # 1e-5 leaves ~10x headroom while still catching STRUCTURAL
        # divergence: a wrong graph, wrong param slice, or wrong optimizer
        # order moves these numbers to >= 1e-1, not to 2e-6.
        "L1_grad_rel_rms_lt_1e-5": l1_flat["rel_rms"] < 1e-5,
        "L1_grad_cosine_gt_0.9999": l1_flat["cosine"] > 0.9999,
        "L1_gnorm_rel_lt_1e-5": abs(n_np - n_ref) / (n_ref + 1e-300) < 1e-5,
        "L2_loss_max_abs_lt_1e-3": l2_loss["max_abs"] < 1e-3,
        "L2_lr_max_rel_lt_1e-6": l2_lr["max_rel"] < 1e-6,
        "L3_weight_rel_rms_lt_1e-5": l3_flat["rel_rms"] < 1e-5,
        "L3_weight_cosine_gt_0.9999": l3_flat["cosine"] > 0.9999,
    }
    ok = all(gates.values())

    print("\n=== Verdict ===")
    for k, passed in gates.items():
        print("  %-32s %s" % (k, "PASS" if passed else "FAIL"))
    print("  overall: %s" % ("PASS" if ok else "FAIL"))

    report["gates"] = gates
    report["overall"] = "PASS" if ok else "FAIL"
    report["limitation"] = (
        "Indirect comparison.  --dump-debug exports init_weights, "
        "final_weights and step0 grads only; opt_m/opt_v are never "
        "exported, so the optimizer state is inferred by replaying all "
        "steps.  The numpy replica itself can diverge; a PASS means the "
        "replica reproduces the asm numbers within the stated tolerance, "
        "NOT that the asm is proven numerically optimal."
    )

    if args.json_out:
        out = Path(args.json_out)
        if not out.is_absolute():
            out = work / out
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(report, indent=2), encoding="utf-8")
        print("\nreport json: %s (%d bytes)" % (out, out.stat().st_size))

    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())