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
9.4 KiB192 linesraw
1"""tools/mtp_pack.py - plan v0.3 P6 prep: the MTP draft block as a Strata GGUF, from the BF16 tensors.
2
3llama.cpp's qwen4exp converter drops the MTP head (`supports_mtp_export = False`), and the flyweight MTP GGUF is
4no longer on this PC, so Strata packs its own from the 31 `mtp.*` tensors fetched by tools/mtp_fetch.py:
5
6    python tools/mtp_pack.py --src Desktop/Strata/mtp-bf16 --experts q2_0 --out mtp-q2_0.gguf
7    python tools/mtp_pack.py --src ... --experts q4_0 --out mtp-q4_0.gguf       (acceptance comparison arm)
8
9Layout: dense tensors (attention, indexer, hyper-connections, shared expert, router, fc/norms) stay BF16 (F32 for
101-D norms), ~0.18 GB. The routed experts keep the checkpoint's fused layout - `gate_up_proj` [512, 1280, 2560] and
11`down_proj` [512, 2560, 640], quantized along the last (input) axis - in one of:
12
13    q2_0   64-element blocks, grid {-1, 0, 1, 2} x d. The scale is chosen per block to MINIMIZE squared error over
14           that grid (the ggml reference sets d = max|w| and never uses the +2 level). Same format as the main
15           model's experts, so Strata's CPU VNNI kernel and GPU hit kernel serve it unchanged. ~0.71 GB.
16    q4_0   ggml reference rounding. ~1.42 GB.       q8_0   ggml reference. ~2.67 GB.
17
18This is round-to-nearest, not GSQ: the plan picks the expert format by MEASURED draft acceptance (P0.3/P6), not
19by this file's reconstruction error, which is reported per tensor only as a sanity check. No model runs here.
20"""
21from __future__ import annotations
22
23import argparse
24import hashlib
25import json
26import sys
27import time
28from pathlib import Path
29
30import numpy as np
31
32HERE = Path(__file__).resolve().parent
33sys.path.insert(0, str(Path(__file__).resolve().parent))
34from _paths import gguf_lib  # noqa: E402
35gguf = gguf_lib()  # noqa: E402  (tools/strata_gguf.py; STRATA_GGUF_PY selects llama.cpp's gguf-py instead)
36
37EXPERT_TENSORS = ("mtp.layers.0.mlp.experts.gate_up_proj", "mtp.layers.0.mlp.experts.down_proj")
38
39
40class _Experts:
41    """Index an expert out of a BF16 memmap as float32 on demand."""
42    def __init__(self, raw):
43        self.raw = raw
44
45    def __getitem__(self, e):
46        return (np.asarray(self.raw[e]).astype(np.uint32) << 16).view(np.float32)
47
48
49def load_bf16(path: Path, shape: list[int]) -> np.ndarray:
50    raw = np.fromfile(path, dtype="<u2")
51    if raw.size != int(np.prod(shape)):
52        raise ValueError(f"{path}: {raw.size} values, expected shape {shape}")
53    return (raw.astype(np.uint32) << 16).view(np.float32).reshape(shape)
54
55
56# ------------------------------------------------------------------------------------------------ quantizers
57def q2_0(w: np.ndarray) -> np.ndarray:
58    """[..., n] float32 -> bytes of Q2_0 blocks (fp16 d, 16 bytes of 2-bit codes, code = q + 1, 4 per byte)."""
59    x = w.reshape(-1, 64).astype(np.float32)
60    amax = np.abs(x).max(axis=1, keepdims=True)
61    best_err = np.full((x.shape[0], 1), np.inf, dtype=np.float32)
62    best_d = np.zeros_like(amax)
63    # Candidate scales span amax/2 (the +2 level reaches the max) to amax (the ggml reference); 17 steps.
64    for f in np.linspace(0.5, 1.0, 17, dtype=np.float32):
65        d = amax * f
66        inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0)
67        q = np.clip(np.rint(x * inv), -1, 2)
68        err = ((q * d - x) ** 2).sum(axis=1, keepdims=True)
69        better = err < best_err
70        best_err = np.where(better, err, best_err)
71        best_d = np.where(better, d, best_d)
72    d16 = best_d.astype(np.float16)
73    d = d16.astype(np.float32)                                   # quantize against the STORED scale
74    inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0)
75    codes = (np.clip(np.rint(x * inv), -1, 2) + 1).astype(np.uint8)          # 0..3
76    c = codes.reshape(-1, 16, 4)
77    packed = (c[:, :, 0] | (c[:, :, 1] << 2) | (c[:, :, 2] << 4) | (c[:, :, 3] << 6)).astype(np.uint8)
78    out = np.empty((x.shape[0], 18), dtype=np.uint8)
79    out[:, :2] = d16.view(np.uint8).reshape(-1, 2)
80    out[:, 2:] = packed
81    return out.reshape(-1)
82
83
84def q4_0(w: np.ndarray) -> np.ndarray:
85    """ggml quantize_row_q4_0_ref: d = max / -8 (signed max), code = clamp(round(x/d + 8.5) truncated, 0, 15)."""
86    x = w.reshape(-1, 32).astype(np.float32)
87    idx = np.abs(x).argmax(axis=1)
88    mx = x[np.arange(x.shape[0]), idx][:, None]
89    d = mx / -8.0
90    inv = np.where(d != 0, 1.0 / np.where(d != 0, d, 1.0), 0.0)
91    q = np.minimum(15, np.trunc(x * inv + 8.5)).astype(np.uint8)
92    packed = (q[:, :16] | (q[:, 16:] << 4)).astype(np.uint8)
93    out = np.empty((x.shape[0], 18), dtype=np.uint8)
94    out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2)
95    out[:, 2:] = packed
96    return out.reshape(-1)
97
98
99def q8_0(w: np.ndarray) -> np.ndarray:
100    x = w.reshape(-1, 32).astype(np.float32)
101    d = np.abs(x).max(axis=1, keepdims=True) / 127.0
102    inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0)
103    q = np.rint(x * inv).astype(np.int8)
104    out = np.empty((x.shape[0], 34), dtype=np.uint8)
105    out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2)
106    out[:, 2:] = q.view(np.uint8)
107    return out.reshape(-1)
108
109
110def dequant(kind: str, blob: np.ndarray, n: int) -> np.ndarray:
111    if kind == "q2_0":
112        b = blob.reshape(-1, 18)
113        d = b[:, :2].copy().view(np.float16).astype(np.float32)
114        qs = b[:, 2:]
115        codes = np.stack([(qs >> s) & 3 for s in (0, 2, 4, 6)], axis=2).reshape(-1, 64).astype(np.float32)
116        return ((codes - 1.0) * d).reshape(-1)[:n]
117    if kind == "q4_0":
118        b = blob.reshape(-1, 18)
119        d = b[:, :2].copy().view(np.float16).astype(np.float32)
120        qs = b[:, 2:]
121        q = np.concatenate([qs & 15, qs >> 4], axis=1).astype(np.float32)
122        return ((q - 8.0) * d).reshape(-1)[:n]
123    b = blob.reshape(-1, 34)
124    d = b[:, :2].copy().view(np.float16).astype(np.float32)
125    return (b[:, 2:].view(np.int8).astype(np.float32) * d).reshape(-1)[:n]
126
127
128QUANT = {"q2_0": (q2_0, gguf.GGMLQuantizationType.Q2_0, 64, 18),
129         "q4_0": (q4_0, gguf.GGMLQuantizationType.Q4_0, 32, 18),
130         "q8_0": (q8_0, gguf.GGMLQuantizationType.Q8_0, 32, 34)}
131
132
133def main() -> int:
134    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
135    ap.add_argument("--src", required=True, help="directory written by tools/mtp_fetch.py fetch")
136    ap.add_argument("--experts", choices=sorted(QUANT), default="q2_0")
137    ap.add_argument("--out", required=True)
138    ap.add_argument("--check-experts", type=int, default=8, help="experts per tensor used for the error report")
139    a = ap.parse_args()
140    src = Path(a.src)
141    manifest = json.loads((src / "mtp-manifest.json").read_text())
142    fn, qtype, block, block_bytes = QUANT[a.experts]
143    w = gguf.GGUFWriter(a.out, "qwen4exp-mtp")
144    w.add_string("strata.mtp.source", "Qwen/Qwen3.8-Flash-Next BF16 checkpoint, mtp.* tensors")
145    w.add_string("strata.mtp.source_sha256", hashlib.sha256(
146        json.dumps({t["name"]: t["sha256"] for t in manifest}, sort_keys=True).encode()).hexdigest())
147    w.add_string("strata.mtp.expert_format", a.experts)
148    w.add_string("strata.mtp.expert_quantizer", "per-block MSE scale search" if a.experts == "q2_0" else "ggml reference")
149    report = []
150    for t in sorted(manifest, key=lambda t: t["name"]):
151        name, shape = t["name"], t["shape"]
152        t0 = time.time()
153        if name in EXPERT_TENSORS:
154            # Streamed one expert at a time from a read-only view: the fused gate_up tensor alone is 6.7 GB as
155            # float32, so it is never materialized whole.
156            raw = np.memmap(src / t["file"], dtype="<u2", mode="r", shape=tuple(shape))
157            x = _Experts(raw)
158            if shape[-1] % block:
159                raise ValueError(f"{name}: inner dim {shape[-1]} not a multiple of {block}")
160            parts = [fn(x[e]) for e in range(shape[0])]            # one expert at a time bounds memory
161            blob = np.concatenate(parts)
162            errs = []
163            for e in range(min(a.check_experts, shape[0])):
164                ref = x[e].reshape(-1)
165                got = dequant(a.experts, parts[e], ref.size)
166                errs.append(float(np.sqrt(((got - ref) ** 2).mean()) / (np.sqrt((ref ** 2).mean()) + 1e-12)))
167            # the writer takes the quantized bytes with the ELEMENT shape; ggml order is innermost-first.
168            w.add_tensor(name, blob, raw_shape=list(shape[:-1]) + [shape[-1] // block * block_bytes], raw_dtype=qtype)
169            report.append({"tensor": name, "format": a.experts, "bytes": int(blob.size),
170                           "relative_rms_error_first_experts": round(float(np.mean(errs)), 5),
171                           "seconds": round(time.time() - t0, 1)})
172        elif len(shape) == 1:
173            x = load_bf16(src / t["file"], shape)
174            w.add_tensor(name, x.astype(np.float32))
175            report.append({"tensor": name, "format": "F32", "bytes": x.size * 4})
176        else:
177            bf = np.fromfile(src / t["file"], dtype="<u2").reshape(shape)
178            w.add_tensor(name, bf, raw_dtype=gguf.GGMLQuantizationType.BF16)
179            report.append({"tensor": name, "format": "BF16", "bytes": bf.size * 2})
180        print(f"{name}: {report[-1]['format']} {report[-1]['bytes'] / 1e6:.1f} MB", flush=True)
181    w.write_header_to_file()
182    w.write_kv_data_to_file()
183    w.write_tensors_to_file()
184    w.close()
185    total = sum(r["bytes"] for r in report)
186    Path(a.out + ".report.json").write_text(json.dumps({"total_bytes": total, "tensors": report}, indent=1))
187    print(f"wrote {a.out}: {total / 1e9:.3f} GB of tensor data")
188    return 0
189
190
191if __name__ == "__main__":
192    sys.exit(main())