Files
leleka/scripts/quality/logits_dump_check.py

100 lines
4.0 KiB
Python

#!/usr/bin/env python3
"""Offline reader guard for the Original's `--dump-logits PATH` file.
Layout: int32 n_vocab, int32 n_rows, then n_rows x n_vocab float32 (little endian). Builds before upstream `504579da` wrote that header
when the file was OPENED, so on a native pack (which never reaches the per-token dump site) the file held a header that promised
rows and no row at all, and the count in it was one too high even where rows were written (n_prompt + max_new, not n_prompt - 1 +
max_new). A reader that trusts the header reports "0 differing positions" for such a file. This reader trusts the SIZE:
python3 logits_dump_check.py FILE [--vocab 248320] [--rows N] exit 0 and print the row count, or exit 1 and say why
python3 logits_dump_check.py --selftest
Never part of serving; no model needed.
"""
import os
import struct
import sys
import tempfile
def check(path, vocab=None, rows=None):
"""Return (n_vocab, rows_by_size). Raise ValueError when the file is not a consistent dump."""
size = os.path.getsize(path)
if size < 8:
raise ValueError(f"{path}: {size} bytes, shorter than the 8-byte header")
with open(path, "rb") as f:
n_vocab, n_rows = struct.unpack("<ii", f.read(8))
if n_vocab <= 0 or n_rows < 0:
raise ValueError(f"{path}: nonsense header n_vocab={n_vocab} n_rows={n_rows}")
body = size - 8
if body % (4 * n_vocab) != 0:
raise ValueError(f"{path}: body of {body} bytes is not a whole number of {n_vocab}-float rows")
by_size = body // (4 * n_vocab)
if by_size != n_rows:
raise ValueError(f"{path}: the header promises {n_rows} rows, the size holds {by_size} (a pre-504579da build on a native pack writes the header and no rows)")
if by_size == 0:
raise ValueError(f"{path}: no rows were written; do not compare against an empty dump")
if vocab is not None and n_vocab != vocab:
raise ValueError(f"{path}: n_vocab {n_vocab}, expected {vocab}")
if rows is not None and by_size != rows:
raise ValueError(f"{path}: {by_size} rows, expected {rows}")
return n_vocab, by_size
def selftest():
def write(d, name, header_rows, real_rows, vocab=4):
p = os.path.join(d, name)
with open(p, "wb") as f:
f.write(struct.pack("<ii", vocab, header_rows))
f.write(struct.pack(f"<{vocab * real_rows}f", *([0.5] * (vocab * real_rows))))
return p
with tempfile.TemporaryDirectory() as d:
assert check(write(d, "ok", 3, 3)) == (4, 3)
assert check(write(d, "ok2", 3, 3), vocab=4, rows=3) == (4, 3)
for name, hdr, real in [("lies", 66, 0), ("off_by_one", 11, 10), ("empty", 0, 0), ("short", 5, 3)]:
try:
check(write(d, name, hdr, real))
except ValueError:
continue
raise AssertionError(f"{name}: a lying dump was accepted")
p = os.path.join(d, "trunc")
with open(p, "wb") as f:
f.write(struct.pack("<ii", 4, 1) + b"\0" * 7)
try:
check(p)
raise AssertionError("a truncated row was accepted")
except ValueError:
pass
try:
check(write(d, "v", 3, 3), vocab=5)
raise AssertionError("a wrong vocabulary was accepted")
except ValueError:
pass
print("logits_dump_check selftest: OK")
if __name__ == "__main__":
args = sys.argv[1:]
if args == ["--selftest"]:
selftest()
sys.exit(0)
if not args or args[0].startswith("--"):
print(__doc__)
sys.exit(2)
opts = {"vocab": None, "rows": None}
i = 1
while i < len(args):
if args[i] in ("--vocab", "--rows") and i + 1 < len(args):
opts[args[i][2:]] = int(args[i + 1])
i += 2
else:
print(__doc__)
sys.exit(2)
try:
n_vocab, n = check(args[0], **opts)
except ValueError as e:
print(f"REFUSED: {e}")
sys.exit(1)
print(f"{args[0]}: {n} rows of {n_vocab} floats (by size, matching the header)")