okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
5.8 KiB139 linesraw
1"""tools/embd_bf16_pack.py - the token embedding exactly as the checkpoint ships it (BF16), as a GGUF the engine reads.
2
3    python tools/embd_bf16_pack.py --model <checkpoint dir> --out <token-embd-bf16.gguf>
4
5nvfp4_convert.py stores token_embd as Q8_0 (0.56% off per value). The engine keeps the table in mapped host memory
6and reads one row per token, so BF16 costs 0.6 GB of RAM more and no VRAM; `--embd-gguf` takes it from this file.
7
8The output is a one-tensor GGUF: `token_embd.weight`, ne = [n_embd, n_vocab], type BF16, the bytes copied straight
9out of the safetensors file - nothing decoded or rounded.
10
11    python tools/embd_bf16_pack.py --gguf <model.gguf> --out <token-embd-bf16.gguf>
12
13instead dequantizes a GGUF's own token_embd.weight to BF16 (round-to-nearest-even, tools/strata_quants.py), for a file whose
14embedding type has no GPU dequantizer in the engine (Agention's Gyro-S stores it as Q6_K).  That is the GGUF's values
15rounded to BF16, not the checkpoint's.
16"""
17import argparse
18import json
19import pathlib
20import struct
21import sys
22
23GGUF_TYPE_STRING = 8
24GGML_TYPE_BF16 = 30
25ALIGN = 32
26CHUNK = 64 << 20
27
28
29def safetensors_header(path):
30    with open(path, "rb") as f:
31        n = struct.unpack("<Q", f.read(8))[0]
32        return json.loads(f.read(n)), 8 + n
33
34
35def gguf_string(s):
36    b = s.encode("utf-8")
37    return struct.pack("<Q", len(b)) + b
38
39
40def kv_string(key, val):
41    return gguf_string(key) + struct.pack("<I", GGUF_TYPE_STRING) + gguf_string(val)
42
43
44def write_header(dim, vocab, source, what):
45    kvs = [kv_string("general.architecture", "strata-embd"),
46           kv_string("general.name", what),
47           kv_string("strata.embd.source", source)]
48    head = b"GGUF" + struct.pack("<IQQ", 3, 1, len(kvs)) + b"".join(kvs)
49    head += gguf_string("token_embd.weight") + struct.pack("<I", 2) + struct.pack("<QQ", dim, vocab)
50    head += struct.pack("<I", GGML_TYPE_BF16) + struct.pack("<Q", 0)
51    head += b"\0" * ((-len(head)) % ALIGN)
52    return head
53
54
55def from_gguf(src, out):
56    """token_embd.weight of a GGUF, dequantized and rounded to BF16 (nearest-even), in row chunks."""
57    import numpy as np
58    sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
59    import gguf_reader as G
60    from _paths import gguf_lib
61    gguf = gguf_lib()
62    Q, quants = gguf.GGMLQuantizationType, gguf.quants
63    g = G.GGUFFile(src)
64    t = next((t for t in g.tensors if t.name == "token_embd.weight"), None)
65    if t is None or len(t.shape) != 2 or t.expected_bytes() is None:
66        sys.exit("%s: no 2-D token_embd.weight of a known type" % src)
67    dim, vocab = int(t.shape[0]), int(t.shape[1])
68    row = t.expected_bytes() // vocab
69    mm = np.memmap(src, dtype=np.uint8, mode="r")
70    base = g.data_start + t.offset
71    print("token_embd.weight: %d x %d %s -> BF16, %.2f GB" % (vocab, dim, t.type_name, vocab * dim * 2 / 1e9), flush=True)
72    head = write_header(dim, vocab, src.name, "token embedding, %s dequantized to BF16" % t.type_name)
73    out.parent.mkdir(parents=True, exist_ok=True)
74    tmp = out.with_suffix(out.suffix + ".part")
75    rows = 8192
76    with open(tmp, "wb") as w:
77        w.write(head)
78        for r0 in range(0, vocab, rows):
79            r1 = min(vocab, r0 + rows)
80            raw = np.asarray(mm[base + r0 * row: base + r1 * row]).reshape(r1 - r0, row)
81            vals = quants.dequantize(raw, Q[t.type_name]).astype(np.float32)
82            if not np.isfinite(vals).all():
83                sys.exit("token_embd.weight has non-finite values")
84            w.write(quants.quantize(vals, Q.BF16).tobytes())
85    if tmp.stat().st_size != len(head) + vocab * dim * 2:
86        sys.exit("size check failed")
87    tmp.replace(out)
88    print("wrote %s (header %d B)" % (out, len(head)))
89
90
91def main():
92    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
93    src = ap.add_mutually_exclusive_group(required=True)
94    src.add_argument("--model", help="the checkpoint directory (model.safetensors.index.json)")
95    src.add_argument("--gguf", help="a model GGUF whose token_embd.weight is dequantized to BF16")
96    ap.add_argument("--out", required=True)
97    a = ap.parse_args()
98    if a.gguf:
99        from_gguf(pathlib.Path(a.gguf).absolute(), pathlib.Path(a.out))
100        return
101    model, out = pathlib.Path(a.model), pathlib.Path(a.out)
102    wmap = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
103
104    names = [n for n in wmap if n.endswith("embed_tokens.weight") and "visual" not in n and "mtp" not in n]
105    if len(names) != 1:
106        sys.exit("expected one text embed_tokens.weight in %s, found %s" % (model, names))
107    name = names[0]
108    hdr, base = safetensors_header(model / wmap[name])
109    t = hdr[name]
110    if t["dtype"] != "BF16" or len(t["shape"]) != 2:
111        sys.exit("%s is %s %s, not a 2-D BF16 tensor" % (name, t["dtype"], t["shape"]))
112    vocab, dim = t["shape"]
113    n = vocab * dim * 2
114    if t["data_offsets"][1] - t["data_offsets"][0] != n:
115        sys.exit("%s: data size does not match its shape" % name)
116    print("%s: %d x %d BF16, %.2f GB" % (name, vocab, dim, n / 1e9), flush=True)
117
118    head = write_header(dim, vocab, model.name, "token embedding, BF16 as shipped")
119
120    out.parent.mkdir(parents=True, exist_ok=True)
121    tmp = out.with_suffix(out.suffix + ".part")
122    with open(tmp, "wb") as w, open(model / wmap[name], "rb") as f:
123        w.write(head)
124        f.seek(base + t["data_offsets"][0])
125        left = n
126        while left:
127            b = f.read(min(CHUNK, left))
128            if not b:
129                sys.exit("short read in " + str(model / wmap[name]))
130            w.write(b)
131            left -= len(b)
132    if tmp.stat().st_size != len(head) + n:
133        sys.exit("size check failed: %d != %d" % (tmp.stat().st_size, len(head) + n))
134    tmp.replace(out)
135    print("wrote %s (header %d B)" % (out, len(head)))
136
137
138if __name__ == "__main__":
139    main()