Files
Strata/terminal/tools/test_quant_header.py
T
Niko1221 4058aa782b Layout move for 0.2.16: the top level becomes app/, engine/, terminal/, docs/, tools/ and .github/
Made by tools/layout/move_0216.py (the commit before this one) on db8e0be9c, the final code head of 0.2.16:
- 75 git mv (renames, so `git log --follow` and blame keep working; packaging/acceptance_matrix.md shows as delete + add because its links
  changed too) and 3 removals: SETUP.bat, UPDATE.bat and update.sh (setup.py --update pulls the code now);
- 1,425 path edits in 307 files: root-relative paths in CI, Docker, .gitignore and the release scripts; Markdown links; Python and
  Node joins from a root that moved with its folder; explicit edits for code that computes a root or names a moved path; tables of
  repository paths inside tests.

engine/ holds what CMake builds (src, include, cmake, metal, sycl, spark, third_party, the C++ tests and benches). app/ is the desktop
app and its host (was apps/). terminal/ is the Terminal in the layout of the installed one (strata.py, setup.py, strata_cli,
strata_control, serve, bin, data, ref, crates, the Python tools and tests). docs/ has the documentation, docs/lang/ the translated
READMEs, docs/history and docs/bench-results. tools/ has the repository's own checks, packaging, docker, research and nix.
tests/core/test_tqp_ref.py is a pytest file and stays with the Python tests (terminal/tests/core/).
AGENTS.md, README.md, LICENSE, setup.sh and START-HERE.bat stay at the root.

No behaviour change: the same command lines, the same sources. For this head a replay of the script gave the same numbers and the path
scan (tools/layout/checks/path_scan.py) reports no hit; the suites and the builds run on this commit next.
2026-11-17 13:19:21 +01:00

197 lines
9.5 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.parent / "engine" / "include" / "strata" / "quant" / "strata-quant-common.h"
REFERENCE = ROOT.parent / "engine" / "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.parent / "engine" / "third_party" / "strata-ggml" / "strata-quant-common.h").exists())
fwd = [ln for ln in (ROOT.parent / "engine" / "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()