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.

26.2 KB
Raw Blame
#!/usr/bin/env python3
"""
Export a Qwen3 dense model with tied embeddings (Qwen3-0.6B, -1.7B, -4B; BF16,
F16 or F32 safetensors + tokenizer.json) into a compact, 64-byte aligned,
directly mmap-able .asmbin file for asm-llm.

Input: --model-dir with config.json, tokenizer.json and either one
model.safetensors or shards model-0000N-of-0000M.safetensors (the
model.safetensors.index.json next to them is used when present). Tensors are
read and quantized a block of rows at a time, so peak RAM stays well under
1 GB even for Qwen3-4B. Models the format cannot hold (untied lm_head, as in
Qwen3-8B and larger; other architectures; shapes outside the engines' limits)
are refused with an error and exit status 2. The output is written to a
temporary file next to --out and renamed over it only after the whole export
succeeded, so a failed export leaves an existing --out file as it was.

Weight format: Per-row split Q8_0 (block size = 32, symmetric int8 in [-127, 127]):
  Each row of K elements (K multiple of 32) is stored as:
    - v2 (--scale-dtype fp16, default): [K int8 weights][K/32 * 2B fp16 scales]
      row stride K + K/16: Qwen3-0.6B {1024, 2048, 3072} -> {1088, 2176, 3264} B,
      Qwen3-4B {2560, 4096, 9728} -> {2720, 4352, 10336} B.
    - v1 (--scale-dtype fp32):          [K int8 weights][K/32 * 4B fp32 scales]
      row stride K + K/8: Qwen3-0.6B -> {1152, 2304, 3456} B.
  Rows follow each other without padding, so a row starts on a 64-byte
  boundary only when its stride is a multiple of 64 (true for 0.6B and 1.7B,
  not for Qwen3-4B v2: 2720 and 10336 are multiples of 32 only). The kernels
  use unaligned loads for weights. Each matrix starts 64-byte aligned.

Header (128 bytes): u32 dimensions, u64 section offsets, layer stride and file
size, so files larger than 4 GiB (Qwen3-4B: ~4.28 GB) need no format change.
"""

import argparse
import contextlib
import glob
import json
import os
import struct
import sys
import time
import numpy as np

MAGIC = b"ASML"
VERSION_V1 = 1
VERSION_V2 = 2
FLAG_TIED_EMB = 1
FLAG_QK_NORM = 2
FLAG_FP16_SCALES = 4
HEADER_SIZE = 128
TOK_HEADER_SIZE = 64
HT_BITS = 19
HT_SIZE = 1 << HT_BITS  # 524,288 slots for 151,387 merges (load factor ~0.289)
HT_MASK = HT_SIZE - 1
FIB_MULT = 0x9E3779B97F4A7C15


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


def pad64(f) -> int:
    pos = f.tell()
    aligned = align64(pos)
    if aligned > pos:
        f.write(b"\x00" * (aligned - pos))
    return aligned


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]))


