"""Exact upper enclosures for the dense-layer extraction theorem.""" from fractions import Fraction as F from functools import cache from math import isqrt, lcm @cache def parameters(rho, log_bounds, ln2_low, ln2_high): ratio = rho / (rho - F(1,2)) shift = 0 while ratio >= 2: ratio /= 2 shift += 1 lo, _ = log_bounds((ratio - 1) / (ratio + 1)) rank_low = shift + lo / ln2_high curvature_high = 1 / (8 * ln2_low * (rho - F(1,2))**2) return rank_low, curvature_high def select_bound(x, rho, greedy, log_bounds, ln2_low, ln2_high): if not (0 < x <= F('.022') and F('.64') <= rho <= F('.96')): return greedy slope, curvature = parameters(rho, log_bounds, ln2_low, ln2_high) # The shadow bound supplies a quadratic gain for every dense layer. z_floor = F(2,5) curvature -= z_floor / (2*ln2_high*rho*(rho-z_floor)) assert curvature > 0 scale = 10**12 # For a grid numerator j the condition is Aj² - Bj + C <= 0. # The first integer at or above the smaller root is obtained using # floor(sqrt(discriminant)); the left side of the comparison is integral. a, b = curvature / scale**2, slope / scale denominator = lcm(a.denominator, b.denominator, x.denominator) A, B, C = (int(coefficient * denominator) for coefficient in (a, b, x)) discriminant = B*B - 4*A*C if discriminant < 0: return greedy j = -((isqrt(discriminant)-B)//(2*A)) if A*j*j - B*j + C > 0: return greedy return min(greedy, F(j, scale))