Files
leleka/tools/kernel-ab/verify_manifest.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 9750539d4d STRA-329: native-cpu-expert AVX2 IQ4_XS multi-token route, fused Q2_0 correction, KAB1 ext case set
Confirmed against the C++ in engine/strata and fixed:
- rust_native_general.rs group_dot_bytes_policy omitted the `gu == 23 && !avx512` multi-token branch of
  native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`);
  rust_pool.rs had it since STRA-324. The choice is now one function, gu_multi_route, shared in shape with the
  pool. Regression: a differential test (re-runs itself with STRATA_FORCE_AVX2=1 on an AVX-512 CPU) fails
  with a 1-ULP difference on the old code, plus a routing-table test.
- rust_legacy.rs row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) now fuses `corr += d*(hx0+hx1)` like expert.cpp
  row_dot (line 242) and row_dot_multi (line 294) under GCC -mfma. Regression: scalar model, fails on old code.

NOT changed, unconfirmed (need the pinned ggml source, which is not in the repo): rust_kq.rs small_dot
`sums += m*s`, rust_k_blocks.rs mins_sum, rust_ggml_extra.rs iq1 scalar.

KAB1: new `--cases ext` (72 cases; the 40 of `all` are untouched) adds token counts 4-7 for the row-type list
and IQ2_XXS / IQ2_XS at 1..8 tokens; GateUpFormat gains Iq2Xxs / Iq2Xs (additive; the runtime still admits only
18/21/22/23/42). The C++ driver edits are list-only and were NOT compiled here (no ggml). 16 tokens exceed MAXT
and the KAB1 header and are not covered. New Rust-only test token_count_invariance: the first two tokens of a
group are bit-identical for groups of 2..8 tokens on all 14 gate/up x down pairs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 01:26:26 +01:00

183 lines
8.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""Verify a KAB1 run directory (STRA-248). Standard library only, Python >= 3.9.
verify_manifest.py D recompute everything; exit 0 and "OK <n> files" when the directory is whole
verify_manifest.py D --ids additionally print the set of ggml type ids found in the case headers
Exit codes: 0 verified; 1 a file differs from the manifest or violates the format (the message names the file);
2 incomplete directory (no manifest.json: the writer publishes it LAST, so its absence means the run did not finish).
Reader rule (KAB1): verify the manifest, recompute every sha256 and length, check the header-derived sizes, then use;
any mismatch refuses the WHOLE directory. Nothing in a case file is trusted before it has been checked here.
"""
import hashlib
import json
import math
import os
import struct
import sys
MAGIC_IN = 0x4942414B # 'KABI'
MAGIC_OUT = 0x4F42414B # 'KABO'
VERSION = 1
H, FF = 2560, 640
GU_IDS = (16, 17, 18, 21, 22, 23, 42) # 16 / 17 only in the `ext` case set (STRA-329)
DOWN_IDS = (20, 42)
REQUIRED_IDS = {18, 20, 21, 22, 23, 42}
EXT_IDS = REQUIRED_IDS | {16, 17}
# ggml id -> (elements per block, bytes per block): crates/native-cpu-expert/src/lib.rs block()
BLOCK = {18: (256, 98), 21: (256, 110), 22: (256, 82), 23: (256, 136), 42: (64, 18), 20: (32, 18), 16: (256, 66), 17: (256, 74)}
TREE_ID = {"avx512": 0, "avx2": 1}
IN_HEADER = 64
OUT_HEADER = 20
class Refused(Exception):
def __init__(self, name, why):
Exception.__init__(self, "%s: %s" % (name, why))
def sha256_of(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def finite_f32_block(raw):
"""True when no 4-byte little-endian word of `raw` has the f32 exponent field all ones (inf or NaN)."""
for (w,) in struct.iter_unpack("<I", raw):
if (w & 0x7F800000) == 0x7F800000:
return False
return True
def check_in(name, path):
with open(path, "rb") as f:
raw = f.read()
if len(raw) < IN_HEADER:
raise Refused(name, "shorter than the 64-byte header")
magic, version, gu, down, rows, n_embd, n_ff, gb, ub, db = struct.unpack_from("<IIiiIIIIII", raw, 0)
if magic != MAGIC_IN or version != VERSION:
raise Refused(name, "bad magic or version")
if gu not in GU_IDS or down not in DOWN_IDS:
raise Refused(name, "gate/up type %d or down type %d is not in the KAB1 row-type list" % (gu, down))
if not 1 <= rows <= 8 or n_embd != H or n_ff != FF:
raise Refused(name, "rows/n_embd/n_ff out of range")
gq, gbk = BLOCK[gu]
dq, dbk = BLOCK[down]
gsize = H // gq * gbk * FF
dsize = FF // dq * dbk * H
if (gb, ub, db) != (gsize, gsize, dsize):
raise Refused(name, "byte counts %r differ from the format-derived %r" % ((gb, ub, db), (gsize, gsize, dsize)))
if any(raw[IN_HEADER - 24:IN_HEADER]):
raise Refused(name, "header padding is not zero")
want = IN_HEADER + 2 * gsize + dsize + rows * H * 4
if len(raw) != want:
raise Refused(name, "file length %d differs from the header-derived length %d" % (len(raw), want))
off = IN_HEADER
for label, size, block in (("gate", gsize, gbk), ("up", gsize, gbk), ("down", dsize, dbk)):
for at in range(0, size, block):
lo = raw[off + at] | (raw[off + at + 1] << 8)
if (lo & 0x7C00) == 0x7C00:
raise Refused(name, "%s block at byte %d has a non-finite FP16 header" % (label, at))
off += size
if not finite_f32_block(raw[off:]):
raise Refused(name, "an activation value is not finite")
return gu, down, rows
def check_out(name, path, tree, rows):
with open(path, "rb") as f:
raw = f.read()
if len(raw) < OUT_HEADER:
raise Refused(name, "shorter than the output header")
magic, version, orows, n_embd, tree_id = struct.unpack_from("<IIIII", raw, 0)
if magic != MAGIC_OUT or version != VERSION:
raise Refused(name, "bad magic or version")
if orows != rows or n_embd != H or tree_id != TREE_ID[tree]:
raise Refused(name, "header (rows %d, n_embd %d, tree %d) does not match the case and the file name" % (orows, n_embd, tree_id))
if len(raw) != OUT_HEADER + rows * H * 4:
raise Refused(name, "file length differs from the header-derived length")
if not finite_f32_block(raw[OUT_HEADER:]):
raise Refused(name, "a non-finite output value")
def verify(d, want_ids):
man_path = os.path.join(d, "manifest.json")
if not os.path.isfile(man_path):
print("incomplete directory: %s has no manifest.json (the writer publishes it last)" % d, file=sys.stderr)
return 2
try:
with open(man_path, "r", encoding="utf-8") as f:
man = json.load(f)
except (OSError, ValueError) as e:
print("manifest.json: unreadable (%s)" % e, file=sys.stderr)
return 1
try:
if man.get("format") != "KAB1" or man.get("version") != 1:
raise Refused("manifest.json", "format is not KAB1 version 1")
files = man["files"]
cases = man["cases"]
prov = man["provenance"]
for key in ("avx2_ok", "avx512_ok"):
if not isinstance(prov.get(key), bool):
raise Refused("manifest.json", "provenance.%s is not a boolean" % key)
present = sorted(n for n in os.listdir(d) if n != "manifest.json")
if present != sorted(files):
extra = sorted(set(present) - set(files))
missing = sorted(set(files) - set(present))
raise Refused(extra[0] if extra else missing[0], "%s (the directory and the manifest disagree)" % ("not in the manifest" if extra else "listed but absent"))
for name in sorted(files):
p = os.path.join(d, name)
if os.path.getsize(p) != files[name]["bytes"]:
raise Refused(name, "byte length differs from the manifest")
if sha256_of(p) != files[name]["sha256"]:
raise Refused(name, "sha256 differs from the manifest")
ids = set()
for c in cases:
gu, down, rows = check_in(c["in"], os.path.join(d, c["in"]))
if (gu, down, rows) != (c["gu_type"], c["down_type"], c["rows"]):
raise Refused(c["in"], "header differs from the manifest entry")
if c["in"] not in files or files[c["in"]]["sha256"] != c["in_sha256"] or files[c["in"]]["bytes"] != c["in_bytes"]:
raise Refused(c["in"], "case entry and files table disagree")
ids.update((gu, down))
for tree in ("avx512", "avx2"):
out = c["out_cpp_" + tree]
check_out(out, os.path.join(d, out), tree, rows)
if files[out]["sha256"] != c["out_cpp_%s_sha256" % tree]:
raise Refused(out, "case entry and files table disagree")
if c.get("tolerance") is not None and not isinstance(c["tolerance"], dict):
raise Refused(c["in"], "tolerance must be null or an object with its basis")
if len(files) != 3 * len(cases):
raise Refused("manifest.json", "files table does not hold exactly .in + 2 .out per case")
newest = max(os.stat(os.path.join(d, n)).st_mtime_ns for n in present)
if os.stat(man_path).st_mtime_ns < newest:
raise Refused("manifest.json", "is older than another file: it must be written last")
if want_ids:
print("{" + ", ".join(str(i) for i in sorted(ids)) + "}")
if ids not in (REQUIRED_IDS, EXT_IDS):
raise Refused("manifest.json", "id set %s is not the row-type list %s (or, for the ext case set, %s)" % (sorted(ids), sorted(REQUIRED_IDS), sorted(EXT_IDS)))
except Refused as e:
print("REFUSED %s" % e, file=sys.stderr)
return 1
except (KeyError, TypeError) as e:
print("REFUSED manifest.json: malformed (%r)" % (e,), file=sys.stderr)
return 1
print("OK %d files" % len(files))
return 0
def main(argv):
args = [a for a in argv if not a.startswith("--")]
flags = [a for a in argv if a.startswith("--")]
if len(args) != 1 or any(f != "--ids" for f in flags):
print(__doc__, file=sys.stderr)
return 64
return verify(args[0], "--ids" in flags)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))