File size: 3,261 Bytes
ebf8f81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Pack a trained checkpoint into one small file the browser can load.

python export.py ckpt.pt data/tok4096.json web/storyteller.bin

Each weight matrix is stored as small whole numbers plus one float "scale" per row:
  - the word-piece table (emb.weight) with 8 bits per number
  - every other matrix with 6 bits per number
That is about 5x smaller than the float32 checkpoint. quant_eval.py measures what this
costs in quality (almost nothing). Tiny norm weights stay float32.

File layout:  b"STRY" | uint32 header_len | JSON header | tensor data
Also writes <name>.wasm: the same bytes wrapped as a WebAssembly custom section, for web
hosts that refuse unknown file types but do serve .wasm.
"""
import argparse, json, struct, numpy as np, torch
from tokenizer import Tokenizer

p = argparse.ArgumentParser()
p.add_argument("ckpt"); p.add_argument("tok"); p.add_argument("out")
p.add_argument("--emb-bits", type=int, default=8)
p.add_argument("--body-bits", type=int, default=6)
p.add_argument("--val-loss", type=float, default=None, help="recorded in the file header, for reference")
a = p.parse_args()

ck = torch.load(a.ckpt, map_location="cpu")
sd, cfg = ck["model"], ck["config"]
tok = Tokenizer.load(a.tok)


def pack(w, bits):
    """Rows of floats -> (per-row scales, bit-packed integers). Value i sits at bits [i*bits, (i+1)*bits)."""
    q = 2 ** (bits - 1) - 1
    scale = np.abs(w).max(1, keepdims=True) / q + 1e-12
    ints = np.clip(np.round(w / scale), -q, q).astype(np.int16)
    if bits == 8:
        data = ints.astype(np.int8).tobytes()
    else:
        u = (ints + q).astype(np.uint8).reshape(-1, 1)
        data = np.packbits(np.unpackbits(u, axis=1, bitorder="little")[:, :bits].reshape(-1), bitorder="little").tobytes()
    return scale.astype(np.float32).tobytes() + data


tensors, blobs, off = [], [], 0
for name, t in sd.items():
    w = t.float().numpy()
    if w.ndim == 2:
        bits = a.emb_bits if name == "emb.weight" else a.body_bits
        data = pack(w, bits)
        entry = {"name": name, "shape": list(w.shape), "kind": "q", "bits": bits, "offset": off}
    else:
        data = w.astype(np.float32).tobytes()
        entry = {"name": name, "shape": list(w.shape), "kind": "f32", "offset": off}
    data += b"\0" * ((-len(data)) % 4)
    tensors.append(entry); blobs.append(data); off += len(data)

info = {"steps": ck["step"], "train_minutes": round(ck.get("seconds", 0) / 60), "val_loss": a.val_loss,
        "data": "TinyStories (Eldan & Li, 2023)"}
header = json.dumps({"config": cfg, "info": info, "merges": tok.merges, "tensors": tensors},
                    separators=(",", ":")).encode()
header += b" " * ((-(8 + len(header))) % 4)
payload = b"STRY" + struct.pack("<I", len(header)) + header + b"".join(blobs)
open(a.out, "wb").write(payload)


def leb(n):
    out = b""
    while True:
        b, n = n & 127, n >> 7
        out += bytes([b | (128 if n else 0)])
        if not n:
            return out


name = b"stry"
section = leb(len(name)) + name + payload
wasm_path = a.out.rsplit(".", 1)[0] + ".wasm"
open(wasm_path, "wb").write(b"\0asm" + struct.pack("<I", 1) + b"\0" + leb(len(section)) + section)
print(f"wrote {a.out}: {len(payload)/1e6:.2f} MB ({len(payload):,} bytes), and {wasm_path}")