Download research/verify_learning.py from PureOne/Neiru-Siha-II: direct link, hf CLI and curl.
- Browser
- Download file 9.79 kB
-
https://huggingface.co/datasets/PureOne/Neiru-Siha-II/resolve/main/research/verify_learning.py
- Command line
-
hf download hf://datasets/PureOne/Neiru-Siha-II/research/verify_learning.py
-
curl -L -o verify_learning.py https://huggingface.co/datasets/PureOne/Neiru-Siha-II/resolve/main/research/verify_learning.py
9.79 kB
| #!/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() | |