Files
Strata/tools/test_quant_header.py
T
Niko1221 ffb11f0707 [Engine] quant format header: Strata's own, generated from its type tables (own-stack step 5)
include/strata/quant/strata-quant-common.h replaces llama.cpp's ggml-common.h text (third_party/strata-ggml/strata-quant-common.h, deleted).
tools/gen_quant_header.py writes it from tools/strata_quants.py BLOCK (every struct must add up to the bytes and values per block there, or
nothing is written) and tools/strata_quant_tables.py (the codebooks; ksigns64 and iq1s_grid_gpu are computed from them).

tools/test_quant_header.py: the header is current; every table equals strata_quant_tables.py and the GGUF reference (llama.cpp's
ggml-common.h in the vendored test oracle) byte for byte; every declaration is the reference's token for token (comments and static_assert
lines aside; the Metal iq1s_grid line is the one intended difference, Strata's since phase 1B); the static_asserts carry strata_quants'
sizes; with a C++ compiler the header compiles and its sizes and tables hold at run time.

The names (block_*, QK*, QI*/QR*, GGML_COMMON_DECL_* / GGML_COMMON_IMPL_*, GGML_TABLE_BEGIN) are unchanged, so every kernel compiles the
same tokens. third_party/ggml/ggml-common.h forwards to the new file; src/quant/internal.hpp and the split engine's qdot.cuh include it by
its new path; the Metal runtime's default path and the Mac package script take it from include/strata/quant. strata_quant_tables.py is
now described as Strata's copy (gen_strata_quant_tables.py --check proves it still equals the reference). The trellis header
(third_party/ggml/ggml-common-tq.h) is unchanged: Strata has no own copy of its codebook to generate it from.
2026-11-16 10:57:00 +01:00

197 lines
9.4 KiB
Python

