okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
10.3 KiB223 linesraw
1"""build_swap.py - Gyro-S with a few layers' experts swapped, without copying the 58 GB file.
2
3Writes <var>/swap.bin (the new gate / up / down tensors of the chosen layers) and a pack <var>/pack whose native_experts.txt
4points those layers at swap.bin (the shard column), everything else being the shipped Gyro-S pack and file: <var>/ holds a
5symlink to the shipped GGUF, so `--native <var>/<gguf name>` finds swap.bin beside it.
6
7Modes (all from the ORIGINAL Qwen weights, rotated into the file's basis with the file's own sign vectors):
8  q8     Q8_0 (types 8/8): the near-lossless reference for the swapped layers
9  plain  TQK6 gate/up + TQK7 down, plain-MSE trellis encode (tools/tqenc.py)
10  diag   the same with per-input-column importance weights h = E[x^2]^power from the calibration dump (STRATA_ACT_DUMP)
11  ldl    the same with block feedback from the full second-moment matrix of the dump (STRATA_ACT_DUMP_COV=1), blockldl.py
12
13  python3 tools/trellis/build_swap.py --gguf SHIPPED --pack PACK --orig DIR --layers 4,16,28,40 --mode plain --var DIR [--gpu]
14"""
15from __future__ import annotations
16
17import argparse
18import pathlib
19import sys
20import time
21
22import numpy as np
23
24HERE = pathlib.Path(__file__).resolve().parent
25sys.path.insert(0, str(HERE.parent))
26sys.path.insert(0, str(HERE))
27import gguf_reader  # noqa: E402
28import blockldl  # noqa: E402
29import tqenc  # noqa: E402
30
31N_EXP, N_EMBD, N_FF = 512, 2560, 640
32ALIGN = 4096
33
34
35def q8_0_quantize(w: np.ndarray) -> np.ndarray:
36    """float32 [..., n] (n % 32 == 0) -> uint8 [..., n/32 * 34] block_q8_0 (fp16 scale, 32 int8)."""
37    shp = w.shape
38    b = w.reshape(-1, 32).astype(np.float32)
39    amax = np.abs(b).max(axis=1)
40    d = amax / 127.0
41    d16 = d.astype(np.float16)
42    dq = d16.astype(np.float32)
43    with np.errstate(divide="ignore", invalid="ignore"):
44        q = np.where(dq[:, None] > 0, b / dq[:, None], 0.0)
45    q = np.clip(np.sign(q) * np.floor(np.abs(q) + 0.5), -127, 127).astype(np.int8)
46    out = np.empty((b.shape[0], 34), dtype=np.uint8)
47    out[:, :2] = d16.view(np.uint8).reshape(-1, 2)
48    out[:, 2:] = q.view(np.uint8)
49    return out.reshape(*shp[:-1], shp[-1] // 32 * 34)
50
51
52def bf16(raw: np.ndarray) -> np.ndarray:
53    return (raw.astype(np.uint32) << 16).view(np.float32)
54
55
56def load_h(dump_dir, layer, kind, power):
57    p = pathlib.Path(dump_dir) / ("act_L%d_%s.bin" % (layer, kind))
58    raw = p.read_bytes()
59    n, count = np.frombuffer(raw[:16], dtype=np.int64)
60    sq = np.frombuffer(raw[16:16 + 8 * n], dtype=np.float64)
61    h = (sq / max(count, 1)) ** power
62    h = np.maximum(h, h.mean() * 1e-4)    # no weight below 1e-4 of the mean
63    return (h / h.mean()).astype(np.float32), int(count)
64
65
66def load_hessian(dump_dir, layer, kind):
67    p = pathlib.Path(dump_dir) / ("act_L%d_%s.bin" % (layer, kind))
68    raw = p.read_bytes()
69    n, count = np.frombuffer(raw[:16], dtype=np.int64)
70    n = int(n)
71    if len(raw) < 16 + 8 * n + 8 * n * n:
72        raise SystemExit("%s has no covariance (run the calibration with STRATA_ACT_DUMP_COV=1)" % p)
73    cov = np.frombuffer(raw[16 + 8 * n:16 + 8 * n + 8 * n * n], dtype=np.float64).reshape(n, n)
74    return cov / max(int(count), 1)
75
76
77def main() -> int:
78    ap = argparse.ArgumentParser()
79    ap.add_argument("--gguf", required=True)
80    ap.add_argument("--pack", required=True)
81    ap.add_argument("--orig", required=True)
82    ap.add_argument("--layers", required=True)
83    ap.add_argument("--mode", required=True, choices=["q8", "plain", "diag", "ldl"])
84    ap.add_argument("--var", required=True)
85    ap.add_argument("--dump-dir", default=None)
86    ap.add_argument("--power", type=float, default=1.0)
87    ap.add_argument("--gpu", action="store_true")
88    ap.add_argument("--threads", type=int, default=16)
89    ap.add_argument("--iters", type=int, default=2)
90    ap.add_argument("--ncand", type=int, default=2)
91    ap.add_argument("--chunk", type=int, default=16)
92    ap.add_argument("--damp", type=float, default=0.3, help="ldl: damping, a fraction of the mean diagonal of H")
93    a = ap.parse_args()
94    layers = [int(x) for x in a.layers.split(",")]
95    var = pathlib.Path(a.var)
96    var.mkdir(parents=True, exist_ok=True)
97    gg = pathlib.Path(a.gguf)
98    link = var / gg.name
99    if not link.exists():
100        link.symlink_to(gg)
101    g = gguf_reader.GGUFFile(a.gguf)
102    sw = [int(x) for x in g.metadata["prism.hadamard.sign_widths"]]
103    sv = np.array(g.metadata["prism.hadamard.sign_values"], dtype=np.float32)
104    signs, at = {}, 0
105    for w in sw:
106        signs[w] = sv[at:at + w]
107        at += w
108    if a.mode == "q8":
109        gu_t = d_t = 8
110        row_gu, row_d = N_EMBD // 32 * 34, N_FF // 32 * 34
111    else:
112        gu_t, d_t = tqenc.TQK6, tqenc.TQK7
113        row_gu, row_d = N_EMBD // 128 * tqenc.block_bytes(gu_t), N_FF // 128 * tqenc.block_bytes(d_t)
114    t_gate = N_EXP * N_FF * row_gu          # bytes of the gate (and up) tensor of a layer
115    t_down = N_EXP * N_EMBD * row_d
116    swap = open(var / "swap.bin", "wb")
117    offs = {}
118    pos = 0
119    for l in layers:
120        offs[l] = {}
121        for role, nbytes in (("gate", t_gate), ("up", t_gate), ("down", t_down)):
122            offs[l][role] = pos
123            pos += (nbytes + ALIGN - 1) // ALIGN * ALIGN
124    swap.truncate(pos)
125
126    def enc(w2d, t, h):
127        kw = dict(iters=a.iters, ncand=a.ncand, gpu=a.gpu)
128        if not a.gpu:
129            kw["threads"] = a.threads
130        hh = None
131        if h is not None:
132            hh = np.broadcast_to(h, w2d.shape).astype(np.float32)
133        packed, err, tot, st = tqenc.encode(w2d, t, h=hh, **kw)
134        return packed, tot
135
136    stats = {}
137    t_start = time.time()
138    for l in layers:
139        gu_raw = np.memmap(pathlib.Path(a.orig) / ("L%d_gate_up.bf16" % l), dtype=np.uint16, mode="r").reshape(N_EXP, 2 * N_FF, N_EMBD)
140        dn_raw = np.memmap(pathlib.Path(a.orig) / ("L%d_down.bf16" % l), dtype=np.uint16, mode="r").reshape(N_EXP, N_EMBD, N_FF)
141        h_gu = h_dn = None
142        fb_gu = fb_dn = None
143        if a.mode == "ldl":
144            fb_gu = blockldl.feedback_matrices(blockldl.hessian_factor(load_hessian(a.dump_dir, l, "gu"), a.damp))
145            fb_dn = blockldl.feedback_matrices(blockldl.hessian_factor(load_hessian(a.dump_dir, l, "dn"), a.damp))
146        if a.mode == "diag":
147            h_gu, c1 = load_h(a.dump_dir, l, "gu", a.power)
148            h_dn, c2 = load_h(a.dump_dir, l, "dn", a.power)
149            print("layer %d: calibration counts gu %d dn %d; h cv gu %.2f dn %.2f" % (l, c1, c2, h_gu.std() / h_gu.mean(), h_dn.std() / h_dn.mean()))
150        err_sum = {"gate": 0.0, "up": 0.0, "down": 0.0}
151        en_sum = {"gate": 0.0, "up": 0.0, "down": 0.0}
152        for e0 in range(0, N_EXP, a.chunk):
153            e1 = min(N_EXP, e0 + a.chunk)
154            gu = bf16(np.asarray(gu_raw[e0:e1]))
155            dn = bf16(np.asarray(dn_raw[e0:e1]))
156            mats = {"gate": (gu[:, :N_FF], signs[N_EMBD], h_gu, row_gu, N_FF, t_gate, gu_t),
157                    "up": (gu[:, N_FF:], signs[N_EMBD], h_gu, row_gu, N_FF, t_gate, gu_t),
158                    "down": (dn, signs[N_FF], h_dn, row_d, N_EMBD, t_down, d_t)}
159            ldl_done = {}
160            if a.mode == "ldl":
161                # gate and up share H: one batch of rows
162                both = np.concatenate([tqenc.rotate(np.ascontiguousarray(gu[:, :N_FF]), signs[N_EMBD]).reshape(-1, N_EMBD),
163                                       tqenc.rotate(np.ascontiguousarray(gu[:, N_FF:]), signs[N_EMBD]).reshape(-1, N_EMBD)])
164                pk, dec = blockldl.encode_ldl(both, gu_t, fb_gu, gpu=a.gpu, iters=a.iters, ncand=a.ncand, threads=a.threads)
165                half = pk.shape[0] // 2
166                ldl_done["gate"] = (pk[:half].reshape(half, -1), dec[:half])
167                ldl_done["up"] = (pk[half:].reshape(half, -1), dec[half:])
168                wrd = tqenc.rotate(np.ascontiguousarray(dn), signs[N_FF]).reshape(-1, N_FF)
169                pk, dec = blockldl.encode_ldl(wrd, d_t, fb_dn, gpu=a.gpu, iters=a.iters, ncand=a.ncand, threads=a.threads)
170                ldl_done["down"] = (pk.reshape(pk.shape[0], -1), dec)
171            for role, (w, sg, h, row, n_out, tb, ty) in mats.items():
172                wr = tqenc.rotate(np.ascontiguousarray(w), sg)           # [chunk, n_out, n_in]
173                n_in = wr.shape[-1]
174                if a.mode == "q8":
175                    data = q8_0_quantize(wr)
176                    dec = None
177                elif a.mode == "ldl":
178                    data, dec = ldl_done[role]
179                    err_sum[role] += float(np.sum((wr.reshape(-1, n_in).astype(np.float64) - dec) ** 2))
180                else:
181                    packed, tot = enc(wr.reshape(-1, n_in), ty, h if a.mode == "diag" else None)
182                    data = packed
183                    err_sum[role] += tot
184                en_sum[role] += float(np.sum(wr.astype(np.float64) ** 2))
185                swap.seek(offs[l][role] + e0 * n_out * row)
186                swap.write(np.ascontiguousarray(data).tobytes())
187            if e0 % 128 == 0:
188                print("layer %d experts %d-%d done  (%.0f s)" % (l, e0, e1, time.time() - t_start), flush=True)
189        stats[l] = {r: (10 * np.log10(en_sum[r] / err_sum[r]) if err_sum[r] > 0 else None) for r in err_sum}
190        print("layer %d weight SQNR (dB, unweighted): %s" % (l, {k: (round(v, 3) if v else v) for k, v in stats[l].items()}), flush=True)
191    swap.close()
192    # the pack: symlinks to the shipped pack's files, a new native_experts.txt
193    pk = var / "pack"
194    pk.mkdir(exist_ok=True)
195    src = pathlib.Path(a.pack)
196    for f in src.iterdir():
197        if f.name == "native_experts.txt":
198            continue
199        d = pk / f.name
200        if not d.exists():
201            d.symlink_to(f.resolve())
202    lines = (src / "native_experts.txt").read_text().splitlines()
203    head, body = lines[0], lines[1:]
204    out_lines, arena = [], 0
205    for ln in body:
206        f = ln.split()
207        l = int(f[0])
208        if l in offs:
209            blob = row_gu * N_FF * 2 + row_d * N_EMBD
210            f = [str(l), str(gu_t), str(d_t), str(arena), str(blob), str(offs[l]["gate"]), str(offs[l]["up"]), str(offs[l]["down"]), "swap.bin"]
211        else:
212            f[3] = str(arena)
213        out_lines.append(" ".join(f))
214        arena += N_EXP * int(f[4])
215    import re
216    head = re.sub(r"total \d+", "total %d" % arena, head)
217    (pk / "native_experts.txt").write_text(head + "\n" + "\n".join(out_lines) + "\n")
218    print("wrote", var, "swap.bin %.2f GB, pack %s" % (pos / 1e9, pk))
219    return 0
220
221
222if __name__ == "__main__":
223    sys.exit(main())