#!/usr/bin/env python3 """Independent MPFR gate. Requires gmpy2==2.3.0 in tooling, never in the VM. Build numeric_probe in debug/release, run against each with identical seed/count, then compare the emitted corpora. Directed MPFR intervals adapt precision until binary64 rounding and strict trig error classification can be certified. """ import argparse import hashlib import json import platform import random import struct import subprocess from pathlib import Path import gmpy2 as g def fbits(value): return struct.unpack(">Q", struct.pack(">d", value))[0] def host(bits): return struct.unpack(">d", struct.pack(">Q", bits))[0] def exact(bits): """Import through the exact rational representation, including subnormals.""" n, d = host(bits).as_integer_ratio() return g.mpq(n, d) def evaluate(op, args, precision, rounding): with g.context(precision=precision, round=rounding): xs = [g.mpfr("-0") if int(x[2:],16)==1<<63 else g.mpfr(exact(int(x[2:], 16))) for x in args if x.startswith("f:")] if op == "3010": return g.sqrt(xs[0]) if op == "3011": return g.sin(xs[0]) if op == "3012": return g.cos(xs[0]) if op == "3013": return g.atan2(xs[0], xs[1]) if op in ("3016", "3017"): return g.mpfr(int(args[0][2:])) if op == "ADD": return xs[0] + xs[1] if op == "SUB": return xs[0] - xs[1] if op == "MUL": return xs[0] * xs[1] if op == "DIV": return xs[0] / xs[1] raise ValueError(op) def rounded_bits(value): # MPFR IEEE context includes gradual underflow and binary64 exponent bounds. with g.context(g.ieee(64), round=g.RoundToNearest): rounded = g.mpfr(value) return fbits(float(rounded)) def certify(op, args, result): if op in ("300c", "300d", "300e", "300f", "3018", "3019"): bits = int(args[0][2:], 16) n, d = host(bits).as_integer_ratio() integer = abs(n) // d if op == "300c": integer = n // d elif op == "300d": integer = -((-n) // d) elif op == "300f": integer, remainder = divmod(abs(n), d) if 2*remainder > d or (2*remainder == d and integer % 2): integer += 1 if n < 0: integer = -integer elif n < 0: integer = -integer if op in ("3018", "3019"): width = 32 if op == "3018" else 64 expected = "trap:13" if not -(1 << (width-1)) <= integer < (1 << (width-1)) else ("i:" if width == 32 else "l:")+str(integer) else: with g.context(precision=160, round=g.RoundToNearest): rounded = rounded_bits(g.mpfr(integer)) if integer == 0: rounded = bits & (1 << 63) expected = f"f:{rounded:016x}" if result != expected: raise AssertionError(f"{op} {args}: {result}, exact {expected}") return 0.0, 160 if op in ("1000", "1001"): with g.context(g.ieee(64), round=g.RoundToNearest): xs = [g.mpfr("-0") if int(x[2:],16)==1<<63 else g.mpfr(exact(int(x[2:],16))) for x in args] if op == "1000": p1 = xs[0]*xs[2] p2 = xs[1]*xs[3] value = p1+p2 if not g.is_finite(p1) or not g.is_finite(p2): value = g.mpfr("inf") else: m, n = max(abs(xs[0]),abs(xs[1])), min(abs(xs[0]),abs(xs[1])) if m == 0: value = g.mpfr(0) else: r = n/m q = r*r s = g.mpfr(1)+q t = g.sqrt(s) value = m*t expected = "trap:13" if not g.is_finite(value) else f"f:{fbits(float(value)):016x}" if result != expected: raise AssertionError(f"{op} {args}: {result}, MPFR sequence {expected}") return 0.0, 53 trig = op in ("3011", "3012", "3013") for precision in (160, 320, 640, 1280, 2560, 5120, 10240): lo = evaluate(op, args, precision, g.RoundDown) hi = evaluate(op, args, precision, g.RoundUp) lb, hb = rounded_bits(lo), rounded_bits(hi) if not trig: if lo == hi == 0: lb=hb=rounded_bits(evaluate(op,args,precision,g.RoundToNearest)) if lb != hb: continue expected = "trap:13" if lb & 0x7ff0000000000000 == 0x7ff0000000000000 else f"f:{lb:016x}" if result != expected: raise AssertionError(f"{op} {args}: {result}, MPFR {expected}") return 0.0, precision if not result.startswith("f:"): raise AssertionError(f"unexpected trig fault: {op} {args}: {result}") out_bits = int(result[2:], 16) with g.context(precision=precision, round=g.RoundUp): out = g.mpfr(exact(out_bits)) # Use a conservative spacing if interval crosses a power of two. magnitude_lo = min(abs(lo), abs(hi)) if lo <= 0 <= hi: magnitude_lo = g.mpfr(0) exponent = max(-1074, int(g.get_exp(magnitude_lo)) - 53) if magnitude_lo else -1074 ulp = g.mul_2exp(g.mpfr(1), exponent) # Each positive endpoint distance rounds upward. Taking abs after # an upward-rounded negative subtraction would underestimate it. error_hi = max(out - lo, hi - out, g.mpfr(0)) / ulp if error_hi < 1: return float(error_hi), precision with g.context(precision=precision, round=g.RoundDown): error_lo = (lo-out if out < lo else out-hi if out > hi else g.mpfr(0)) / ulp if error_lo >= 1: raise AssertionError(f"{op} {args}: {result}, error >= {float(error_lo):.12g} ULP") raise AssertionError(f"unresolved MPFR interval: {op} {args}") def corpus(count, seed): rng = random.Random(seed) # Both sides of binades, subnormal transitions, pi/2 reductions, huge angles. critical = [0, 1, 2, 0xfffffffffffff, 0x10000000000000, 0x3fdfffffffffffff, 0x3fe0000000000000, 0x3fe0000000000001, 0x3ff0000000000000, 0x4000000000000000, 0x3ff921fb54442d18, 0x400921fb54442d18, 0x401921fb54442d18, 0x7fefffffffffffff] critical += [v + delta for v in critical[4:] for delta in (-2, -1, 1, 2)] critical = [v for v in critical if v & 0x7ff0000000000000 != 0x7ff0000000000000] bits = critical + [rng.getrandbits(64) & 0x7fefffffffffffff for _ in range(count)] # Masked samples omit half the exponent binades; add unmasked finite samples. while len(bits) < 2*count + len(critical): v = rng.getrandbits(64) if v & 0x7ff0000000000000 != 0x7ff0000000000000: bits.append(v) rows = [] for v in bits: positive = v & 0x7fffffffffffffff rows.append(("3010", [f"f:{positive:016x}"])) for op in ("300c", "300d", "300e", "300f", "3018", "3019"): rows.append((op, [f"f:{v:016x}"])) for signed in (positive, positive | (1 << 63)): rows.append(("3011", [f"f:{signed:016x}"])) rows.append(("3012", [f"f:{signed:016x}"])) other = rng.choice(bits) rows.append(("1001", [f"f:{v:016x}", f"f:{other:016x}"])) rows.append(("1000", [f"f:{v:016x}", f"f:{other:016x}", f"f:{rng.choice(bits):016x}", f"f:{rng.choice(bits):016x}"])) if v & 0x7fffffffffffffff or other & 0x7fffffffffffffff: rows.append(("3013", [f"f:{v:016x}", f"f:{other:016x}"])) for op in ("ADD", "SUB", "MUL", "DIV"): if op != "DIV" or other & 0x7fffffffffffffff: rows.append((op, [f"f:{v:016x}", f"f:{other:016x}"])) for n in [-(1 << 63), (1 << 63)-1, 0, 1, -1, (1 << 53)-1, (1 << 53)+1] + [rng.randrange(-(1<<63), 1<<63) for _ in range(count)]: rows.append(("3017", [f"l:{n}"])) for n in [-(1<<31), (1<<31)-1, 0, 1, -1] + [rng.randrange(-(1<<31), 1<<31) for _ in range(count)]: rows.append(("3016", [f"i:{n}"])) return rows def main(): parser = argparse.ArgumentParser() parser.add_argument("--probe", required=True) parser.add_argument("--output", required=True) parser.add_argument("--count", type=int, default=1000) parser.add_argument("--seed", type=int, default=560053) args = parser.parse_args() rows = corpus(args.count, args.seed) wire = "".join(" ".join([op] + values) + "\n" for op, values in rows) process = subprocess.run([args.probe], input=wire, text=True, capture_output=True, check=True) results = process.stdout.splitlines() assert len(rows) == len(results) maxima = {} max_precision = 0 output = [] for (op, values), line in zip(rows, results): result, cycles = line.split() error, precision = certify(op, values, result) maxima[op] = max(maxima.get(op, 0), error) max_precision = max(max_precision, precision) output.append(" ".join([op] + values + [result, cycles]) + "\n") content = "".join(output).encode() Path(args.output).parent.mkdir(parents=True, exist_ok=True) Path(args.output).write_bytes(content) print(json.dumps({ "rows": len(rows), "count": args.count, "seed": args.seed, "corpus_sha256": hashlib.sha256(content).hexdigest(), "max_error_ulp_upper_bound": maxima, "max_mpfr_precision": max_precision, "gmpy2": g.version(), "mpfr": g.mpfr_version(), "oracle_architecture": platform.machine(), "probe": args.probe, "cross_host_execution": "pending", }, indent=2)) if __name__ == "__main__": main()