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
7.8 KiB168 linesraw
1"""tools/q8_dense_gguf.py - a copy of a model whose natively served dense projections and head are Q8_0, for the
2Pascal GP100 decode kernel (STRATA_Q8_SM60=1, docs/OLDER_GPUS.md).
3
4The GSQ-RCO packs keep those matrices in K- and i-quants (Q6_K, IQ4_XS, Q4_K, IQ3_S, Q5_K, Q2_0, IQ4_NL), whose
5decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices. Every shard of the model is
6handled, because a model may keep dense matrices in more than one (Swift 1.5 IQ3_XXS: 78 in shard 1, 223 in
7shard 2). A shard that holds any of them is written as:
8
9  * the tensor-info block with the SAME byte length: names and dims are unchanged, only the u32 type and the u64
10    offset of each converted tensor change, so the data section starts where it did and every other tensor - the
11    routed experts above all - keeps its absolute offset. An existing native pack (its native_experts.txt) stays
12    valid; nothing is repacked.
13  * the original data section, then each converted tensor's Q8_0 blocks appended (the old bytes stay, unused).
14    Qwen3.8-Flash-Next IQ3_XXS: 301 tensors, +3.5 GiB, the worst requantization error 0.41% of a tensor's |w|max
15    (Q8_0 is finer than every source format).
16
17A shard that holds none is hard-linked into the output folder (--copy copies it): the engine finds the shards beside
18--native, so --native and --ple-gguf must both name files in the new folder (it refuses two shard 2s).
19
20    python tools/q8_dense_gguf.py <folder>/<model>-00001-of-00002.gguf <new folder> [--copy]
21
22Any shard of the model may be named. Then point the config's --native and --ple-gguf at the new folder and run the
23engine with STRATA_Q8_SM60=1.
24"""
25from __future__ import annotations
26
27import argparse
28import os
29import re
30import shutil
31import struct
32import sys
33import time
34from pathlib import Path
35
36import numpy as np
37
38sys.path.insert(0, str(Path(__file__).resolve().parent))
39import _paths  # noqa: E402
40
41_gguf = _paths.gguf_lib()
42GGUFReader, QT = _gguf.GGUFReader, _gguf.GGMLQuantizationType
43dequantize, quantize = _gguf.quants.dequantize, _gguf.quants.quantize
44from gguf_writer import dequantize_q2_0  # noqa: E402
45
46# what src/core/native_dense.cpp serves natively (eligible()), and the head
47SUFFIXES = (".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", ".attn_q.weight", ".attn_k.weight",
48            ".attn_v.weight", ".attn_output.weight", ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight",
49            ".ffn_down_shexp.weight")
50Q2_0 = 42   # GSQ's 2-bit type (gguf-py's quants cannot dequantize it; tools/gguf_writer.py can)
51
52
53def is_target(name: str) -> bool:
54    return name == "output.weight" or (name.startswith("blk.") and name.endswith(SUFFIXES))
55
56
57def to_f32(t) -> np.ndarray:
58    ne0, ne1 = int(t.shape[0]), int(t.shape[1])
59    raw = np.asarray(t.data)
60    if int(t.tensor_type) == Q2_0:
61        return np.asarray(dequantize_q2_0(raw.tobytes()), dtype=np.float32).reshape(ne1, ne0)
62    return np.asarray(dequantize(raw, t.tensor_type), dtype=np.float32).reshape(ne1, ne0)
63
64
65def shards_of(path: Path) -> list[Path]:
66    """Every shard of the model `path` belongs to (just `path` for an unsplit file)."""
67    m = re.match(r"(.*-)(\d{5})-of-(\d{5})(\.gguf)$", path.name)
68    if not m:
69        return [path]
70    return [path.parent / f"{m[1]}{k:05d}-of-{m[3]}{m[4]}" for k in range(1, int(m[3]) + 1)]
71
72
73def jobs_of(r) -> list:
74    """The shard's convertible tensors and where each one's type/offset fields sit in its tensor-info block."""
75    data_start, mm, jobs = r.data_offset, r.data, []
76    for t in r.tensors:
77        if not is_target(t.name) or int(t.tensor_type) == int(QT.Q8_0):
78            continue
79        p = t.field.offset                                   # the tensor-info entry: name, n_dims, dims, type, offset
80        nlen = struct.unpack_from("<Q", mm, p)[0]; p += 8
81        assert bytes(mm[p:p + nlen]).decode() == t.name; p += nlen
82        ndim = struct.unpack_from("<I", mm, p)[0]; p += 4 + 8 * ndim
83        ttype, toff = struct.unpack_from("<IQ", mm, p)
84        assert ttype == int(t.tensor_type) and data_start + toff == t.data_offset, t.name
85        if int(t.shape[0]) % 32:
86            print(f"  {t.name}: rows of {int(t.shape[0])} are not whole Q8_0 blocks, kept")
87            continue
88        jobs.append((t, p))
89    return jobs
90
91
92def convert(src: Path, dst: Path, r, jobs) -> int:
93    t0 = time.time()
94    align, data_start, src_size = r.alignment, r.data_offset, os.path.getsize(src)
95    blobs, worst = [], 0.0
96    for t, p in jobs:
97        f = to_f32(t)
98        q = np.ascontiguousarray(quantize(f, QT.Q8_0)).view(np.uint8).reshape(-1)
99        assert q.nbytes == int(t.shape[0]) // 32 * 34 * int(t.shape[1]), t.name
100        back = dequantize(q, QT.Q8_0).reshape(f.shape)
101        worst = max(worst, float(np.abs(back - f).max() / max(float(np.abs(f).max()), 1e-30)))
102        blobs.append((t, p, q))
103    print(f"  converted in {time.time() - t0:.0f} s; worst requantization error {worst:.2e} of a tensor's |w|max; "
104          f"{sum(b[2].nbytes for b in blobs) / 2**30:.2f} GiB to append", flush=True)
105
106    tmp = dst.with_name(dst.name + ".part")
107    shutil.copyfile(src, tmp)
108    with open(tmp, "r+b") as fh:
109        end = src_size
110        for t, p, blob in blobs:
111            at = (end + align - 1) // align * align
112            fh.seek(end); fh.write(b"\0" * (at - end))
113            fh.seek(at); fh.write(blob.tobytes())
114            end = at + blob.nbytes
115            fh.seek(p); fh.write(struct.pack("<IQ", int(QT.Q8_0), at - data_start))
116        fh.flush(); os.fsync(fh.fileno())
117    os.replace(tmp, dst)
118
119    v = GGUFReader(dst)                                      # every other tensor where it was, every new one as written
120    conv = {t.name: blob for t, _, blob in blobs}
121    orig = {t.name: t for t in r.tensors}
122    assert len(v.tensors) == len(r.tensors) and v.data_offset == data_start
123    for t in v.tensors:
124        if t.name in conv:
125            assert t.tensor_type == QT.Q8_0 and np.array_equal(np.asarray(t.data).view(np.uint8).reshape(-1), conv[t.name]), t.name
126        else:
127            assert t.tensor_type == orig[t.name].tensor_type and t.data_offset == orig[t.name].data_offset, t.name
128    print(f"  wrote {dst} ({os.path.getsize(dst) / 2**30:.2f} GiB): {len(conv)} converted, {len(v.tensors) - len(conv)} "
129          "untouched, offsets checked", flush=True)
130    return len(conv)
131
132
133def main() -> int:
134    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
135    ap.add_argument("shard", type=Path, help="any GGUF shard of the model (or the model's only file)")
136    ap.add_argument("out_dir", type=Path, help="folder for the converted shards and the others' links")
137    ap.add_argument("--copy", action="store_true", help="copy the shards with nothing to convert instead of linking them")
138    a = ap.parse_args()
139    out = a.out_dir.resolve()
140    shards = shards_of(a.shard.resolve())
141    if out == shards[0].parent:
142        sys.exit("the output folder must not be the model's own folder")
143    missing = [s for s in shards if not s.is_file()]
144    if missing:
145        sys.exit(f"missing shard(s): {', '.join(str(s) for s in missing)}")
146    out.mkdir(parents=True, exist_ok=True)
147    total = 0
148    for src in shards:
149        dst = out / src.name
150        r = GGUFReader(src)
151        jobs = jobs_of(r)
152        print(f"{src.name}: {len(r.tensors)} tensors, {len(jobs)} to convert to Q8_0", flush=True)
153        if jobs:
154            total += convert(src, dst, r, jobs)
155            continue
156        if dst.exists():
157            dst.unlink()                                     # a link or copy from an earlier run
158        if a.copy:
159            shutil.copyfile(src, dst)
160        else:
161            os.link(src, dst)
162        print(f"  {'copied' if a.copy else 'linked'} (nothing to convert)", flush=True)
163    print(f"{total} tensors converted over {len(shards)} shard(s) in {out}")
164    return 0
165
166
167if __name__ == "__main__":
168    sys.exit(main())