okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
10.6 KiB218 linesraw
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3"""tools/ds4/drafter_pack.py - DeepSeek-V4.1's DSpark drafter (the speculative decoder the GGUFs leave out) for a GGUF
4install: its three blocks from DeepSeek's own checkpoint (the shards that hold only them, model-00044..46-of-00048),
5in the formats the GGUF path runs, as one file beside them that pack_gguf.py adds to the pack.
6
7    python tools/ds4/drafter_pack.py --dir <folder with the three shards>     -> dspark.bin + dspark.json there
8
9Every value is kept exactly: the FP8 (E4M3) matrices with their E8M0 scale a 32 x 32 block become BF16 (an E4M3 value
10times a power of two has at most four significant bits); the routed experts (FP4 E2M1 codes two to a byte, the first in
11the low nibble, an E8M0 scale a 32) become ggml's MXFP4 blocks (the scale byte, then value j's code in byte j's low
12nibble and value j + 16's in its high one); BF16 and F32 tensors are copied.  dspark.json lists every tensor (name,
13dtype, offset, bytes, shape) under the checkpoint's names, as tensors.txt does.
14"""
15from __future__ import annotations
16
17import argparse
18import json
19import pathlib
20import re
21import struct
22import sys
23
24import numpy as np
25
26SHARDS = ("model-00044-of-00048.safetensors", "model-00045-of-00048.safetensors", "model-00046-of-00048.safetensors")
27ALIGN = 256
28
29
30def e4m3_table() -> np.ndarray:
31    t = np.zeros(256, np.float32)
32    for c in range(256):
33        s, e, m = c >> 7, (c >> 3) & 15, c & 7
34        v = np.nan if (e == 15 and m == 7) else (m / 8.0) * 2.0 ** -6 if e == 0 else (1 + m / 8.0) * 2.0 ** (e - 7)
35        t[c] = -v if s else v
36    return t
37
38
39E4M3 = e4m3_table()
40
41
42def shard(path: pathlib.Path):
43    raw = np.memmap(path, np.uint8, mode="r")
44    n = struct.unpack("<Q", bytes(raw[:8]))[0]
45    head = json.loads(bytes(raw[8:8 + n]))
46    head.pop("__metadata__", None)
47    return raw, head, 8 + n
48
49
50def data(raw, base: int, e: dict) -> np.ndarray:
51    a, b = e["data_offsets"]
52    return raw[base + a:base + b]
53
54
55def bf16(x: np.ndarray) -> np.ndarray:
56    """float32 -> BF16 bits, rounded to nearest even (exact here)."""
57    u = x.astype(np.float32).view(np.uint32)
58    return ((u + 0x7FFF + ((u >> 16) & 1)) >> 16).astype(np.uint16)
59
60
61def fp8_to_bf16(w: np.ndarray, s: np.ndarray, rows: int, cols: int) -> np.ndarray:
62    w = w.reshape(rows, cols)
63    scale = np.exp2(s.reshape((rows + 31) // 32, (cols + 31) // 32).astype(np.float32) - 127.0)
64    v = E4M3[w] * np.repeat(np.repeat(scale, 32, 0), 32, 1)[:rows, :cols]
65    return bf16(v)
66
67
68def fp4_to_mxfp4(w: np.ndarray, s: np.ndarray, rows: int, k: int) -> np.ndarray:
69    nb = k // 32
70    p = w.reshape(rows, nb, 16)
71    codes = np.empty((rows, nb, 32), np.uint8)
72    codes[..., 0::2] = p & 15
73    codes[..., 1::2] = p >> 4
74    out = np.empty((rows, nb, 17), np.uint8)
75    out[..., 0] = s.reshape(rows, nb)
76    out[..., 1:] = codes[..., :16] | (codes[..., 16:] << 4)
77    return out
78
79
80QTYPES = {"Q8_0": (8, 32, 34), "Q2_K": (10, 256, 84), "Q3_K": (11, 256, 110), "Q4_K": (12, 256, 144),
81          "Q5_K": (13, 256, 176), "Q6_K": (14, 256, 210), "IQ2_XXS": (16, 256, 66), "IQ3_XXS": (18, 256, 98),
82          "IQ3_S": (21, 256, 110), "IQ2_S": (22, 256, 82), "IQ4_XS": (23, 256, 136)}
83DENSE_KEEP = ("markov_head", "confidence_head", "norm", "hc_", "ffn.gate.", "attn_sink")
84E2M1 = np.array([0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12], dtype=np.float32)
85
86
87def requant(d: pathlib.Path, name: str, experts: str, dense: str, lib: str, jobs: int, out=None) -> int:
88    """dspark.bin's tensors again with the routed experts in `experts` and the dense matrices (the ones the engine reads
89    as matrices) in `dense`, through ggml's quantizers (libggml-base): dspark-<name>.bin / .json beside it - a smaller
90    drafter (pack_gguf.py --drafter dspark-<name>)."""
91    import ctypes
92    from concurrent.futures import ThreadPoolExecutor
93    g = ctypes.CDLL(lib)
94    g.ggml_quantize_chunk.restype = ctypes.c_size_t
95    g.ggml_quantize_chunk.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64,
96                                      ctypes.c_int64, ctypes.c_void_p]
97    src = json.loads((d / "dspark.json").read_text())
98    raw = np.memmap(d / "dspark.bin", np.uint8, mode="r")
99
100    def f32(dt, b):
101        if dt == "BF16":
102            return (np.frombuffer(b, np.uint16).astype(np.uint32) << 16).view(np.float32)
103        if dt == "MXFP4":
104            blk = np.frombuffer(b, np.uint8).reshape(-1, 17)
105            v = np.empty((blk.shape[0], 32), np.float32)
106            v[:, :16] = E2M1[blk[:, 1:] & 15]
107            v[:, 16:] = E2M1[blk[:, 1:] >> 4]
108            return (v * np.ldexp(np.float32(1), blk[:, :1].astype(np.int32) - 128)).reshape(-1)
109        raise ValueError(dt)
110
111    def quant(t, x, rows, ne0):   # (one tensor on the calling thread; the pool runs tensors side by side)
112        tid, per, bpb = QTYPES[t]
113        q = np.empty(rows * ne0 // per * bpb, np.uint8)
114        ones = np.ones(ne0, np.float32)
115        g.ggml_quantize_chunk(tid, x.ctypes.data, q.ctypes.data, 0, rows, ne0, ones.ctypes.data)
116        return q
117
118    role_re = re.compile(r"(mtp\.\d+\.ffn\.experts\.)\d+\.(w[123])\.weight$")
119
120    def prep(item):
121        t, dt, so, nb, shape = item
122        b = raw[so:so + nb]
123        m = role_re.match(t)
124        role = (m.group(1), m.group(2)) if m else None
125        want = experts if role else dense
126        if (not role and (dt != "BF16" or len(shape) != 2 or shape[1] % 32 or any(k in t for k in DENSE_KEEP))) \
127                or want in ("keep", dt):
128            return t, dt, np.asarray(b), shape, role
129        if shape[1] % QTYPES[want][1]:
130            raise SystemExit("%s: rows of %d are not whole %s blocks" % (t, shape[1], want))
131        return t, want, quant(want, np.ascontiguousarray(f32(dt, b)), shape[0], shape[1]), shape, role
132
133    for t in {experts, dense} - {"keep"}:
134        g.ggml_quantize_init(QTYPES[t][0])
135    entries, off, prev = [], 0, None
136    o = pathlib.Path(out) if out else d
137    o.mkdir(parents=True, exist_ok=True)
138    items = list(src["tensors"])
139    with (o / ("dspark-%s.bin.part" % name)).open("wb") as f, ThreadPoolExecutor(jobs) as ex:
140        for i0 in range(0, len(items), 2 * jobs):
141            for t, odt, q, shape, role in ex.map(prep, items[i0:i0 + 2 * jobs]):
142                if role is None or role != prev:   # (a role's experts back to back: expert e at the first's + e x size)
143                    pad = (-off) % ALIGN
144                    f.write(b"\0" * pad)
145                    off += pad
146                f.write(q.tobytes())
147                entries.append([t, odt, off, q.nbytes, shape])
148                off += q.nbytes
149                prev = role
150    (o / ("dspark-%s.bin.part" % name)).replace(o / ("dspark-%s.bin" % name))
151    (o / ("dspark-%s.json" % name)).write_text(json.dumps({"from": "dspark.bin", "experts": experts, "dense": dense,
152                                                          "tensors": entries}))
153    print("dspark-%s.bin: %d tensors, %.2f GB (experts %s, dense %s)" % (name, len(entries), off / 1e9, experts, dense))
154    return 0
155
156
157def main() -> int:
158    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
159    ap.add_argument("--dir", required=True, help="the folder with the drafter's three shards")
160    ap.add_argument("--requant", metavar="NAME",
161                    help="from dspark.bin there: dspark-NAME.bin with --experts / --dense types (ggml's quantizers)")
162    ap.add_argument("--experts", default="IQ4_XS", help="(--requant) the routed experts' type, or keep")
163    ap.add_argument("--dense", default="Q8_0", help="(--requant) the dense matrices' type, or keep")
164    ap.add_argument("--lib", default=str(pathlib.Path("~/llama.cpp/build/bin/libggml-base.so").expanduser()),
165                    help="(--requant) libggml-base")
166    ap.add_argument("--jobs", type=int, default=8)
167    ap.add_argument("--out", help="(--requant) the folder to write to (default: --dir)")
168    a = ap.parse_args()
169    d = pathlib.Path(a.dir)
170    if a.requant:
171        return requant(d, a.requant, a.experts, a.dense, a.lib, a.jobs, a.out)
172    entries, off = [], 0
173    exp = re.compile(r"(mtp\.\d+\.ffn\.experts\.)(\d+)\.(w[123])\.weight$")
174
175    def order(head):
176        """The block's tensors, then each role's experts (w1, w3, w2) back to back in expert order - the engine reads
177        expert e of a role at the first one's offset + e x its size, as the GGUF stacks them."""
178        plain = sorted(t for t in head if t.startswith("mtp.") and not t.endswith(".scale") and not exp.match(t))
179        ex = [exp.match(t) for t in head if exp.match(t)]
180        roles = sorted({(m.group(1), m.group(3)) for m in ex}, key=lambda pr: (pr[0], "w1w3w2".index(pr[1])))
181        n = {pr: 1 + max(int(m.group(2)) for m in ex if (m.group(1), m.group(3)) == pr) for pr in roles}
182        return [(t, False) for t in plain] + [("%s%d.%s.weight" % (p, i, r), i < n[(p, r)] - 1)
183                                              for p, r in roles for i in range(n[(p, r)])]
184
185    with (d / "dspark.bin.part").open("wb") as f:
186        for name in SHARDS:
187            raw, head, base = shard(d / name)
188            for t, packed in order(head):
189                e, shape = head[t], list(head[t]["shape"])
190                if e["dtype"] == "F8_E4M3":
191                    s = head[t[:-len("weight")] + "scale"]
192                    out, dt = fp8_to_bf16(data(raw, base, e), data(raw, base, s), shape[0], shape[1]), "BF16"
193                elif e["dtype"] == "I8":
194                    s = head[t[:-len("weight")] + "scale"]
195                    shape = [shape[0], shape[1] * 2]
196                    out, dt = fp4_to_mxfp4(data(raw, base, e), data(raw, base, s), shape[0], shape[1]), "MXFP4"
197                elif e["dtype"] in ("BF16", "F32"):
198                    out, dt = data(raw, base, e), e["dtype"]
199                else:
200                    raise SystemExit(f"{name}: {t} is {e['dtype']}, not a type the drafter's pack covers")
201                b = out.tobytes()
202                f.write(b)
203                entries.append([t, dt, off, len(b), shape])
204                off += len(b)
205                if packed:   # (the next expert of the role follows at once)
206                    continue
207                pad = (-off) % ALIGN
208                f.write(b"\0" * pad)
209                off += pad
210            del raw
211    (d / "dspark.bin.part").replace(d / "dspark.bin")
212    (d / "dspark.json").write_text(json.dumps({"from": list(SHARDS), "tensors": entries}))
213    print(f"dspark.bin: {len(entries)} tensors, {off / 1e9:.2f} GB")
214    return 0
215
216
217if __name__ == "__main__":
218    sys.exit(main())