class Checkpoint:
    """Tensors of a Hugging Face checkpoint: one model.safetensors, or shards
    (model-0000N-of-0000M.safetensors, listed by model.safetensors.index.json
    when it exists). Every tensor is located through its shard's own header;
    nothing is loaded until it is read, and reads go row range by row range."""

    def __init__(self, model_dir: str):
        single = os.path.join(model_dir, "model.safetensors")
        index = os.path.join(model_dir, "model.safetensors.index.json")
        weight_map = None
        if os.path.isfile(single):
            files = [single]
        elif os.path.isfile(index):
            try:
                with open(index, "r") as f:
                    weight_map = json.load(f)["weight_map"]
            except (ValueError, KeyError, TypeError):
                raise ExportError(f"{index}: not a JSON object with a weight_map")
            if not isinstance(weight_map, dict):
                raise ExportError(f"{index}: weight_map is not an object")
            for name, shard in weight_map.items():
                if not is_plain_file_name(shard):
                    raise ExportError(f"{index}: {name} is listed in {shard!r}, which is not a plain file name "
                                      f"in the checkpoint directory")
            files = [os.path.join(model_dir, n) for n in sorted(set(weight_map.values()))]
        else:
            files = sorted(glob.glob(os.path.join(model_dir, "model-*-of-*.safetensors")))
        if not files:
            raise ExportError(f"{model_dir}: no model.safetensors, model.safetensors.index.json "
                              f"or model-*-of-*.safetensors")
        self.files = files
        self.tensors = {}  # name -> (path, dtype, shape, absolute start, absolute end)
        for path in files:
            if not os.path.isfile(path):
                raise ExportError(f"missing shard {path}")
            size = os.path.getsize(path)
            with open(path, "rb") as f:
                raw = f.read(8)
                hdr_len = struct.unpack("<Q", raw)[0] if len(raw) == 8 else size
                if hdr_len > size - 8:
                    raise ExportError(f"{path}: safetensors header runs past the end of the file")
                try:
                    hdr = json.loads(f.read(hdr_len))
                except ValueError:
                    hdr = None
            if not isinstance(hdr, dict):
                raise ExportError(f"{path}: safetensors header is not a JSON object")
            base = 8 + hdr_len
            data_size = size - base
            for name, meta in hdr.items():
                if name == "__metadata__":
                    continue
                if name in self.tensors:
                    raise ExportError(f"tensor {name} is in both {self.tensors[name][0]} and {path}")
                try:
                    dtype, shape, (start, end) = meta["dtype"], tuple(meta["shape"]), meta["data_offsets"]
                except (KeyError, TypeError, ValueError):
                    raise ExportError(f"{path}: tensor {name} has no dtype, shape and data_offsets [start, end]")
                if not all(type(v) is int and v >= 0 for v in shape + (start, end)):
                    raise ExportError(f"{path}: tensor {name} has a shape or data offset that is not a "
                                      f"non-negative integer")
                if start > end:
                    raise ExportError(f"{path}: tensor {name} starts at {start}, after its end {end}")
                if end > data_size:
                    raise ExportError(f"{path}: tensor {name} runs past the end of the file (truncated shard?)")
                self.tensors[name] = (path, dtype, shape, base + start, base + end)
        if weight_map is not None:
            for name, shard in weight_map.items():
                t = self.tensors.get(name)
                if t is None or os.path.basename(t[0]) != shard:
                    raise ExportError(f"{index}: {name} is listed in {shard} but not found there")
        self._fh = {}

    def __contains__(self, name):
        return name in self.tensors

    def shape(self, name):
        return self._get(name)[2]

    def _get(self, name):
        t = self.tensors.get(name)
        if t is None:
            raise ExportError(f"tensor {name} not found in the checkpoint")
        return t

    def _file(self, path):
        f = self._fh.get(path)
        if f is None:
            f = self._fh[path] = open(path, "rb")
        return f

    def read_rows_f32(self, name: str, r0: int, r1: int) -> np.ndarray:
        """Rows [r0, r1) of a tensor (axis 0) as float32; 1-D tensors: elements."""
        path, dtype, shape, start, end = self._get(name)
        if dtype not in ("BF16", "F32", "F16"):
            raise ExportError(f"Unsupported dtype {dtype} for tensor {name}")
        esize = 4 if dtype == "F32" else 2
        row = int(np.prod(shape[1:], dtype=np.int64)) if len(shape) > 1 else 1
        if (end - start) != row * shape[0] * esize:
            raise ExportError(f"tensor {name}: data size does not match shape {shape} {dtype}")
        f = self._file(path)
        f.seek(start + r0 * row * esize)
        raw = f.read((r1 - r0) * row * esize)
        out_shape = (r1 - r0,) + tuple(shape[1:])
        if dtype == "BF16":
            u16 = np.frombuffer(raw, dtype=np.uint16)
            f32 = (u16.astype(np.uint32) << 16).view(np.float32)
            return f32.reshape(out_shape)
        elif dtype == "F32":
            return np.frombuffer(raw, dtype=np.float32).reshape(out_shape).copy()
        else:
            return np.frombuffer(raw, dtype=np.float16).astype(np.float32).reshape(out_shape)

    def read_f32(self, name: str) -> np.ndarray:
        return self.read_rows_f32(name, 0, self.shape(name)[0])

    def close(self):
        for f in self._fh.values():
            f.close()
        self._fh = {}


