ztripez's picture
Publish portable two-encoder heat recovery and archived replay
24ba655 verified
Raw History Blame Contribute Delete
3 kB
# @locus component: cge.compiler_guided_extraction
"""Replay held original-heat fields with the recovered library and standard Python."""
import argparse
import ctypes
import json
import math
from pathlib import Path
import struct
import sys
def replay(library, interface, tape):
"""Compare field bytes after ordinary calls and terminal-code writes."""
ptr = ctypes.POINTER(ctypes.c_float)
run = ctypes.CDLL(str(library)).cge_run
buffers = interface["scratch_buffers"]
run.argtypes = [*([ctypes.c_uint64] * 3), *([ptr] * (3 + len(buffers)))]
run.restype = None
results = {}
for case in tape:
n, q = case["shape"]
sizes = {"n": n, "q": q}
ports = []
for port in case["ports"]:
raw = bytes.fromhex(port)
ports.append((ctypes.c_float * (len(raw) // 4)).from_buffer_copy(raw))
outputs = {}
for name, (rows, width, dtype) in buffers.items():
scalar = {"f4": ctypes.c_float, "f8": ctypes.c_double}[dtype]
outputs[name] = (scalar * (sizes.get(rows, rows) * sizes.get(width, width)))()
write_mask = 0
for arm, value in case["writes"].items():
write_mask |= 1 << int(arm)
destination = outputs[interface["terminal_writes"][int(arm)]]
raw = bytes.fromhex(value)
if len(raw) != ctypes.sizeof(destination):
raise ValueError(f"terminal-code write {arm} has a different size")
ctypes.memmove(destination, raw, len(raw))
run(n, q, write_mask, *(ctypes.cast(value, ptr) for value in [*ports, *outputs.values()]))
expected, actual = bytes.fromhex(case["field"]), bytes(outputs[interface["output"]])
if len(expected) != len(actual):
raise ValueError(f"case {case['name']} has a different field size")
pairs = zip(struct.iter_unpack("<f", expected), struct.iter_unpack("<f", actual), strict=True)
errors = [abs(reference - observed) for (reference,), (observed,) in pairs]
if not all(map(math.isfinite, errors)):
raise ValueError(f"case {case['name']} has a nonfinite field difference")
results[case["name"]] = {
"matched": sum(expected[i:i + 4] == actual[i:i + 4] for i in range(0, len(expected), 4)),
"total": len(expected) // 4,
"max_abs": max(errors),
}
return results
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
for name in ("library", "interface", "tape"):
parser.add_argument(name, type=Path)
parser.add_argument("--report-only", action="store_true", help="Report finite drift without a bitwise gate.")
args = parser.parse_args()
verdict = replay(args.library.resolve(), json.loads(args.interface.read_text()), json.loads(args.tape.read_text()))
print(json.dumps(verdict, indent=2))
sys.exit(not args.report_only and any(row["matched"] != row["total"] for row in verdict.values()))