okami.mom/strata

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

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
4.8 KiB110 linesraw
1"""tools/mtp_rt.py - plan v0.3 P6: the MTP draft layer's runtime files, from the packed MTP GGUF.
2
3    python tools/mtp_rt.py --gguf <Strata>/mtp-bf16/mtp-q2_0.gguf --out <Strata>/mtp-bf16/rt
4
5Writes
6  experts.bin   512 routed experts in the engine's blob layout (`include/strata/kernels/cpu/expert.hpp`): gate/up
7                rows interleaved (2r = gate r, 2r+1 = up r), then down rows; the Q2_0 codes in one plane and the fp16
8                scales in another.  A lossless relayout of the GGUF's Q2_0 blocks (same bytes, `cpu_expert_fixture.py`).
9  dense.bin     every other tensor: the large projections quantized to Q8_0 (ggml's reference rounding) so the
10                engine's multi-column MMVQ can run them; the hyper-connection and router weights kept BF16; the
11                RMSNorm weights as F32 with the Gemma "+1" applied (vLLM GemmaRMSNorm scales by 1 + w).
12  dense.txt     one line per tensor: name kind rows cols offset bytes   (kind = q8_0 | bf16 | f32)
13"""
14from __future__ import annotations
15
16import argparse
17import sys
18from pathlib import Path
19
20import numpy as np
21
22sys.path.insert(0, str(Path(__file__).resolve().parent))
23from _paths import gguf_lib  # noqa: E402
24gguf = gguf_lib()
25
26H, FF, NE = 2560, 640, 512
27BLOB = 3 * (H * FF * 18 // 64)
28Q8 = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight",
29      "self_attn.v_proj.weight", "self_attn.o_proj.weight", "self_attn.indexer.index_qk_proj.weight",
30      "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"}
31
32
33def q8_0(x: np.ndarray) -> bytes:
34    """ggml quantize_row_q8_0_ref over rows of a 2-D float32 array: 32-value blocks, fp16 d = amax / 127."""
35    b = x.reshape(-1, 32).astype(np.float32)
36    amax = np.abs(b).max(axis=1)
37    d = amax / 127.0
38    inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0).astype(np.float32)
39    v = b * inv[:, None]
40    q = (np.sign(v) * np.floor(np.abs(v) + 0.5)).astype(np.int8)
41    out = np.empty((b.shape[0], 34), dtype=np.uint8)
42    out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2)
43    out[:, 2:] = q.view(np.uint8)
44    return out.tobytes()
45
46
47def blob_of(gu: np.ndarray, dn: np.ndarray) -> bytes:
48    """gu: (1280, 720) Q2_0 rows (gate rows 0..639, up rows 640..1279); dn: (2560, 180)."""
49    gub = gu.reshape(2 * FF, H // 64, 18)
50    inter = np.empty_like(gub)
51    inter[0::2] = gub[:FF]
52    inter[1::2] = gub[FF:]
53    dnb = dn.reshape(H, FF // 64, 18)
54    parts = [inter[:, :, 2:].tobytes(), dnb[:, :, 2:].tobytes(), inter[:, :, :2].tobytes(), dnb[:, :, :2].tobytes()]
55    out = b"".join(parts)
56    assert len(out) == BLOB, len(out)
57    return out
58
59
60def main() -> int:
61    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
62    ap.add_argument("--gguf", required=True)
63    ap.add_argument("--out", required=True)
64    a = ap.parse_args()
65    out = Path(a.out)
66    out.mkdir(parents=True, exist_ok=True)
67    r = gguf.GGUFReader(a.gguf)
68    tens = {t.name: t for t in r.tensors}
69    gu = np.asarray(tens["mtp.layers.0.mlp.experts.gate_up_proj"].data)
70    dn = np.asarray(tens["mtp.layers.0.mlp.experts.down_proj"].data)
71    assert gu.shape == (NE, 2 * FF, 720) and dn.shape == (NE, H, 180), (gu.shape, dn.shape)
72    with open(out / "experts.bin", "wb") as f:
73        for e in range(NE):
74            f.write(blob_of(gu[e], dn[e]))
75    lines = []
76    off = 0
77    with open(out / "dense.bin", "wb") as f:
78        for name, t in tens.items():
79            if "experts." in name:
80                continue
81            short = name[len("mtp."):]
82            short = short[len("layers.0."):] if short.startswith("layers.0.") else short
83            data = np.asarray(t.data)
84            if int(t.tensor_type) == 0:        # F32 norm weights: raw GemmaRMSNorm w -> 1 + w
85                arr = (data.astype(np.float32) + 1.0)
86                raw, kind, rows, cols = arr.tobytes(), "f32", 1, arr.size
87            else:                              # BF16
88                u16 = data.view(np.uint16) if data.dtype != np.uint16 else data
89                u16 = u16.reshape(data.shape[0], -1)
90                rows, cols = u16.shape
91                if short in Q8:
92                    f32 = (u16.astype(np.uint32) << 16).view(np.float32)
93                    raw, kind = q8_0(f32), "q8_0"
94                else:
95                    raw, kind = u16.tobytes(), "bf16"
96            pad = (-off) % 256
97            f.write(b"\0" * pad)
98            off += pad
99            f.write(raw)
100            lines.append(f"{short} {kind} {rows} {cols} {off} {len(raw)}")
101            off += len(raw)
102    (out / "dense.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
103    print(f"experts.bin {NE * BLOB} B, dense.bin {off} B, {len(lines)} tensors -> {out}")
104    for l in lines:
105        print("  " + l)
106    return 0
107
108
109if __name__ == "__main__":
110    sys.exit(main())