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.
#!/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()