okami.mom/strata

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

Niko1221Merge f-dsv41-rel (0be62ccad) into v0.2.3.1: DeepSeek V4.1-Flash on top of the released 0.2.3 line28ce98bf1

main
5.3 KiB107 linesraw
1"""gyro_reencode.py - gate 2/3 quality check of the trellis encoder against agentionai's Gyro files.
2
3Decodes expert tensors of a Gyro GGUF (TQK6 gate/up, TQK7 down in Gyro-S; TQ2_T in Gyro-M) with the Strata decoder
4(libtqenc's decode, bit-identical to tq_states.hpp, see tqenc_test), re-encodes the decoded weights at the same type
5with tools/tqenc.py and reports the reconstruction error.  The decoded weights are a feasible trellis point, so an
6ideal encoder recovers them exactly (error 0): the error measures the search, not the quantization.
7
8  python3 tools/trellis/gyro_reencode.py --gguf /data/models/gyro/Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf \
9      --layers 0,20,39 --experts 0,7 --rows 256 [--cfg default,rot3,scale3]
10"""
11from __future__ import annotations
12
13import argparse
14import mmap
15import pathlib
16import sys
17import time
18
19import numpy as np
20
21HERE = pathlib.Path(__file__).resolve().parent
22sys.path.insert(0, str(HERE.parent))
23import gguf_reader  # noqa: E402
24import tqenc  # noqa: E402
25
26CFGS = {
27    "fast": dict(iters=0, ncand=1, scale_tries=1),
28    "default": dict(iters=1, ncand=1, scale_tries=1),
29    "iters3": dict(iters=3, ncand=1, scale_tries=1),
30    "rot3": dict(iters=3, ncand=3, scale_tries=1),
31    "scale3": dict(iters=3, ncand=3, scale_tries=3),
32    "scale5": dict(iters=3, ncand=3, scale_tries=5),
33}
34
35
36def main() -> int:
37    ap = argparse.ArgumentParser()
38    ap.add_argument("--gguf", required=True)
39    ap.add_argument("--layers", default="0,20,39")
40    ap.add_argument("--experts", default="0")
41    ap.add_argument("--rows", type=int, default=256, help="rows (output channels) of each expert slice to test")
42    ap.add_argument("--cfg", default="fast,default,rot3")
43    ap.add_argument("--roles", default="gate,up,down")
44    ap.add_argument("--threads", type=int, default=0)
45    a = ap.parse_args()
46
47    g = gguf_reader.GGUFFile(a.gguf)
48    fh = open(a.gguf, "rb")
49    mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
50    by_name = {t.name: t for t in g.tensors}
51    print("file", pathlib.Path(a.gguf).name, "tensors", len(g.tensors), "types", g.by_type())
52    hk = {k: v for k, v in g.metadata.items() if k.startswith("prism.") and not isinstance(v, list)}
53    print("prism metadata:", hk)
54    cfgs = a.cfg.split(",")
55    rows_total = {c: [0.0, 0.0, 0, 0, 0.0] for c in cfgs}   # err, energy, blocks, exact blocks, seconds
56    for layer in [int(x) for x in a.layers.split(",")]:
57        for role in a.roles.split(","):
58            name = "blk.%d.ffn_%s_exps.weight" % (layer, role)
59            ti = by_name.get(name)
60            if ti is None:
61                print("no tensor", name)
62                continue
63            t = tqenc.TYPE_BY_NAME.get(ti.type_name)
64            if t is None:
65                print(name, "type", ti.type_name, "is not a trellis type: skipped")
66                continue
67            n_in, n_out, n_exp = ti.shape[0], ti.shape[1], ti.shape[2]
68            bb = tqenc.block_bytes(t)
69            row_bytes = n_in // 128 * bb
70            for e in [int(x) for x in a.experts.split(",")]:
71                nrows = min(a.rows, n_out)
72                off = g.data_start + ti.offset + (e * n_out) * row_bytes
73                raw = np.frombuffer(mm, dtype=np.uint8, count=nrows * row_bytes, offset=off)
74                wd = tqenc.decode(raw, t).reshape(nrows, n_in)
75                en = float(np.sum(wd.astype(np.float64) ** 2))
76                scales = raw.reshape(-1, bb)[:, :2].copy().view(np.float16).astype(np.float32).ravel()
77                print("%s expert %d: %d rows x %d, %s %.3f bpw, |w| rms %.4g, agentionai block scales: median %.4g, "
78                      "p1 %.4g, p99 %.4g, zero-scale blocks %d" % (
79                          name, e, nrows, n_in, ti.type_name, tqenc.bpw(t), np.sqrt(en / wd.size),
80                          np.median(scales), np.percentile(scales, 1), np.percentile(scales, 99), int((scales == 0).sum())))
81                for c in cfgs:
82                    t0 = time.time()
83                    packed, err, tot, st = tqenc.encode(wd, t, threads=a.threads, **CFGS[c])
84                    sec = time.time() - t0
85                    dec = tqenc.decode(packed, t)
86                    chk = float(np.sum((wd.ravel().astype(np.float64) - dec) ** 2))
87                    nexact = int((err == 0).sum())
88                    same_bytes = int((packed.reshape(-1) == raw).sum()) / raw.size
89                    print("    %-8s rel MSE %.3e  SQNR %7.2f dB  exact blocks %5d/%d (%.1f%%)  scale==theirs %.1f%%  "
90                          "%.0f weights/s  (recheck %.3e)" % (
91                              c, tot / en, tqenc.sqnr_db(wd, dec), nexact, err.size, 100.0 * nexact / err.size,
92                              100.0 * float(np.mean(packed[:, :2].reshape(-1, 2).view(np.uint16).ravel()
93                                                    == raw.reshape(-1, bb)[:, :2].copy().view(np.uint16).ravel())),
94                              wd.size / sec, chk / en))
95                    r = rows_total[c]
96                    r[0] += tot; r[1] += en; r[2] += err.size; r[3] += nexact; r[4] += sec
97    print("\nTOTAL over all tested slices")
98    for c in cfgs:
99        r = rows_total[c]
100        if r[1] > 0:
101            print("  %-8s rel MSE %.3e  SQNR %.2f dB  exact blocks %.1f%%  %.0f weights/s" % (
102                c, r[0] / r[1], 10 * np.log10(r[1] / max(r[0], 1e-300)), 100.0 * r[3] / r[2], r[2] * 128 / max(r[4], 1e-9)))
103    return 0
104
105
106if __name__ == "__main__":
107    sys.exit(main())