| | @@ -0,0 +1,135 @@ |
| 1 | +"""Audit the grouped scores against the published, independently decoded R = 32 table.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from fractions import Fraction |
| 5 | +from pathlib import Path |
| 6 | +from runpy import run_path |
| 7 | + |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +HERE = Path(__file__).resolve().parent |
| 11 | +reference = run_path(str(HERE.parent / "upper-smaller-k3" / "verify_k3.py")) |
| 12 | +verify = run_path(str(HERE / "verify.py")) |
| 13 | +N = 512 |
| 14 | +REPS = (0, 1, -12, 12, -24, 24, -40, 40, -56, 56, -80, 80) |
| 15 | + |
| 16 | + |
| 17 | +def check_heights(entries): |
| 18 | + ref_table = reference["Table"](entries, N) |
| 19 | + ref_band = reference["band"] |
| 20 | + assert [ref_band(t) for t in REPS] == list(range(12)) |
| 21 | + assert all(verify["band_index"](t) == ref_band(t) for t in range(-N, N+1)) |
| 22 | + for b, low, high in verify["BANDS"]: |
| 23 | + assert all(ref_band(t) == b for t in range(low, high+1)) |
| 24 | + heights = np.zeros((N+1, 12, N+1), dtype=np.int32) |
| 25 | + count = 0 |
| 26 | + for entry in entries: |
| 27 | + row = verify["AllocationRow"](entry) |
| 28 | + for overlap in range(row.lo, row.hi+1): |
| 29 | + for b, t in enumerate(REPS): |
| 30 | + values = [ref_table.P(overlap, i, t) for i in range(overlap+1)] |
| 31 | + assert values == [row.height(overlap, i, t) for i in range(overlap+1)] |
| 32 | + heights[overlap, b, :overlap+1] = values |
| 33 | + count += len(values) |
| 34 | + print(f"{count} height numerators match verify_k3.Table.P (every pair and signed band)") |
| 35 | + return heights |
| 36 | + |
| 37 | + |
| 38 | +def check_scores(data, entries, heights): |
| 39 | + unit = verify["POT_UNIT"] |
| 40 | + den = verify["KERNEL_DEN"] |
| 41 | + hden = reference["HEIGHT"] |
| 42 | + scale = reference["S"] * unit / (2*hden) |
| 43 | + ref_weights = [reference["W"](Fraction(t, 16)) for t in range(-N, N+1)] |
| 44 | + assert all(verify["kernel_num"](t) == ref_weights[N+t]*den for t in range(-N, N+1)) |
| 45 | + count = full_count = 0 |
| 46 | + for entry, blocks in zip(entries, data["rows"]): |
| 47 | + row = verify["AllocationRow"](entry) |
| 48 | + for a, b, c, d, _ in blocks: |
| 49 | + low, high = max(-111, -a), min(111, N-b) |
| 50 | + terms = sorted(row.coefficient_bounds(a, b, c, d, low, high)) |
| 51 | + offsets = np.arange(low, high+1) |
| 52 | + assert [t for t, _ in terms] == offsets.tolist() |
| 53 | + bands = np.array([reference["band"](int(t)) for t in offsets]) |
| 54 | + cells = [(l, i) for i in range(a, b+1) |
| 55 | + for l in range(max(row.lo, i+c), min(row.hi, i+d)+1)] |
| 56 | + overlaps, centers = np.array(cells).T[:, :, None] |
| 57 | + j = centers + offsets |
| 58 | + own = heights[overlaps, bands, centers] |
| 59 | + partner = heights[overlaps, bands, np.maximum(0, overlaps-j)] |
| 60 | + actual = np.where(j > overlaps, 2*hden, hden+own-partner) |
| 61 | + lower = np.array([v for _, v in terms]) |
| 62 | + assert np.all(lower >= 0) and np.all(lower <= actual) |
| 63 | + # Check the verifier's score floor also in the reference rational units. |
| 64 | + weight = np.array([verify["KERNEL"][111+t] for t in offsets]) |
| 65 | + z = (2*6997*weight*lower) // (1000*den) |
| 66 | + factors = [scale*ref_weights[N+t] for t in offsets] |
| 67 | + mul = np.array([q.numerator for q in factors]) |
| 68 | + div = np.array([q.denominator for q in factors]) |
| 69 | + assert np.array_equal(z, mul*lower // div) |
| 70 | + assert np.all(z <= mul*actual // div) |
| 71 | + count += actual.size |
| 72 | + if row.hi == N: |
| 73 | + # Compare the actual averaged share at every full-overlap (i,j). |
| 74 | + cols = np.arange(N+1) |
| 75 | + for i in range(N+1): |
| 76 | + bands = np.array([reference["band"](int(j)-i) for j in cols]) |
| 77 | + reflected = np.array([reference["band"](i-int(j)) for j in cols]) |
| 78 | + forward = hden + heights[N, bands, i] - heights[N, bands, N-cols] |
| 79 | + reverse = hden + heights[N, reflected, N-i] - heights[N, reflected, cols] |
| 80 | + both = [row.share_num(N, i, j) + row.share_num(N, N-i, N-j) for j in range(N+1)] |
| 81 | + assert np.array_equal(both, forward + reverse) |
| 82 | + full_count += len(both) |
| 83 | + print(f"{count} block score lower bounds checked at individual placements and offsets") |
| 84 | + print(f"{full_count} full-overlap averaged shares match in units of 1/{4*hden}") |
| 85 | + |
| 86 | + |
| 87 | +def check_witnesses(data): |
| 88 | + # Independent dense matrix multiplication against the sparse prefix-sum implementation. |
| 89 | + _, matrix, den = reference["grid"](32, reference["kernel"]()) |
| 90 | + assert den == verify["KERNEL_DEN"] |
| 91 | + broad = matrix - np.eye(N+1, dtype=np.int64)*(4*den) |
| 92 | + u, c = verify["POT_UNIT"], verify["MASS_UNIT"] |
| 93 | + for record in data["witnesses"]: |
| 94 | + level, bins = record |
| 95 | + mass = np.r_[np.repeat(bins[:-1], 8), bins[-1]] |
| 96 | + # Every row of the nonnegative matrix has sum <= 16*den, mass[j] <= c. |
| 97 | + assert max(mass) <= c and 16*den*c < 2**63 |
| 98 | + prod = broad @ mass |
| 99 | + x = [max(0, level - (int(v)*u) // (den*c)) for v in prod] |
| 100 | + norm = Fraction(sum(int(v)*int(w) for v, w in zip(mass, prod)), den*c*c) |
| 101 | + energy = 4*u*u*norm |
| 102 | + cost = -(-energy.numerator // energy.denominator) |
| 103 | + base = 8*3099999*u*level - 100000*(cost + sum(v*v for v in x)) |
| 104 | + assert verify["prepare"](record) == (base, x) |
| 105 | + print(f"{len(data['witnesses'])} witness costs and node potentials match the dense grid matrix") |
| 106 | + |
| 107 | + |
| 108 | +def expect_rejection(data, entries, message): |
| 109 | + try: |
| 110 | + verify["replay"](data, entries) |
| 111 | + except ValueError as error: |
| 112 | + if message not in str(error): |
| 113 | + raise |
| 114 | + print(f"rejected corruption: {error}") |
| 115 | + else: |
| 116 | + raise AssertionError("corrupt certificate passed") |
| 117 | + |
| 118 | + |
| 119 | +def main(): |
| 120 | + data = json.loads((HERE / "row.json").read_text()) |
| 121 | + entries = json.loads(verify["TABLE"].read_text()) |
| 122 | + heights = check_heights(entries) |
| 123 | + check_scores(data, entries, heights) |
| 124 | + check_witnesses(data) |
| 125 | + bad = data["witnesses"].copy() |
| 126 | + idx = data["rows"][0][0][-1] |
| 127 | + bad[idx] = [1, bad[idx][1]] # well-typed positive level, arithmetically insufficient |
| 128 | + expect_rejection(dict(data, witnesses=bad), entries, "insufficient bound") |
| 129 | + missing = data["rows"].copy() |
| 130 | + missing[-1] = missing[-1][:-1] |
| 131 | + expect_rejection(dict(data, rows=missing), entries, "incomplete coverage") |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + main() |