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
8.8 KiB195 linesraw
1#!/usr/bin/env python3
2"""engram_fold.py - the Engram tensors a pack needs, folded out of the quant's own shards, so a pack built around their
3`engram-IQ4_NL.gguf` uses none of our substitutes.
4
5The IST-DAS sets keep the Engram as three per-layer tensors (`blk.N.engram_k`, `engram_q`, `engram_wkv`); the engine's
6layout wants `engram.gate` (k*q folded, [4, 5120] F32) and `engram.wkv` ([25600, 6144] BF16).  Theirs are stored the other
7way round - their `engram_wkv` is `[6144, 25600]` and their `k/q` are `[5120, 4]` - so this tool dequantises, transposes and
8writes the engine's layout:
9
10  gate = transpose(k) * transpose(q)      F32
11  wkv  = transpose(dequant(wkv))          BF16
12
13Output is a `dense_requant.py`-style folder (dense.json + dense.bin) for `pack_gguf.py --dense-override`.
14
15usage:
16  engram_fold.py --model /data/helcig/set200/2.00bpw --out /data/helcig/engram_fold_200 [--layers 1,14]
17  pack_gguf.py --model <set> --out <pack> --engram <their engram dir> \
18      --skip-tensors 'attn_output_a|engram_(k|q|wkv)\\.' --dense-override <fold dir> ...
19"""
20from __future__ import annotations
21
22import argparse
23import json
24import os
25import pathlib
26import re
27import sys
28
29import numpy as np
30
31sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
32import pack_gguf  # noqa: E402  (its GGUF reader and its type table)
33
34
35def shards(model: pathlib.Path):
36    return [pack_gguf.Gguf(p) for p in sorted(model.glob("*.gguf"))]
37
38
39def find(gs, name):
40    for g in gs:
41        for t in g.tensors:
42            if t[0] == name:
43                return g, t
44    return None, None
45
46
47def nbytes(typ: int, dims) -> int:
48    tname, per, bpb = pack_gguf.TYPES[typ]
49    nel = 1
50    for d in dims:
51        nel *= int(d)
52    return nel // per * bpb if per > 1 else nel * bpb
53
54
55def dequant_q5k(raw: np.ndarray, nblocks: int) -> np.ndarray:
56    """ggml block_q5_K (176 B, 256 values): f16 d, f16 dmin, uint8 scales[12], qh[32], qs[128]."""
57    b = raw.reshape(nblocks, 176)
58    d = b[:, 0:2].copy().view(np.float16).astype(np.float32).reshape(-1)
59    dmin = b[:, 2:4].copy().view(np.float16).astype(np.float32).reshape(-1)
60    scales, qh, qs = b[:, 4:16].astype(np.int32), b[:, 16:48].astype(np.int32), b[:, 48:176].astype(np.int32)
61    sc = np.empty((nblocks, 8), np.float32)
62    mn = np.empty((nblocks, 8), np.float32)
63    # ggml's get_scale_min_k4: the first four 6-bit scales are bytes 0..3 (low) and 4..7 (mins);
64    # the last four take the top two bits of bytes 0..3 plus the low/high nibbles of 8..11
65    for j in range(8):
66        if j < 4:
67            sc[:, j] = scales[:, j] & 63
68            mn[:, j] = scales[:, j + 4] & 63
69        else:
70            sc[:, j] = (scales[:, j + 4] & 0xF) | ((scales[:, j - 4] >> 6) << 4)
71            mn[:, j] = (scales[:, j + 4] >> 4) | ((scales[:, j] >> 6) << 4)
72    out = np.empty((nblocks, 256), dtype=np.float32)
73    for j in range(4):
74        for half in range(2):
75            d1 = d * sc[:, j * 2 + half]
76            m1 = dmin * mn[:, j * 2 + half]
77            q = qs[:, j * 32:(j + 1) * 32]
78            h = (qh >> (j * 2 + half)) & 1
79            nib = ((q & 0xF) if half == 0 else (q >> 4)) + (h << 4)
80            out[:, j * 64 + half * 32: j * 64 + half * 32 + 32] = d1[:, None] * nib - m1[:, None]
81    return out.reshape(-1)
82
83
84def dequant(g, t) -> np.ndarray:
85    name, typ, dims, off = t
86    tname = pack_gguf.TYPES[typ][0]
87    nb = nbytes(typ, dims)
88    # Gguf's tensor offsets are relative to the shard's data section; pack_gguf adds data_start when it writes a pack
89    raw = np.fromfile(g.path, dtype=np.uint8, count=nb, offset=g.data_start + off)
90    if tname == "Q5_K":
91        return dequant_q5k(raw, nb // 176).astype(np.float64)
92    if tname == "Q4_K":
93        raise SystemExit("%s: Q4_K not handled by the fold yet (Q5_K, F32, F16, BF16 are)" % name)
94    if tname == "F32":
95        return raw.view(np.float32).astype(np.float64)
96    if tname == "BF16":
97        return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32).astype(np.float64)
98    if tname == "F16":
99        return raw.view(np.float16).astype(np.float64)
100    raise SystemExit("%s: type %s is not one the fold reads" % (name, tname))
101
102
103def to_bf16_bytes(v: np.ndarray) -> bytes:
104    """F32 -> BF16, round to nearest even (what ggml's ggml_compute_fp32_to_bf16 does)."""
105    u = v.astype(np.float32).view(np.uint32)
106    lsb = (u >> 16) & 1
107    rounded = (u + 0x7FFF + lsb) >> 16
108    return rounded.astype(np.uint16).tobytes()
109
110
111def main() -> int:
112    ap = argparse.ArgumentParser()
113    ap.add_argument("--model", required=True, help="the folder of the quant's GGUF shards")
114    ap.add_argument("--out", required=True, help="the override folder to write (dense.json + dense.bin)")
115    ap.add_argument("--layers", default="", help="comma list of Engram layers; default: every layer with an engram_k")
116    ap.add_argument("--gate-kv-from", default="", help="a known-good pack to copy engram.gate/wkv from (the ple table stays the only difference)")
117    a = ap.parse_args()
118    model = pathlib.Path(a.model).expanduser().resolve()
119    out = pathlib.Path(a.out).expanduser().resolve()
120    gs = shards(model)
121    if not gs:
122        raise SystemExit("%s: no .gguf files" % model)
123    names = {t[0] for g in gs for t in g.tensors}
124    if a.layers:
125        layers = [int(x) for x in a.layers.split(",") if x.strip()]
126    else:
127        layers = sorted({int(n.split(".")[1]) for n in names if n.startswith("blk.") and ".engram_k." in n})
128    out.mkdir(parents=True, exist_ok=True)
129    idx: dict[str, list] = {}
130    blobs: list[bytes] = []
131    off = 0
132
133    def add(name: str, tname: str, data: bytes, shape: list[int]) -> None:
134        nonlocal off
135        pad = (-off) % 64
136        if pad:
137            blobs.append(b"\0" * pad)
138            off += pad
139        blobs.append(data)
140        idx[name] = [tname, "dense.bin", off, len(data), shape]
141        off += len(data)
142
143    # --gate-kv-from PACK: take the gate and the kv from a pack that is known good (the engine's own layout, already in the
144    # right orientation) instead of deriving them from their k/q/wkv.  That leaves the ple table as the only difference
145    # between the two packs, which is the only way to score their IQ4_NL Engram against our MXFP8 one.
146    if a.gate_kv_from:
147        src = pathlib.Path(a.gate_kv_from).expanduser().resolve()
148        md = [l.split(None, 1)[1] for l in (src / "ds4.txt").read_text().splitlines() if l.startswith("model_dir ")][0]
149        files, want = {}, {}
150        for line in (src / "tensors.txt").read_text().splitlines():
151            f = line.split()
152            if not f:
153                continue
154            if f[0] == "file":
155                files[int(f[1])] = " ".join(f[2:])
156            elif f[0] == "t" and re.match(r"layers\.\d+\.engram\.(gate|wkv)\.weight$", f[1]):
157                want[f[1]] = (f[2], int(f[3]), int(f[4]), int(f[5]), [int(x) for x in f[6:]])
158        for name, (tname, fi, o, nb, shape) in sorted(want.items()):
159            p = (pathlib.Path(md) / files[fi]).resolve()
160            add(name, tname, np.fromfile(p, dtype=np.uint8, count=nb, offset=o).tobytes(), shape)
161            print("%s: copied from %s (%s, %d bytes)" % (name, src.name, tname, nb))
162        (out / "dense.bin").write_bytes(b"".join(blobs))
163        json.dump(idx, open(out / "dense.json", "w"), indent=1)
164        print("wrote %s (%.2f MB), dense.json with %d tensors" % (out / "dense.bin", os.path.getsize(out / "dense.bin") / 1e6, len(idx)))
165        return 0
166
167    for il in layers:
168        kg, kt = find(gs, "blk.%d.engram_k.weight" % il)
169        qg, qt = find(gs, "blk.%d.engram_q.weight" % il)
170        wg, wt = find(gs, "blk.%d.engram_wkv.weight" % il)
171        if kt is None or qt is None:
172            print("layer %d: no engram_k/q in these shards, skipped" % il)
173            continue
174        # their k/q are [5120, 4] (ne0 = 5120): the engine's gate is [4, 5120]
175        k = dequant(kg, kt).reshape(kt[2][1], kt[2][0]).T
176        q = dequant(qg, qt).reshape(qt[2][1], qt[2][0]).T
177        if k.shape != q.shape:
178            raise SystemExit("layer %d: k %s and q %s differ after the transpose" % (il, k.shape, q.shape))
179        gate = (k * q).astype(np.float32)
180        add("layers.%d.engram.gate.weight" % il, "F32", gate.tobytes(), [gate.shape[1], gate.shape[0]])
181        note = "MISSING"
182        if wt is not None:
183            w = dequant(wg, wt).reshape(wt[2][1], wt[2][0]).T.astype(np.float32)
184            add("layers.%d.engram.wkv.weight" % il, "BF16", to_bf16_bytes(w), [w.shape[1], w.shape[0]])
185            note = "BF16 [%d, %d]" % (w.shape[1], w.shape[0])
186        print("layer %d: gate [%d, %d] F32, wkv %s" % (il, gate.shape[1], gate.shape[0], note))
187
188    (out / "dense.bin").write_bytes(b"".join(blobs))
189    json.dump(idx, open(out / "dense.json", "w"), indent=1)
190    print("wrote %s (%.2f MB), dense.json with %d tensors" % (out / "dense.bin", os.path.getsize(out / "dense.bin") / 1e6, len(idx)))
191    return 0
192
193
194if __name__ == "__main__":
195    sys.exit(main())