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
4.9 KiB92 linesraw
1"""gyro_error_profile.py - how is agentionai's quantization error distributed, compared with a plain-MSE encode?
2
3For a few expert matrices of a Gyro file: W' = rotated original (hf_slice), Wd = the file's decoded weights, Wo = our plain
4encode.  Reports, per column of the (rotated) input axis and per row, how uneven the squared error is (a plain-MSE encoder
5spreads it evenly; an activation-weighted one concentrates it where the weights matter less), the scale ratio of their
6blocks to the least-squares scale of their own path, and the correlation of their error with ours.
7"""
8from __future__ import annotations
9
10import argparse
11import mmap
12import pathlib
13import sys
14
15import numpy as np
16
17HERE = pathlib.Path(__file__).resolve().parent
18sys.path.insert(0, str(HERE.parent))
19sys.path.insert(0, str(HERE))
20import gguf_reader  # noqa: E402
21import hf_slice  # noqa: E402
22import tqenc  # noqa: E402
23
24
25def main() -> int:
26    ap = argparse.ArgumentParser()
27    ap.add_argument("--gguf", required=True)
28    ap.add_argument("--repo", default="Qwen/Qwen3.8-Flash-Next")
29    ap.add_argument("--layers", default="10")
30    ap.add_argument("--experts", default="0")
31    ap.add_argument("--roles", default="gate,down")
32    a = ap.parse_args()
33    g = gguf_reader.GGUFFile(a.gguf)
34    fh = open(a.gguf, "rb")
35    mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
36    by = {t.name: t for t in g.tensors}
37    sw = [int(x) for x in g.metadata["prism.hadamard.sign_widths"]]
38    sv = np.array(g.metadata["prism.hadamard.sign_values"], dtype=np.float32)
39    signs, at = {}, 0
40    for w in sw:
41        signs[w] = sv[at:at + w]
42        at += w
43    repo = hf_slice.Repo(a.repo)
44    for layer in [int(x) for x in a.layers.split(",")]:
45        pre = "model.language_model.layers.%d.mlp.experts." % layer
46        for e in [int(x) for x in a.experts.split(",")]:
47            gu = repo.tensor(pre + "gate_up_proj", e)[0]
48            dn = repo.tensor(pre + "down_proj", e)[0]
49            mats = {"gate": gu[:640], "up": gu[640:], "down": dn}
50            for role in a.roles.split(","):
51                W = mats[role]
52                ti = by["blk.%d.ffn_%s_exps.weight" % (layer, role)]
53                t = tqenc.TYPE_BY_NAME[ti.type_name]
54                n_in, n_out = ti.shape[0], ti.shape[1]
55                bb = tqenc.block_bytes(t)
56                rb = n_in // 128 * bb
57                raw = np.frombuffer(mm, dtype=np.uint8, count=n_out * rb, offset=g.data_start + ti.offset + e * n_out * rb)
58                Wd = tqenc.decode(raw, t).reshape(n_out, n_in)
59                Wr = tqenc.rotate(W, signs[n_in])
60                packed, _, _, _ = tqenc.encode(Wr, t, iters=3, ncand=3, threads=8)
61                Wo = tqenc.decode(packed, t).reshape(n_out, n_in)
62                Ed, Eo = (Wr - Wd).astype(np.float64), (Wr - Wo).astype(np.float64)
63                print("L%d e%d %s %s" % (layer, e, role, ti.type_name))
64                for name, E in (("agentionai", Ed), ("ours (plain MSE)", Eo)):
65                    col = (E ** 2).mean(axis=0)
66                    row = (E ** 2).mean(axis=1)
67                    blk = (E ** 2).reshape(n_out, n_in // 128, 128).mean(axis=2)
68                    pos = (E ** 2).reshape(-1, 128).mean(axis=0)
69                    print("  %-18s rel MSE %.4f | per-column error: cv %.3f, max/mean %.2f | per-row: cv %.3f | per-128-block: cv %.3f | "
70                          "position-in-block cv %.3f | corr(error, |w|) %.3f" % (
71                              name, (E ** 2).sum() / (Wr.astype(np.float64) ** 2).sum(), col.std() / col.mean(), col.max() / col.mean(),
72                              row.std() / row.mean(), blk.std() / blk.mean(), pos.std() / pos.mean(),
73                              np.corrcoef(np.abs(Wr).ravel()[::7], np.abs(E).ravel()[::7])[0, 1]))
74                # their scale vs the least-squares scale for their own path
75                dv = raw.reshape(-1, bb)[:, :2].copy().view(np.float16).astype(np.float64).ravel()
76                cw = tqenc.decode(np.concatenate([np.zeros((raw.size // bb, 2), np.uint8), raw.reshape(-1, bb)[:, 2:]], axis=1), t)  # d = 0 -> zeros
77                # unit-scale path values: decode with d = 1.0 (fp16 0x3c00)
78                one = raw.reshape(-1, bb).copy()
79                one[:, 0] = 0x00
80                one[:, 1] = 0x3c
81                cu = tqenc.decode(one, t).reshape(-1, 128).astype(np.float64)
82                wb = Wr.reshape(-1, 128).astype(np.float64)
83                ls = (wb * cu).sum(axis=1) / (cu * cu).sum(axis=1)
84                print("  their scale / LS-optimal scale for their own path: median %.3f  p10 %.3f  p90 %.3f" % (
85                    np.median(dv / ls), np.percentile(dv / ls, 10), np.percentile(dv / ls, 90)))
86                print("  error correlation (theirs, ours): %.3f   energy of their error that is orthogonal to ours: %.3f" % (
87                    np.corrcoef(Ed.ravel()[::5], Eo.ravel()[::5])[0, 1], 1 - (Ed * Eo).sum() ** 2 / ((Ed ** 2).sum() * (Eo ** 2).sum())))
88    return 0
89
90
91if __name__ == "__main__":
92    sys.exit(main())