mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 15:28:40 +00:00
P-5 src/kernels/cpu/expert_oracle_parts.hpp: quantize_oracle_q8_0, chunk_dot_oracle, row_dot_oracle
P-6 tools/format_tables/*.txt, gen_strata_quant_tables.py now builds strata_quant_tables.py from them
(the module is byte-identical to the current one), property checks, test_quant_header.py compares
with the data files and the FORMAT-SPEC layouts instead of the vendored reference header,
gen_iq2xs_host_tables.py + iq2xs_host_tables_gen.inc (identical values to the old .inc),
strata_gguf_core.py (enum, sizes, get_type, shape helpers, pack_value, typed adders) with
test_strata_gguf_core.py (compared with the current writer as a black box, byte-identical file)
Written from phaseA-tests/clean/P2-INTERFACES.md and FORMAT-SPEC.md only.
196 lines
11 KiB
Python
196 lines
11 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 data files of tools/format_tables/ (FORMAT-SPEC Part II section 18) byte
|
|
for byte, and the two derived forms (ksigns64, the GPU form of iq1s_grid) follow their rules;
|
|
* every block struct has the layout (size and field offsets) of FORMAT-SPEC Parts I and II;
|
|
* the Metal branch of the header 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 gen_strata_quant_tables as GQT # 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"
|
|
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)}
|
|
#: FORMAT-SPEC Parts I and II: struct -> (bytes, [(field, offset, size)]); a field that holds two halves of the spec (d and m, d and dmin) is one range
|
|
SPEC_LAYOUT = {
|
|
"block_q1_0": (18, [("d", 0, 2), ("qs", 2, 16)]),
|
|
"block_q2_0": (18, [("d", 0, 2), ("qs", 2, 16)]),
|
|
"block_q4_0": (18, [("d", 0, 2), ("qs", 2, 16)]),
|
|
"block_q4_1": (20, [("d", 0, 4), ("qs", 4, 16)]),
|
|
"block_mxfp4": (17, [("e", 0, 1), ("qs", 1, 16)]),
|
|
"block_nvfp4": (36, [("d", 0, 4), ("qs", 4, 32)]),
|
|
"block_q5_0": (22, [("d", 0, 2), ("qh", 2, 4), ("qs", 6, 16)]),
|
|
"block_q5_1": (24, [("d", 0, 4), ("qh", 4, 4), ("qs", 8, 16)]),
|
|
"block_q8_0": (34, [("d", 0, 2), ("qs", 2, 32)]),
|
|
"block_q8_1": (36, [("d", 0, 4), ("qs", 4, 32)]),
|
|
"block_tq1_0": (54, [("qs", 0, 48), ("qh", 48, 4), ("d", 52, 2)]),
|
|
"block_tq2_0": (66, [("qs", 0, 64), ("d", 64, 2)]),
|
|
"block_q2_K": (84, [("scales", 0, 16), ("qs", 16, 64), ("d", 80, 4)]),
|
|
"block_q3_K": (110, [("hmask", 0, 32), ("qs", 32, 64), ("scales", 96, 12), ("d", 108, 2)]),
|
|
"block_q4_K": (144, [("d", 0, 4), ("scales", 4, 12), ("qs", 16, 128)]),
|
|
"block_q5_K": (176, [("d", 0, 4), ("scales", 4, 12), ("qh", 16, 32), ("qs", 48, 128)]),
|
|
"block_q6_K": (210, [("ql", 0, 128), ("qh", 128, 64), ("scales", 192, 16), ("d", 208, 2)]),
|
|
"block_q8_K": (292, [("d", 0, 4), ("qs", 4, 256), ("bsums", 260, 32)]),
|
|
"block_iq2_xxs": (66, [("d", 0, 2), ("qs", 2, 64)]),
|
|
"block_iq2_xs": (74, [("d", 0, 2), ("qs", 2, 64), ("scales", 66, 8)]),
|
|
"block_iq2_s": (82, [("d", 0, 2), ("qs", 2, 64), ("qh", 66, 8), ("scales", 74, 8)]),
|
|
"block_iq3_xxs": (98, [("d", 0, 2), ("qs", 2, 96)]),
|
|
"block_iq3_s": (110, [("d", 0, 2), ("qs", 2, 64), ("qh", 66, 8), ("signs", 74, 32), ("scales", 106, 4)]),
|
|
"block_iq1_s": (50, [("d", 0, 2), ("qs", 2, 32), ("qh", 34, 16)]),
|
|
"block_iq1_m": (56, [("qs", 0, 32), ("qh", 32, 16), ("scales", 48, 8)]),
|
|
"block_iq4_nl": (18, [("d", 0, 2), ("qs", 2, 16)]),
|
|
"block_iq4_xs": (136, [("d", 0, 2), ("scales_h", 2, 2), ("scales_l", 4, 4), ("qs", 8, 128)]),
|
|
}
|
|
|
|
|
|
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)
|
|
|
|
|
|
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)
|
|
|
|
def test_every_table_matches_the_data_files(self):
|
|
got = table_bytes(HEADER.read_text(encoding="utf-8"))
|
|
for name, width, signed in GQT.TABLES:
|
|
self.assertEqual(got[name], GQT.table_bytes(name, width, signed), name)
|
|
self.assertEqual(GQT.check_properties(), [])
|
|
|
|
def test_the_derived_table_forms_follow_their_rules(self):
|
|
got = table_bytes(HEADER.read_text(encoding="utf-8"))
|
|
ks = GQT.load("ksigns_iq2xs")[0]
|
|
want = b"".join(bytes(0xFF if (v >> j) & 1 else 0 for j in range(8)) for v in ks)
|
|
self.assertEqual(got["ksigns64"], want, "ksigns64: each sign byte spread to 8 bytes of 00 / ff")
|
|
gpu = bytearray()
|
|
for r in GQT.load("iq1s_grid"): # values -1, 0, 1 stored as v + 1 in 4-bit fields: values 0-3 in the low nibbles of bytes 0-3, 4-7 in the high nibbles
|
|
gpu += bytes((r[k] + 1) | ((r[k + 4] + 1) << 4) for k in range(4))
|
|
self.assertEqual(got["iq1s_grid_gpu"], bytes(gpu), "iq1s_grid_gpu")
|
|
|
|
def test_every_struct_has_the_layout_of_the_format_spec(self):
|
|
by_name = {b[0]: b for b in GEN.BLOCKS if b[4] is not None}
|
|
self.assertEqual(sorted(by_name), sorted(SPEC_LAYOUT))
|
|
for name, (size, ranges) in SPEC_LAYOUT.items():
|
|
fields = by_name[name][4]
|
|
self.assertEqual(GEN.struct_bytes(fields), size, name)
|
|
got = [(f[1], GEN.struct_bytes(fields[:i]), GEN.struct_bytes(fields[:i + 1]) - GEN.struct_bytes(fields[:i])) for i, f in enumerate(fields)]
|
|
self.assertEqual(got, ranges, name)
|
|
|
|
def test_the_metal_branch_gets_iq1s_grid(self):
|
|
text = HEADER.read_text(encoding="utf-8").split(chr(10))
|
|
at = [i for i, ln in enumerate(text) if ln.startswith("GGML_TABLE_BEGIN(") and " iq1s_grid," in ln]
|
|
self.assertEqual(len(at), 1)
|
|
cond = [ln for ln in text[:at[0]] if ln.startswith("#if") or ln.startswith("#elif")][-1]
|
|
self.assertIn("GGML_COMMON_IMPL_METAL", cond)
|
|
|
|
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()
|