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
11.8 KiB228 linesraw
1"""pilot.py - gate-3 block-quality pilot: a few experts from several layers of a source checkpoint, encoded at TQK4X / TQK5X /
2TQK6 / TQK7 with and without the input-only block-128 Hadamard, and measured.
3
4Sources:  --gguf <shard1 or shard dir files...>  (UD-Q8_K_XL: MXFP4 / Q8_0 / BF16 / F16 tensors, decoded exactly: the decoded
5          source is the teacher, as the plan says)   or   --hf Qwen/...  (range requests; test of the pipeline)
6
7Metrics per (layer, role, expert, rate, transform), over a random row subset of the projection (--rows):
8  mse     relative weight MSE ||W - W^||^2 / ||W||^2 in the original basis (the Hadamard is orthonormal: the same in either basis)
9  act_iso ||(W - W^) X||^2 / ||W X||^2 with X i.i.d. N(0,1) columns - PLACEHOLDER; in expectation equal to mse
10  act_syn ||(W - W^) X||^2 / ||W X||^2 with X whose input channels have heavy-tailed scales (a few outlier channels,
11          log-normal rest) - SYNTHETIC PLACEHOLDER for real calibration activations, labelled as such in every output
12Real activation-weighted numbers need calibration activations from the reference runtime (not done here).
13"""
14from __future__ import annotations
15
16import argparse
17import json
18import mmap
19import pathlib
20import sys
21import time
22
23import numpy as np
24
25HERE = pathlib.Path(__file__).resolve().parent
26sys.path.insert(0, str(HERE.parent))
27sys.path.insert(0, str(HERE))
28import gguf_reader  # noqa: E402
29import tqenc  # noqa: E402
30
31MXFP4_LUT = np.array([0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12], dtype=np.float32)
32RATES = {"K4": tqenc.TQK4X, "K5": tqenc.TQK5X, "K6": tqenc.TQK6, "K7": tqenc.TQK7, "K4t": tqenc.TQK4T, "K5t": tqenc.TQK5T}   # K4 / K5: computed codebook (v2); K4t / K5t: point table (v1)
33CFGS = {
34    "fast": dict(iters=0, ncand=1, scale_tries=1),
35    "default": dict(iters=1, ncand=1, scale_tries=1),
36    "rot3": dict(iters=3, ncand=3, scale_tries=1),
37}
38
39
40def decode_mxfp4(raw: np.ndarray, n_in: int) -> np.ndarray:
41    """raw: [rows * n_in/32 * 17] bytes -> float32 [rows, n_in].  ggml block_mxfp4: e8m0 scale, 16 bytes, low nibble =
42    element j, high nibble = element j + 16, value = kvalues[nibble] * 2^(e - 128) (the e8m0 half scale)."""
43    b = raw.reshape(-1, 17)
44    e = b[:, 0].astype(np.int32)
45    d = np.where(e == 0, np.float32(2.0 ** -127), np.ldexp(np.float32(1.0), e - 128)).astype(np.float32)
46    q = b[:, 1:]
47    vals = np.concatenate([MXFP4_LUT[q & 15], MXFP4_LUT[q >> 4]], axis=1) * d[:, None]
48    return vals.reshape(-1, n_in)
49
50
51def decode_q8_0(raw: np.ndarray, n_in: int) -> np.ndarray:
52    b = raw.reshape(-1, 34)
53    d = b[:, :2].copy().view(np.float16).astype(np.float32)
54    q = b[:, 2:].copy().view(np.int8).astype(np.float32)
55    return (q * d).reshape(-1, n_in)
56
57
58class Source:
59    """Yields float32 [rows, n_in] row subsets of one expert's projection.  Local GGUF files (mmap) or, with
60    remote=(repo, rev, [shard paths]), the same files read by HTTP range requests (headers and the few experts needed)."""
61
62    def __init__(self, gguf_paths=None, remote=None, tmpdir="/tmp"):
63        self.tensors = {}
64        if gguf_paths:
65            for p in gguf_paths:
66                g = gguf_reader.GGUFFile(p)
67                fh = open(p, "rb")
68                mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
69                for t in g.tensors:
70                    self.tensors[t.name] = (g, (lambda off, n, mm=mm: np.frombuffer(mm, dtype=np.uint8, count=n, offset=off)), t)
71        if remote:
72            import urllib.request
73            repo, rev, shards = remote
74            for sh in shards:
75                url = "https://huggingface.co/%s/resolve/%s/%s" % (repo, rev, sh)
76
77                def rd(off, n, url=url):
78                    req = urllib.request.Request(url, headers={"Range": "bytes=%d-%d" % (off, off + n - 1)})
79                    with urllib.request.urlopen(req, timeout=300) as r:
80                        return np.frombuffer(r.read(), dtype=np.uint8)
81                hdr = rd(0, 6 << 20)
82                tp = pathlib.Path(tmpdir) / ("hdr_%s" % pathlib.Path(sh).name)
83                tp.write_bytes(hdr.tobytes())
84                g = gguf_reader.GGUFFile(tp)
85                for t in g.tensors:
86                    self.tensors[t.name] = (g, rd, t)
87
88    def names(self, needle):
89        return sorted(n for n in self.tensors if needle in n)
90
91    def expert_rows(self, name: str, expert: int, rows: np.ndarray) -> np.ndarray:
92        g, rd, ti = self.tensors[name]
93        n_in, n_out = ti.shape[0], ti.shape[1]
94        if ti.type_name == "MXFP4":
95            rb = n_in // 32 * 17
96        elif ti.type_name == "Q8_0":
97            rb = n_in // 32 * 34
98        elif ti.type_name in ("BF16", "F16"):
99            rb = n_in * 2
100        elif ti.type_name == "F32":
101            rb = n_in * 4
102        else:
103            raise ValueError("%s: tensor type %s is not readable by this pilot" % (name, ti.type_name))
104        base = g.data_start + ti.offset + expert * n_out * rb
105        whole = rd(base, n_out * rb)     # one expert's projection (6.3 MB for MXFP4 2304 x 5120), then the row subset
106        out = np.empty((len(rows), n_in), dtype=np.float32)
107        for k, r in enumerate(rows):
108            raw = whole[int(r) * rb:(int(r) + 1) * rb]
109            if ti.type_name == "MXFP4":
110                out[k] = decode_mxfp4(raw, n_in)[0]
111            elif ti.type_name == "Q8_0":
112                out[k] = decode_q8_0(raw, n_in)[0]
113            elif ti.type_name == "BF16":
114                out[k] = (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32)
115            elif ti.type_name == "F16":
116                out[k] = raw.view(np.float16).astype(np.float32)
117            else:
118                out[k] = raw.view(np.float32)
119        return out
120
121
122def synth_x(n_in: int, T: int, seed: int) -> np.ndarray:
123    """SYNTHETIC activations: channel scale exp(N(0, 0.5)), 1% of the channels x (10..40)."""
124    r = np.random.default_rng(seed)
125    s = np.exp(0.5 * r.standard_normal(n_in)).astype(np.float32)
126    out = r.choice(n_in, size=max(1, n_in // 100), replace=False)
127    s[out] *= r.uniform(10, 40, size=out.size).astype(np.float32)
128    return (r.standard_normal((n_in, T)).astype(np.float32) * s[:, None])
129
130
131def act_err(W, What, X):
132    D = (W - What).astype(np.float32) @ X
133    Y = W.astype(np.float32) @ X
134    return float(np.sum(D.astype(np.float64) ** 2) / max(np.sum(Y.astype(np.float64) ** 2), 1e-300))
135
136
137def main() -> int:
138    ap = argparse.ArgumentParser()
139    ap.add_argument("--gguf", nargs="+", default=None)
140    ap.add_argument("--remote", default=None, help="REPO@REV: read the shards named in --shards by HTTP range requests")
141    ap.add_argument("--shards", nargs="+", default=[])
142    ap.add_argument("--layers", default="1,7,14,21,30,38")
143    ap.add_argument("--experts", default="0,97,200,383")
144    ap.add_argument("--roles", default="gate,up,down")
145    ap.add_argument("--rates", default="K4,K5,K6,K7")
146    ap.add_argument("--rows", type=int, default=256)
147    ap.add_argument("--tokens", type=int, default=256, help="columns of the placeholder X")
148    ap.add_argument("--cfg", default="default")
149    ap.add_argument("--threads", type=int, default=0)
150    ap.add_argument("--out", required=True, help="jsonl results")
151    ap.add_argument("--seed", type=int, default=1)
152    ap.add_argument("--pattern", default="blk.{L}.ffn_{R}_exps.weight")
153    ap.add_argument("--gpu", action="store_true", help="encode on the GPU (run under the box locks, HIP_VISIBLE_DEVICES)")
154    ap.add_argument("--act-diag-dir", default=None,
155                    help="directory with L<layer>_<role>.npy = E[x^2] per input channel of that projection (calibration "
156                         "second moments, diagonal).  Adds act_diag (the exact diagonal-Hessian error) and an importance-weighted "
157                         "encode (h = E[x^2]; in the Hadamard basis h = the block average of it)")
158    a = ap.parse_args()
159
160    if a.remote:
161        repo, rev = a.remote.split("@")
162        src = Source(remote=(repo, rev, a.shards))
163    else:
164        src = Source(a.gguf)
165    rng = np.random.default_rng(a.seed)
166    cfg = CFGS[a.cfg]
167    sign_cache, x_cache = {}, {}
168    out = open(a.out, "a")
169    for layer in [int(x) for x in a.layers.split(",")]:
170        for role in a.roles.split(","):
171            name = a.pattern.format(L=layer, R=role)
172            if name not in src.tensors:
173                print("no tensor", name, "(have e.g. %s)" % src.names("exps")[:3])
174                continue
175            g, rd, ti = src.tensors[name]
176            n_in, n_out, n_exp = ti.shape[0], ti.shape[1], ti.shape[2]
177            for e in [int(x) for x in a.experts.split(",")]:
178                if e >= n_exp:
179                    continue
180                rows = np.sort(rng.choice(n_out, size=min(a.rows, n_out), replace=False))
181                W = src.expert_rows(name, e, rows)
182                en = float(np.sum(W.astype(np.float64) ** 2))
183                if n_in not in sign_cache:
184                    sign_cache[n_in] = tqenc.make_signs(n_in, 1000 + n_in)
185                    x_cache[n_in] = (np.random.default_rng(7).standard_normal((n_in, a.tokens)).astype(np.float32),
186                                     synth_x(n_in, a.tokens, 9))
187                Xi, Xs = x_cache[n_in]
188                diag = None
189                if a.act_diag_dir:
190                    dp = pathlib.Path(a.act_diag_dir) / ("L%d_%s.npy" % (layer, role))
191                    if dp.exists():
192                        diag = np.load(dp).astype(np.float64)
193                        assert diag.shape == (n_in,), (dp, diag.shape)
194                for had in (False, True):
195                    sg = sign_cache[n_in] if had else None
196                    Wr = tqenc.rotate(W, sg) if had else W
197                    for rname in a.rates.split(","):
198                        t = RATES[rname]
199                        t0 = time.time()
200                        packed, err, tot, st = tqenc.encode(Wr, t, threads=a.threads, gpu=a.gpu, **cfg)
201                        sec = time.time() - t0
202                        dec = tqenc.decode(packed, t).reshape(Wr.shape)
203                        What = tqenc.unrotate(dec, sg) if had else dec
204                        rec = dict(layer=layer, role=role, expert=e, rate=rname, had=had, n_in=n_in, rows=len(rows),
205                                   mse=float(np.sum((W.astype(np.float64) - What) ** 2) / en),
206                                   act_iso=act_err(W, What, Xi), act_syn=act_err(W, What, Xs),
207                                   bpw=tqenc.bpw(t), seconds=sec, zero_blocks=st["zero_blocks"], cfg=a.cfg,
208                                   x_kind="placeholder: iso gaussian / synthetic outlier channels")
209                        if diag is not None:
210                            hv = np.maximum(diag, 1e-30).astype(np.float32)
211                            rec["act_diag"] = float(np.sum(((W - What).astype(np.float64) ** 2) * hv) / np.sum((W.astype(np.float64) ** 2) * hv))
212                            hb = hv if not had else np.repeat(hv.reshape(-1, 128).mean(axis=1), 128)
213                            hw = np.broadcast_to(hb, Wr.shape).astype(np.float32)
214                            packed2, _, _, _ = tqenc.encode(Wr, t, h=hw, threads=a.threads, gpu=a.gpu, **cfg)
215                            dec2 = tqenc.decode(packed2, t).reshape(Wr.shape)
216                            What2 = tqenc.unrotate(dec2, sg) if had else dec2
217                            rec["act_diag_weighted_encode"] = float(np.sum(((W - What2).astype(np.float64) ** 2) * hv) / np.sum((W.astype(np.float64) ** 2) * hv))
218                            rec["mse_weighted_encode"] = float(np.sum((W.astype(np.float64) - What2) ** 2) / en)
219                        out.write(json.dumps(rec) + "\n")
220                        out.flush()
221                        print("L%-3d %-4s e%-3d %s %-5s mse %.4f (%.2f dB)  act_iso %.4f  act_syn %.4f  %.1fs" % (
222                            layer, role, e, rname, "had" if had else "plain", rec["mse"], -10 * np.log10(rec["mse"]),
223                            rec["act_iso"], rec["act_syn"], sec), flush=True)
224    return 0
225
226
227if __name__ == "__main__":
228    sys.exit(main())