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.

11.2 KB
Raw Blame
#!/usr/bin/env python3
"""
test_export.py -- scripts/export_weights.py on fabricated checkpoints
(scripts/make_synth_hf.py), no real weights needed:

  1. single model.safetensors, v2 and v1; with --old (a copy of the exporter
     before sharded-checkpoint support) the output must be byte-identical to
     that version's
  2. the same tensors in 3 shards with model.safetensors.index.json, in 2
     shards without the index, with a tied lm_head.weight in the last shard,
     and with list-style tokenizer merges: identical to (1)
  3. untied lm_head (tie_word_embeddings false, as in Qwen3-8B+): refused, exit 2
  4. a second shape (dim 160, hidden 608: K not a multiple of 128) single vs
     sharded
  5. a failed export (checkpoint without model.norm.weight, found only after
     every layer is written) leaves an existing output file's bytes as they
     were and no temporary file; a successful one replaces it
  6. refused with exit 2: num_attention_heads 0; an index that names a shard
     outside the checkpoint directory (../, a subdirectory, an absolute
     path); a tensor whose data offsets are reversed, negative or past the
     end of its shard; a shard cut short
  7. optionally (--engine build/asm-llm): the engine loads the exported files
     and prints the same bytes at 1 and 3 threads

Usage: test_export.py --work DIR [--old OLD_EXPORTER.py] [--engine build/asm-llm]
"""

import argparse
import filecmp
import json
import os
import shutil
import struct
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
EXPORT = os.path.join(HERE, "export_weights.py")
MAKE = os.path.join(HERE, "make_synth_hf.py")

fails = []


def run(cmd, **kw):
    return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kw)


def make(d, *args):
    if os.path.exists(d):
        shutil.rmtree(d)
    r = run([sys.executable, MAKE, "--out", d, *args])
    if r.returncode:
        sys.exit(f"make_synth_hf failed: {r.stderr.decode()}")


def export(exporter, d, out, scale="fp16"):
    r = run([sys.executable, exporter, "--model-dir", d, "--out", out, "--scale-dtype", scale])
    return r


def check(name, ok, detail=""):
    print(f"{'PASS' if ok else 'FAIL'} {name}{(': ' + detail) if detail and not ok else ''}")
    if not ok:
        fails.append(name)


def same(a, b):
    return os.path.exists(a) and os.path.exists(b) and filecmp.cmp(a, b, shallow=False)


def edit_json(path, fn):
    with open(path) as f:
        j = json.load(f)
    fn(j)
    with open(path, "w") as f:
        json.dump(j, f)


def edit_st_header(path, fn):
    """Rewrite a safetensors header (data offsets are relative to its end)."""
    with open(path, "rb") as f:
        n = struct.unpack("<Q", f.read(8))[0]
        hdr, data = json.loads(f.read(n)), f.read()
    fn(hdr)
    hb = json.dumps(hdr, separators=(",", ":")).encode()
    with open(path, "wb") as f:
        f.write(struct.pack("<Q", len(hb)) + hb + data)