class ExportError(Exception):
    pass


def is_plain_file_name(name) -> bool:
    """True for a file name without any directory part: no separators (of
    either OS), not empty, not "." or ".."."""
    return (isinstance(name, str) and name not in ("", ".", "..")
            and not any(ch in name for ch in ("/", "\\", "\0"))
            and name == os.path.basename(name))


def quantize_matrix_q8_0_row_split(w: np.ndarray, scale_dtype: str = "fp16") -> bytes:
    """Quantize [M, K] float32 matrix into per-row split Q8_0 bytes."""
    assert w.ndim == 2
    M, K = w.shape
    assert K % 32 == 0, f"K={K} must be a multiple of 32"
    nb = K // 32
    blocks = w.reshape(M, nb, 32).astype(np.float32, copy=False)
    amax = np.max(np.abs(blocks), axis=2)  # [M, nb]
    scale_f32 = np.where(amax > 0.0, amax / np.float32(127.0), np.float32(0.0)).astype(np.float32)
    if scale_dtype == "fp16":
        scale_f16 = scale_f32.astype(np.float16)
        scale_eff = scale_f16.astype(np.float32)
        inv_scale = np.where(scale_eff > 0.0, np.float32(1.0) / scale_eff, np.float32(0.0)).astype(np.float32)
        q = np.clip(np.rint(blocks * inv_scale[:, :, None]), -127, 127).astype(np.int8)
        s_bytes = scale_f16.astype("<f2").view(np.uint8).reshape(M, nb * 2)
        scale_bytes_per_block = 2
    elif scale_dtype == "fp32":
        inv_scale = np.where(scale_f32 > 0.0, np.float32(1.0) / scale_f32, np.float32(0.0)).astype(np.float32)
        q = np.clip(np.rint(blocks * inv_scale[:, :, None]), -127, 127).astype(np.int8)
        s_bytes = scale_f32.astype("<f4").view(np.uint8).reshape(M, nb * 4)
        scale_bytes_per_block = 4
    else:
        raise ValueError(f"Unsupported scale_dtype: {scale_dtype}")
    q_flat = q.reshape(M, K)  # [M, K] int8
    # Pack each row contiguously: [K int8][nb*scale_bytes_per_block scale bytes]
    row_packed = np.concatenate([q_flat.view(np.uint8), s_bytes], axis=1)
    assert row_packed.shape == (M, K + nb * scale_bytes_per_block)
    return row_packed.tobytes()


