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.

6.8 KB
Raw Blame
#!/usr/bin/env python3
"""
Pack trained MiniCPM5-2B Zero-App OS GRPO Q4_K_M GGUF + GPT-2 byte-level BPE tokenizer
into a flat bare-metal binary (.zappm) for Zero-App Ephemeral OS Stage 3.
"""
from __future__ import annotations
import argparse
import json
import os
import struct
import sys

sys.path.insert(0, "/mnt/nvme/engines/llama-cpp/llama.cpp-hy4-flash-2cbca38/gguf-py")
from gguf import GGUFReader

DTYPE_MAP = {"F32": 0, "Q4_K": 1, "Q6_K": 2, "Q8_0": 3}

def bytes_to_unicode():
    bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
    cs = bs[:]
    n = 0
    for b in range(256):
        if b not in bs:
            bs.append(b)
            cs.append(256 + n)
            n += 1
    return dict(zip(bs, [chr(c) for c in cs]))

def align64(n: int) -> int:
    return (n + 63) & ~63

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--gguf", default="/mnt/ssd/models/minicpm5-2b-zeroapp/gguf/minicpm5-2b-zeroapp-q4_k_m.gguf")
    ap.add_argument("--tok-dir", default="/mnt/ssd/models/minicpm5-2b-zeroapp/bf16")
    ap.add_argument("--out", default="/mnt/ssd/models/minicpm5-2b-zeroapp/minicpm5-2b-zeroapp.zappm")
    ap.add_argument("--pad-2g", action="store_true", help="Pad output to exact 2 GiB for NVDIMM")
    ap.add_argument("--patch-trained", action="store_true", help="Enable surgical PATCH repair by default")
    args = ap.parse_args()

    print(f"[PACK] Reading GGUF: {args.gguf}", flush=True)
    r = GGUFReader(args.gguf)
    tmap = {t.name: t for t in r.tensors}

    dim = int(r.get_field("llama.embedding_length").contents())
    n_layers = int(r.get_field("llama.block_count").contents())
    ffn_dim = int(r.get_field("llama.feed_forward_length").contents())
    n_heads = int(r.get_field("llama.attention.head_count").contents())
    n_kv_heads = int(r.get_field("llama.attention.head_count_kv").contents())
    head_dim = dim // n_heads
    rms_eps = float(r.get_field("llama.attention.layer_norm_rms_epsilon").contents())
    rope_theta = float(r.get_field("llama.rope.freq_base").contents())
    vocab_size = int(tmap["output.weight"].shape[1])

    print(f"[PACK] Model: dim={dim} layers={n_layers} ffn={ffn_dim} heads={n_heads}/{n_kv_heads} vocab={vocab_size} eps={rms_eps} theta={rope_theta}", flush=True)

    tj = json.load(open(os.path.join(args.tok_dir, "tokenizer.json"), encoding="utf-8"))
    vocab_dict = tj["model"]["vocab"]
    added_tokens = {a["id"]: a["content"] for a in tj.get("added_tokens", [])}
    b2u = bytes_to_unicode()
    u2b = {v: k for k, v in b2u.items()}

    id_to_str = [""] * vocab_size
    for tok_s, tid in vocab_dict.items():
        if 0 <= tid < vocab_size:
            id_to_str[tid] = tok_s
    for tid, tok_s in added_tokens.items():
        if 0 <= tid < vocab_size:
            id_to_str[tid] = tok_s

    vocab_pool = bytearray()
    vocab_offs = []
    vocab_lens = []
    for tid in range(vocab_size):
        s = id_to_str[tid]
        if tid in added_tokens:
            raw = s.encode("utf-8")
        else:
            raw = bytes(u2b[ch] if ch in u2b else ord("?") for ch in s)
        vocab_offs.append(len(vocab_pool))
        vocab_lens.append(len(raw))
        vocab_pool.extend(raw)

    byte_to_tok = [0] * 256
    for b in range(256):
        byte_to_tok[b] = vocab_dict[b2u[b]]

    merges = tj["model"]["merges"]
    merge_entries = []
    for rank, m in enumerate(merges):
        a, b = m.split(" ", 1) if isinstance(m, str) else (m[0], m[1])
        ab = a + b
        if a in vocab_dict and b in vocab_dict and ab in vocab_dict:
            merge_entries.append((vocab_dict[a], vocab_dict[b], vocab_dict[ab], rank))

    ht_cap = 1
    while ht_cap < len(merge_entries) * 3:
        ht_cap <<= 1
    print(f"[PACK] BPE merges: {len(merge_entries)} -> hash table cap={ht_cap} ({ht_cap*16/1048576:.1f} MiB)", flush=True)

    ht_buf = bytearray(ht_cap * 16)
    for i in range(ht_cap):
        struct.pack_into("<IIII", ht_buf, i * 16, 0, 0, 0, 0xFFFFFFFF)

    mask = ht_cap - 1
    for lid, rid, mid, rank in merge_entries:
        h = ((lid * 2654435761) ^ (rid * 2246822519)) & 0xFFFFFFFF
        idx = h & mask
        while struct.unpack_from("<I", ht_buf, idx * 16 + 12)[0] != 0xFFFFFFFF:
            idx = (idx + 1) & mask
        struct.pack_into("<IIII", ht_buf, idx * 16, lid, rid, mid, rank)

    tensor_names = ["token_embd.weight", "output_norm.weight", "output.weight"]
    for l in range(n_layers):
        for suffix in [
            "attn_norm.weight", "attn_q.weight", "attn_k.weight", "attn_v.weight", "attn_output.weight",
            "ffn_norm.weight", "ffn_gate.weight", "ffn_up.weight", "ffn_down.weight"
        ]:
            tensor_names.append(f"blk.{l}.{suffix}")
    assert len(tensor_names) == 3 + n_layers * 9

    cur = 4096
    tdesc_off = cur
    cur = align64(cur + len(tensor_names) * 16)
    b2t_off = cur
    cur = align64(cur + 256 * 4)
    voffs_off = cur
    cur = align64(cur + vocab_size * 4)
    vlens_off = cur
    cur = align64(cur + vocab_size * 2)
    vpool_off = cur
    cur = align64(cur + len(vocab_pool))
    ht_off = cur
    cur = (cur + len(ht_buf) + 4095) & ~4095

    tdescs = []
    for name in tensor_names:
        t = tmap[name]
        dt = DTYPE_MAP[t.tensor_type.name]
        nb = int(t.n_bytes)
        tdescs.append((cur, dt, nb, t))
        cur = align64(cur + nb)

    total_used = (cur + 4095) & ~4095
    print(f"[PACK] Total packed bytes: {total_used / (1024**3):.3f} GiB ({total_used} B)", flush=True)

    hdr = struct.pack(
        "<8sIIIIIIIIffIIIIIIIIQQQQQQQQI",
        b"ZAPP5M01",
        dim, n_layers, ffn_dim, n_heads, n_kv_heads, head_dim, vocab_size, len(tensor_names),
        rms_eps, rope_theta,
        0, 1, 130072, 130073, 8, 9, 130063, ht_cap,
        tdesc_off, b2t_off, voffs_off, vlens_off, vpool_off, len(vocab_pool), ht_off, total_used, int(args.patch_trained)
    )
    assert len(hdr) <= 4096

    os.makedirs(os.path.dirname(args.out), exist_ok=True)
    with open(args.out, "wb") as out:
        out.write(hdr + b"\x00" * (4096 - len(hdr)))
        out.seek(tdesc_off)
        for off, dt, nb, _ in tdescs:
            out.write(struct.pack("<QII", off, dt, nb))
        out.seek(b2t_off)
        out.write(struct.pack("<256I", *byte_to_tok))
        out.seek(voffs_off)
        out.write(struct.pack(f"<{vocab_size}I", *vocab_offs))
        out.seek(vlens_off)
        out.write(struct.pack(f"<{vocab_size}H", *vocab_lens))
        out.seek(vpool_off)
        out.write(vocab_pool)
        out.seek(ht_off)
        out.write(ht_buf)
        for idx, (off, dt, nb, t) in enumerate(tdescs):
            out.seek(off)
            out.write(memoryview(t.data).tobytes())
        out.truncate(2 * 1024 * 1024 * 1024 if args.pad_2g else total_used)

    print(f"[PACK] DONE -> {args.out} ({os.path.getsize(args.out)} bytes)", flush=True)

if __name__ == "__main__":
    main()