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.

Exporter: sharded checkpoints and streaming quantization (Qwen3-1.7B, Qwen3-4B)

Jordan Ritterd8f013e1244d
diff --git a/01-qwen3-inference/README.md b/01-qwen3-inference/README.md
index 8b4225a..f2829e6 100644
--- a/01-qwen3-inference/README.md
+++ b/01-qwen3-inference/README.md
@@ -59,6 +59,8 @@ python3 scripts/export_weights.py \
Both formats are auto-detected at load time (`model_init`) by `HDR_VERSION` / `HDR_FLAGS` in both `FAST_Q8=1` and `FAST_Q8=0` builds.
+The exporter also reads sharded checkpoints (`model-0000N-of-0000M.safetensors`, with or without `model.safetensors.index.json`), such as `Qwen/Qwen3-1.7B` and `Qwen/Qwen3-4B`: point `--model-dir` at the download. It quantizes a block of rows at a time, so peak RAM stays far below the checkpoint size, and it refuses models with an untied `lm_head` (`Qwen3-8B` and larger). `make export-check` runs it on fabricated checkpoints (no real weights needed).
+
### 3. Build the 15 KB Pure x86-64 Binary
From the repository root, choose the compile-time `FAST_Q8` mode (`FAST_Q8=1` is the default):
diff --git a/Makefile b/Makefile
index f16b791..1d02197 100644
--- a/Makefile
+++ b/Makefile
@@ -101,7 +101,7 @@ TRAIN_OBJS := \
$(TRAIN_BUILD)/tui.o \
$(TRAIN_BUILD)/main.o
-.PHONY: all inference test-math check os os-check os-iso os-run isa-check train train-check check-all clean
+.PHONY: all inference test-math check os os-check os-iso os-run isa-check train train-check check-all export-check clean
all: inference $(TEST) os train
@@ -218,5 +218,10 @@ train-check: $(TRAIN_TARGET)
check-all: check os-check train-check
+# Exporter on fabricated checkpoints (no real weights): single file vs shards,
+# tied lm_head.weight, untied lm_head refused, engine loads the result.
+export-check: $(TARGET)
+ python3 scripts/test_export.py --work $(BUILD)/export-test --engine $(TARGET)
+
clean:
rm -rf $(BUILD)
diff --git a/scripts/export_weights.py b/scripts/export_weights.py
index 33e8681..4a450a9 100644
--- a/scripts/export_weights.py
+++ b/scripts/export_weights.py
@@ -1,21 +1,42 @@
#!/usr/bin/env python3
"""
-Export Qwen3-0.6B (BF16 safetensors + tokenizer.json) into a compact,
-64-byte aligned, directly mmap-able .asmbin file for pure x86-64 asm-llm.
+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]
- For Qwen3-0.6B (K in {1024, 2048, 3072}), row strides are {1088, 2176, 3264} B.
+ 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]
- For Qwen3-0.6B (K in {1024, 2048, 3072}), row strides are {1152, 2304, 3456} B.
- Every row stride is an exact multiple of 64 bytes, ensuring 32-byte aligned AVX2 loads.
+ 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
@@ -61,31 +82,138 @@ def bytes_to_unicode():
return dict(zip(bs, [chr(c) for c in cs]))
-def load_safetensors_header(path: str):
- with open(path, "rb") as f:
- hdr_len = struct.unpack("<Q", f.read(8))[0]
- hdr = json.loads(f.read(hdr_len))
- data_offset = 8 + hdr_len
- return hdr, data_offset
-
-
-def read_tensor_f32(f, hdr, data_offset: int, name: str) -> np.ndarray:
- meta = hdr[name]
- dtype = meta["dtype"]
- shape = tuple(meta["shape"])
- start, end = meta["data_offsets"]
- f.seek(data_offset + start)
- raw = f.read(end - start)
- if dtype == "BF16":
- u16 = np.frombuffer(raw, dtype=np.uint16)
- f32 = (u16.astype(np.uint32) << 16).view(np.float32)
- return f32.reshape(shape)
- elif dtype == "F32":
- return np.frombuffer(raw, dtype=np.float32).reshape(shape).copy()
- elif dtype == "F16":
- return np.frombuffer(raw, dtype=np.float16).astype(np.float32).reshape(shape)
- else:
- raise ValueError(f"Unsupported dtype {dtype} for tensor {name}")
+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:
@@ -220,52 +348,171 @@ def build_tokenizer_blob(tok_json_path: str, vocab_size: int) -> 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)
+
+
+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
- with open(os.path.join(model_dir, "config.json"), "r") as f:
- cfg = json.load(f)
+ 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
- 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"])
- head_dim = int(cfg["head_dim"])
- vocab_size = int(cfg["vocab_size"])
- rms_norm_eps = float(cfg["rms_norm_eps"])
- rope_theta = float(cfg["rope_theta"])
- tie_emb = bool(cfg.get("tie_word_embeddings", True))
-
- st_path = os.path.join(model_dir, "model.safetensors")
+ ck = Checkpoint(model_dir)
tok_path = os.path.join(model_dir, "tokenizer.json")
- hdr, data_offset = load_safetensors_header(st_path)
+ 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 open(st_path, "rb") as sf, open(out_path, "wb") as out:
+ 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)
- emb = read_tensor_f32(sf, hdr, data_offset, "model.embed_tokens.weight")
- assert emb.shape == (vocab_size, dim), f"Unexpected embed shape {emb.shape}"
- if "lm_head.weight" in hdr and tie_emb:
- lmh = read_tensor_f32(sf, hdr, data_offset, "lm_head.weight")
- max_diff = float(np.max(np.abs(emb - lmh)))
- assert max_diff == 0.0, f"tie_word_embeddings=True but diff={max_diff}"
+ 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)")
- del lmh
- print(f"Quantizing embed_tokens {emb.shape} -> Q8_0 (scale_dtype={scale_dtype}, v{version})...")
- out.write(quantize_matrix_q8_0_row_split(emb, scale_dtype=scale_dtype))
- del emb
# 3. Transformer layers (fixed 64-byte aligned stride)
off_layers = pad64(out)
@@ -275,20 +522,10 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_d
prefix = f"model.layers.{l}"
# 4 FP32 norm vectors
- in_norm = read_tensor_f32(sf, hdr, data_offset, f"{prefix}.input_layernorm.weight")
- q_norm = read_tensor_f32(sf, hdr, data_offset, f"{prefix}.self_attn.q_norm.weight")
- k_norm = read_tensor_f32(sf, hdr, data_offset, f"{prefix}.self_attn.k_norm.weight")
- post_norm = read_tensor_f32(sf, hdr, data_offset, f"{prefix}.post_attention_layernorm.weight")
-
- assert in_norm.shape == (dim,)
- assert q_norm.shape == (head_dim,)
- assert k_norm.shape == (head_dim,)
- assert post_norm.shape == (dim,)
-
- out.write(in_norm.astype("<f4").tobytes())
- out.write(q_norm.astype("<f4").tobytes())
- out.write(k_norm.astype("<f4").tobytes())
- out.write(post_norm.astype("<f4").tobytes())
+ 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 = [
@@ -302,9 +539,7 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_d
]
for name, expected_shape in proj_specs:
pad64(out)
- mat = read_tensor_f32(sf, hdr, data_offset, name)
- assert mat.shape == expected_shape, f"{name}: got {mat.shape}, expected {expected_shape}"
- out.write(quantize_matrix_q8_0_row_split(mat, scale_dtype=scale_dtype))
+ write_q8_matrix(out, ck, name, expected_shape, scale_dtype)
layer_end = pad64(out)
this_stride = layer_end - layer_start
@@ -318,12 +553,12 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_d
# 4. Final RMSNorm
off_final_norm = pad64(out)
- final_norm = read_tensor_f32(sf, hdr, data_offset, "model.norm.weight")
- assert final_norm.shape == (dim,)
- out.write(final_norm.astype("<f4").tobytes())
+ 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
+ # 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|>
@@ -339,8 +574,8 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_d
head_dim,
vocab_size,
max_seq_len,
- rms_norm_eps,
- rope_theta,
+ c["rms_norm_eps"],
+ c["rope_theta"],
eos_1,
eos_2,
HT_MASK,
@@ -356,6 +591,7 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_d
assert len(header) == HEADER_SIZE
out.seek(0)
out.write(header)
+ ck.close()
dt = time.time() - t0
print(f"\nExport complete: {out_path}")
@@ -369,13 +605,21 @@ def export_model(model_dir: str, out_path: str, max_seq_len: int = 4096, scale_d
def main():
- ap = argparse.ArgumentParser(description="Export Qwen3-0.6B safetensors to .asmbin Q8_0")
- ap.add_argument("--model-dir", default="models/qwen3-0.6b-bf16", help="Directory containing Qwen3-0.6B config.json, model.safetensors, tokenizer.json")
+ 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()
- export_model(args.model_dir, args.out, args.max_seq_len, scale_dtype=args.scale_dtype)
+ 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__":
diff --git a/scripts/make_synth_hf.py b/scripts/make_synth_hf.py
new file mode 100644
index 0000000..a2d507f
--- /dev/null
+++ b/scripts/make_synth_hf.py
@@ -0,0 +1,314 @@
+#!/usr/bin/env python3
+"""
+make_synth_hf.py -- fabricate a Hugging Face style Qwen3 checkpoint directory
+with random weights, for testing scripts/export_weights.py without real weights:
+
+ config.json Qwen3ForCausalLM fields as in the real 0.6B/1.7B/4B configs
+ tokenizer.json byte-level BPE (GPT-2 byte map, merges trained on a small
+ built-in corpus, Qwen3 special tokens at 151643..151668)
+ model.safetensors --shards 1 (default)
+ model-0000N-of-0000M.safetensors + model.safetensors.index.json --shards M
+
+Weights are BF16 (or --dtype F16 / F32), deterministic for a given --seed and
+shape, so the single-file and sharded variants of a shape hold the same bytes.
+
+Usage:
+ make_synth_hf.py --out DIR [--shape tiny|s4|q17|q4] [--shards N] [--no-index]
+ [--lm-head] [--untied] [--dtype BF16|F16|F32] [--seed N]
+
+Shapes: tiny/s4 are small (seconds); q17 and q4 are full Qwen3-1.7B / Qwen3-4B
+sizes (4 / 8 GB of BF16 written in streaming fashion; the 4B export is > 4 GiB).
+"""
+
+import argparse
+import json
+import os
+import struct
+import sys
+
+import numpy as np
+
+VOCAB_SIZE = 151936
+
+TOK_ENDOFTEXT = 151643
+TOK_IM_END = 151645
+FIXED_IDS = {"\n\n": 271, "user": 872, "assistant": 77091}
+SPECIALS = [
+ "<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|object_ref_start|>",
+ "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>",
+ "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>",
+ "<|image_pad|>", "<|video_pad|>", "<tool_call>", "</tool_call>",
+ "<|fim_prefix|>", "<|fim_middle|>", "<|fim_suffix|>", "<|fim_pad|>",
+ "<|repo_name|>", "<|file_sep|>", "<tool_response>", "</tool_response>",
+ "<think>", "</think>",
+] # ids 151643 .. 151668; 151669 .. 151935 stay empty, like Qwen3
+
+CORPUS = """
+The quick brown fox jumps over the lazy dog. A user asks a question and the
+assistant answers it. The assistant thinks before it answers when thinking is
+enabled. Hello! How are you today? I am fine, thank you. What is the capital of
+France? The capital of France is Paris. Write a short poem about the sea.
+The sea is wide and the sea is deep; the waves roll in and the sailors sleep.
+Explain how a transformer works: tokens are embedded, attention mixes them,
+and a feed forward network transforms every position. Numbers: 0 1 2 3 4 5 6 7
+8 9 10 42 100 2024 3.14159 1e-6. Code: def main(): return 0; int x = y + 1;
+user assistant user assistant system tool think answer question reply hello
+world the and of to in is that for it with as was on be at by this had not
+are but from or have an they which one you were her all she there would their
+we him been has when who will more no if out so said what up its about into
+than them can only other new some could time these two may then do first any
+my now such like our over man me even most made after also did many before must
+through back years where much your way well down should because each just those
+people how too little state good very make world still own see men work long get
+here between both life being under never day same another know while last might
+us great old year off come since against go came right used take three
+Café naïve résumé über Straße à la carte, señor, niño, crème brûlée.
+日本語のテキストです。中文测试。你好,世界!
+Привет, мир! Как дела?
+Γειά σου κόσμε. مرحبا بالعالم.
+\U0001F600 \U0001F680 ∑ ∞ → ✓ °C € © …
+"""
+
+
+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 bs # bs[i] = raw byte of base token id i (Qwen/GPT-2 order)
+
+
+def train_merges(n_merges):
+ """Deterministic byte-level BPE on CORPUS (words keep their leading space,
+ newlines are their own words). Returns list of (a_bytes, b_bytes)."""
+ text = (CORPUS * 3).encode("utf-8")
+ words = {}
+ cur = b""
+ for ch in text.decode("utf-8"):
+ c = ch.encode("utf-8")
+ if ch == " ":
+ if cur:
+ words[cur] = words.get(cur, 0) + 1
+ cur = c
+ elif ch == "\n":
+ if cur:
+ words[cur] = words.get(cur, 0) + 1
+ cur = b""
+ words[b"\n\n"] = words.get(b"\n\n", 0) + 1
+ else:
+ cur += c
+ if cur:
+ words[cur] = words.get(cur, 0) + 1
+ seqs = [([bytes([b]) for b in w], f) for w, f in sorted(words.items())]
+ merges = []
+ for _ in range(n_merges):
+ counts = {}
+ for seq, f in seqs:
+ for i in range(len(seq) - 1):
+ p = (seq[i], seq[i + 1])
+ counts[p] = counts.get(p, 0) + f
+ if not counts:
+ break
+ best = min(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0]
+ if counts[best] < 2:
+ break
+ merges.append(best)
+ a, b = best
+ new = []
+ for seq, f in seqs:
+ out = []
+ i = 0
+ while i < len(seq):
+ if i + 1 < len(seq) and seq[i] == a and seq[i + 1] == b:
+ out.append(a + b)
+ i += 2
+ else:
+ out.append(seq[i])
+ i += 1
+ new.append((out, f))
+ seqs = new
+ return merges
+
+
+SHAPES = {
+ # dim, hidden, layers, heads, kv_heads, head_dim
+ "tiny": dict(dim=64, hidden=96, layers=2, heads=4, kv_heads=2, head_dim=32),
+ "s4": dict(dim=160, hidden=608, layers=4, heads=8, kv_heads=2, head_dim=32),
+ "q17": dict(dim=2048, hidden=6144, layers=28, heads=16, kv_heads=8, head_dim=128),
+ "q4": dict(dim=2560, hidden=9728, layers=36, heads=32, kv_heads=8, head_dim=128),
+}
+
+
+def gpt2_unicode():
+ bs = bytes_to_unicode() # bs[i] = byte of base token i
+ cs, n = [], 0
+ b2u = {}
+ printable = (list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1))
+ + list(range(ord("®"), ord("ÿ") + 1)))
+ for b in range(256):
+ if b in printable:
+ b2u[b] = chr(b)
+ else:
+ b2u[b] = chr(256 + n)
+ n += 1
+ return bs, b2u
+
+
+def make_tokenizer(merge_style="string"):
+ bs, b2u = gpt2_unicode()
+ u = lambda raw: "".join(b2u[x] for x in raw)
+ vocab = {}
+ for i, b in enumerate(bs):
+ vocab[u(bytes([b]))] = i
+ merges = train_merges(600)
+ for s in (b"\n\n", b"user", b"assistant"):
+ # make sure the fixed-id strings exist as merges (left-to-right chain)
+ for k in range(2, len(s) + 1):
+ pair = (s[:k - 1], s[k - 1:k])
+ if pair not in merges:
+ merges.append(pair)
+ reserved = set(FIXED_IDS.values())
+ next_id = 256
+ out_merges = []
+ for a, b in merges:
+ if u(a) not in vocab or u(b) not in vocab:
+ continue
+ piece = u(a + b)
+ if piece not in vocab:
+ fixed = FIXED_IDS.get((a + b).decode("utf-8", "replace"))
+ if fixed is None:
+ while next_id in reserved:
+ next_id += 1
+ fixed = next_id
+ next_id += 1
+ vocab[piece] = fixed
+ m = [u(a), u(b)] if merge_style == "list" else f"{u(a)} {u(b)}"
+ if m not in out_merges:
+ out_merges.append(m)
+ added = [dict(id=TOK_ENDOFTEXT + k, content=s, special=True) for k, s in enumerate(SPECIALS)]
+ return dict(version="1.0", added_tokens=added,
+ model=dict(type="BPE", vocab=vocab, merges=out_merges))
+
+
+def bf16_bytes(x32):
+ u = x32.astype(np.float32).view(np.uint32)
+ r = ((u + 0x7FFF + ((u >> 16) & 1)) >> 16).astype(np.uint16) # round to nearest even
+ return r.tobytes()
+
+
+def tensor_list(sh, lm_head):
+ dim, hid, L = sh["dim"], sh["hidden"], sh["layers"]
+ H, KV, hd = sh["heads"], sh["kv_heads"], sh["head_dim"]
+ t = [("model.embed_tokens.weight", (VOCAB_SIZE, dim))]
+ for l in range(L):
+ p = f"model.layers.{l}"
+ t += [(f"{p}.input_layernorm.weight", (dim,)),
+ (f"{p}.mlp.down_proj.weight", (dim, hid)),
+ (f"{p}.mlp.gate_proj.weight", (hid, dim)),
+ (f"{p}.mlp.up_proj.weight", (hid, dim)),
+ (f"{p}.post_attention_layernorm.weight", (dim,)),
+ (f"{p}.self_attn.k_norm.weight", (hd,)),
+ (f"{p}.self_attn.k_proj.weight", (KV * hd, dim)),
+ (f"{p}.self_attn.o_proj.weight", (dim, H * hd)),
+ (f"{p}.self_attn.q_norm.weight", (hd,)),
+ (f"{p}.self_attn.q_proj.weight", (H * hd, dim)),
+ (f"{p}.self_attn.v_proj.weight", (KV * hd, dim))]
+ t.append(("model.norm.weight", (dim,)))
+ if lm_head:
+ t.append(("lm_head.weight", (VOCAB_SIZE, dim)))
+ return t
+
+
+def tensor_chunks(name, shape, dtype, seed, rows_per=8192):
+ """Deterministic data of one tensor, yielded in row blocks (bounded RAM).
+ lm_head.weight reproduces embed_tokens (tied)."""
+ src = "model.embed_tokens.weight" if name == "lm_head.weight" else name
+ M = shape[0]
+ K = shape[1] if len(shape) > 1 else 1
+ for r0 in range(0, M, rows_per):
+ r1 = min(M, r0 + rows_per)
+ rng = np.random.default_rng([seed, sum(map(ord, src)), r0])
+ if len(shape) == 1:
+ x = rng.uniform(0.7, 1.3, size=M).astype(np.float32)
+ else:
+ x = (rng.standard_normal((r1 - r0, K)) * (1.0 / np.sqrt(K))).astype(np.float32)
+ if dtype == "BF16":
+ yield bf16_bytes(x)
+ elif dtype == "F16":
+ yield x.astype("<f2").tobytes()
+ else:
+ yield x.astype("<f4").tobytes()
+
+
+def write_shards(out, tensors, n_shards, dtype, seed, index):
+ esize = 4 if dtype == "F32" else 2
+ sizes = [int(np.prod(s)) * esize for _, s in tensors]
+ total = sum(sizes)
+ # contiguous split by bytes, like HF's max_shard_size
+ groups, cur, acc = [[] for _ in range(n_shards)], 0, 0
+ for (name, shape), sz in zip(tensors, sizes):
+ if acc >= total * (cur + 1) / n_shards and cur < n_shards - 1:
+ cur += 1
+ groups[cur].append((name, shape, sz))
+ acc += sz
+ weight_map = {}
+ for i, g in enumerate(groups):
+ fname = "model.safetensors" if n_shards == 1 else f"model-{i + 1:05d}-of-{n_shards:05d}.safetensors"
+ hdr, off = {"__metadata__": {"format": "pt"}}, 0
+ for name, shape, sz in g:
+ hdr[name] = dict(dtype=dtype, shape=list(shape), data_offsets=[off, off + sz])
+ off += sz
+ weight_map[name] = fname
+ hb = json.dumps(hdr, separators=(",", ":")).encode()
+ hb += b" " * ((8 - len(hb) % 8) % 8)
+ with open(os.path.join(out, fname), "wb") as f:
+ f.write(struct.pack("<Q", len(hb)))
+ f.write(hb)
+ for name, shape, _ in g:
+ for chunk in tensor_chunks(name, shape, dtype, seed):
+ f.write(chunk)
+ if n_shards > 1 and index:
+ with open(os.path.join(out, "model.safetensors.index.json"), "w") as f:
+ json.dump(dict(metadata=dict(total_size=total), weight_map=weight_map), f, indent=2, sort_keys=True)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[1])
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--shape", default="tiny", choices=sorted(SHAPES))
+ ap.add_argument("--shards", type=int, default=1)
+ ap.add_argument("--no-index", action="store_true", help="sharded, but no model.safetensors.index.json")
+ ap.add_argument("--lm-head", action="store_true", help="also store lm_head.weight (equal to embed_tokens)")
+ ap.add_argument("--untied", action="store_true", help="tie_word_embeddings false (+ lm_head.weight)")
+ ap.add_argument("--dtype", default="BF16", choices=["BF16", "F16", "F32"])
+ ap.add_argument("--merges", default="string", choices=["string", "list"], help="tokenizer.json merges style")
+ ap.add_argument("--seed", type=int, default=20261129)
+ a = ap.parse_args()
+ sh = SHAPES[a.shape]
+ os.makedirs(a.out, exist_ok=True)
+ cfg = {
+ "architectures": ["Qwen3ForCausalLM"], "attention_bias": False, "attention_dropout": 0.0,
+ "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": sh["head_dim"], "hidden_act": "silu",
+ "hidden_size": sh["dim"], "initializer_range": 0.02, "intermediate_size": sh["hidden"],
+ "max_position_embeddings": 40960, "max_window_layers": sh["layers"], "model_type": "qwen3",
+ "num_attention_heads": sh["heads"], "num_hidden_layers": sh["layers"],
+ "num_key_value_heads": sh["kv_heads"], "rms_norm_eps": 1e-06, "rope_scaling": None,
+ "rope_theta": 1000000, "sliding_window": None, "tie_word_embeddings": not a.untied,
+ "torch_dtype": "bfloat16", "transformers_version": "4.51.0", "use_cache": True,
+ "use_sliding_window": False, "vocab_size": VOCAB_SIZE,
+ }
+ with open(os.path.join(a.out, "config.json"), "w") as f:
+ json.dump(cfg, f, indent=2)
+ with open(os.path.join(a.out, "tokenizer.json"), "w", encoding="utf-8") as f:
+ json.dump(make_tokenizer(a.merges), f, ensure_ascii=False)
+ write_shards(a.out, tensor_list(sh, a.lm_head or a.untied), a.shards, a.dtype, a.seed, not a.no_index)
+ print(f"wrote {a.out} (shape {a.shape}, {a.shards} shard(s), {a.dtype})", file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_export.py b/scripts/test_export.py
new file mode 100644
index 0000000..a37bf77
--- /dev/null
+++ b/scripts/test_export.py
@@ -0,0 +1,259 @@
+#!/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())