def build_tokenizer_blob(tok_json_path: str, vocab_size: int) -> bytes:
    with open(tok_json_path, "r", encoding="utf-8") as f:
        tj = json.load(f)

    vocab = tj["model"]["vocab"]
    merges = tj["model"]["merges"]
    added_tokens = tj.get("added_tokens", [])

    b2u = bytes_to_unicode()
    u2b = {v: k for k, v in b2u.items()}

    # 1. byte_to_tok[256]
    byte_to_tok = np.array([vocab[b2u[b]] for b in range(256)], dtype=np.uint32)

    # 2. Raw decoded UTF-8 byte string for every token ID 0..vocab_size-1
    tok_raw = [b""] * vocab_size
    for piece, tid in vocab.items():
        if tid < vocab_size:
            tok_raw[tid] = bytes(u2b[ch] for ch in piece)
    for at in added_tokens:
        tid = at["id"]
        if tid < vocab_size:
            tok_raw[tid] = at["content"].encode("utf-8")

    tok_offsets = np.zeros(vocab_size + 1, dtype=np.uint32)
    chunks = []
    cur = 0
    for tid in range(vocab_size):
        b = tok_raw[tid]
        tok_offsets[tid] = cur
        chunks.append(b)
        cur += len(b)
    tok_offsets[vocab_size] = cur
    tok_bytes = b"".join(chunks)

    # 3. Pre-built Fibonacci-hashed open-addressing merge table
    # Entry layout (16 bytes): <Q key, <I merged_id, <I rank (0xFFFFFFFF = empty)
    ht_keys = np.zeros(HT_SIZE, dtype=np.uint64)
    ht_merged = np.zeros(HT_SIZE, dtype=np.uint32)
    ht_rank = np.full(HT_SIZE, 0xFFFFFFFF, dtype=np.uint32)

    max_probe = 0
    total_probes = 0
    for rank, m in enumerate(merges):
        if isinstance(m, list):
            a, b = m[0], m[1]
        else:
            a, b = m.split(" ")
        ia = vocab[a]
        ib = vocab[b]
        ic = vocab[a + b]
        key = (ia << 32) | ib
        slot = ((key * FIB_MULT) & 0xFFFFFFFFFFFFFFFF) >> (64 - HT_BITS)
        probes = 1
        while ht_rank[slot] != 0xFFFFFFFF:
            slot = (slot + 1) & HT_MASK
            probes += 1
        ht_keys[slot] = key
        ht_merged[slot] = ic
        ht_rank[slot] = rank
        total_probes += probes
        if probes > max_probe:
            max_probe = probes

    print(
        f"Tokenizer: {len(merges)} merges in {HT_SIZE} slots "
        f"(load={len(merges)/HT_SIZE:.3f}, avg_probe={total_probes/len(merges):.2f}, max_probe={max_probe}), "
        f"tok_bytes={len(tok_bytes):,} B"
    )

    # Pack structured array for merge table
    ht_dtype = np.dtype([("key", "<u8"), ("merged_id", "<u4"), ("rank", "<u4")])
    ht_arr = np.empty(HT_SIZE, dtype=ht_dtype)
    ht_arr["key"] = ht_keys
    ht_arr["merged_id"] = ht_merged
    ht_arr["rank"] = ht_rank
    ht_bytes = ht_arr.tobytes()

    # Lay out sub-sections inside tokenizer blob (all 64-byte aligned relative to blob start)
    off_byte_to_tok = TOK_HEADER_SIZE
    off_tok_offsets = align64(off_byte_to_tok + byte_to_tok.nbytes)
    off_tok_bytes = align64(off_tok_offsets + tok_offsets.nbytes)
    off_merge_ht = align64(off_tok_bytes + len(tok_bytes))
    total_tok_size = align64(off_merge_ht + len(ht_bytes))

    buf = bytearray(total_tok_size)
    struct.pack_into(
        "<QQQQ",
        buf,
        0,
        off_byte_to_tok,
        off_tok_offsets,
        off_tok_bytes,
        off_merge_ht,
    )
    buf[off_byte_to_tok : off_byte_to_tok + byte_to_tok.nbytes] = byte_to_tok.tobytes()
    buf[off_tok_offsets : off_tok_offsets + tok_offsets.nbytes] = tok_offsets.tobytes()
    buf[off_tok_bytes : off_tok_bytes + len(tok_bytes)] = tok_bytes
    buf[off_merge_ht : off_merge_ht + len(ht_bytes)] = ht_bytes
    return bytes(buf)


# Engine limits
MAX_K = 16384            # Q8_MAX_K: longest matrix row (dim, hidden_dim, n_heads*head_dim)
MAX_LAYERS = 255
TOK_THINK_END = 151668   # highest special token id the engines hardcode
CHUNK_ELEMS = 1 << 23    # elements quantized per step (bounds peak RAM)


