Files
leleka/scripts/check-kar-cuda-records.py

117 lines
5.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Compare isolated KAR CPU/CUDA decoders for selected real records.
This does not run model inference or establish a throughput improvement.
"""
import argparse
import datetime as dt
import hashlib
import json
import os
import pathlib
import re
import subprocess
import sys
CHECKSUM = re.compile(r"^output_fnv1a64=([0-9a-f]{1,16})\b", re.MULTILINE)
GPU_TIMING = re.compile(r"decode_median_ms=([0-9.eE+-]+)")
GPU_RESIDENT = re.compile(r"resident_bytes=(\d+)")
def digest(path):
h = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def run(command):
completed = subprocess.run(command, capture_output=True, text=True, check=False)
if completed.returncode:
raise RuntimeError(f"{pathlib.Path(command[0]).name} exited {completed.returncode}")
match = CHECKSUM.search(completed.stdout)
if not match:
raise RuntimeError(f"{pathlib.Path(command[0]).name} omitted output checksum")
return completed.stdout, match.group(1)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--archive", type=pathlib.Path, required=True)
parser.add_argument("--records-json", type=pathlib.Path, required=True,
help="JSON with records containing name and elements")
parser.add_argument("--cpu", type=pathlib.Path, required=True,
help="leleka-api CLI executable")
parser.add_argument("--gpu", type=pathlib.Path, required=True,
help="strata-kar-gpu-smoke executable")
parser.add_argument("--level", type=int, required=True)
parser.add_argument("--iterations", type=int, default=30)
parser.add_argument("--output", type=pathlib.Path, required=True)
args = parser.parse_args()
if not 1 <= args.level <= 8 or not 1 <= args.iterations <= 1000:
parser.error("level must be 1..8 and iterations 1..1000")
repository = pathlib.Path(__file__).resolve().parent.parent
output = args.output.resolve()
if output == repository or repository in output.parents:
parser.error("output must be outside the repository")
archive = args.archive.resolve(strict=True)
source = json.loads(args.records_json.read_text())
records = source["records"] if isinstance(source, dict) else source
if not isinstance(records, list) or not records:
parser.error("records JSON must contain a nonempty list")
results = []
for record in records:
name = record["name"]
elements = record["elements"]
if not isinstance(name, str) or not isinstance(elements, int) or elements <= 0:
raise ValueError("invalid record name or element count")
row = elements > 1_000_000
cpu_command = [str(args.cpu), "model",
"checksum-kar-row" if row else "checksum-kar-preview",
str(archive), name, str(args.level)]
gpu_command = [str(args.gpu), str(archive), name,
str(args.level), str(args.iterations)]
if row:
cpu_command += ["--row", "0"]
gpu_command += ["--row", "0"]
cpu_stdout, cpu_checksum = run(cpu_command)
gpu_stdout, gpu_checksum = run(gpu_command)
median = GPU_TIMING.search(gpu_stdout)
resident = GPU_RESIDENT.search(gpu_stdout)
if not median or not resident:
raise RuntimeError("GPU smoke omitted timing or residency")
results.append({"name": name, "elements": elements, "mode": "row-0" if row else "full",
"cpu_fnv1a64": cpu_checksum, "gpu_fnv1a64": gpu_checksum,
"equal": cpu_checksum == gpu_checksum,
"gpu_decode_median_ms": float(median.group(1)),
"gpu_resident_bytes": int(resident.group(1)),
"base_relative_l2": record.get("base_relative_l2"),
"overlay_relative_l2": record.get("overlay_relative_l2")})
report = {"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"archive_sha256": digest(archive), "level": args.level,
"iterations": args.iterations, "results": results,
"summary": {"records": len(results),
"cpu_cuda_equal": sum(result["equal"] for result in results)}}
output.parent.mkdir(parents=True, exist_ok=True)
old_mask = os.umask(0o077)
try:
with output.open("x", encoding="utf-8") as stream:
json.dump(report, stream, indent=2)
stream.write("\n")
finally:
os.umask(old_mask)
print(json.dumps({"output": str(output), "summary": report["summary"]}))
if report["summary"]["cpu_cuda_equal"] != len(results):
raise RuntimeError("CPU/CUDA reconstruction mismatch")
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyError, RuntimeError) as error:
print(f"KAR decoder check failed: {type(error).__name__}: {error}", file=sys.stderr)
sys.exit(1)