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
3.2 KiB70 linesraw
1"""gyro_column_profile.py - is the unevenness of agentionai's per-input-column error a property of the layer (an
2activation-aware objective shared by all experts that read the same input) or noise?  Compares the per-column squared-error
3profile (rotated basis) between experts and between gate and up of one layer, for their file and for our plain encode.
4"""
5from __future__ import annotations
6
7import argparse
8import mmap
9import pathlib
10import sys
11
12import numpy as np
13
14HERE = pathlib.Path(__file__).resolve().parent
15sys.path.insert(0, str(HERE.parent))
16sys.path.insert(0, str(HERE))
17import gguf_reader  # noqa: E402
18import hf_slice  # noqa: E402
19import tqenc  # noqa: E402
20
21
22def main() -> int:
23    ap = argparse.ArgumentParser()
24    ap.add_argument("--gguf", required=True)
25    ap.add_argument("--repo", default="Qwen/Qwen3.8-Flash-Next")
26    ap.add_argument("--layer", type=int, default=10)
27    ap.add_argument("--experts", default="0,1,2,3")
28    a = ap.parse_args()
29    g = gguf_reader.GGUFFile(a.gguf)
30    fh = open(a.gguf, "rb")
31    mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
32    by = {t.name: t for t in g.tensors}
33    sw = [int(x) for x in g.metadata["prism.hadamard.sign_widths"]]
34    sv = np.array(g.metadata["prism.hadamard.sign_values"], dtype=np.float32)
35    signs, at = {}, 0
36    for w in sw:
37        signs[w] = sv[at:at + w]
38        at += w
39    repo = hf_slice.Repo(a.repo)
40    pre = "model.language_model.layers.%d.mlp.experts." % a.layer
41    prof = {}   # (who, role, expert) -> per-column mean squared error / mean
42    for e in [int(x) for x in a.experts.split(",")]:
43        gu = repo.tensor(pre + "gate_up_proj", e)[0]
44        for role, W in (("gate", gu[:640]), ("up", gu[640:])):
45            ti = by["blk.%d.ffn_%s_exps.weight" % (a.layer, role)]
46            t = tqenc.TYPE_BY_NAME[ti.type_name]
47            n_in, n_out = ti.shape[0], ti.shape[1]
48            bb = tqenc.block_bytes(t)
49            rb = n_in // 128 * bb
50            raw = np.frombuffer(mm, dtype=np.uint8, count=n_out * rb, offset=g.data_start + ti.offset + e * n_out * rb)
51            Wd = tqenc.decode(raw, t).reshape(n_out, n_in)
52            Wr = tqenc.rotate(W, signs[n_in])
53            packed, _, _, _ = tqenc.encode(Wr, t, iters=1, threads=8)
54            Wo = tqenc.decode(packed, t).reshape(n_out, n_in)
55            for who, Wq in (("theirs", Wd), ("ours", Wo)):
56                c = ((Wr - Wq).astype(np.float64) ** 2).mean(axis=0)
57                # remove the part explained by the signal's own column energy (weights of large columns err more)
58                prof[(who, role, e)] = c / c.mean()
59            print("expert %d %s fetched and encoded" % (e, role), flush=True)
60    es = [int(x) for x in a.experts.split(",")]
61    for who in ("theirs", "ours"):
62        cc = [np.corrcoef(prof[(who, "gate", es[0])], prof[(who, "gate", e)])[0, 1] for e in es[1:]]
63        cu = [np.corrcoef(prof[(who, "gate", e)], prof[(who, "up", e)])[0, 1] for e in es]
64        print("%-7s corr of the per-column error profile: gate expert %d vs other experts' gate %s | gate vs up of the same expert %s" % (
65            who, es[0], " ".join("%.3f" % x for x in cc), " ".join("%.3f" % x for x in cu)))
66    return 0
67
68
69if __name__ == "__main__":
70    sys.exit(main())