def read_config(model_dir: str) -> dict:
    """config.json -> the fields the .asmbin header needs. Refuses models the
    format or the engines cannot represent instead of writing a wrong file."""
    with open(os.path.join(model_dir, "config.json"), "r") as f:
        cfg = json.load(f)
    name = os.path.basename(os.path.normpath(model_dir))

    def refuse(why):
        raise ExportError(f"{name}: {why}")

    arch = cfg.get("architectures") or ["Qwen3ForCausalLM"]
    if cfg.get("model_type", "qwen3") != "qwen3" or "Qwen3ForCausalLM" not in arch:
        refuse(f"not a Qwen3 dense text model (model_type={cfg.get('model_type')!r}, "
               f"architectures={arch}); only Qwen3ForCausalLM is supported")
    if not bool(cfg.get("tie_word_embeddings", True)):
        refuse("tie_word_embeddings is false (untied lm_head, e.g. Qwen3-8B and larger); "
               ".asmbin stores one matrix for the embedding and the LM head, so this model is not supported")
    if cfg.get("hidden_act", "silu") != "silu":
        refuse(f"hidden_act {cfg.get('hidden_act')!r} is not silu")
    if cfg.get("attention_bias", False):
        refuse("attention_bias is true; the engines have no attention biases")
    if cfg.get("rope_scaling"):
        refuse(f"rope_scaling {cfg.get('rope_scaling')!r} is set; the engines implement plain RoPE only")
    if cfg.get("use_sliding_window", False):
        refuse("use_sliding_window is true; the engines implement full attention only")

    c = dict(
        dim=int(cfg["hidden_size"]),
        hidden_dim=int(cfg["intermediate_size"]),
        n_layers=int(cfg["num_hidden_layers"]),
        n_heads=int(cfg["num_attention_heads"]),
        n_kv_heads=int(cfg["num_key_value_heads"]),
        vocab_size=int(cfg["vocab_size"]),
        rms_norm_eps=float(cfg["rms_norm_eps"]),
        rope_theta=float(cfg["rope_theta"]),
    )
    if c["n_heads"] <= 0:
        refuse(f"num_attention_heads is {c['n_heads']}")
    head_dim = cfg.get("head_dim")
    c["head_dim"] = int(c["dim"] // c["n_heads"] if head_dim is None else head_dim)
    if min(c["dim"], c["hidden_dim"], c["n_layers"], c["n_heads"], c["n_kv_heads"], c["head_dim"]) <= 0:
        refuse("a dimension in config.json is zero")
    if c["dim"] % 32 or c["hidden_dim"] % 32 or c["head_dim"] % 32:
        refuse("hidden_size, intermediate_size and head_dim must be multiples of 32 (Q8_0 blocks)")
    if c["n_heads"] % c["n_kv_heads"]:
        refuse("num_attention_heads must be a multiple of num_key_value_heads")
    if max(c["dim"], c["hidden_dim"], c["n_heads"] * c["head_dim"]) > MAX_K:
        refuse(f"a matrix row is longer than {MAX_K} values, the engines' limit")
    if c["n_layers"] > MAX_LAYERS:
        refuse(f"more than {MAX_LAYERS} layers")
    if c["vocab_size"] <= TOK_THINK_END:
        refuse(f"vocab_size {c['vocab_size']} does not hold the Qwen3 special tokens (up to id {TOK_THINK_END})")
    return c


def write_q8_matrix(out, ck: Checkpoint, name: str, expected_shape, scale_dtype: str, tied_check=None):
    """Quantize a [M, K] tensor to per-row split Q8_0 and write it, a block of
    rows at a time. Rows are independent, so the bytes equal quantizing the
    whole matrix at once. tied_check: name of a tensor that must be equal."""
    shape = ck.shape(name)
    if shape != tuple(expected_shape):
        raise ExportError(f"{name}: got {shape}, expected {tuple(expected_shape)}")
    M, K = shape
    step = max(1, CHUNK_ELEMS // K)
    max_diff = 0.0
    for r0 in range(0, M, step):
        r1 = min(M, r0 + step)
        w = ck.read_rows_f32(name, r0, r1)
        if tied_check is not None:
            max_diff = max(max_diff, float(np.max(np.abs(w - ck.read_rows_f32(tied_check, r0, r1)))))
        out.write(quantize_matrix_q8_0_row_split(w, scale_dtype=scale_dtype))
        del w
    return max_diff


def write_f32_vector(out, ck: Checkpoint, name: str, n: int):
    v = ck.read_f32(name)
    if v.shape != (n,):
        raise ExportError(f"{name}: got {v.shape}, expected ({n},)")
    out.write(v.astype("<f4").tobytes())


def asmbin_size(c: dict, tok_blob_len: int, scale_dtype: str = "fp16") -> int:
    """Exact size of the .asmbin export_model writes for config c."""
    sh = 4 if scale_dtype == "fp16" else 3
    rs = lambda k: k + (k >> sh)
    dim, hid, hd = c["dim"], c["hidden_dim"], c["head_dim"]
    qd, kvd = c["n_heads"] * hd, c["n_kv_heads"] * hd
    pos = align64(HEADER_SIZE) + tok_blob_len
    pos = align64(pos) + c["vocab_size"] * rs(dim)
    layer = 4 * (2 * dim + 2 * hd)
    for m, k in ((qd, dim), (kvd, dim), (kvd, dim), (dim, qd), (hid, dim), (hid, dim), (dim, hid)):
        layer = align64(layer) + m * rs(k)
    pos = align64(pos) + c["n_layers"] * align64(layer)
    return align64(align64(pos) + 4 * dim)


@contextlib.contextmanager
def atomic_output(out_path: str):
    """Binary output file that appears at out_path only when the block ends
    without an error. The bytes go to a temporary file in the same directory
    (same filesystem, so the rename is atomic), which then replaces out_path.
    On any error the temporary file is removed and an existing out_path keeps
    its bytes."""
    tmp_path = f"{out_path}.tmp{os.getpid()}"
    out = open(tmp_path, "xb")
    try:
        with out:
            yield out
            out.flush()
            os.fsync(out.fileno())
        os.replace(tmp_path, out_path)
    except BaseException:
        with contextlib.suppress(OSError):
            os.remove(tmp_path)
        raise


def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_dtype: str = "fp16"):
    t0 = time.time()
    use_fp16 = scale_dtype == "fp16"
    version = VERSION_V2 if use_fp16 else VERSION_V1
    c = read_config(model_dir)
    dim, hidden_dim, n_layers = c["dim"], c["hidden_dim"], c["n_layers"]
    n_heads, n_kv_heads, head_dim = c["n_heads"], c["n_kv_heads"], c["head_dim"]
    vocab_size = c["vocab_size"]
    tie_emb = True  # read_config refuses untied models

    ck = Checkpoint(model_dir)
    tok_path = os.path.join(model_dir, "tokenizer.json")
    print(f"Checkpoint: {len(ck.files)} file(s), {len(ck.tensors)} tensors; dim={dim} hidden={hidden_dim} "
          f"layers={n_layers} heads={n_heads}/{n_kv_heads} head_dim={head_dim} vocab={vocab_size}")

    os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
    tok_blob = build_tokenizer_blob(tok_path, vocab_size)
    expect = asmbin_size(c, len(tok_blob), scale_dtype)
    print(f"Expected output size: {expect:,} bytes ({expect / (1024**3):.2f} GiB)")

    with atomic_output(out_path) as out:
        # Reserve header
        out.write(b"\x00" * HEADER_SIZE)

        # 1. Tokenizer section
        off_tokenizer = pad64(out)
        out.write(tok_blob)
        del tok_blob

        # 2. Embeddings (tied with lm_head)
        off_embed = pad64(out)
        lm_head = "lm_head.weight" if "lm_head.weight" in ck else None
        print(f"Quantizing embed_tokens ({vocab_size}, {dim}) -> Q8_0 (scale_dtype={scale_dtype}, v{version})...")
        max_diff = write_q8_matrix(out, ck, "model.embed_tokens.weight", (vocab_size, dim), scale_dtype,
                                   tied_check=lm_head)
        if lm_head:
            if max_diff != 0.0:
                raise ExportError(f"tie_word_embeddings=True but lm_head.weight differs from embed_tokens "
                                  f"(max diff {max_diff})")
            print("Verified embed_tokens == lm_head exact (max_diff=0.0)")

        # 3. Transformer layers (fixed 64-byte aligned stride)
        off_layers = pad64(out)
        layer_stride = 0
        for l in range(n_layers):
            layer_start = pad64(out)
            prefix = f"model.layers.{l}"

            # 4 FP32 norm vectors
            write_f32_vector(out, ck, f"{prefix}.input_layernorm.weight", dim)
            write_f32_vector(out, ck, f"{prefix}.self_attn.q_norm.weight", head_dim)
            write_f32_vector(out, ck, f"{prefix}.self_attn.k_norm.weight", head_dim)
            write_f32_vector(out, ck, f"{prefix}.post_attention_layernorm.weight", dim)

            # 7 Q8_0 projection matrices in fixed order
            proj_specs = [
                (f"{prefix}.self_attn.q_proj.weight", (n_heads * head_dim, dim)),
                (f"{prefix}.self_attn.k_proj.weight", (n_kv_heads * head_dim, dim)),
                (f"{prefix}.self_attn.v_proj.weight", (n_kv_heads * head_dim, dim)),
                (f"{prefix}.self_attn.o_proj.weight", (dim, n_heads * head_dim)),
                (f"{prefix}.mlp.gate_proj.weight", (hidden_dim, dim)),
                (f"{prefix}.mlp.up_proj.weight", (hidden_dim, dim)),
                (f"{prefix}.mlp.down_proj.weight", (dim, hidden_dim)),
            ]
            for name, expected_shape in proj_specs:
                pad64(out)
                write_q8_matrix(out, ck, name, expected_shape, scale_dtype)

            layer_end = pad64(out)
            this_stride = layer_end - layer_start
            if l == 0:
                layer_stride = this_stride
            else:
                assert this_stride == layer_stride, f"Layer {l} stride {this_stride} != {layer_stride}"

            if (l + 1) % 7 == 0 or l == n_layers - 1:
                print(f"  Exported layer {l + 1}/{n_layers} (stride={layer_stride:,} B)")

        # 4. Final RMSNorm
        off_final_norm = pad64(out)
        write_f32_vector(out, ck, "model.norm.weight", dim)
        file_size = pad64(out)
        assert file_size == expect, f"wrote {file_size} bytes, expected {expect}"

        # Write 128-byte header. All offsets and sizes are u64: files over 4 GiB
        # (Qwen3-4B, ~4.28 GB) need no format change.
        flags = (FLAG_TIED_EMB if tie_emb else 0) | FLAG_QK_NORM | (FLAG_FP16_SCALES if use_fp16 else 0)
        eos_1 = 151645  # <|im_end|>
        eos_2 = 151643  # <|endoftext|>
        header = struct.pack(
            "<4sIIIIIIIIIffIIIIQQQQQQ16s",
            MAGIC,
            version,
            dim,
            hidden_dim,
            n_layers,
            n_heads,
            n_kv_heads,
            head_dim,
            vocab_size,
            max_seq_len,
            c["rms_norm_eps"],
            c["rope_theta"],
            eos_1,
            eos_2,
            HT_MASK,
            flags,
            off_tokenizer,
            off_embed,
            off_layers,
            layer_stride,
            off_final_norm,
            file_size,
            b"\x00" * 16,
        )
        assert len(header) == HEADER_SIZE
        out.seek(0)
        out.write(header)
    ck.close()

    dt = time.time() - t0
    print(f"\nExport complete: {out_path}")
    print(f"  Format       : .asmbin v{version} (scale_dtype={scale_dtype}, flags=0x{flags:x})")
    print(f"  Total size   : {file_size:,} bytes ({file_size / (1024**2):.2f} MiB)")
    print(f"  off_tokenizer: {off_tokenizer:,}")
    print(f"  off_embed    : {off_embed:,}")
    print(f"  off_layers   : {off_layers:,} (stride={layer_stride:,} x {n_layers})")
    print(f"  off_final_nrm: {off_final_norm:,}")
    print(f"  Elapsed      : {dt:.2f} s")


def main():
    ap = argparse.ArgumentParser(
        description="Export a Qwen3 dense model with tied embeddings (Qwen3-0.6B, 1.7B, 4B) from Hugging Face "
                    "safetensors (one file or shards) to .asmbin Q8_0")
    ap.add_argument("--model-dir", default="models/qwen3-0.6b-bf16",
                    help="Directory with config.json, tokenizer.json and model.safetensors or "
                         "model-0000N-of-0000M.safetensors shards (model.safetensors.index.json optional)")
    ap.add_argument("--out", default="models/qwen3-0.6b-q8_0.asmbin", help="Output .asmbin path")
    ap.add_argument("--max-seq-len", type=int, default=4096)
    ap.add_argument("--scale-dtype", choices=["fp16", "fp32"], default="fp16", help="Per-block Q8_0 scale dtype (fp16 -> v2 compact, fp32 -> v1 legacy)")
    args = ap.parse_args()
    try:
        export_model(args.model_dir, args.out, args.max_seq_len, scale_dtype=args.scale_dtype)
    except ExportError as e:
        print(f"error: {e}", file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    main()