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
8.4 KiB186 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"""dumpcmp.py - two maya-ds4 runs' debug dumps side by side (the prompt path's numerics: where two runs part).
4
5  layers A B [--pos P]       DS4_DUMP_L files: each layer record's relative error between the runs - the median over
6                             the positions, the worst position, and position P's
7  route R --pos P            a DS4_DUMP_R file: position P's experts a layer (virtual slot, the expert's rows, P's row)
8  gate R... --pos P          DS4_DUMP_R files: position P's router a layer - its picks and the margin between the k-th
9                             pick's score and the next expert's (sqrt(softplus(logit)) + bias)
10  sets A B --pos P --route RA RB
11                             DS4_DUMP_Y files (and each run's DS4_DUMP_R): each layer's set rows' h / y error between
12                             the runs (rows matched by token and expert), the worst row and position P's, with their
13                             expert's rows and the piece they were computed in
14"""
15import argparse
16import sys
17
18import numpy as np
19
20
21def read_l(path, dim_hc):
22    out = []
23    with open(path, "rb") as f:
24        while True:
25            h = f.read(24)
26            if len(h) < 24:
27                break
28            il, p0, t = (int(v) for v in np.frombuffer(h, dtype=np.int64))
29            v = np.frombuffer(f.read(t * dim_hc * 4), dtype=np.float32).reshape(t, dim_hc)
30            out.append(((il, p0), v))
31    return out
32
33
34def rel(a, b):
35    a = a.astype(np.float64)
36    b = b.astype(np.float64)
37    return np.linalg.norm(a - b, axis=-1) / np.maximum(np.linalg.norm(b, axis=-1), 1e-30)
38
39
40def read_r(path):
41    out = {}
42    with open(path, "rb") as f:
43        while True:
44            h = f.read(64)
45            if len(h) < 64:
46                break
47            il, p0, t, k, ne, nvs, nsl, kp = (int(v) for v in np.frombuffer(h, dtype=np.int64))
48            ri = np.frombuffer(f.read(t * kp * 4), dtype=np.int32).reshape(t, kp)[:, :k]
49            vs = np.frombuffer(f.read(ne * 4), dtype=np.int32)
50            b = np.frombuffer(f.read((nvs + 1) * 4), dtype=np.int32)
51            rt = np.frombuffer(f.read(t * k * 4), dtype=np.int32)
52            gl = np.frombuffer(f.read(t * ne * 4), dtype=np.float32).reshape(t, ne)
53            gb = np.frombuffer(f.read(ne * 4), dtype=np.float32)
54            out[(il, p0)] = dict(t=t, k=k, ri=ri, vs=vs, b=b, rt=rt, nsl=nsl, glog=gl, bias=gb)
55    return out
56
57
58def read_y(path, ff, dim):   # a layer's pieces at a time (the dump holds the layers in order)
59    cur, il0 = [], None
60    with open(path, "rb") as f:
61        while True:
62            h = f.read(48)
63            if len(h) < 48:
64                break
65            il, a, n, ne, ring, mr = (int(v) for v in np.frombuffer(h, dtype=np.int64))
66            b = np.frombuffer(f.read((ne + 1) * 4), dtype=np.int32)
67            hv = np.frombuffer(f.read(n * ff * 2), dtype=np.float16).reshape(n, ff)
68            yv = np.frombuffer(f.read(n * dim * 4), dtype=np.float32).reshape(n, dim)
69            if il0 is not None and il != il0:
70                yield il0, cur
71                cur = []
72            il0 = il
73            cur.append(dict(il=il, a=a, n=n, ne=ne, ring=ring, mr=mr, b=b, h=hv, y=yv))
74    if cur:
75        yield il0, cur
76
77
78def row_keys(r):
79    """A layer's sorted rows -> (token, expert, the expert's rows, the row's place among them)."""
80    keys = {}
81    for e, v in enumerate(r["vs"]):
82        lo, hi = int(r["b"][v]), int(r["b"][v + 1])
83        for g in range(lo, hi):
84            keys[g] = (int(r["rt"][g]), e, hi - lo, g - lo)
85    return keys
86
87
88def sets(a):
89    """Each layer: the set rows' y / h error between run A and run B, a row matched to the other run's by its (token,
90    expert) - DS4_DUMP_R of each run (--route RA RB: the routing may differ) - the median, the worst row, position P's
91    rows, with the expert's rows, the row's place in them and the piece it was computed in (row0+rows/experts x max)."""
92    RA, RB = (read_r(f) for f in a.route)
93    YB = read_y(a.files[1], a.ff, a.dim)
94    print("%-3s %8s | %-52s | %s" % ("L", "median y", "worst: y err, h err, token, expert rows+place, ring, piece",
95                                     "pos %d: y err, h err, expert rows+place, ring, piece" % a.pos))
96    for il, pa in read_y(a.files[0], a.ff, a.dim):
97        ilb, pb = next(YB)
98        assert ilb == il, (il, ilb)
99        ka = [row_keys(r) for (l2, _), r in RA.items() if l2 == il]
100        kb = [row_keys(r) for (l2, _), r in RB.items() if l2 == il]
101        if len(ka) != 1 or len(kb) != 1:   # (one chunk: p0 0)
102            continue
103        ka, kb = ka[0], kb[0]
104        rows = {}
105        for d in pb:
106            for i in range(d["n"]):
107                t, e, _, _ = kb[d["a"] + i]
108                rows[(t, e)] = (d, i)
109        errs = []
110        for d in pa:
111            for i in range(d["n"]):
112                t, e, n, pl = ka[d["a"] + i]
113                if (t, e) not in rows:
114                    continue
115                db, ib = rows[(t, e)]
116                eh = float(rel(d["h"][i:i + 1].astype(np.float32), db["h"][ib:ib + 1].astype(np.float32))[0])
117                ey = float(rel(d["y"][i:i + 1], db["y"][ib:ib + 1])[0])
118                errs.append((ey, eh, t, e, n, pl, d["ring"], "%d+%d/%dx%d" % (d["a"], d["n"], d["ne"], d["mr"])))
119        if not errs:
120            continue
121        w = max(errs)
122        mine = sorted((x for x in errs if x[2] == a.pos), reverse=True)
123        print("%-3d %8.1e | %7.1e %7.1e t%-4d e%-3d %3d+%-3d %d %-16s | %s" % (
124            il, float(np.median([x[0] for x in errs])), w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7],
125            "; ".join("%.1e %.1e e%d %d+%d %d %s" % (x[0], x[1], x[3], x[4], x[5], x[6], x[7]) for x in mine)))
126
127
128def main():
129    ap = argparse.ArgumentParser()
130    ap.add_argument("mode", choices=["layers", "route", "sets", "gate"])
131    ap.add_argument("files", nargs="+")
132    ap.add_argument("--pos", type=int, default=-1)
133    ap.add_argument("--dim", type=int, default=5120)
134    ap.add_argument("--hc", type=int, default=4)
135    ap.add_argument("--ff", type=int, default=2304)
136    ap.add_argument("--route", nargs=2, metavar=("RA", "RB"))
137    a = ap.parse_args()
138    if a.mode == "layers":
139        A = read_l(a.files[0], a.dim * a.hc)
140        B = dict(read_l(a.files[1], a.dim * a.hc))
141        print("%-12s %10s %10s %6s %10s" % ("record", "median", "worst", "at", "pos %d" % a.pos))
142        for key, va in A:
143            if key not in B:
144                continue
145            e = rel(va, B[key])
146            w = int(np.argmax(e))
147            p = a.pos - key[1]
148            ep = "%.3e" % e[p] if 0 <= p < len(e) else "-"
149            print("%-12s %10.3e %10.3e %6d %10s" % ("L%d@%d" % key, float(np.median(e)), float(e[w]), w + key[1], ep))
150        return
151    if a.mode == "gate":
152        for f in a.files:   # each run's router at position P: the picks and the margin past the k-th
153            print("== %s" % f)
154            for (il, p0), r in sorted(read_r(f).items()):
155                p = a.pos - p0
156                if not 0 <= p < r["t"]:
157                    continue
158                lg = r["glog"][p].astype(np.float64)
159                sc = np.sqrt(np.where(lg > 20, lg, np.log1p(np.exp(np.minimum(lg, 20)))))
160                sel = sc + r["bias"]
161                o = np.argsort(-sel, kind="stable")
162                k = r["k"]
163                print("L%-3d picks %s | k-th %.5f, next e%d %.5f: margin %.2e" % (
164                    il, " ".join("e%d" % e for e in o[:k]), sel[o[k - 1]], o[k], sel[o[k]], sel[o[k - 1]] - sel[o[k]]))
165        return
166    if a.mode == "route":
167        R = read_r(a.files[0])
168        for (il, p0), r in sorted(R.items()):
169            p = a.pos - p0
170            if not 0 <= p < r["t"]:
171                continue
172            rows = np.nonzero(r["rt"] == p)[0]
173            parts = []
174            for e in r["ri"][p]:
175                v = int(r["vs"][e])
176                lo, hi = int(r["b"][v]), int(r["b"][v + 1])
177                mine = [int(x) for x in rows if lo <= x < hi]
178                parts.append("e%d v%d%s rows %d (row %s, %d into it)" % (e, v, "" if v < r["nsl"] else "*", hi - lo,
179                             mine[0] if mine else "?", (mine[0] - lo) if mine else -1))
180            print("L%d@%d: %s" % (il, p0, "; ".join(parts)))
181        return
182    sets(a)
183
184
185if __name__ == "__main__":
186    sys.exit(main())