File size: 2,996 Bytes
24ba655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# @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()))