File size: 9,786 Bytes
19591f3 | 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | #!/usr/bin/env python3
"""Independent exact checks of the learning certificate calculations.
This verifies concrete rational examples, equality cases, and finite algebraic
identities. It is not a proof assistant or a substitute for the manuscript's
universal proofs. Standard library only; no floating-point comparisons.
"""
from fractions import Fraction as Q
import argparse
import json
from pathlib import Path
def dot(x, y):
return sum((a*b for a, b in zip(x, y)), Q(0))
def norm2(x):
return dot(x, x)
def vecadd(x, y):
return tuple(a+b for a, b in zip(x, y))
def vecscale(a, x):
return tuple(a*t for t in x)
def outer(x, y):
return tuple(tuple(a*b for b in y) for a in x)
def madd(a, b):
return tuple(tuple(x+y for x, y in zip(r, s)) for r, s in zip(a, b))
def mscale(a, x):
return tuple(tuple(a*t for t in row) for row in x)
def mv(a, x):
return tuple(dot(row, x) for row in a)
def frob2(a):
return sum((norm2(row) for row in a), Q(0))
def eye(d):
return tuple(tuple(Q(i == j) for j in range(d)) for i in range(d))
def inv2(a):
det = a[0][0]*a[1][1]-a[0][1]*a[1][0]
if not det:
raise ValueError('Singular matrix')
return ((a[1][1]/det, -a[0][1]/det),
(-a[1][0]/det, a[0][0]/det))
def weighted_mean(items, weights, add, scale):
result = scale(Q(0), items[0])
for value, weight in zip(items, weights):
result = add(result, scale(weight, value))
return result
def quadratic_example():
"""A 2D variable-Hessian task, feature rank one, n=5, positive loss."""
u = (Q(3, 5), Q(4, 5))
assert norm2(u) == 1
identity = eye(2)
projection = outer(u, u)
a1 = madd(identity, mscale(Q(1, 2), projection))
a2 = madd(identity, mscale(Q(-1, 2), projection))
r1, r2 = u, vecscale(Q(-1), u)
p = (Q(1, 2), Q(1, 2))
q = (Q(3, 5), Q(2, 5))
ahat = weighted_mean((a1, a2), q, madd, mscale)
rhat = weighted_mean((r1, r2), q, vecadd, vecscale)
assert weighted_mean((a1, a2), p, madd, mscale) == identity
assert weighted_mean((r1, r2), p, vecadd, vecscale) == (0, 0)
curvature_variance = sum(w*frob2(madd(a, mscale(-1, identity)))
for w, a in zip(p, (a1, a2)))
residual_variance = sum(w*norm2(r) for w, r in zip(p, (r1, r2)))
assert curvature_variance == Q(1, 4) and residual_variance == 1
c = Q(1, 9)
sqrt_c_m = Q(1, 6)
assert sqrt_c_m**2 == c*curvature_variance
tau2 = c*residual_variance/(sqrt_c_m*(1-sqrt_c_m))
assert tau2 == Q(4, 5)
delta = madd(ahat, mscale(-1, identity))
actual_e = tau2*frob2(delta)+norm2(rhat)
universal_e = c*(tau2*curvature_variance+residual_variance)
assert actual_e == Q(6, 125)
assert universal_e == Q(2, 15)
assert 0 < actual_e <= universal_e < tau2
theta_hat = vecscale(-1, mv(inv2(ahat), rhat))
assert theta_hat == vecscale(Q(-2, 11), u)
true_excess = norm2(theta_hat)/2
posterior_bound = actual_e/(2*(1-actual_e/tau2))
universal_bound = universal_e/(2*(1-universal_e/tau2))
optimized_bound = c*residual_variance/(2*(1-sqrt_c_m)**2)
assert true_excess == Q(2, 121)
assert posterior_bound == Q(6, 235)
assert universal_bound == optimized_bound == Q(2, 25)
assert 0 < true_excess < posterior_bound < optimized_bound
# Enumerate the six aggregate count choices to verify this example's ERM
# optimum independently of any mean-selection implementation.
losses = []
for first in range(6):
weights = (Q(first, 5), Q(5-first, 5))
a = weighted_mean((a1, a2), weights, madd, mscale)
r = weighted_mean((r1, r2), weights, vecadd, vecscale)
theta = vecscale(-1, mv(inv2(a), r))
losses.append(norm2(theta)/2)
assert min(losses) == Q(2, 121) and losses.index(min(losses)) == 3
# The scalar perturbation implication has an exact rational equality case.
tight_a = Q(5, 6)
tight_r = Q(1, 3)
tight_e = tau2*(tight_a-1)**2+tight_r**2
assert tight_e == universal_e
tight_loss = tight_r**2/(2*tight_a**2)
tight_bound = tight_e/(2*(1-tight_e/tau2))
assert tight_loss == tight_bound == Q(2, 25)
# Same selected loss, reused away from theta_0=0. The gradient discrepancy
# is (1/10) u u^T theta + (1/5)u. Its exact curvature drift is 1/10.
theta = u
ghat = vecadd(mv(ahat, theta), rhat)
assert ghat == vecscale(Q(13, 10), u)
exact_error = Q(3, 10)
assert norm2(vecadd(ghat, vecscale(-1, theta))) == exact_error**2
anchor_error = Q(1, 5)
general_lipschitz_drift = Q(1, 10)*Q(3, 2)+Q(1, 10)*Q(1)
assert general_lipschitz_drift == Q(1, 4)
assert exact_error == anchor_error+Q(1, 10)
assert exact_error <= anchor_error+general_lipschitz_drift
a = exact_error/Q(13, 10)
step = 1-a # Full objective L=1.
next_theta = vecadd(theta, vecscale(-step, ghat))
assert step == Q(10, 13) and next_theta == (0, 0)
actual_decrease = (norm2(theta)-norm2(next_theta))/2
guaranteed_decrease = (Q(13, 10)-exact_error)**2/2
assert actual_decrease == guaranteed_decrease == Q(1, 2)
return {
'parameter_dimension': 2,
'feature_affine_rank': 1,
'budget': 5,
'probabilities': ['1/2', '1/2'],
'selected_counts': [3, 2],
'curvature_variance_M': str(curvature_variance),
'residual_variance_G': str(residual_variance),
'universal_constant_c': str(c),
'optimized_tau_squared': str(tau2),
'actual_joint_certificate_E': str(actual_e),
'universal_joint_certificate_E': str(universal_e),
'true_excess': str(true_excess),
'posterior_certificate_bound': str(posterior_bound),
'optimized_universal_bound': str(optimized_bound),
'enumerated_count_patterns': 6,
'certificate_equality_example_excess': str(tight_loss),
'trust_region_radius': '1',
'trust_region_gradient_error': str(exact_error),
'observable_step_size': str(step),
'actual_and_certified_decrease': str(actual_decrease),
}
def unbiased_examples():
checked = 0
for n in range(1, 21):
for N in (2*n+1, 5*n+3, 100*n+1):
p = Q(1, N)
# Every legal scalar output satisfies the key lattice inequality.
for k in range(n+1):
h = Q(k, n)
assert h*h >= h/n
# The best two-adjacent-grid-point unbiased lottery for p<1/n.
draw_probability = n*p
assert 0 <= draw_probability <= 1
mean = draw_probability/n
variance = draw_probability*(Q(1, n)-p)**2+(1-draw_probability)*p*p
assert mean == p
assert variance == p/n-p*p
normalized = variance/(p*(1-p))
lower = (Q(1, n)-p)/(1-p)
assert normalized == lower
assert Q(1, n)-lower == p*(n-1)/(n*(1-p))
if n > 1:
assert lower > Q(1, 2*n-1)
checked += 1
return {'checked_rational_instances': checked,
'finite_example_n': 5, 'finite_example_N': 11,
'best_unbiased_excess_factor': '3/25',
'planar_biased_factor': '1/9',
'gap': '2/225',
'universal_unbiased_supremum_formula': '1/n'}
def recursion_examples():
checked = 0
eps = Q(1, 10)
last = {}
for contraction in (Q(1, 2), Q(1), Q(3, 2)):
error = Q(0)
for horizon in range(1, 21):
error = contraction*error+eps
exact_bound = eps*sum((contraction**j for j in range(horizon)), Q(0))
assert error == exact_bound
if contraction < 1:
assert error < eps/(1-contraction)
if contraction == 1:
assert error == horizon*eps
checked += 1
last[str(contraction)] = str(error)
return {'checked_equality_instances': checked,
'per_step_error': str(eps), 'horizon': 20,
'error_by_lipschitz_factor': last}
def matrix_lottery_example():
# A regular 2-simplex in its rational 3D embedding; the affine rank is 2.
points = ((Q(2, 3), Q(-1, 3), Q(-1, 3)),
(Q(-1, 3), Q(2, 3), Q(-1, 3)),
(Q(-1, 3), Q(-1, 3), Q(2, 3)))
p = (Q(1, 3),)*3
covariance = weighted_mean(tuple(outer(x, x) for x in points), p, madd, mscale)
lottery_second_moment = weighted_mean(tuple(outer(x, x) for x in points), p, madd, mscale)
assert covariance == lottery_second_moment
for x in points:
scalar_error = norm2(x)
variance = sum(covariance[i][i] for i in range(3))
assert scalar_error == variance == Q(2, 3)
# Along its own error direction every deterministic choice needs 2Σ.
lhs = norm2(x)**2
rhs = dot(x, mv(covariance, x))
assert lhs == 2*rhs and lhs > rhs
return {'affine_rank': 2, 'budget': 1, 'lottery_support_size': 3,
'lottery_matrix_bound': 'equality with covariance',
'necessary_deterministic_factor': 2}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path)
args = parser.parse_args()
report = {
'status': 'PASS',
'arithmetic': 'fractions.Fraction; exact comparisons only',
'scope': 'Finite certificate and equality-case checks; universal proofs are in the manuscript.',
'quadratic_erm_and_trust_region': quadratic_example(),
'unbiasedness': unbiased_examples(),
'recursive_composition': recursion_examples(),
'matrix_lottery': matrix_lottery_example(),
}
text = json.dumps(report, indent=2)+'\n'
if args.output:
args.output.write_text(text)
print(text, end='')
if __name__ == '__main__':
main()
|