Files
leleka/scripts/check-kar-expert-result.py
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

95 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Offline independent archive decode and FP64 expert oracle; no serving use.
Consumes private output from strata-kar-expert-probe. It does not compare with
the source GGUF or establish model quality, native arithmetic parity or speed.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import numpy as np
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--archive", type=Path, required=True)
parser.add_argument("--result", type=Path, required=True)
args = parser.parse_args()
os.umask(0o077)
root = args.result.resolve(strict=True)
repo = Path(__file__).resolve().parent.parent
if root == repo or repo in root.parents:
parser.error("qualification outputs must remain outside Git")
m = json.loads((root / "metadata.json").read_text())
h, ff, tokens, level, expert = (m[k] for k in
("hidden", "intermediate", "tokens", "level", "expert"))
if not (0 < h <= 16384 and 0 < ff <= 16384 and h * ff <= 16777216
and h % 32 == 0 and ff % 32 == 0 and 1 <= tokens <= 8
and 1 <= level <= 8 and 0 <= expert < 65536):
raise ValueError("invalid evidence geometry")
words = h * ff // 32
matrices, checks = [], []
with args.archive.open("rb") as archive:
def read(offset, size, dtype):
if not isinstance(offset, int) or offset < 0:
raise ValueError("invalid archive offset")
archive.seek(offset)
raw = archive.read(size)
if len(raw) != size:
raise ValueError("short archive slice")
return np.frombuffer(raw, dtype=dtype)
for role, t in zip(("gate", "up", "down"), m["tensors"], strict=True):
book = read(t["books_offset"] + ((1 << level) - 2) * 2,
(1 << level) * 2, "<f2").astype(np.float32)
scale = read(t["scales_offset"] + expert * words * 2,
words * 2, "<f2").astype(np.float32)
codes = np.zeros((words, 32), dtype=np.uint16)
for p in range(level):
bits = read(t["planes_offset"] + p * t["plane_stride_bytes"]
+ expert * words * 4, words * 4, "<u4")
codes = (codes << 1) | ((bits[:, None] >> np.arange(32, dtype=np.uint32)) & 1)
values = (book[codes] * scale[:, None]).astype("<f4").ravel()
gpu = (root / (role + ".f32")).read_bytes()
exact = gpu == values.tobytes()
checks.append({"role": role, "decoded_bytes_equal": exact,
"cpu_sha256": hashlib.sha256(values.tobytes()).hexdigest(),
"gpu_sha256": hashlib.sha256(gpu).hexdigest()})
matrices.append(values.astype(np.float64).reshape((h, ff) if role == "down" else (ff, h)))
x = np.fromfile(root / "input.f32", dtype="<f4").astype(np.float64).reshape(tokens, h)
expected_input = ((np.arange(tokens * h) % 31 - 15) / 32).reshape(tokens, h)
if not np.array_equal(x, expected_input):
raise ValueError("unexpected input corpus")
gate, up = x @ matrices[0].T, x @ matrices[1].T
# Stable sigmoid, independent of the CUDA expf implementation.
sigmoid = np.empty_like(gate)
positive = gate >= 0
sigmoid[positive] = 1 / (1 + np.exp(-gate[positive]))
exp = np.exp(gate[~positive])
sigmoid[~positive] = exp / (1 + exp)
expected = (gate * sigmoid * up) @ matrices[2].T
actual = np.fromfile(root / "output.f32", dtype="<f4").astype(np.float64).reshape(tokens, h)
delta = actual - expected
relative = float(np.linalg.norm(delta) / max(float(np.linalg.norm(expected)), 1e-30))
max_abs = float(np.max(np.abs(delta)))
scale = max(1.0, float(np.max(np.abs(expected))))
passed = (all(c["decoded_bytes_equal"] for c in checks) and np.isfinite(actual).all()
and relative <= 2e-5 and max_abs <= 1e-4 * scale)
report = {"passed": bool(passed), "decode": checks,
"multiply_relative_l2": relative, "multiply_max_abs": max_abs,
"reference_max_abs_floor_one": scale,
"tolerance": {"decode_bytes": 0, "relative_l2": 2e-5, "scaled_max_abs": 1e-4},
"limits": "Archived KAR oracle only. No GGUF/model quality or speed claim."}
with (root / "oracle.json").open("x") as output:
json.dump(report, output, indent=2, allow_nan=False)
print(json.dumps(report))
if not passed:
raise SystemExit(1)
if __name__ == "__main__":
main()