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
17.4 KiB389 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/dspark_ref.py - DeepSeek-V4.1's DSpark drafter in torch, straight from DeepSeek's checkpoint, against what
4the engine's drafter computed (the engine's oracle for the drafter; ref.py / ref_gguf.py cover the trunk only).
5
6    DS4_DSPARK_DUMP=d.bin maya-ds4 --pack <pack> ... --n 64        (the engine: its drafter's inputs and outputs)
7    python tools/ds4/dspark_ref.py --dump d.bin --shards <dir with model-00044..46-of-00048> --pack <pack>
8                                   [--rounds 4] [--head]
9
10It follows DeepSeek's inference/model.py (MIT) - DSparkBlock / DSparkAttention / forward_spec: the taps of target
11layers 37..39 (the streams' mean entering them) through main_proj / main_norm into every block's window ring (wkv,
12kv_norm, rope, FP8 rounding), the block [y, noise x 4] at the positions after the ring's through the three blocks
13(Hyper-Connections, window attention over the ring and the whole block, the 128-expert MoE with 3 picks), the final
14collapse and, with --head, the trunk's head plus the markov bias (the drafts) - with every weight decoded here from
15the checkpoint's own FP8 / FP4 / BF16 tensors (not from drafter_pack.py's dspark.bin), activations F32.  Per round
16it prints how far the engine's hidden rows and confidences are from it, and with --head whether the drafts agree.
17"""
18from __future__ import annotations
19
20import argparse
21import json
22import math
23import pathlib
24import struct
25import sys
26
27import numpy as np
28import torch
29import torch.nn.functional as F
30
31SHARDS = ("model-00044-of-00048.safetensors", "model-00045-of-00048.safetensors", "model-00046-of-00048.safetensors")
32
33
34def e4m3_table() -> np.ndarray:
35    t = np.zeros(256, np.float32)
36    for c in range(256):
37        s, e, m = c >> 7, (c >> 3) & 15, c & 7
38        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)
39        t[c] = -v if s else v
40    return t
41
42
43E4M3 = e4m3_table()
44E2M1 = np.array([0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6], np.float32)
45
46
47class Ckpt:
48    """The drafter's shards: each tensor decoded to F32 on request (FP8 with its 32 x 32 E8M0 block scales; FP4 codes
49    two to a byte, the first in the low nibble, an E8M0 scale per 32 along K; BF16; F32)."""
50
51    def __init__(self, d: pathlib.Path):
52        self.t = {}
53        for name in SHARDS:
54            raw = np.memmap(d / name, np.uint8, mode="r")
55            n = struct.unpack("<Q", bytes(raw[:8]))[0]
56            head = json.loads(bytes(raw[8:8 + n]))
57            head.pop("__metadata__", None)
58            for k, e in head.items():
59                self.t[k] = (raw, 8 + n, e)
60
61    def raw(self, k):
62        raw, base, e = self.t[k]
63        a, b = e["data_offsets"]
64        return raw[base + a:base + b], e["dtype"], e["shape"]
65
66    def get(self, k) -> torch.Tensor:
67        w, dt, sh = self.raw(k)
68        if dt == "F32":
69            v = np.frombuffer(w, np.float32).reshape(sh)
70        elif dt == "BF16":
71            v = (np.frombuffer(w, np.uint16).astype(np.uint32) << 16).view(np.float32).reshape(sh)
72        elif dt == "F8_E4M3":
73            s, _, ssh = self.raw(k[:-len("weight")] + "scale")
74            r, c = sh
75            sc = np.exp2(np.asarray(s, np.float32).reshape(ssh) - 127.0)
76            v = E4M3[np.asarray(w).reshape(r, c)] * np.repeat(np.repeat(sc, 32, 0), 32, 1)[:r, :c]
77        elif dt == "I8":
78            s, _, ssh = self.raw(k[:-len("weight")] + "scale")
79            r, c2 = sh
80            p = np.asarray(w).reshape(r, c2)
81            codes = np.empty((r, c2 * 2), np.uint8)
82            codes[:, 0::2] = p & 15
83            codes[:, 1::2] = p >> 4
84            sc = np.exp2(np.asarray(s, np.float32).reshape(ssh) - 127.0)
85            v = E2M1[codes] * np.repeat(sc, 32, 1)
86        else:
87            raise SystemExit("%s: dtype %s" % (k, dt))
88        return torch.from_numpy(np.ascontiguousarray(v, np.float32))
89
90
91def fp8_round(x: torch.Tensor, block: int = 32) -> torch.Tensor:
92    sh = x.shape
93    v = x.float().reshape(*sh[:-1], sh[-1] // block, block)
94    amax = v.abs().amax(-1, keepdim=True).clamp_min(1e-4)
95    s = torch.exp2(torch.ceil(torch.log2(amax / 448.0)))
96    y = (v / s).clamp(-448.0, 448.0).to(torch.float8_e4m3fn).float() * s
97    return y.reshape(sh)
98
99
100def rms(x, w, eps):
101    x = x.float()
102    y = x * torch.rsqrt(x.square().mean(-1, keepdim=True) + eps)
103    return y * w if w is not None else y
104
105
106def freqs(dim, n, base):
107    f = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
108    a = torch.outer(torch.arange(n, dtype=torch.float32), f)
109    return torch.polar(torch.ones_like(a), a)
110
111
112def rope(x, fc, inverse=False):
113    c = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2).contiguous())
114    if inverse:
115        fc = fc.conj()
116    if x.ndim == 3:
117        fc = fc[:, None, :]
118    return torch.view_as_real(c * fc).flatten(-2)
119
120
121def pack_conf(pack: pathlib.Path):
122    cfg = {}
123    for line in (pack / "ds4.txt").read_text().splitlines():
124        k, _, v = line.partition(" ")
125        cfg[k] = v
126    files, tens = {}, {}
127    for line in (pack / "tensors.txt").read_text().splitlines():
128        p = line.split()
129        if p[0] == "file":
130            files[int(p[1])] = p[2]
131        elif p[0] == "t":
132            tens[p[1]] = (p[2], int(p[3]), int(p[4]), int(p[5]), [int(x) for x in p[6:]])
133    return cfg, files, tens
134
135
136def gguf_rows(pack, cfg, files, tens, name):
137    dt, fi, off, nb, sh = tens[name]
138    if dt != "BF16":
139        raise SystemExit("%s: %s, the oracle reads a BF16 one" % (name, dt))
140    path = pathlib.Path(cfg["model_dir"]) / files[fi]
141    return np.memmap(path, np.uint16, mode="r", offset=off, shape=tuple(sh))
142
143
144def bf16_rows(m, idx):
145    return torch.from_numpy((np.asarray(m[idx]).astype(np.uint32) << 16).view(np.float32))
146
147
148class Drafter:
149    def __init__(self, ck: Ckpt, cfg: dict):
150        self.ck, self.cfg = ck, cfg
151        self.D = int(cfg["hidden_size"])
152        self.hc = int(cfg["hc_mult"])
153        self.eps = float(cfg["rms_norm_eps"])
154        self.hc_eps = float(cfg["hc_eps"])
155        self.sink_iters = int(cfg["hc_sinkhorn_iters"])
156        self.H, self.HD, self.rd = int(cfg["num_attention_heads"]), int(cfg["head_dim"]), int(cfg["qk_rope_head_dim"])
157        self.G = int(cfg["o_groups"])
158        self.win = int(cfg["sliding_window"])
159        self.k = int(cfg["dspark_num_experts_per_tok"])
160        self.scale = float(cfg["routed_scaling_factor"])
161        self.lim = float(cfg["swiglu_limit"])
162        self.fc = freqs(self.rd, 1 << 16, float(cfg["rope_theta"]))
163        self.nb = 3
164        self.cache = {}
165        self.ring = [dict() for _ in range(self.nb)]   # position -> main KV row, per block
166
167    def W(self, k):
168        if k not in self.cache:
169            self.cache[k] = self.ck.get(k)
170        return self.cache[k]
171
172    def seed(self, p0, taps):   # taps [n, 3 * D]
173        main_x = rms(taps @ self.W("mtp.0.main_proj.weight").T, self.W("mtp.0.main_norm.weight"), self.eps)
174        n = taps.shape[0]
175        fc = self.fc[p0:p0 + n]
176        for b in range(self.nb):
177            A = "mtp.%d.attn." % b
178            kv = rms(main_x @ self.W(A + "wkv.weight").T, self.W(A + "kv_norm.weight"), self.eps)
179            kv = torch.cat([kv[:, :-self.rd], rope(kv[:, -self.rd:], fc)], -1)
180            kv = fp8_round(kv)
181            for i in range(n):
182                self.ring[b][p0 + i] = kv[i]
183
184    def hc_mixes(self, x, P):
185        hc = self.hc
186        fn, scale, base = self.W(P + "_fn"), self.W(P + "_scale"), self.W(P + "_base")
187        xf = x.flatten(1).float()
188        r = torch.rsqrt(xf.square().mean(-1, keepdim=True) + self.eps)
189        mixes = (xf @ fn.T) * r
190        pre = torch.sigmoid(mixes[:, :hc] * scale[0] + base[:hc]) + self.hc_eps
191        post = 2 * torch.sigmoid(mixes[:, hc:2 * hc] * scale[1] + base[hc:2 * hc])
192        comb = (mixes[:, 2 * hc:] * scale[2] + base[2 * hc:]).view(-1, hc, hc)
193        eps = self.hc_eps
194        comb = comb.softmax(-1) + eps
195        comb = comb / (comb.sum(-2, keepdim=True) + eps)
196        for _ in range(self.sink_iters - 1):
197            comb = comb / (comb.sum(-1, keepdim=True) + eps)
198            comb = comb / (comb.sum(-2, keepdim=True) + eps)
199        return pre, post, comb
200
201    def attention(self, b, x, p0):
202        A = "mtp.%d.attn." % b
203        T = x.shape[0]
204        H, D, rd = self.H, self.HD, self.rd
205        fc = self.fc[p0:p0 + T]
206        qr = rms(x @ self.W(A + "wq_a.weight").T, self.W(A + "q_norm.weight"), self.eps)
207        q = (qr @ self.W(A + "wq_b.weight").T).view(T, H, D)
208        q = torch.cat([q[..., :-rd], rope(q[..., -rd:], fc)], -1)
209        kv = rms(x @ self.W(A + "wkv.weight").T, self.W(A + "kv_norm.weight"), self.eps)
210        kv = torch.cat([kv[:, :-rd], rope(kv[:, -rd:], fc)], -1)
211        kv = fp8_round(kv)
212        ring = [self.ring[b][p] for p in range(max(0, p0 - self.win), p0) if p in self.ring[b]]
213        allkv = torch.cat([torch.stack(ring), kv], 0) if ring else kv
214        sink = self.W(A + "attn_sink")
215        s = torch.einsum("thd,kd->thk", q, allkv) * D ** -0.5
216        m = torch.maximum(s.amax(-1), sink[None, :])
217        pr = torch.exp(s - m.unsqueeze(-1))
218        den = pr.sum(-1) + torch.exp(sink[None, :] - m)
219        o = torch.einsum("thk,kd->thd", pr, allkv) / den.unsqueeze(-1)
220        o = torch.cat([o[..., :-rd], rope(o[..., -rd:], fc, inverse=True)], -1)
221        o = fp8_round(o.reshape(T, self.G, -1))
222        wo_a = self.W(A + "wo_a.weight").view(self.G, -1, o.shape[-1])
223        oa = torch.einsum("tgd,grd->tgr", o, wo_a)
224        return oa.flatten(1) @ self.W(A + "wo_b.weight").T
225
226    def moe(self, b, x):
227        M = "mtp.%d.ffn." % b
228        T = x.shape[0]
229        scores = F.softplus(x.float() @ self.W(M + "gate.weight").T).sqrt()
230        idx = (scores + self.W(M + "gate.bias")).topk(self.k, dim=-1)[1]
231        wts = scores.gather(1, idx)
232        wts = wts / (wts.sum(-1, keepdim=True) + 1e-20) * self.scale
233        lim = self.lim
234        y = torch.zeros(T, self.D)
235        for e in torch.unique(idx).tolist():
236            P = M + "experts.%d." % e
237            rows, slot = torch.where(idx == e)
238            xs = x[rows]
239            w1, w3 = self.ck.get(P + "w1.weight"), self.ck.get(P + "w3.weight")
240            h = F.silu((xs @ w1.T).clamp(max=lim)) * (xs @ w3.T).clamp(-lim, lim)
241            del w1, w3
242            w2 = self.ck.get(P + "w2.weight")
243            y.index_add_(0, rows, (h * wts[rows, slot, None]) @ w2.T)
244            del w2
245        S = M + "shared_experts."
246        h = F.silu((x @ self.W(S + "w1.weight").T).clamp(max=lim)) * (x @ self.W(S + "w3.weight").T).clamp(-lim, lim)
247        return y + h @ self.W(S + "w2.weight").T, idx
248
249    def block_forward(self, emb, p0):   # emb [T, D] -> the collapsed hidden rows [T, D], each block's stream
250        T = emb.shape[0]
251        h = emb.unsqueeze(1).repeat(1, self.hc, 1)
252        pre = torch.zeros(T, self.hc)
253        pre[:, 0] = 1.0
254        routes = []
255        streams = []
256        for b in range(self.nb):
257            B = "mtp.%d." % b
258            res = h
259            a_pre, a_post, a_comb = self.hc_mixes(h, B + "hc_attn")
260            x = rms((pre.unsqueeze(-1) * h).sum(1), self.W(B + "attn_norm.weight"), self.eps)
261            y = self.attention(b, x, p0)
262            h = a_post.unsqueeze(-1) * y.unsqueeze(1) + (a_comb.unsqueeze(-1) * res.unsqueeze(2)).sum(1)
263            res = h
264            f_pre, f_post, f_comb = self.hc_mixes(h, B + "hc_ffn")
265            x = rms((a_pre.unsqueeze(-1) * h).sum(1), self.W(B + "ffn_norm.weight"), self.eps)
266            y, idx = self.moe(b, x)
267            routes.append(idx)
268            h = f_post.unsqueeze(-1) * y.unsqueeze(1) + (f_comb.unsqueeze(-1) * res.unsqueeze(2)).sum(1)
269            pre = f_pre
270            streams.append(h)
271        return (pre.unsqueeze(-1) * h).sum(1), routes, streams
272
273
274def records(path, nb, hc, win, hd):
275    """The engine's dump: 'S' seeds (first position, the taps), 'D' draft rounds (the block's position, y, the drafts,
276    their confidences, the collapsed hidden rows, then per block the ring it read (BF16) and the stream it left)."""
277    with open(path, "rb") as f:
278        while True:
279            hb = f.read(32)
280            if len(hb) < 32:
281                return
282            kind, a, b, c = struct.unpack("<4q", hb)
283            if kind == ord("S"):
284                n, w = b, c
285                taps = np.frombuffer(f.read(n * w * 4), np.float32).reshape(n, w)
286                yield "S", a, taps
287            elif kind == ord("D"):
288                T = c
289                D = int(DIM[0])
290                toks = np.frombuffer(f.read(T * 4), np.int32)
291                conf = np.frombuffer(f.read(T * 4), np.float32)
292                x = np.frombuffer(f.read(T * 4 * D), np.float32).reshape(T, D)
293                rings, streams = [], []
294                for _ in range(nb):
295                    r = np.frombuffer(f.read(win * hd * 2), np.uint16).reshape(win, hd)
296                    rings.append((r.astype(np.uint32) << 16).view(np.float32))
297                    streams.append(np.frombuffer(f.read(T * hc * D * 4), np.float32).reshape(T, hc, D))
298                yield "D", (a, b, T, toks, conf, x, rings, streams), None
299            else:
300                raise SystemExit("dump: record %d" % kind)
301
302
303DIM = [5120]
304
305
306def rel(a: torch.Tensor, b: torch.Tensor) -> float:
307    return float((a - b).norm() / b.norm().clamp_min(1e-30))
308
309
310def main() -> int:
311    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
312    ap.add_argument("--dump", required=True)
313    ap.add_argument("--shards", required=True, help="the folder with DeepSeek's model-00044..46-of-00048")
314    ap.add_argument("--pack", required=True, help="the maya-ds4 pack (ds4.txt, tensors.txt: the embedding, the head)")
315    ap.add_argument("--rounds", type=int, default=4, help="draft rounds to check (from --skip)")
316    ap.add_argument("--skip", type=int, default=0, help="draft rounds to pass over first")
317    ap.add_argument("--head", action="store_true", help="also the drafts: the trunk's head + the markov bias")
318    ap.add_argument("--threads", type=int, default=4)
319    a = ap.parse_args()
320    torch.set_num_threads(a.threads)
321    pack = pathlib.Path(a.pack)
322    cfg, files, tens = pack_conf(pack)
323    DIM[0] = int(cfg["hidden_size"])
324    ck = Ckpt(pathlib.Path(a.shards))
325    dr = Drafter(ck, cfg)
326    emb = gguf_rows(pack, cfg, files, tens, "embed.weight")
327    head = gguf_rows(pack, cfg, files, tens, "head.weight") if a.head else None
328    noise = int(cfg["dspark_noise_token_id"])
329    seen = done = 0
330    worst_x = worst_c = 0.0
331    agree = total = 0
332    for kind, v, taps in records(a.dump, dr.nb, dr.hc, dr.win, dr.HD):
333        if kind == "S":
334            dr.seed(v, torch.from_numpy(taps.copy()))
335            continue
336        p0, y, T, toks, conf, xd, rings, streams = v
337        seen += 1
338        if seen <= a.skip:
339            continue
340        ex = torch.from_numpy(xd.copy())
341        ids = [y] + [noise] * (T - 1)
342        xh, routes, ref_streams = dr.block_forward(bf16_rows(emb, ids), p0)
343        for b in range(dr.nb):   # the ring each block read (the positions the reference holds), the stream it left
344            ps = [p for p in range(max(0, p0 - dr.win), p0) if p in dr.ring[b]]
345            er = torch.from_numpy(rings[b][[p % dr.win for p in ps]].copy())
346            rr = torch.stack([dr.ring[b][p] for p in ps])
347            print("  block %d: ring rel err %.4f (%d rows), stream rel err %.4f, routes %s" % (
348                b, rel(er, rr), len(ps), rel(torch.from_numpy(streams[b].copy()), ref_streams[b]),
349                routes[b].tolist()), flush=True)
350        prev = [y] + [int(t) for t in toks[:-1]]
351        me = dr.W("mtp.2.markov_head.embed.weight")[prev]
352        cw = dr.W("mtp.2.confidence_head.proj.weight")[0]
353        cf = torch.sigmoid(torch.cat([xh, me], -1) @ cw)
354        rerr = ((ex - xh).norm(dim=-1) / xh.norm(dim=-1)).tolist()
355        cos = F.cosine_similarity(ex, xh, dim=-1).tolist()
356        dc = (torch.from_numpy(conf.copy()) - cf).abs().tolist()
357        worst_x = max(worst_x, max(rerr))
358        worst_c = max(worst_c, max(dc))
359        line = "round %d (pos %d, y %d): hidden rel err %s, cos %s; conf engine %s ref %s" % (
360            seen, p0, y, " ".join("%.4f" % r for r in rerr), " ".join("%.5f" % c for c in cos),
361            " ".join("%.3f" % c for c in conf.tolist()), " ".join("%.3f" % c for c in cf.tolist()))
362        if head is not None:
363            xn = rms(xh, dr.W("mtp.2.norm.weight"), dr.eps)
364            lg = torch.zeros(T, head.shape[0])
365            for c0 in range(0, head.shape[0], 16384):
366                c1 = min(head.shape[0], c0 + 16384)
367                lg[:, c0:c1] = xn @ bf16_rows(head, slice(c0, c1)).T
368            mh = dr.W("mtp.2.markov_head.head.weight")
369            ref_t = []
370            p = y
371            for i in range(T):   # greedy chain on the reference's own drafts
372                row = lg[i] + mh @ dr.W("mtp.2.markov_head.embed.weight")[p]
373                p = int(row.argmax())
374                ref_t.append(p)
375            same = sum(int(r == int(t)) for r, t in zip(ref_t, toks))
376            agree += same
377            total += T
378            line += "; drafts engine %s ref %s" % (list(map(int, toks)), ref_t)
379        print(line, flush=True)
380        done += 1
381        if done >= a.rounds:
382            break
383    print("checked %d rounds: worst hidden rel err %.4f, worst conf diff %.4f%s" % (
384        done, worst_x, worst_c, (", drafts agree %d/%d" % (agree, total)) if head is not None else ""))
385    return 0
386
387
388if __name__ == "__main__":
389    sys.exit(main())