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
"""Merge sharded .safetensors files into one file.
scripts/export_weights.py reads a single model.safetensors. Qwen3-1.7B and
larger ship as several shards, so merge them first:
python3 scripts/merge_safetensors.py OUT.safetensors SHARD1 SHARD2 ...
Tensors are copied byte-for-byte in chunks (low RAM); the header is rebuilt with
fresh data offsets.
"""
import json
import struct
import sys
CHUNK = 1 << 24
def main() -> int:
if len(sys.argv) < 3:
print(__doc__, file=sys.stderr)
return 2
out_path, shards = sys.argv[1], sys.argv[2:]
tensors = [] # (name, meta, shard_path, shard_data_base)
for path in shards:
with open(path, "rb") as f:
(n,) = struct.unpack("<Q", f.read(8))
header = json.loads(f.read(n))
for name, meta in header.items():
if name != "__metadata__":
tensors.append((name, meta, path, 8 + n))
out_header, off = {}, 0
for name, meta, _, _ in tensors:
start, end = meta["data_offsets"]
out_header[name] = {
"dtype": meta["dtype"],
"shape": meta["shape"],
"data_offsets": [off, off + end - start],
}
off += end - start
hb = json.dumps(out_header).encode()
hb += b" " * ((8 - len(hb) % 8) % 8)
with open(out_path, "wb") as out:
out.write(struct.pack("<Q", len(hb)))
out.write(hb)
for _, meta, path, base in tensors:
start, end = meta["data_offsets"]
with open(path, "rb") as f:
f.seek(base + start)
left = end - start
while left:
buf = f.read(min(left, CHUNK))
if not buf:
raise EOFError(f"truncated shard: {path}")
out.write(buf)
left -= len(buf)
print(f"merged {len(tensors)} tensors, {off} bytes -> {out_path}")
return 0
if __name__ == "__main__":
sys.exit(main())