okami.mom/strata

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

Niko1221Merge f-022-macgyro: Gyro-S and Gyro-M on Apple Silicon (Metal trellis kernels, Gyro dense tiles)31fa54fb6

main
1.8 KiB50 linesraw
1#!/usr/bin/env python3
2"""metal/tools/gen_tq_lut.py - writes the trellis codebook into metal/kernels/quant.metal.
3
4third_party/ggml/ggml-common-tq.h holds tq_lut_f16[4096]: 2048 codebook points of two fp16 values each.  The Metal
5kernels read a point as one 32-bit word (low half = the first value), so this script rewrites the table between the
6"BEGIN tq_lut" and "END tq_lut" markers of quant.metal with tq_lut_u[2048] = lut[2i] | lut[2i+1] << 16.
7
8    python metal/tools/gen_tq_lut.py            rewrite quant.metal
9    python metal/tools/gen_tq_lut.py --check    exit 1 when quant.metal differs from what would be written
10"""
11import pathlib
12import re
13import sys
14
15ROOT = pathlib.Path(__file__).resolve().parents[2]
16SRC = ROOT / "third_party" / "ggml" / "ggml-common-tq.h"
17DST = ROOT / "metal" / "kernels" / "quant.metal"
18BEGIN, END = "// BEGIN tq_lut", "// END tq_lut"
19
20
21def table():
22    text = SRC.read_text()
23    m = re.search(r"tq_lut_f16\[4096\]\s*=\s*\{(.*?)\};", text, re.S)
24    vals = [int(v, 16) for v in re.findall(r"0x[0-9a-fA-F]+", m.group(1))]
25    assert len(vals) == 4096, len(vals)
26    return [vals[2 * i] | (vals[2 * i + 1] << 16) for i in range(2048)]
27
28
29def block():
30    words = table()
31    lines = [BEGIN + " (generated by metal/tools/gen_tq_lut.py from third_party/ggml/ggml-common-tq.h; do not edit)",
32             "constant uint tq_lut_u[2048] = {"]
33    for i in range(0, 2048, 8):
34        lines.append("    " + ", ".join("0x%08x" % w for w in words[i:i + 8]) + ",")
35    lines.append("};")
36    lines.append(END)
37    return "\n".join(lines)
38
39
40def main():
41    src = DST.read_text()
42    i, j = src.index(BEGIN), src.index(END) + len(END)
43    new = src[:i] + block() + src[j:]
44    if "--check" in sys.argv:
45        sys.exit(0 if new == src else 1)
46    DST.write_text(new)
47
48
49if __name__ == "__main__":
50    main()