"""Strata's quant format header (include/strata/quant/strata-quant-common.h), generated by tools/gen_quant_header.py.
python -m unittest tools.test_quant_header -v (or: python tools/test_quant_header.py)
Checks:
* the header is exactly what the generator writes now;
* every codebook table equals tools/strata_quant_tables.py and the GGUF reference tables byte for byte. The reference is llama.cpp's
ggml-common.h in the vendored test oracle (third_party/strata-ggml/ggml/src/ggml-common.h); those checks skip when it is absent;
* every declaration (types, structs, macros, the language branches) is the reference's, token for token: comments and the static_assert
lines may differ, nothing else. One difference is intended: the Metal branch also gets iq1s_grid (the Metal IQ1_M kernels read it);
* every struct adds up to the bytes and values of tools/strata_quants.py BLOCK;
* with a C++ compiler on PATH: the header compiles in C++ mode and its sizes and tables hold in a running program.
"""
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
import gen_quant_header as GEN # noqa: E402
import strata_quant_tables as T # noqa: E402
import strata_quants as SQ # noqa: E402
HEADER = ROOT / "include" / "strata" / "quant" / "strata-quant-common.h"
REFERENCE = ROOT / "third_party" / "strata-ggml" / "ggml" / "src" / "ggml-common.h"
TABLE_RE = re.compile(r"^GGML_TABLE_BEGIN\(\s*(\w+)\s*,\s*(\w+)\s*,\s*(\w+)\s*\)(.*?)^GGML_TABLE_END\(\)", re.S | re.M)
WIDTH = {"uint8_t": (1, False), "int8_t": (1, True), "uint16_t": (2, False), "uint32_t": (4, False), "uint64_t": (8, False)}
# the one intended difference from the reference (Strata's since own-stack phase 1B)
METAL_IQ1S = ("#if defined(GGML_COMMON_IMPL_C) || defined(GGML_COMMON_IMPL_CPP)",
"#if defined(GGML_COMMON_IMPL_C) || defined(GGML_COMMON_IMPL_CPP) || defined(GGML_COMMON_IMPL_METAL)")
def strip_comments(text: str) -> str:
out, i, n = [], 0, len(text)
while i < n:
c = text[i]
if c == '"':
j = i + 1
while j < n and text[j] != '"':
j += 2 if text[j] == "\\" else 1
out.append(text[i:j + 1])
i = j + 1
elif text.startswith("//", i):
j = text.find("\n", i)
i = n if j < 0 else j
elif text.startswith("/*", i):
j = text.find("*/", i + 2)
out.append(" ")
i = n if j < 0 else j + 2
else:
out.append(c)
i += 1
return "".join(out)
TOKEN = re.compile(r'0[xX][0-9a-fA-F]+[uUlL]*|\d+\.\d*f?|\d+[uUlL]*|\w+|"(?:[^"\\]|\\.)*"|\S')
def _norm_tok(t: str):
m = re.fullmatch(r"(0[xX][0-9a-fA-F]+|\d+)[uUlL]*", t)
return ("int", int(m.group(1), 0)) if m else t
def items(text: str) -> list:
"""the header as a list: each preprocessor line as one string (whitespace runs made one space), every other token alone (integer literals
as their values); static_assert(...); statements and a table's comma after its last value (no meaning in an initializer) dropped"""
out = []
for line in strip_comments(text).split("\n"):
s = line.strip()
if not s:
continue
if s.startswith("#"):
out.append(("#", " ".join(s.split())))
else:
out += [_norm_tok(t) for t in TOKEN.findall(s)]
res, i = [], 0
while i < len(out):
if out[i] == "static_assert":
depth, j = 0, i + 1
while True:
if out[j] == "(":
depth += 1
elif out[j] == ")":
depth -= 1
if depth == 0:
break
j += 1
assert out[j + 1] == ";"
i = j + 2
continue
if out[i] == "," and i + 1 < len(out) and out[i + 1] == "GGML_TABLE_END":
i += 1
continue
res.append(out[i])
i += 1
return res
def table_bytes(text: str) -> dict:
found = {}
for ctype, name, _size, body in TABLE_RE.findall(strip_comments(text)):
width, signed = WIDTH[ctype]
raw = bytearray()
for tok in re.findall(r"-?0[xX][0-9a-fA-F]+|-?\d+", body):
v = int(tok, 0)
raw += (v & ((1 << (8 * width)) - 1)).to_bytes(width, "little")
found[name] = bytes(raw)
return found
class QuantHeader(unittest.TestCase):
def test_the_header_is_current(self):
self.assertEqual(HEADER.read_text(encoding="utf-8"), GEN.render(), "stale: python tools/gen_quant_header.py")
def test_the_tables_are_strata_quant_tables(self):
got = table_bytes(HEADER.read_text(encoding="utf-8"))
self.assertEqual(sorted(got), sorted(["kmask_iq2xs", "ksigns_iq2xs", "ksigns64", "iq2xxs_grid", "iq2xs_grid", "iq2s_grid", "iq3xxs_grid",
"iq3s_grid", "kvalues_iq4nl", "kvalues_fp4", "iq1s_grid", "iq1s_grid_gpu"]))
for name in ("kmask_iq2xs", "ksigns_iq2xs", "iq2xxs_grid", "iq2xs_grid", "iq2s_grid", "iq3xxs_grid", "iq3s_grid", "kvalues_iq4nl",
"kvalues_fp4", "iq1s_grid"):
self.assertEqual(got[name], getattr(T, name.upper()), name)
self.assertEqual(len(got["ksigns64"]), 128 * 8)
self.assertEqual(len(got["iq1s_grid_gpu"]), 2048 * 4)
@unittest.skipUnless(REFERENCE.exists(), "no reference header (third_party/strata-ggml)")
def test_every_table_matches_the_reference_byte_for_byte(self):
ours = table_bytes(HEADER.read_text(encoding="utf-8"))
ref = table_bytes(REFERENCE.read_text(encoding="utf-8"))
self.assertEqual(sorted(ours), sorted(ref))
for name in ref:
self.assertEqual(ours[name], ref[name], name)
@unittest.skipUnless(REFERENCE.exists(), "no reference header (third_party/strata-ggml)")
def test_the_declarations_are_the_reference_token_for_token(self):
ours = items(HEADER.read_text(encoding="utf-8"))
ref = [("#", METAL_IQ1S[1]) if it == ("#", METAL_IQ1S[0]) else it for it in items(REFERENCE.read_text(encoding="utf-8"))]
self.assertIn(("#", METAL_IQ1S[1]), ref)
for k, (a, b) in enumerate(zip(ours, ref)):
self.assertEqual(a, b, "item %d: ours %r, reference %r (ours before: %r)" % (k, a, b, ours[max(0, k - 6):k]))
self.assertEqual(len(ours), len(ref))
def test_the_static_asserts_hold_the_gguf_sizes(self):
text = HEADER.read_text(encoding="utf-8")
sizes = dict((n, int(b)) for n, b in re.findall(r"static_assert\(sizeof\((\w+)\) == (\d+),", text))
self.assertEqual(len(sizes), 27)
for name, _defs, _qk, gguf, _fields, _note in GEN.BLOCKS:
if gguf:
self.assertEqual(sizes[name], SQ.BLOCK[gguf][1], name)
self.assertEqual((sizes["block_q1_0"], sizes["block_q8_1"], sizes["block_q8_K"]), (18, 36, 292))
def test_the_generator_refuses_a_struct_that_does_not_add_up(self):
saved = GEN.BLOCKS
try:
GEN.BLOCKS = tuple(b if b[0] != "block_q4_0" else b[:4] + ((("ggml_half", "d", None), ("uint8_t", "qs", "QK4_0")), b[5])
for b in saved)
with self.assertRaises(SystemExit):
GEN.render()
finally:
GEN.BLOCKS = saved
def test_nothing_includes_the_old_location(self):
self.assertFalse((ROOT / "third_party" / "strata-ggml" / "strata-quant-common.h").exists())
fwd = [ln for ln in (ROOT / "third_party" / "ggml" / "ggml-common.h").read_text(encoding="utf-8").splitlines()
if ln.strip() and not ln.startswith("//")]
self.assertEqual(fwd, ['#include "../../include/strata/quant/strata-quant-common.h"'])
@unittest.skipUnless(shutil.which("c++") or shutil.which("g++") or shutil.which("clang++"), "no C++ compiler")
def test_it_compiles_and_the_tables_hold_at_run_time(self):
cxx = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
checks = []
for name, _defs, _qk, gguf, fields, _note in GEN.BLOCKS:
if fields is not None:
checks.append("sizeof(%s) == %d" % (name, GEN.struct_bytes(fields)))
ref = table_bytes(HEADER.read_text(encoding="utf-8"))
for name in ("iq2s_grid", "iq3s_grid", "iq1s_grid", "ksigns64"):
checks.append("sum(%s, sizeof(%s)) == %dull" % (name, name, sum(ref[name]) & ((1 << 64) - 1)))
src = ("#define GGML_COMMON_DECL_CPP\n#define GGML_COMMON_IMPL_CPP\n#include \"strata-quant-common.h\"\n"
"static unsigned long long sum(const void * p, unsigned long n) { unsigned long long s = 0;"
" for (unsigned long i = 0; i < n; ++i) s += ((const unsigned char *) p)[i]; return s; }\n"
"int main() { int bad = 0;\n" + "".join(" if (!(%s)) { ++bad; }\n" % c for c in checks) + " return bad; }\n")
with tempfile.TemporaryDirectory() as d:
(pathlib.Path(d) / "t.cpp").write_text(src, encoding="utf-8")
exe = pathlib.Path(d) / "t"
done = subprocess.run([cxx, "-std=c++17", "-Wall", "-I", str(HEADER.parent), str(pathlib.Path(d) / "t.cpp"), "-o", str(exe)],
capture_output=True, text=True)
self.assertEqual(done.returncode, 0, done.stderr[-1500:])
self.assertEqual(subprocess.run([str(exe)]).returncode, 0)
if __name__ == "__main__":
unittest.main()