okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
7.9 KiB157 linesraw
1#!/usr/bin/env python3
2"""tq_convert.py - re-encode the routed experts of some layers of a DeepSeek-V4.1 pack with the trellis encoder
3(tools/tqenc.py, HIP) and write them in the format the engine reads (strata-dsv41: ds4_tq.cu / ds4_tq_cpu.cpp):
4
5    HIP_VISIBLE_DEVICES=2 TQENC_GPU_LOCK=2 python tools/dsv41/tq_convert.py --pack PACK --out DIR --layers 1,7 --type K5
6
7PACK is the pack pack_gguf.py wrote (its tensors.txt names the source MXFP4 experts in the GGUF shards).  Per layer one file
8DIR/tq-L<layer>.bin holds the three roles one after another (gate = w1, up = w3, down = w2), each stacked [n_exp][rows][row
9bytes] in the trellis types' file layout (a row = k / 128 blocks of {fp16 d; 4 K stream bytes}, tools/trellis/tqenc.hpp), 4096-aligned;
10DIR/tq.json lists them as {"layers.N.ffn.experts.w1": [type name, file, offset, bytes, [n_exp, rows, cols]], ...}.  Then
11
12    python tools/dsv41/pack_gguf.py --model <gguf dir> --out PACK2 --tq-experts DIR
13
14writes a pack whose layers listed there read these experts (the other layers keep their MXFP4).  The weights are encoded as they
15are (plain error, no rotation, no activation weights): what the dense override experiments of gate 3 measure.  Types:
16K4 = TQK4X, K5 = TQK5X (computed codebook, version 2), K4T / K5T (the table, version 1), K6 = TQK6, K7 = TQK7.
17"""
18import argparse
19import concurrent.futures as cf
20import json
21import os
22import pathlib
23import sys
24import threading
25import time
26
27import numpy as np
28
29sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
30import tqenc  # noqa: E402
31
32TYPES = {"K4": tqenc.TQK4X, "K5": tqenc.TQK5X, "K4T": tqenc.TQK4T, "K5T": tqenc.TQK5T, "K6": tqenc.TQK6, "K7": tqenc.TQK7}
33CFGS = {"fast": dict(iters=0, ncand=1, scale_tries=1), "default": dict(iters=1, ncand=1, scale_tries=1)}
34MXFP4_LUT = np.array([0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12], dtype=np.float32)
35ROLES = (("w1", "gate"), ("w3", "up"), ("w2", "down"))
36
37
38def decode_mxfp4(raw, n_in):
39    """ggml MXFP4 blocks (32 values in 17 bytes: E8M0 scale, 16 code bytes) -> float32 [rows, n_in]"""
40    b = raw.reshape(-1, 17)
41    e = b[:, 0].astype(np.int32)
42    d = np.where(e == 0, np.float32(2.0 ** -127), np.ldexp(np.float32(1.0), e - 128)).astype(np.float32)
43    q = b[:, 1:]
44    return (np.concatenate([MXFP4_LUT[q & 15], MXFP4_LUT[q >> 4]], axis=1) * d[:, None]).reshape(-1, n_in)
45
46
47def read_pack(path):
48    files, tensors, cfg = {}, {}, {}
49    for line in open(os.path.join(path, "tensors.txt"), encoding="utf-8"):
50        f = line.split()
51        if f and f[0] == "file":
52            files[int(f[1])] = line.split(None, 2)[2].strip()
53        elif f and f[0] == "t":
54            tensors[f[1]] = (f[2], int(f[3]), int(f[4]), int(f[5]), [int(x) for x in f[6:]])
55    for line in open(os.path.join(path, "ds4.txt"), encoding="utf-8"):
56        k, _, v = line.strip().partition(" ")
57        cfg[k] = v
58    return files, tensors, cfg
59
60
61def align(n, a=4096):
62    return (n + a - 1) // a * a
63
64
65def main():
66    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
67    ap.add_argument("--pack", required=True)
68    ap.add_argument("--out", required=True)
69    ap.add_argument("--layers", required=True, help="comma list")
70    ap.add_argument("--type", required=True, choices=sorted(TYPES))
71    ap.add_argument("--cfg", default="fast", choices=sorted(CFGS))
72    ap.add_argument("--experts", type=int, default=0, help="only the first N experts (tests; the others stay zero streams)")
73    ap.add_argument("--act", default="", help="calibration dir with L<l>_gu.f64 [n_exp][dim], L<l>_dn.f64 [n_exp][ff] (sums of x^2 of the "
74                    "gate/up and down inputs per expert) and L<l>_cnt.u64 [n_exp]: an input-column weighted encode (error = sum h (w - dec)^2)")
75    ap.add_argument("--prior", type=float, default=64.0, help="pseudo-count of the layer-mean prior for rarely used experts")
76    ap.add_argument("--threads", type=int, default=4)
77    ap.add_argument("--cpu", action="store_true", help="the CPU encoder instead of the card")
78    a = ap.parse_args()
79    t = TYPES[a.type]
80    cfg = CFGS[a.cfg]
81    files, tensors, pcfg = read_pack(a.pack)
82    model_dir = pcfg["model_dir"]
83    n_exp = int(pcfg["n_routed_experts"])
84    ff, dim = int(pcfg["moe_intermediate_size"]), int(pcfg["hidden_size"])
85    n_do = a.experts or n_exp
86    os.makedirs(a.out, exist_ok=True)
87    idx_path = os.path.join(a.out, "tq.json")
88    idx = json.load(open(idx_path)) if os.path.exists(idx_path) else {}
89    bb = tqenc.block_bytes(t)
90    mm = {}
91    gpu_lock = threading.Lock()
92    for L in [int(x) for x in a.layers.split(",")]:
93        path = os.path.join(a.out, "tq-L%d.bin" % L)
94        if all("layers.%d.ffn.experts.%s" % (L, r) in idx for r, _ in ROLES) and os.path.exists(path):
95            print("layer %d: already in %s, skipped" % (L, idx_path), flush=True)
96            continue
97        sizes = {}
98        offs = {}
99        off = 0
100        for role, _ in ROLES:
101            rows, cols = (ff, dim) if role != "w2" else (dim, ff)
102            sizes[role] = (rows, cols, n_exp * rows * (cols // 128) * bb)
103            offs[role] = off
104            off += align(sizes[role][2])
105        with open(path, "wb") as f:
106            f.truncate(off)
107        fd = os.open(path, os.O_RDWR)
108        act = None
109        if a.act:
110            gu = np.fromfile("%s/L%d_gu.f64" % (a.act, L), dtype=np.float64).reshape(n_exp, dim)
111            dn = np.fromfile("%s/L%d_dn.f64" % (a.act, L), dtype=np.float64).reshape(n_exp, ff)
112            cnt = np.fromfile("%s/L%d_cnt.u64" % (a.act, L), dtype=np.uint64).astype(np.float64)
113            tot = max(cnt.sum(), 1.0)
114            act = (gu, dn, cnt, gu.sum(0) / tot, dn.sum(0) / tot)
115        for role, rname in ROLES:
116            rows, cols, total = sizes[role]
117            t0 = time.time()
118            per_out = rows * (cols // 128) * bb
119            names = ["layers.%d.ffn.experts.%d.%s.weight" % (L, e, role) for e in range(n_do)]
120            err2 = np.zeros(n_do)
121            ref2 = np.zeros(n_do)
122
123            def one(e):
124                dt, fi, off_, nb, shape = tensors[names[e]]
125                if dt != "MXFP4":
126                    raise SystemExit("%s is %s, not MXFP4: only MXFP4 sources are re-encoded" % (names[e], dt))
127                key = files[fi]
128                if key not in mm:
129                    mm[key] = np.memmap(os.path.join(model_dir, key), dtype=np.uint8, mode="r")
130                w = decode_mxfp4(np.asarray(mm[key][off_:off_ + nb]), cols)
131                h = None
132                if act is not None:   # the input columns' mean x^2 of this expert, shrunk toward the layer's mean by the prior
133                    gu_, dn_, cnt_, mg, md = act
134                    sq, m = (dn_[e], md) if role == "w2" else (gu_[e], mg)
135                    hc = (sq + a.prior * m) / (cnt_[e] + a.prior)
136                    hc = np.maximum(hc / hc.mean(), 1e-3).astype(np.float32)
137                    h = np.ascontiguousarray(np.broadcast_to(hc, (rows, cols)))
138                with gpu_lock:
139                    packed, err, tot, st = tqenc.encode(w, t, h=h, gpu=not a.cpu, **cfg)
140                dec = tqenc.decode(packed, t).reshape(rows, cols)
141                err2[e] = ((w.astype(np.float64) - dec) ** 2).sum()
142                ref2[e] = (w.astype(np.float64) ** 2).sum()
143                os.pwrite(fd, packed.tobytes(), offs[role] + e * per_out)
144                return st["nonfinite_blocks"]
145
146            with cf.ThreadPoolExecutor(a.threads) as ex:
147                nonfin = sum(ex.map(one, range(n_do)))
148            print("layer %d %s: %d experts %s %.0f s, rel mse %.4f (sqnr %.2f dB), nonfinite blocks %d" %
149                  (L, rname, n_do, a.type, time.time() - t0, err2.sum() / ref2.sum(), 10 * np.log10(ref2.sum() / err2.sum()), nonfin), flush=True)
150            idx["layers.%d.ffn.experts.%s" % (L, role)] = [tqenc.TYPE_NAMES[t], os.path.basename(path), offs[role], total, [n_exp, rows, cols]]
151        os.fsync(fd)
152        os.close(fd)
153        json.dump(idx, open(idx_path, "w"), indent=1)
154
155
156if __name__ == "__main__":
157    main()