#!/usr/bin/env python3 """metal/tools/gen_tq_lut.py - writes the trellis codebook into metal/kernels/quant.metal. third_party/ggml/ggml-common-tq.h holds tq_lut_f16[4096]: 2048 codebook points of two fp16 values each. The Metal kernels read a point as one 32-bit word (low half = the first value), so this script rewrites the table between the "BEGIN tq_lut" and "END tq_lut" markers of quant.metal with tq_lut_u[2048] = lut[2i] | lut[2i+1] << 16. python metal/tools/gen_tq_lut.py rewrite quant.metal python metal/tools/gen_tq_lut.py --check exit 1 when quant.metal differs from what would be written """ import pathlib import re import sys ROOT = pathlib.Path(__file__).resolve().parents[2] SRC = ROOT / "third_party" / "ggml" / "ggml-common-tq.h" DST = ROOT / "metal" / "kernels" / "quant.metal" BEGIN, END = "// BEGIN tq_lut", "// END tq_lut" def table(): text = SRC.read_text() m = re.search(r"tq_lut_f16\[4096\]\s*=\s*\{(.*?)\};", text, re.S) vals = [int(v, 16) for v in re.findall(r"0x[0-9a-fA-F]+", m.group(1))] assert len(vals) == 4096, len(vals) return [vals[2 * i] | (vals[2 * i + 1] << 16) for i in range(2048)] def block(): words = table() lines = [BEGIN + " (generated by metal/tools/gen_tq_lut.py from third_party/ggml/ggml-common-tq.h; do not edit)", "constant uint tq_lut_u[2048] = {"] for i in range(0, 2048, 8): lines.append(" " + ", ".join("0x%08x" % w for w in words[i:i + 8]) + ",") lines.append("};") lines.append(END) return "\n".join(lines) def main(): src = DST.read_text() i, j = src.index(BEGIN), src.index(END) + len(END) new = src[:i] + block() + src[j:] if "--check" in sys.argv: sys.exit(0 if new == src else 1) DST.write_text(new) if __name__ == "__main__": main()