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
13.9 KiB303 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/ref_gguf.py - tools/ds4/ref.py's oracle over a GGUF (tools/ds4/pack_gguf.py's pack): the same forward,
4each weight dequantised in torch from the GGUF's own blocks (BF16, Q8_0, MXFP4, MXFP8) - a check of maya-ds4's GGUF
5path that shares none of its code.
6
7    python tools/ds4/ref_gguf.py --pack <model>/maya-ds4 --ids 0,671,6102 [--dump out.npz] [--gen 8]
8
9The token ids come from the server's tokenizer (maya-ds4 --serve, or the engine's own --ids runs); --dump writes
10what tools/ds4/compare.py reads.
11"""
12from __future__ import annotations
13
14import argparse
15import math
16import os
17import pathlib
18import struct
19import sys
20import time
21from types import SimpleNamespace
22
23import numpy as np
24import torch
25import torch.nn.functional as F
26
27HERE = pathlib.Path(__file__).resolve().parent
28sys.path.insert(0, str(HERE))
29import ref as R  # noqa: E402
30
31BLOCK = {"Q8_0": 34, "MXFP4": 17, "MXFP8": 33}
32E2M1 = torch.tensor([0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12], dtype=torch.float32)
33
34
35class Pack:
36    """pack_gguf.py's tensors.txt over the GGUF's files (memory-mapped), and ds4.txt's geometry."""
37
38    def __init__(self, d: pathlib.Path):
39        self.kv = {}
40        for line in (d / "ds4.txt").read_text().splitlines():
41            k, _, v = line.partition(" ")
42            self.kv[k] = v
43        model = pathlib.Path(self.kv["model_dir"])
44        self.mm, self.t = {}, {}
45        for line in (d / "tensors.txt").read_text().splitlines():
46            f = line.split()
47            if f[0] == "file":
48                self.mm[int(f[1])] = np.memmap(model / f[2], dtype=np.uint8, mode="r")
49            elif f[0] == "t":
50                self.t[f[1]] = (f[2], int(f[3]), int(f[4]), int(f[5]), tuple(int(x) for x in f[6:]))
51        self._embed = None
52
53    def has(self, name):
54        return name in self.t
55
56    def raw(self, name) -> np.ndarray:
57        dt, fi, off, nb, _ = self.t[name]
58        return self.mm[fi][off:off + nb]
59
60    def num(self, k, d=0.0):
61        return float(self.kv.get(k, d))
62
63    def ints(self, k):
64        return [int(x) for x in self.kv.get(k, "").split(",") if x]
65
66
67def dequant(p: Pack, name: str, dev) -> torch.Tensor:
68    """A tensor as F32 on dev, shaped as stored ([out][in] for a matrix)."""
69    dt, _, _, _, shape = p.t[name]
70    r = torch.from_numpy(np.array(p.raw(name))).to(dev)
71    if dt == "F32":
72        v = r.view(torch.float32)
73    elif dt == "F16":
74        v = r.view(torch.float16).float()
75    elif dt == "BF16":
76        v = r.view(torch.bfloat16).float()
77    elif dt == "Q8_0":
78        b = r.view(-1, 34)
79        v = (b[:, :2].contiguous().view(torch.float16).float() * b[:, 2:].view(torch.int8).float()).reshape(-1)
80    elif dt == "MXFP4":
81        b = r.view(-1, 17)
82        s = torch.ldexp(torch.ones(1, device=dev), b[:, :1].int() - 128)          # 2^(e - 128)
83        q = b[:, 1:].long()
84        lut = E2M1.to(dev)
85        v = (torch.cat([lut[q & 15], lut[q >> 4]], 1) * s).reshape(-1)          # values 0..15, then 16..31
86    elif dt == "MXFP8":
87        b = r.view(-1, 33)
88        s = torch.ldexp(torch.ones(1, device=dev), b[:, :1].int() - 127)
89        v = (b[:, 1:].contiguous().view(torch.float8_e4m3fn).float() * s).reshape(-1)
90    else:   # the low-bit expert types (IQ2_XXS .. Q4_K): gguf-py's numpy dequantisers (ggml's dequantize_row_*)
91        v = torch.from_numpy(gq_values(np.array(p.raw(name)), dt, name)).to(dev)
92    return v.reshape(shape)
93
94
95def gq_values(raw: np.ndarray, dt: str, name: str) -> np.ndarray:
96    """ggml blocks of type dt as F32 (flat) through gguf-py's dequantisers - the installed package, else a llama.cpp
97    checkout's ($GGUF_PY, ~/llama.cpp/gguf-py)."""
98    try:
99        try:
100            import gguf
101        except ImportError:
102            for d in (os.environ.get("GGUF_PY", ""), os.path.expanduser("~/llama.cpp/gguf-py")):
103                if d and os.path.isdir(d):
104                    sys.path.insert(0, d)
105            import gguf
106        from gguf.quants import dequantize as gq_dequant
107        qt = gguf.GGMLQuantizationType[dt]
108    except (ImportError, KeyError):
109        raise SystemExit("%s: dtype %s (no gguf-py with a dequantiser for it: GGUF_PY=<llama.cpp>/gguf-py)" % (name, dt))
110    return np.ascontiguousarray(gq_dequant(raw, qt), dtype=np.float32).reshape(-1)
111
112
113class Hasher:
114    """engram_hash.Hasher from the pack's engram.bin (the token map, multipliers, primes and offsets)."""
115
116    def __init__(self, path: pathlib.Path):
117        b = path.read_bytes()
118        vocab, nl, ngram, heads, hd, pad = struct.unpack_from("<6i", b, 4)
119        cols = (ngram - 1) * heads
120        o = 28
121        self.tm = np.frombuffer(b, np.int32, vocab, o).astype(np.int64)
122        o += 4 * vocab
123        self.mult = np.frombuffer(b, np.int64, nl * ngram, o).reshape(nl, ngram)
124        o += 8 * nl * ngram
125        self.primes = np.frombuffer(b, np.int64, nl * cols, o).reshape(nl, ngram - 1, heads)
126        o += 8 * nl * cols
127        self.off = np.frombuffer(b, np.int64, nl * cols, o).reshape(nl, cols)
128        self.ngram, self.pad, self.hd = ngram, pad, hd
129
130    def ids(self, tokens) -> np.ndarray:   # engram_hash.Hasher.ids
131        c = self.tm[np.asarray(tokens, dtype=np.int64)]
132        T = len(c)
133        pos = np.arange(T)
134        toks, blocked = [], np.zeros(T, dtype=bool)
135        for s in range(self.ngram):
136            src = c[np.clip(pos - s, 0, None)]
137            blocked = blocked | (pos < s)
138            toks.append(np.where(blocked, self.pad, src))
139        toks = np.stack(toks, axis=-1)
140        prod = toks[:, None, :] * self.mult[None]
141        rolling, out = prod[..., 0], []
142        for i in range(1, self.ngram):
143            rolling = np.bitwise_xor(rolling, prod[..., i])
144            out.append(rolling[..., None] % self.primes[None, :, i - 1])
145        return np.concatenate(out, axis=-1) + self.off[None]
146
147
148def q6k_rows(rows: np.ndarray, name: str) -> np.ndarray:
149    """Engram rows of Q6_K superblocks as F32 (ggml's dequantize_row_q6_K, through gguf-py)."""
150    return gq_values(rows.reshape(-1), "Q6_K", name)
151
152
153class RefGguf(R.Ref):
154    def __init__(self, pack: pathlib.Path, dev: str = "cuda:0", max_seq: int = 8192):
155        self.dir = pack
156        self.st = p = Pack(pack)
157        g = p.num
158        t = {k: int(g(k)) for k in ("hidden_size", "hc_mult", "num_hidden_layers", "candidate_source_layer_id",
159                                    "qk_rope_head_dim", "num_experts_per_tok", "sliding_window", "o_groups",
160                                    "num_attention_heads", "index_topk", "index_n_heads", "index_head_dim", "head_dim",
161                                    "candidate_topk_blocks", "candidate_block_size")}
162        t.update(hc_eps=g("hc_eps"), hc_sinkhorn_iters=int(g("hc_sinkhorn_iters")),
163                 rms_norm_eps=g("rms_norm_eps"), routed_scaling_factor=g("routed_scaling_factor"),
164                 swiglu_limit=g("swiglu_limit"), rope_theta=g("rope_theta"), compress_rope_theta=g("compress_rope_theta"),
165                 compress_ratios=p.ints("compress_ratios"), kv_source_layer_ids=p.ints("kv_source_layer_ids"),
166                 index_source_layer_ids=p.ints("index_source_layer_ids"),
167                 rope_scaling={"factor": g("rope_scaling.factor"), "beta_fast": g("rope_scaling.beta_fast"),
168                               "beta_slow": g("rope_scaling.beta_slow"),
169                               "original_max_position_embeddings": int(g("rope_scaling.original_max_position_embeddings"))})
170        self.cfg = {"text_config": t}
171        self.t = t
172        self.dev = dev
173        self.dim, self.hc = t["hidden_size"], t["hc_mult"]
174        self.eps = t["rms_norm_eps"]
175        self.nl = t["num_hidden_layers"]
176        self.ratios = t["compress_ratios"]
177        self.kv_src = set(t["kv_source_layer_ids"])
178        self.ix_src = set(t["index_source_layer_ids"])
179        self.cand_src = t["candidate_source_layer_id"]
180        rs, rd = t["rope_scaling"], t["qk_rope_head_dim"]
181        self.fc_window = R.freqs_cis(rd, max_seq, 0, t["rope_theta"], rs["factor"], rs["beta_fast"], rs["beta_slow"], dev)
182        self.fc_comp = R.freqs_cis(rd, max_seq, rs["original_max_position_embeddings"], t["compress_rope_theta"],
183                                   rs["factor"], rs["beta_fast"], rs["beta_slow"], dev)
184        self.hasher = Hasher(pack / "engram.bin")
185        self.lay = SimpleNamespace(layer_ids=tuple(p.ints("engram_layer_ids")), head_dim=self.hasher.hd)
186        self.timing = {}
187        self._embed = None
188
189    def W(self, prefix: str) -> torch.Tensor:
190        return dequant(self.st, prefix + ".weight", self.dev)
191
192    def V(self, name: str) -> torch.Tensor:
193        return dequant(self.st, name, self.dev).float()
194
195    def engram(self, li, x, hash_ids):
196        P = "layers.%d.engram." % li
197        T, cols = hash_ids.shape
198        hd = self.lay.head_dim
199        dt = self.st.t[P + "embed.weight"][0]
200        rb = hd // 256 * 210 if dt == "Q6_K" else hd // 32 * 33        # (a row's bytes: Q6_K or MXFP8 blocks)
201        tab = self.st.raw(P + "embed.weight").reshape(-1, rb)
202        flat = hash_ids.reshape(-1)
203        order = np.argsort(flat)
204        rows = np.empty((flat.size, rb), np.uint8)
205        rows[order] = tab[flat[order]]
206        if dt == "Q6_K":
207            e = torch.from_numpy(q6k_rows(rows, P)).to(self.dev).view(T, cols * hd)
208        else:
209            b = torch.from_numpy(rows).to(self.dev).view(-1, 33)
210            s = torch.ldexp(torch.ones(1, device=self.dev), b[:, :1].int() - 127)
211            e = (b[:, 1:].contiguous().view(torch.float8_e4m3fn).float() * s).view(T, cols * hd)
212        e = e.to(torch.bfloat16).float()
213        kv = e @ self.W(P + "wkv").T
214        d, hc = self.dim, self.hc
215        key, value = kv[:, :hc * d].view(T, hc, d), kv[:, hc * d:]
216        w = self.V(P + "gate.weight")                                     # q_weight * k_weight (folded)
217        h = x.float()
218        rstd = torch.rsqrt(h.square().mean(-1) + self.eps) * torch.rsqrt(key.square().mean(-1) + self.eps)
219        dot = (h * w * key).sum(-1) * rstd * d ** -0.5
220        gate = torch.sigmoid(torch.copysign(dot.abs().clamp_min(1e-6).sqrt(), dot))
221        return h + gate.unsqueeze(-1) * value.unsqueeze(1)
222
223    def moe(self, li, x):
224        t = self.t
225        M = "layers.%d.ffn." % li
226        T = x.shape[0]
227        gw = self.V(M + "gate.weight")
228        scores = F.softplus(x.float() @ gw.T).sqrt()
229        idx = (scores + self.V(M + "gate.bias")).topk(t["num_experts_per_tok"], dim=-1)[1]
230        wts = scores.gather(1, idx)
231        wts = wts / (wts.sum(-1, keepdim=True) + 1e-20) * t["routed_scaling_factor"]
232        lim = t["swiglu_limit"]
233        y = torch.zeros(T, self.dim, device=self.dev)
234        for e in torch.unique(idx).tolist():
235            P = M + "experts.%d." % e
236            rows, slot = torch.where(idx == e)
237            xs = x[rows]
238            h = F.silu((xs @ self.W(P + "w1").T).clamp(max=lim)) * (xs @ self.W(P + "w3").T).clamp(-lim, lim)
239            y.index_add_(0, rows, (h * wts[rows, slot, None]) @ self.W(P + "w2").T)
240        S = M + "shared_experts."
241        h = F.silu((x @ self.W(S + "w1").T).clamp(max=lim)) * (x @ self.W(S + "w3").T).clamp(-lim, lim)
242        y += h @ self.W(S + "w2").T
243        self.last_route = (idx, wts)
244        return y
245
246    @torch.inference_mode()
247    def forward(self, ids, dump=None):
248        # ref.py's forward reads the embedding rows as BF16: a Q8_0 table is dequantised for the rows asked
249        dt = self.st.t["embed.weight"][0]
250        if dt != "BF16":
251            full = self.st.raw("embed.weight").reshape(-1, self.dim // 32 * 34)
252            sel = torch.from_numpy(np.array(full[np.asarray(ids)])).to(self.dev).view(-1, 34)
253            v = (sel[:, :2].contiguous().view(torch.float16).float() * sel[:, 2:].view(torch.int8).float())
254            rows = v.reshape(len(ids), self.dim).to(torch.bfloat16).view(torch.uint16).cpu().numpy()
255            raw0 = self.st.raw
256            emb = np.zeros((max(ids) + 1, self.dim), np.uint16)
257            emb[np.asarray(ids)] = rows
258            self.st.raw = lambda n, e=emb, r=raw0: e.view(np.uint8) if n == "embed.weight" else r(n)
259            try:
260                return super().forward(ids, dump)
261            finally:
262                self.st.raw = raw0
263        return super().forward(ids, dump)
264
265
266def main() -> int:
267    ap = argparse.ArgumentParser()
268    ap.add_argument("--pack", required=True, help="pack_gguf.py's pack (<model>/maya-ds4)")
269    ap.add_argument("--ids", required=True, help="comma-separated token ids")
270    ap.add_argument("--gen", type=int, default=0, help="greedy tokens to append (a whole forward each)")
271    ap.add_argument("--dump", help="write the per-layer residual streams, the logits and the ids (.npz)")
272    ap.add_argument("--no-hs", action="store_true", help="--dump without the per-layer residual streams")
273    ap.add_argument("--dev", default="cuda:0")
274    a = ap.parse_args()
275    ids = [int(x) for x in a.ids.split(",")]
276    r = RefGguf(pathlib.Path(a.pack).expanduser(), a.dev)
277    print("tokens:", len(ids), ids[:32], flush=True)
278    dump = [] if a.dump and not a.no_hs else None
279    t0 = time.time()
280    logits = r.forward(ids, dump)
281    print("forward %.1fs" % (time.time() - t0), flush=True)
282    lp = torch.log_softmax(logits.float(), -1)
283    if len(ids) > 1:
284        tgt = torch.tensor(ids[1:], device=lp.device)
285        nll = -lp[:-1].gather(1, tgt[:, None]).squeeze(1)
286        print("ppl over %d tokens: %.4f" % (len(ids) - 1, math.exp(nll.mean().item())))
287    top = lp[-1].topk(8)
288    print("next:", list(zip(top.indices.tolist(), [round(v, 3) for v in top.values.tolist()])))
289    if a.dump:
290        np.savez(a.dump, ids=np.array(ids), logits=logits.cpu().numpy(), hs=np.stack(dump) if dump else np.zeros(0))
291    out = list(ids)
292    for _ in range(a.gen):
293        nxt = int(lp[-1].argmax())
294        out.append(nxt)
295        print("gen ids:", out[len(ids):], flush=True)
296        if nxt == 1:
297            break
298        lp = torch.log_softmax(r.forward(out).float(), -1)
299    return 0
300
301
302if __name__ == "__main__":
303    sys.exit(main())