okami.mom/strata

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

Niko1221Merge branch 'f-132-pr' into rel-0.1.32b0abdeb44

main
5.2 KiB123 linesraw
1"""tools/ple_fp8_pack.py - the PLE n-gram table exactly as Qwen shipped it (FP8 E4M3), as a GGUF the engine reads.
2
3    python tools/ple_fp8_pack.py --model <checkpoint dir> --out <ple-fp8.gguf>
4
5Qwen3.8-Flash-Next's checkpoint stores the table as 128 shards `...ngram_embedding.shard_{k}.weight` of
6[2500012, 160] F8_E4M3 with one BF16 `weight_scale`: 320,001,536 rows of 160 values, 51.2 GB. The engine used to take
7it from ISTA-DASLab's GGUF as IQ4_NL (90 B/row), which is 8% off these values per row; this keeps them bit for bit.
8
9The output is a one-tensor GGUF: `per_layer_token_embd.weight`, ne = [160, 320001536], type I8 holding the FP8 bytes
10(GGUF has no FP8 type), with `strata.ple.format` = "f8_e4m3" and `strata.ple.scale` (F32). The bytes are copied
11straight out of the safetensors files in shard order - nothing is decoded or rounded - so memory stays flat.
12"""
13import argparse
14import json
15import pathlib
16import struct
17import sys
18
19GGUF_TYPE_STRING, GGUF_TYPE_F32 = 8, 6
20GGML_TYPE_I8 = 24
21ALIGN = 32
22CHUNK = 64 << 20
23
24
25def safetensors_header(path):
26    with open(path, "rb") as f:
27        n = struct.unpack("<Q", f.read(8))[0]
28        return json.loads(f.read(n)), 8 + n
29
30
31def gguf_string(s):
32    b = s.encode("utf-8")
33    return struct.pack("<Q", len(b)) + b
34
35
36def kv_string(key, val):
37    return gguf_string(key) + struct.pack("<I", GGUF_TYPE_STRING) + gguf_string(val)
38
39
40def kv_f32(key, val):
41    return gguf_string(key) + struct.pack("<I", GGUF_TYPE_F32) + struct.pack("<f", val)
42
43
44def main():
45    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
46    ap.add_argument("--model", required=True, help="the checkpoint directory (model.safetensors.index.json)")
47    ap.add_argument("--out", required=True)
48    a = ap.parse_args()
49    model, out = pathlib.Path(a.model), pathlib.Path(a.out)
50    wmap = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]
51
52    shards = {}
53    scale_name = None
54    for name in wmap:
55        if ".ngram_embedding.shard_" in name and name.endswith(".weight"):
56            shards[int(name.rsplit(".shard_", 1)[1].split(".")[0])] = name
57        elif name.endswith(".ngram_embedding.weight_scale"):
58            scale_name = name
59    if not shards or scale_name is None:
60        sys.exit("no ngram_embedding shards / weight_scale in " + str(model))
61    if sorted(shards) != list(range(len(shards))):
62        sys.exit("the n-gram shards are not numbered 0..%d without gaps" % (len(shards) - 1))
63
64    hdr, base = safetensors_header(model / wmap[scale_name])
65    t = hdr[scale_name]
66    if t["dtype"] != "BF16" or t["shape"] not in ([1], []):
67        sys.exit("unexpected weight_scale: %s %s" % (t["dtype"], t["shape"]))
68    with open(model / wmap[scale_name], "rb") as f:
69        f.seek(base + t["data_offsets"][0])
70        (bits,) = struct.unpack("<H", f.read(2))
71    scale = struct.unpack("<f", struct.pack("<I", bits << 16))[0]
72
73    parts, rows, dim = [], 0, None
74    for k in range(len(shards)):
75        name = shards[k]
76        hdr, base = safetensors_header(model / wmap[name])
77        t = hdr[name]
78        if t["dtype"] != "F8_E4M3" or len(t["shape"]) != 2:
79            sys.exit("%s is %s %s, not a 2-D F8_E4M3 tensor" % (name, t["dtype"], t["shape"]))
80        if dim is None:
81            dim = t["shape"][1]
82        if t["shape"][1] != dim or t["data_offsets"][1] - t["data_offsets"][0] != t["shape"][0] * dim:
83            sys.exit("%s: inconsistent shape %s" % (name, t["shape"]))
84        parts.append((model / wmap[name], base + t["data_offsets"][0], t["shape"][0] * dim))
85        rows += t["shape"][0]
86    print("%d shards, %d rows x %d, scale %.9g, %.2f GB" % (len(parts), rows, dim, scale, rows * dim / 1e9), flush=True)
87
88    kvs = [kv_string("general.architecture", "strata-ple"),
89           kv_string("general.name", "PLE n-gram table, FP8 E4M3 as shipped"),
90           kv_string("strata.ple.format", "f8_e4m3"),
91           kv_f32("strata.ple.scale", scale),
92           kv_string("strata.ple.source", model.name)]
93    head = b"GGUF" + struct.pack("<IQQ", 3, 1, len(kvs)) + b"".join(kvs)
94    head += gguf_string("per_layer_token_embd.weight") + struct.pack("<I", 2) + struct.pack("<QQ", dim, rows)
95    head += struct.pack("<I", GGML_TYPE_I8) + struct.pack("<Q", 0)
96    head += b"\0" * ((-len(head)) % ALIGN)
97
98    out.parent.mkdir(parents=True, exist_ok=True)
99    tmp = out.with_suffix(out.suffix + ".part")
100    written = 0
101    with open(tmp, "wb") as w:
102        w.write(head)
103        for i, (path, off, n) in enumerate(parts):
104            with open(path, "rb") as f:
105                f.seek(off)
106                left = n
107                while left:
108                    b = f.read(min(CHUNK, left))
109                    if not b:
110                        sys.exit("short read in " + str(path))
111                    w.write(b)
112                    left -= len(b)
113            written += n
114            if i % 16 == 15 or i == len(parts) - 1:
115                print("  %3d/%d shards, %.1f GB" % (i + 1, len(parts), written / 1e9), flush=True)
116    if tmp.stat().st_size != len(head) + rows * dim:
117        sys.exit("size check failed: %d != %d" % (tmp.stat().st_size, len(head) + rows * dim))
118    tmp.replace(out)
119    print("wrote %s (%d rows x %d FP8, header %d B)" % (out, rows, dim, len(head)))
120
121
122if __name__ == "__main__":
123    main()