okami.mom/strata

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

Niko1221rc1 merge df2-q4sel (ebac5686f, incl. df2-comm select kernel)f93c5019f

main
13.4 KiB269 linesraw
1#!/usr/bin/env python3
2"""Pack the incoai DFlash2 drafter for Qwen3.8-Flash-Next (safetensors) into the engine's runtime file.
3
4    python tools/dflash2_pack.py model.safetensors config.json out.pack [--q4_0] [--q4_0-selector]
5    python tools/dflash2_pack.py --convert-selector in.pack out.pack      (a finished Q4_0 pack: its bf16 selector codebooks become Q4_0, nothing else changes)
6
7Format (little endian): "DF2P", u32 version (1), u32 index_len, a text index (padded with spaces so the data starts on a 4096 multiple), then
8the tensors, each 256-byte aligned at its offset (from the end of the index).  Index lines: "cfg <key> <value>", "t <name> <dtype> <rows>
9<cols> <offset> <bytes>" (a matrix [out][in] is rows x cols; a vector or codebook row set is the leading dims folded into rows), "end".
10dtypes: "q8_0" (ggml Q8_0 blocks, 34 bytes per 32 values, rows of the weight matrix [out][in] one after the other: what the engine's
11multi-column MMVQ reads), "f32" (norms, the two conv base kernels), "q4_0" (--q4_0: ggml Q4_0 blocks, 18 bytes per 32 values, the matrices only; the engine tiles them like Q8_0, see gemm4_kernel in
12src/kernels/cuda/dflash2.cu), "bf16" (the selector's two codebooks: only gathered rows are read; with --q4_0-selector they are "q4_0" rows in block order, not tiled).
13The matrices' quantization matches ggml's quantize_row_q8_0 (d = amax / 127, q = round(x / d), d stored as fp16); the research harness
14(tools/dflash2/q8test.py) measured no acceptance loss from it.
15"""
16import json
17import struct
18import sys
19
20import numpy as np
21
22
23class SafeTensors:
24    """A .safetensors file read with numpy alone (no torch, no safetensors package: this runs on the person's PC, where neither is
25    installed). The format is a little-endian u64 header length, a JSON header {name: {dtype, shape, data_offsets}}, then the raw data."""
26
27    def __init__(self, path):
28        self.path = path
29        with open(path, "rb") as fh:
30            (n,) = struct.unpack("<Q", fh.read(8))
31            if n > (64 << 20):
32                raise ValueError("not a safetensors file (header too large)")
33            self.header = json.loads(fh.read(n))
34        self.base = 8 + n
35        self.header.pop("__metadata__", None)
36
37    def raw(self, name):
38        """-> (dtype string, shape, uint8 memmap of the tensor's bytes)"""
39        info = self.header[name]
40        lo, hi = info["data_offsets"]
41        return info["dtype"], info["shape"], np.memmap(self.path, dtype=np.uint8, mode="r", offset=self.base + lo, shape=(hi - lo,))
42
43    def get_float32(self, name):
44        """-> float32 ndarray (bf16 and f16 tensors are widened exactly)"""
45        dtype, shape, data = self.raw(name)
46        if dtype == "BF16":
47            return (np.frombuffer(data, dtype=np.uint16).astype(np.uint32) << 16).view(np.float32).reshape(shape)
48        if dtype == "F16":
49            return np.frombuffer(data, dtype=np.float16).astype(np.float32).reshape(shape)
50        if dtype == "F32":
51            return np.frombuffer(data, dtype=np.float32).reshape(shape).copy()
52        raise ValueError("%s: unsupported dtype %s" % (name, dtype))
53
54    def get_bf16_bits(self, name):
55        dtype, shape, data = self.raw(name)
56        if dtype != "BF16":
57            raise ValueError("%s: expected BF16, found %s" % (name, dtype))
58        return np.frombuffer(data, dtype=np.uint16).reshape(shape).copy()
59
60
61def load_tensor(f, name):
62    """-> float32 ndarray (bf16 tensors are widened exactly)"""
63    return f.get_float32(name)
64
65
66def raw_bf16(f, name):
67    return np.ascontiguousarray(f.get_bf16_bits(name))
68
69
70def quant_q8_0(w):
71    """w: float32 [rows, cols], cols % 32 == 0 -> bytes of rows * cols/32 blocks (fp16 d, 32 int8)"""
72    rows, cols = w.shape
73    assert cols % 32 == 0
74    b = w.reshape(rows, cols // 32, 32)
75    amax = np.abs(b).max(axis=-1)
76    d = amax / 127.0
77    inv = np.where(d != 0, 1.0 / np.where(d == 0, 1, d), 0.0)
78    q = np.rint(b * inv[..., None]).astype(np.int8)       # round half to even; ggml uses roundf (ties are measure-zero for these weights)
79    out = np.empty((rows, cols // 32, 34), np.uint8)
80    out[..., :2] = d.astype(np.float16).view(np.uint8).reshape(rows, cols // 32, 2)
81    out[..., 2:] = q.view(np.uint8)
82    return out.tobytes()
83
84
85def quant_q4_0(w):
86    """w: float32 [rows, cols], cols % 32 == 0 -> bytes of rows * cols/32 ggml Q4_0 blocks (fp16 d, 16 bytes: value i in the low nibble of byte i, value i + 16 in the high
87    nibble).  ggml's quantize_row_q4_0_ref: d = (the value of largest magnitude) / -8, q = min(15, int(x / d + 8.5)); the scale is stored as fp16, q uses the float d."""
88    rows, cols = w.shape
89    assert cols % 32 == 0
90    b = w.reshape(rows, cols // 32, 32).astype(np.float32)
91    idx = np.abs(b).argmax(axis=-1)
92    mx = np.take_along_axis(b, idx[..., None], axis=-1)[..., 0]
93    d = mx / np.float32(-8.0)
94    inv = np.where(d != 0, 1.0 / np.where(d == 0, 1, d), 0.0).astype(np.float32)
95    q = np.minimum(15, (b * inv[..., None] + np.float32(8.5)).astype(np.int32)).astype(np.uint8)
96    out = np.empty((rows, cols // 32, 18), np.uint8)
97    out[..., :2] = d.astype(np.float16).view(np.uint8).reshape(rows, cols // 32, 2)
98    out[..., 2:] = q[..., :16] | (q[..., 16:] << 4)
99    return out.tobytes()
100
101
102def pack(st_path, cfg_path, out_path, say=print, q4=False, q4_selector=False):
103    """Write the engine's runtime file for the drafter in `st_path` (+ its config.json). Returns the number of bytes written."""
104    with open(cfg_path, encoding="utf-8") as fh:
105        cfg = json.load(fh)
106    dc = cfg["dflash_config"]
107    f = SafeTensors(st_path)
108    tensors = []
109    blobs = []
110
111    def add(name, dtype, shape, data):
112        tensors.append({"name": name, "dtype": dtype, "shape": list(shape), "bytes": len(data)})
113        blobs.append(data)
114
115    def mat(name, new=None):
116        w = load_tensor(f, name)
117        assert w.ndim == 2
118        if q4:
119            add(new or name, "q4_0", w.shape, quant_q4_0(w))
120        else:
121            add(new or name, "q8_0", w.shape, quant_q8_0(w))
122
123    def vec(name, new=None):
124        w = load_tensor(f, name)
125        add(new or name, "f32", w.shape, np.ascontiguousarray(w, np.float32).tobytes())
126
127    L = cfg["num_hidden_layers"]
128    mat("fc.weight")
129    vec("hidden_norm.weight")
130    vec("norm.weight")
131    for l in range(L):
132        p = "layers.%d." % l
133        for n in ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "mlp.gate_proj", "mlp.up_proj",
134                  "mlp.down_proj", "attention_conv.kernel_projection", "mlp_conv.kernel_projection"):
135            mat(p + n + ".weight")
136        for n in ("input_layernorm", "post_attention_layernorm", "self_attn.q_norm", "self_attn.k_norm"):
137            vec(p + n + ".weight")
138        vec(p + "attention_conv.base_kernel")
139        vec(p + "mlp_conv.base_kernel")
140    mat("candidate_selector.hidden_projection.weight")
141    for n in ("predecessor_codebook", "successor_codebook"):
142        if q4_selector:   # --q4_0-selector: ggml Q4_0 rows in block order (NOT tiled): 8 blocks of 18 bytes a row of 256, the community GGUF's selector_* bytes
143            w = load_tensor(f, "candidate_selector." + n)
144            add("candidate_selector." + n, "q4_0", w.shape, quant_q4_0(w))
145            continue
146        a = raw_bf16(f, "candidate_selector." + n)
147        add("candidate_selector." + n, "bf16", a.shape, a.tobytes())
148
149    meta = {
150        "hidden": cfg["hidden_size"], "layers": L, "heads": cfg["num_attention_heads"], "kv_heads": cfg["num_key_value_heads"],
151        "head_dim": cfg["head_dim"], "inter": cfg["intermediate_size"], "window": cfg["sliding_window"], "rope_theta": cfg["rope_parameters"]["rope_theta"],
152        "eps": cfg["rms_norm_eps"], "block": dc["block_size"], "conv_group": dc["conv_group_size"], "conv_kernel": dc["conv_kernel_size"],
153        "mask_token": dc["mask_token_id"], "rank": dc["selector_rank"], "top_k": dc["selector_top_k"], "taps": dc["target_layer_ids"],
154        "vocab": cfg["vocab_size"], "source": "incoai/Qwen3.8-Flash-Next-DFlash2 a22a1744",
155    }
156    # offsets: relative to the end of the (padded) index; 256-byte aligned
157    off = 0
158    for t in tensors:
159        off = (off + 255) & ~255
160        t["offset"] = off
161        off += t["bytes"]
162    lines = []
163    for k, v in meta.items():
164        if k == "taps":
165            v = ",".join(str(x) for x in v)
166        lines.append("cfg %s %s" % (k, str(v).replace(" ", "_")))
167    for t in tensors:
168        sh = t["shape"] + [1] * (2 - len(t["shape"])) if len(t["shape"]) < 2 else t["shape"]
169        lines.append("t %s %s %d %d %d %d" % (t["name"], t["dtype"], int(np.prod(sh[:-1])), sh[-1], t["offset"], t["bytes"]))
170    lines.append("end")
171    js = ("\n".join(lines) + "\n").encode()
172    js += b" " * ((-(len(js) + 12)) % 4096)
173    with open(out_path, "wb") as o:
174        o.write(b"DF2P" + struct.pack("<II", 1, len(js)) + js)
175        base = o.tell()
176        for t, b in zip(tensors, blobs):
177            o.seek(base + t["offset"])
178            o.write(b)
179    say("wrote %s: %d tensors, %.1f MB" % (out_path, len(tensors), (base + off) / 1e6))
180    return base + off
181
182
183def convert_selector_q4(src_path, dst_path, say=print, rows_per_step=16384):
184    """Rewrite a finished DF2P pack with the selector's two codebooks as Q4_0 rows: every other tensor's bytes are carried over unchanged, the two bf16 codebooks
185    (tensors `candidate_selector.predecessor_codebook` / `successor_codebook`, [vocab x 256]) are widened exactly to float32 and quantized by quant_q4_0, which is
186    ggml's quantize_row_q4_0_ref.  The result is byte-identical to `pack(..., q4=True, q4_selector=True)` from the same safetensors file (and the codebooks are the
187    bytes of the community GGUF nazeshinjite/Qwen3.8-Flash-Next-DFlash2-GGUF, selector_predecessor / selector_successor).  Memory stays under ~300 MB: the codebooks go
188    through `rows_per_step` rows at a time.  Returns the size written.  Needs only numpy, no network."""
189    with open(src_path, "rb") as fh:
190        if fh.read(4) != b"DF2P":
191            raise ValueError("not a DF2P pack")
192        version, index_len = struct.unpack("<II", fh.read(8))
193        if version != 1:
194            raise ValueError("unknown DF2P version %d" % version)
195        index = fh.read(index_len).decode()
196        base = 12 + index_len
197        cfg_lines, tensors = [], []
198        for line in index.split("\n"):
199            w = line.split()
200            if not w or w[0] == "end":
201                continue
202            if w[0] == "cfg":
203                cfg_lines.append(line)
204            elif w[0] == "t":
205                tensors.append({"name": w[1], "dtype": w[2], "rows": int(w[3]), "cols": int(w[4]), "offset": int(w[5]), "bytes": int(w[6])})
206        books = ("candidate_selector.predecessor_codebook", "candidate_selector.successor_codebook")
207        for t in tensors:
208            if t["name"] in books:
209                if t["dtype"] != "bf16":
210                    raise ValueError("%s is already %s" % (t["name"], t["dtype"]))
211                if t["cols"] % 32:
212                    raise ValueError("%s: %d columns" % (t["name"], t["cols"]))
213        off = 0
214        for t in tensors:
215            if t["name"] in books:
216                t["new_bytes"] = t["rows"] * (t["cols"] // 32) * 18
217                t["new_dtype"] = "q4_0"
218            else:
219                t["new_bytes"], t["new_dtype"] = t["bytes"], t["dtype"]
220            off = (off + 255) & ~255
221            t["new_offset"] = off
222            off += t["new_bytes"]
223        lines = list(cfg_lines)
224        for t in tensors:
225            lines.append("t %s %s %d %d %d %d" % (t["name"], t["new_dtype"], t["rows"], t["cols"], t["new_offset"], t["new_bytes"]))
226        lines.append("end")
227        js = ("\n".join(lines) + "\n").encode()
228        js += b" " * ((-(len(js) + 12)) % 4096)
229        with open(dst_path, "wb") as out:
230            out.write(b"DF2P" + struct.pack("<II", 1, len(js)) + js)
231            new_base = out.tell()
232            for t in tensors:
233                out.seek(new_base + t["new_offset"])
234                fh.seek(base + t["offset"])
235                if t["name"] not in books:
236                    left = t["bytes"]
237                    while left:
238                        block = fh.read(min(left, 1 << 24))
239                        if not block:
240                            raise ValueError("%s: the pack is shorter than its index" % t["name"])
241                        out.write(block)
242                        left -= len(block)
243                    continue
244                for r0 in range(0, t["rows"], rows_per_step):
245                    n = min(rows_per_step, t["rows"] - r0)
246                    raw = np.frombuffer(fh.read(n * t["cols"] * 2), dtype=np.uint16)
247                    if raw.size != n * t["cols"]:
248                        raise ValueError("%s: the pack is shorter than its index" % t["name"])
249                    w = (raw.astype(np.uint32) << 16).view(np.float32).reshape(n, t["cols"])
250                    out.write(quant_q4_0(w))
251            out.seek(new_base + off)        # the last tensor ends the file (the pack writer's size is base + off too)
252            out.truncate(new_base + off)
253    say("wrote %s: %d tensors, %.1f MB" % (dst_path, len(tensors), (new_base + off) / 1e6))
254    return new_base + off
255
256
257def main():
258    if len(sys.argv) == 4 and sys.argv[1] == "--convert-selector":
259        convert_selector_q4(sys.argv[2], sys.argv[3])
260        return
261    flags = ("--q4_0", "--q4_0-selector")
262    args = [a for a in sys.argv[1:] if a not in flags]
263    if len(args) < 3:
264        sys.exit(__doc__)
265    pack(*args[:3], q4="--q4_0" in sys.argv[1:] or "--q4_0-selector" in sys.argv[1:], q4_selector="--q4_0-selector" in sys.argv[1:])
266
267
268if __name__ == "__main__":
269    main()