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.0 KiB107 linesraw
1"""gyro_vs_original.py - the fair comparison: agentionai's Gyro quantization of Qwen3.8-Flash-Next against OUR encoder, both
2measured against the original BF16 expert weights (fetched tensor by tensor with HTTP range requests, ~10 MB per expert).
3
4For a layer and expert: W = original (gate, up from the fused gate_up_proj, down), rotated into the file's basis with the
5file's own sign vectors (prism.hadamard.sign_values, widths 2560 / 640): W' = H (s * w) per row and 128-block.
6  agentionai: Wd  = decode of the file's blocks
7  ours:       Wo  = decode(encode(W'))   at the same type (TQK6 gate/up, TQK7 down), several search settings
8Reported: relative MSE and SQNR of each against W'.
9
10  python3 tools/trellis/gyro_vs_original.py --gguf <Gyro-S> --layers 0,20,39 --experts 0,5 --cfg fast,default,rot3
11"""
12from __future__ import annotations
13
14import argparse
15import mmap
16import pathlib
17import sys
18import time
19
20import numpy as np
21
22HERE = pathlib.Path(__file__).resolve().parent
23sys.path.insert(0, str(HERE.parent))
24sys.path.insert(0, str(HERE))
25import gguf_reader  # noqa: E402
26import hf_slice  # noqa: E402
27import tqenc  # noqa: E402
28
29CFGS = {
30    "fast": dict(iters=0, ncand=1, scale_tries=1),
31    "default": dict(iters=1, ncand=1, scale_tries=1),
32    "iters3": dict(iters=3, ncand=1, scale_tries=1),
33    "rot3": dict(iters=3, ncand=3, scale_tries=1),
34    "scale3": dict(iters=3, ncand=3, scale_tries=3),
35}
36
37
38def main() -> int:
39    ap = argparse.ArgumentParser()
40    ap.add_argument("--gguf", required=True)
41    ap.add_argument("--repo", default="Qwen/Qwen3.8-Flash-Next")
42    ap.add_argument("--layers", default="0,20,39")
43    ap.add_argument("--experts", default="0")
44    ap.add_argument("--cfg", default="fast,default,rot3")
45    ap.add_argument("--threads", type=int, default=0)
46    a = ap.parse_args()
47
48    g = gguf_reader.GGUFFile(a.gguf)
49    fh = open(a.gguf, "rb")
50    mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
51    by_name = {t.name: t for t in g.tensors}
52    sw = [int(x) for x in g.metadata["prism.hadamard.sign_widths"]]
53    sv = np.array(g.metadata["prism.hadamard.sign_values"], dtype=np.float32)
54    signs, at = {}, 0
55    for w in sw:
56        signs[w] = sv[at:at + w]
57        at += w
58    print("sign widths", sw)
59    repo = hf_slice.Repo(a.repo)
60    cfgs = a.cfg.split(",")
61    tot = {k: [0.0, 0.0] for k in ["agentionai"] + cfgs}
62    tot_role = {}
63    for layer in [int(x) for x in a.layers.split(",")]:
64        pre = "model.language_model.layers.%d.mlp.experts." % layer
65        for e in [int(x) for x in a.experts.split(",")]:
66            t0 = time.time()
67            gu = repo.tensor(pre + "gate_up_proj", e)[0]      # [1280, 2560]
68            dn = repo.tensor(pre + "down_proj", e)[0]         # [2560, 640]
69            print("layer %d expert %d fetched in %.1f s: gate_up %s down %s" % (layer, e, time.time() - t0, gu.shape, dn.shape))
70            mats = {"gate": gu[:640], "up": gu[640:], "down": dn}
71            for role, W in mats.items():
72                ti = by_name["blk.%d.ffn_%s_exps.weight" % (layer, role)]
73                t = tqenc.TYPE_BY_NAME[ti.type_name]
74                n_in, n_out = ti.shape[0], ti.shape[1]
75                assert W.shape == (n_out, n_in), (W.shape, ti.shape)
76                bb = tqenc.block_bytes(t)
77                row_bytes = n_in // 128 * bb
78                off = g.data_start + ti.offset + e * n_out * row_bytes
79                raw = np.frombuffer(mm, dtype=np.uint8, count=n_out * row_bytes, offset=off)
80                wd = tqenc.decode(raw, t).reshape(n_out, n_in)
81                Wr = tqenc.rotate(W, signs[n_in])
82                en = float(np.sum(Wr.astype(np.float64) ** 2))
83                ea = float(np.sum((Wr.astype(np.float64) - wd) ** 2))
84                # sanity: the fused gate_up order (gate first) - if swapped the SQNR collapses
85                line = ["agentionai %s %.2f dB" % (ti.type_name, 10 * np.log10(en / ea))]
86                key = "%s" % role
87                tot["agentionai"][0] += ea; tot["agentionai"][1] += en
88                tr = tot_role.setdefault(key, {k: [0.0, 0.0] for k in ["agentionai"] + cfgs})
89                tr["agentionai"][0] += ea; tr["agentionai"][1] += en
90                for c in cfgs:
91                    t1 = time.time()
92                    packed, err, totr, st = tqenc.encode(Wr, t, threads=a.threads, **CFGS[c])
93                    sec = time.time() - t1
94                    line.append("%s %.2f dB (%.0fk w/s)" % (c, 10 * np.log10(en / totr), Wr.size / sec / 1e3))
95                    tot[c][0] += totr; tot[c][1] += en
96                    tr[c][0] += totr; tr[c][1] += en
97                print("  L%d e%d %-4s  " % (layer, e, role) + " | ".join(line))
98    print("\nTOTAL SQNR (dB) against the rotated original, all tested matrices")
99    for k, (er, en) in tot.items():
100        print("  %-10s %.3f dB  (rel MSE %.4e)" % (k, 10 * np.log10(en / er), er / en))
101    for role, d in tot_role.items():
102        print("  %-5s " % role + "  ".join("%s %.3f" % (k, 10 * np.log10(v[1] / v[0])) for k, v in d.items()))
103    return 0
104
105
106if __name__ == "__main__":
107    sys.exit(main())