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
3.8 KiB89 linesraw
1"""tools/gen_strata_quant_tables.py - writes tools/strata_quant_tables.py from the quant header the engines compile.
2
3    python tools/gen_strata_quant_tables.py            (rewrites tools/strata_quant_tables.py)
4    python tools/gen_strata_quant_tables.py --check    (exit 1 when the file is not what the header gives)
5
6The IQ grids, the sign table and the 4-bit value tables are data of the GGUF format; the Python dequantizers (tools/strata_quants.py)
7read them from tools/strata_quant_tables.py, which is generated from third_party/strata-ggml/strata-quant-common.h so the numbers are
8the ones the kernels use. Each table is stored as little-endian bytes (zlib + base64), exactly the memory image of the C array.
9"""
10from __future__ import annotations
11
12import argparse
13import base64
14import pathlib
15import re
16import sys
17import zlib
18
19ROOT = pathlib.Path(__file__).resolve().parents[1]
20HEADER = ROOT / "third_party" / "strata-ggml" / "strata-quant-common.h"
21OUT = ROOT / "tools" / "strata_quant_tables.py"
22
23#: (C name, element bytes, signed) -> the name in the module
24TABLES = (("kmask_iq2xs", 1, False), ("ksigns_iq2xs", 1, False),
25          ("iq2xxs_grid", 8, False), ("iq2xs_grid", 8, False), ("iq2s_grid", 8, False),
26          ("iq3xxs_grid", 4, False), ("iq3s_grid", 4, False),
27          ("kvalues_iq4nl", 1, True), ("kvalues_fp4", 1, True),
28          ("iq1s_grid", 8, False))
29EXPECT = {"kmask_iq2xs": 8, "ksigns_iq2xs": 128, "iq2xxs_grid": 256, "iq2xs_grid": 512, "iq2s_grid": 1024, "iq3xxs_grid": 256,
30          "iq3s_grid": 512, "kvalues_iq4nl": 16, "kvalues_fp4": 16, "iq1s_grid": 2048}
31
32
33def table_bytes(text: str, name: str, width: int, signed: bool) -> bytes:
34    m = re.search(r"GGML_TABLE_BEGIN\(\w+, %s, [A-Za-z0-9_]+\)(.*?)GGML_TABLE_END\(\)" % re.escape(name), text, re.S)
35    if not m:
36        raise SystemExit("table %s not found in %s" % (name, HEADER))
37    body = re.sub(r"//[^\n]*|/\*.*?\*/", "", m.group(1), flags=re.S)
38    out = bytearray()
39    n = 0
40    for tok in re.findall(r"-?0x[0-9a-fA-F]+|-?\d+", body):
41        v = int(tok, 0)
42        if signed:
43            v &= (1 << (8 * width)) - 1
44        out += v.to_bytes(width, "little")
45        n += 1
46    if n != EXPECT[name]:
47        raise SystemExit("table %s: %d entries, expected %d" % (name, n, EXPECT[name]))
48    return bytes(out)
49
50
51def render() -> str:
52    text = HEADER.read_text(encoding="utf-8")
53    lines = ['"""GENERATED by tools/gen_strata_quant_tables.py from third_party/strata-ggml/strata-quant-common.h. Do not edit.',
54             '',
55             'Each table is the little-endian memory image of the C array (zlib + base64); strata_quants.py reads them with numpy."""',
56             'import base64 as _b64',
57             'import zlib as _zlib',
58             '',
59             '', 'def _t(s):', '    return _zlib.decompress(_b64.b64decode(s))', '', '']
60    for name, width, signed in TABLES:
61        raw = table_bytes(text, name, width, signed)
62        blob = base64.b64encode(zlib.compress(raw, 9)).decode()
63        lines.append("%s = _t(" % name.upper())
64        for i in range(0, len(blob), 96):
65            lines.append("    %r" % blob[i:i + 96])
66        lines.append(")")
67        lines.append("")
68    return "\n".join(lines).rstrip() + "\n"
69
70
71def main() -> int:
72    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
73    ap.add_argument("--check", action="store_true")
74    a = ap.parse_args()
75    want = render()
76    if a.check:
77        have = OUT.read_text(encoding="utf-8") if OUT.exists() else ""
78        if have != want:
79            print("tools/strata_quant_tables.py is out of date: run python tools/gen_strata_quant_tables.py")
80            return 1
81        print("strata_quant_tables.py: ok")
82        return 0
83    OUT.write_text(want, encoding="utf-8", newline="\n")
84    print("wrote %s (%d bytes)" % (OUT, len(want)))
85    return 0
86
87
88if __name__ == "__main__":
89    sys.exit(main())