yang
This project has not described itself yet.
Brought by drakestapleton
yang / scripts / haar_slab_bound.py
| 1 | """Conditional product-Haar diagnostics for C + sum_s r_s.T B_s b_s. |
| 2 | |
| 3 | See evidence/wilson_haar_bound.md for the real-arithmetic inequalities. The |
| 4 | returned natural log ceilings are binary64 evaluations, not certificates. |
| 5 | """ |
| 6 | import math |
| 7 | |
| 8 | import numpy as np |
| 9 | |
| 10 | |
| 11 | def bounds(constant, B, dim): |
| 12 | """Return Var(J), log upper P(J<0), log upper (1-|E tanh J|). |
| 13 | |
| 14 | B has shape (2, red_coordinates, blue_coordinates). Each consecutive |
| 15 | dim-vector is uniform on its unit sphere, independently across all blocks. |
| 16 | constant is the total of the two sheet constants, not a per-sheet array. |
| 17 | """ |
| 18 | c = np.asarray(constant) |
| 19 | if c.ndim or c.dtype.kind not in 'ifu' or not math.isfinite(float(c)): |
| 20 | raise ValueError('constant must be a finite real scalar') |
| 21 | c = float(c) |
| 22 | if isinstance(dim, bool) or not isinstance(dim, (int, np.integer)) or dim <= 0: |
| 23 | raise ValueError('dim must be a positive integer') |
| 24 | dim = int(dim) |
| 25 | B = np.asarray(B) |
| 26 | if (B.ndim != 3 or B.shape[0] != 2 or |
| 27 | any(n == 0 or n % dim for n in B.shape[1:]) or B.dtype.kind not in 'ifu'): |
| 28 | raise ValueError('B requires two real matrices with full dim-blocks on both axes') |
| 29 | B = np.asarray(B, dtype=np.float64) |
| 30 | if not np.isfinite(B).all(): |
| 31 | raise ValueError('nonfinite B') |
| 32 | if not B.any(): |
| 33 | # Strict sign event, including the atom at J=0. Avoid tanh saturation. |
| 34 | a = abs(c) |
| 35 | if a < 1.0: |
| 36 | loss = -a - math.log1p(2 * math.sinh(a / 2)**2) |
| 37 | else: |
| 38 | z = -2 * a |
| 39 | if not math.isfinite(z): |
| 40 | raise OverflowError('constant-field log loss outside binary64 range') |
| 41 | loss = math.log(2) + z - math.log1p(math.exp(z)) |
| 42 | return 0.0, -math.inf if c >= 0 else 0.0, loss |
| 43 | |
| 44 | sigma = np.linalg.svd(B, compute_uv=False) |
| 45 | largest = float(sigma.max()) |
| 46 | scale = largest / dim |
| 47 | if not (math.isfinite(scale) and scale > 0): |
| 48 | raise OverflowError('nonzero slab singular scale outside binary64 range') |
| 49 | # q = (sigma / sigma_max)^2; x = t * sigma_max / dim is dimensionless. |
| 50 | q = np.square(sigma / largest) |
| 51 | n = float(q.sum()) |
| 52 | sd = scale * math.sqrt(n) |
| 53 | var = sd * sd |
| 54 | h = abs(c) / scale |
| 55 | if not (math.isfinite(var) and var > 0 and math.isfinite(h)): |
| 56 | raise OverflowError('variance or normalized offset outside binary64 range') |
| 57 | |
| 58 | # Minimize a convex upper envelope, then evaluate the tighter determinant |
| 59 | # at that tilt. Stay back from the pole even if the minimizer rounds to 1. |
| 60 | x = min(0.99, h / (n / 2 + math.hypot(n / 2, h))) |
| 61 | |
| 62 | def log_mgf(x): |
| 63 | if not 0 <= x < 1: |
| 64 | raise ValueError('tilt outside the Gaussian determinant domain') |
| 65 | return -h * x - 0.5 * float(np.log1p(-(x*x) * q).sum()) |
| 66 | |
| 67 | # Reflecting J is valid for the absolute loss, NOT for the negative event. |
| 68 | f = log_mgf(x) |
| 69 | log_p = min(0.0, f) if c > 0 else 0.0 |
| 70 | loss_x = min(x, 2 * scale) |
| 71 | loss_f = f if loss_x == x else log_mgf(loss_x) |
| 72 | return var, log_p, min(0.0, math.log(2) + loss_f) |
| 73 | |
| 74 | |
| 75 | def _controls(): |
| 76 | """Deterministic checks; no chain samples and no optimizer witnesses.""" |
| 77 | # U(1): the difference of two independent Haar angles is uniform, so |
| 78 | # J = 1.9 + 2 cos(theta). Loss is a 40-digit Wolfram quadrature reference. |
| 79 | B = np.zeros((2, 2, 2)) |
| 80 | B[0] = 2 * np.eye(2) |
| 81 | var, lp, ll = bounds(1.9, B, 2) |
| 82 | p, loss = math.acos(19/20) / math.pi, 0.28646635974401333155 |
| 83 | assert math.isclose(var, 2.0) and math.log(p) <= lp < 0 and math.log(loss) <= ll <= 0 |
| 84 | print(f'U1 circle: var={var:.12g} p={p:.12g} log_p_upper={lp:.12g} ' |
| 85 | f'loss={loss:.12g} log_loss_upper={ll:.12g}') |
| 86 | |
| 87 | # Independent signs on two sheets: J = 3 + sum of four Rademachers. |
| 88 | B[:] = np.eye(2) |
| 89 | var, lp, ll = bounds(3, B, 1) |
| 90 | loss = 1 - sum(math.comb(4,k)*math.tanh(3 + 2*k - 4) for k in range(5))/16 |
| 91 | assert math.isclose(var, 4) and math.log(1/16) <= lp < 0 and math.log(loss) <= ll < 0 |
| 92 | assert bounds(-3, B, 1) == (var, 0.0, ll) |
| 93 | print(f'two sheets: var={var:.12g} p={1/16:.12g} log_p_upper={lp:.12g} ' |
| 94 | f'loss={loss:.12g} log_loss_upper={ll:.12g}') |
| 95 | for a in (1e-100, 0.5, 2.0, 1e100): |
| 96 | v, l, loss_bound = bounds(3*a, B*a, 1) |
| 97 | assert math.isclose(v, var*a*a) and math.isclose(l, lp) |
| 98 | assert loss_bound <= 0 |
| 99 | # t=2 cap matters on a small-amplitude field. A large positive offset |
| 100 | # also checks a nonzero field past the ordinary exp underflow threshold. |
| 101 | _, _, limited = bounds(0.1, B*0.001, 1) |
| 102 | assert limited == 0.0 |
| 103 | _, _, far = bounds(1000, B*0.001, 1) |
| 104 | assert -2000 < far < -1000 |
| 105 | assert bounds(0, B, 1) == (var, 0.0, 0.0) |
| 106 | B.fill(0) |
| 107 | assert bounds(0, B, 1) == (0.0, -math.inf, 0.0) |
| 108 | for c in (0.01, 2., 1000.): |
| 109 | v, pplus, lossplus = bounds(c, B, 1) |
| 110 | vminus, pminus, lossminus = bounds(-c, B, 1) |
| 111 | assert (v, pplus, vminus, pminus) == (0., -math.inf, 0., 0.) |
| 112 | exact = -c - (math.log(math.cosh(c)) if c < 100 else c - math.log(2)) |
| 113 | assert lossplus == lossminus and math.isclose(lossplus, exact) |
| 114 | for c, b, d in [(0, B, 0), (0, B, 3), (0, B[:1], 1), (0, np.full_like(B, math.inf), 1), |
| 115 | (math.nan, B, 1), ([1, 2], B, 1), (0, B.astype(complex), 1)]: |
| 116 | try: |
| 117 | bounds(c, b, d) |
| 118 | except ValueError: |
| 119 | continue |
| 120 | raise AssertionError('accepted invalid input') |
| 121 | print('scaling, reflection, t<=2, zero, log-range and invalid-domain controls: PASS') |
| 122 | |
| 123 | |
| 124 | if __name__ == '__main__': |
| 125 | _controls() |