def refused(name, d, out, expect):
    """Export of d must fail with exit 2 and `expect` in the message, and
    leave neither an output file nor a temporary file."""
    out_dir = os.path.dirname(out)
    before = sorted(os.listdir(out_dir))
    r = export(EXPORT, d, out)
    msg = r.stderr.decode()
    check(f"{name}: refused (exit 2, message, no output)",
          r.returncode == 2 and expect in msg and "Traceback" not in msg
          and sorted(os.listdir(out_dir)) == before, f"rc={r.returncode} {msg[-300:]}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--work", required=True)
    ap.add_argument("--old", help="exporter before sharded support (git show <rev>:scripts/export_weights.py)")
    ap.add_argument("--engine", help="asm-llm binary to load the exported files with")
    a = ap.parse_args()
    w = a.work
    os.makedirs(w, exist_ok=True)

    single = os.path.join(w, "tiny-single")
    make(single, "--shape", "tiny")
    outs = {}
    for scale in ("fp16", "fp32"):
        old = os.path.join(w, f"old-{scale}.asmbin")
        new = os.path.join(w, f"new-{scale}.asmbin")
        r2 = export(EXPORT, single, new, scale)
        check(f"single-file {scale}: export succeeds", r2.returncode == 0, r2.stderr.decode()[-400:])
        if a.old:
            r1 = export(a.old, single, old, scale)
            check(f"single-file {scale}: byte-identical to the previous exporter", r1.returncode == 0 and same(old, new),
                  r1.stderr.decode()[-400:])
        outs[scale] = new

    variants = [
        ("3 shards + index", ["--shards", "3"]),
        ("2 shards, no index", ["--shards", "2", "--no-index"]),
        ("4 shards + tied lm_head.weight", ["--shards", "4", "--lm-head"]),
        ("1 file + tied lm_head.weight", ["--lm-head"]),
        ("list-style merges, 3 shards", ["--shards", "3", "--merges", "list"]),
    ]
    for label, args in variants:
        d = os.path.join(w, "tiny-v")
        make(d, "--shape", "tiny", *args)
        for scale in ("fp16", "fp32"):
            o = os.path.join(w, f"v-{scale}.asmbin")
            r = export(EXPORT, d, o, scale)
            check(f"{label} {scale}: identical to single-file", r.returncode == 0 and same(o, outs[scale]),
                  r.stderr.decode()[-400:])
            if a.old and "lm_head" in label and scale == "fp16" and "1 file" in label:
                o2 = os.path.join(w, "v-old.asmbin")
                r = export(a.old, d, o2, scale)
                check(f"{label}: previous exporter gives the same bytes", r.returncode == 0 and same(o2, o))

    d = os.path.join(w, "tiny-untied")
    make(d, "--shape", "tiny", "--untied", "--shards", "2")
    o = os.path.join(w, "untied.asmbin")
    if os.path.exists(o):
        os.remove(o)
    r = export(EXPORT, d, o)
    msg = r.stderr.decode()
    check("untied lm_head refused (exit 2, message, no output)",
          r.returncode == 2 and "tie_word_embeddings is false" in msg and not os.path.exists(o), msg[-300:])

    # A late failure must not touch an existing output file.
    d = os.path.join(w, "tiny-bad")
    out_dir = os.path.join(w, "atomic")
    if os.path.exists(out_dir):
        shutil.rmtree(out_dir)
    os.makedirs(out_dir)
    o = os.path.join(out_dir, "model.asmbin")
    kept = b"existing output file\n" * 1000
    with open(o, "wb") as f:
        f.write(kept)
    make(d, "--shape", "tiny")
    edit_st_header(os.path.join(d, "model.safetensors"), lambda h: h.pop("model.norm.weight"))
    r = export(EXPORT, d, o)
    msg = r.stderr.decode()
    with open(o, "rb") as f:
        untouched = f.read() == kept
    check("missing model.norm.weight: exit 2, existing output untouched, no temporary file",
          r.returncode == 2 and "model.norm.weight not found" in msg and untouched
          and os.listdir(out_dir) == ["model.asmbin"], f"rc={r.returncode} {msg[-300:]} {os.listdir(out_dir)}")
    r = export(EXPORT, single, o)
    check("successful export replaces an existing output, no temporary file",
          r.returncode == 0 and same(o, outs["fp16"]) and os.listdir(out_dir) == ["model.asmbin"]
          and os.stat(o).st_mode == os.stat(outs["fp16"]).st_mode, r.stderr.decode()[-300:])
    o = os.path.join(out_dir, "refused.asmbin")

    for label, head_dim in (("num_attention_heads 0", 32), ("num_attention_heads 0, no head_dim", None)):
        make(d, "--shape", "tiny")

        def no_heads(c):
            c["num_attention_heads"] = 0
            c["head_dim"] = head_dim
            if head_dim is None:
                del c["head_dim"]
        edit_json(os.path.join(d, "config.json"), no_heads)
        refused(label, d, o, "num_attention_heads is 0")

    # Index entries must be file names inside the checkpoint directory. Every
    # path below exists, so only the name check can refuse it.
    outside = os.path.join(w, "tiny-outside")
    for label, where in (("../", lambda n: os.path.join("..", "tiny-outside", n)),
                         ("subdirectory", lambda n: os.path.join("sub", n)),
                         ("absolute path", lambda n: os.path.join(os.path.abspath(outside), n))):
        make(d, "--shape", "tiny", "--shards", "2")
        if os.path.exists(outside):
            shutil.rmtree(outside)
        os.makedirs(outside)
        os.makedirs(os.path.join(d, "sub"))
        shard = "model-00002-of-00002.safetensors"
        shutil.copy(os.path.join(d, shard), outside)
        shutil.copy(os.path.join(d, shard), os.path.join(d, "sub"))

        def move(j):
            for k, v in j["weight_map"].items():
                if v == shard:
                    j["weight_map"][k] = where(shard)
        edit_json(os.path.join(d, "model.safetensors.index.json"), move)
        refused(f"index names a shard by {label}", d, o, "not a plain file name")
    shutil.rmtree(outside)

    # Tensor extents: both ends must lie inside the shard's data section.
    norm = "model.norm.weight"
    for label, fn, expect in (
            ("tensor start after its end", lambda h: h[norm].update(data_offsets=h[norm]["data_offsets"][::-1]),
             "after its end"),
            ("tensor start negative", lambda h: h[norm].update(data_offsets=[-2 * 96, 0]), "non-negative"),
            ("tensor end past the shard", lambda h: h[norm].update(
                data_offsets=[h[norm]["data_offsets"][0] + 2, h[norm]["data_offsets"][1] + 2]), "past the end"),
            ("tensor start and end past the shard", lambda h: h[norm].update(
                data_offsets=[1 << 62, (1 << 62) + 2 * 96]), "past the end"),
            ("tensor offsets not integers", lambda h: h[norm].update(data_offsets=[0.0, "192"]), "non-negative")):
        make(d, "--shape", "tiny")
        edit_st_header(os.path.join(d, "model.safetensors"), fn)
        refused(label, d, o, expect)
    make(d, "--shape", "tiny", "--shards", "2")
    shard = os.path.join(d, "model-00002-of-00002.safetensors")
    os.truncate(shard, os.path.getsize(shard) - 1)
    refused("shard cut short by one byte", d, o, "past the end")
    os.truncate(shard, 4)
    refused("shard cut inside its header", d, o, "header runs past the end")

    s4a, s4b = os.path.join(w, "s4-single"), os.path.join(w, "s4-sharded")
    make(s4a, "--shape", "s4")
    make(s4b, "--shape", "s4", "--shards", "3")
    oa, ob = os.path.join(w, "s4a.asmbin"), os.path.join(w, "s4b.asmbin")
    ra, rb = export(EXPORT, s4a, oa), export(EXPORT, s4b, ob)
    check("shape s4 (K = 160, 608): single == sharded", ra.returncode == 0 and rb.returncode == 0 and same(oa, ob),
          (ra.stderr + rb.stderr).decode()[-400:])
    if a.old:
        ro = export(a.old, s4a, os.path.join(w, "s4-old.asmbin"))
        check("shape s4: single == previous exporter", ro.returncode == 0 and same(oa, os.path.join(w, "s4-old.asmbin")))

    if a.engine:
        for model in (outs["fp16"], outs["fp32"], oa):
            args = ["-m", model, "-p", "Hello there", "-n", "12", "--print-tokens"]
            r1, r3 = run([a.engine] + args + ["-t", "1"]), run([a.engine] + args + ["-t", "3"])
            ok = r1.returncode == 0 and r3.returncode == 0 and r1.stdout and r1.stdout == r3.stdout
            check(f"engine on {os.path.basename(model)}: loads, same stdout at 1 and 3 threads", ok,
                  f"rc={r1.returncode}/{r3.returncode} {r1.stderr.decode()[-200:]}")

    print(f"\n{'ALL PASS' if not fails else str(len(fails)) + ' FAILED'}")
    return 1 if fails else 0


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