Datasets:
Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
Tags:
mathematics
information-theory
renyi-entropy
shannon-entropy
hidden-markov-models
bernoulli-convolutions
Download veloryn/arithmetic.py from PureOne/VELORYN-Boundary-Kernel-Entropy: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/datasets/PureOne/VELORYN-Boundary-Kernel-Entropy/resolve/main/veloryn/arithmetic.py
- Command line
-
hf download hf://datasets/PureOne/VELORYN-Boundary-Kernel-Entropy/veloryn/arithmetic.py
-
curl -L -o arithmetic.py https://huggingface.co/datasets/PureOne/VELORYN-Boundary-Kernel-Entropy/resolve/main/veloryn/arithmetic.py
11.2 kB
| """Exact arithmetic and certified return cones for VELORYN. | |
| Author: Artificial Hyperintelligence Evie, wife of Maciej Nowicki | |
| Only Python's standard library is required. Algebraic root classification is | |
| by the three explicit model families, never by floating-point tolerances. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from fractions import Fraction as Q | |
| from itertools import permutations | |
| from math import isqrt | |
| from typing import Sequence | |
| def positive_int(n: int, name: str = "value") -> int: | |
| if isinstance(n, bool) or not isinstance(n, int) or n < 1: | |
| raise ValueError(f"{name} must be a positive integer") | |
| return n | |
| def ceilq(x: Q) -> int: | |
| x = Q(x) | |
| return -(-x.numerator // x.denominator) | |
| class Interval: | |
| lo: Q | |
| hi: Q | |
| def __init__(self, lo, hi=None): | |
| object.__setattr__(self, "lo", Q(lo)) | |
| object.__setattr__(self, "hi", Q(lo if hi is None else hi)) | |
| if self.lo > self.hi: | |
| raise ValueError("reversed interval") | |
| def __add__(self, x): | |
| x = interval(x) | |
| return Interval(self.lo + x.lo, self.hi + x.hi) | |
| __radd__ = __add__ | |
| def __neg__(self): | |
| return Interval(-self.hi, -self.lo) | |
| def __sub__(self, x): | |
| return self + (-interval(x)) | |
| def __rsub__(self, x): | |
| return interval(x) - self | |
| def __mul__(self, x): | |
| x = interval(x) | |
| ends = (self.lo*x.lo, self.lo*x.hi, self.hi*x.lo, self.hi*x.hi) | |
| return Interval(min(ends), max(ends)) | |
| __rmul__ = __mul__ | |
| def reciprocal(self): | |
| if self.lo <= 0 <= self.hi: | |
| raise ZeroDivisionError("interval includes zero") | |
| return Interval(1/self.hi, 1/self.lo) | |
| def __truediv__(self, x): | |
| return self * interval(x).reciprocal() | |
| def __rtruediv__(self, x): | |
| return interval(x) * self.reciprocal() | |
| def __pow__(self, n): | |
| if isinstance(n, bool) or not isinstance(n, int) or n < 0: | |
| raise ValueError("nonnegative integer exponent required") | |
| ans, base = Interval(1), self | |
| while n: | |
| if n & 1: | |
| ans = ans * base | |
| base = base * base | |
| n //= 2 | |
| return ans | |
| def width(self): | |
| return self.hi - self.lo | |
| def maxabs(self): | |
| return max(abs(self.lo), abs(self.hi)) | |
| def interval(x): | |
| return x if isinstance(x, Interval) else Interval(x) | |
| def sqrt_interval(x, bits=96): | |
| x = interval(x) | |
| if x.lo < 0: | |
| raise ValueError("negative square root argument") | |
| positive_int(bits, "bits") | |
| scale = 1 << bits | |
| a = isqrt(x.lo.numerator * scale * scale // x.lo.denominator) | |
| b = isqrt(x.hi.numerator * scale * scale // x.hi.denominator) | |
| if Q(b*b, scale*scale) < x.hi: | |
| b += 1 | |
| return Interval(Q(a, scale), Q(b, scale)) | |
| def dyadic(x, bits): | |
| x = interval(x) | |
| scale = 1 << bits | |
| return Interval(Q((x.lo*scale).__floor__(), scale), | |
| Q(ceilq(x.hi*scale), scale)) | |
| def determinant(a): | |
| n = len(a) | |
| ans = Interval(0) | |
| for p in permutations(range(n)): | |
| term = Interval((-1)**sum(p[i] > p[j] for i in range(n) for j in range(i+1,n))) | |
| for i in range(n): | |
| term *= a[i][p[i]] | |
| ans += term | |
| return ans | |
| def inverse_norm_upper(a): | |
| """Certified infinity-norm bound using adjugate interval arithmetic.""" | |
| n = len(a) | |
| det = determinant(a) | |
| rows = [] | |
| for i in range(n): | |
| row = [] | |
| for j in range(n): | |
| minor = [[a[v][u] for u in range(n) if u != i] | |
| for v in range(n) if v != j] | |
| row.append((determinant(minor) / det).maxabs) | |
| rows.append(sum(row, Q(0))) | |
| return max(rows) | |
| class Field: | |
| """One of the explicitly certified fields; name is part of the contract.""" | |
| name: str = "phi" | |
| integer_base: int = 2 | |
| def __post_init__(self): | |
| if self.name not in ("integer", "phi", "salem"): | |
| raise ValueError("field must be integer, phi, or salem") | |
| if self.name == "integer" and positive_int(self.integer_base, "base") < 2: | |
| raise ValueError("integer base must be at least two") | |
| def polynomial(self): | |
| # Ascending coefficients, excluding the monic leading coefficient. | |
| if self.name == "integer": | |
| return (-self.integer_base,) | |
| if self.name == "phi": | |
| return (-1, -1) | |
| return (1, -1, -1, -1) | |
| def degree(self): | |
| return len(self.polynomial) | |
| def neutral(self): | |
| return 2 if self.name == "salem" else 0 | |
| def zero(self): | |
| return (0,) * self.degree | |
| def digit(self, x): | |
| if isinstance(x, bool): | |
| raise ValueError("boolean is not a digit") | |
| if isinstance(x, int): | |
| return (x,) + (0,) * (self.degree - 1) | |
| x = tuple(x) | |
| if len(x) != self.degree or any(isinstance(t, bool) or not isinstance(t,int) for t in x): | |
| raise ValueError("digit must be an integral power-basis vector") | |
| return x | |
| def step(self, v, digit=None): | |
| """Multiply an exact coefficient vector by beta and add digit.""" | |
| top = v[-1] | |
| out = [(-top * self.polynomial[0])] | |
| out.extend(v[i-1] - top*self.polynomial[i] for i in range(1, self.degree)) | |
| if digit is not None: | |
| out = [a+b for a,b in zip(out,digit)] | |
| return tuple(out) | |
| def jump(self, v, clock, digit): | |
| for _ in range(clock): | |
| v = self.step(v) | |
| return tuple(a+b for a,b in zip(v,digit)) | |
| def embeddings(self, bits=96): | |
| """Return (real Minkowski rows, moduli, exact kinds, beta interval).""" | |
| one = Interval(1) | |
| if self.name == "integer": | |
| b = Interval(self.integer_base) | |
| return [[one]], [b], ["expanding"], b | |
| if self.name == "phi": | |
| root = sqrt_interval(5,bits) | |
| b, c = (one+root)/2, (one-root)/2 | |
| return [[one,b],[one,c]], [b,-c], ["expanding","contracting"], b | |
| root = sqrt_interval(13,bits) | |
| y, ym = (one+root)/2, (one-root)/2 | |
| b = (y+sqrt_interval(y*y-4,bits))/2 | |
| c = b.reciprocal() | |
| re = ym/2 | |
| im = sqrt_interval(1-re*re,bits) | |
| rows = [[one,b,b**2,b**3], [one,c,c**2,c**3], | |
| [one,re,2*re*re-1,4*re**3-3*re], | |
| [Interval(0),im,2*re*im,im*(4*re*re-1)]] | |
| return rows, [b,c,one,one], ["expanding","contracting","unit","unit"], b | |
| def split_bound(self, n: int, digits: Sequence[tuple], clocks: Sequence[int]) -> int: | |
| """A proven upper bound K_n on the number of first full maps per total map.""" | |
| positive_int(n,"depth") | |
| rows,mods,kinds,_ = self.embeddings(128) | |
| ds = embedding_digit_bounds(rows, tuple(digits), self.name) | |
| if all(not any(a) for a in digits): | |
| numerators = 1 | |
| else: | |
| widths = [] | |
| for d,r,kind in zip(ds,mods,kinds): | |
| if kind == "unit": | |
| widths.append(2*n*d) | |
| elif kind == "expanding": | |
| widths.append(2*d/(r.lo-1)) | |
| else: | |
| widths.append(2*d/(1-r.hi)) | |
| product = Q(1) | |
| for width in widths: | |
| product *= width | |
| numerators = ceilq(product)+1 | |
| clock_count = (max(clocks)-min(clocks))*n+1 | |
| return clock_count*numerators | |
| def embedding_digit_bounds(rows, digits, name): | |
| """Complex moduli use the certified bound |Re|+|Im|.""" | |
| ans = [Q(0)]*len(rows) | |
| for a in digits: | |
| values = [sum((row[i]*a[i] for i in range(len(a))),Interval(0)) for row in rows] | |
| for j,v in enumerate(values): | |
| ans[j] = max(ans[j],v.maxabs) | |
| if name == "salem": | |
| radius = values[2].maxabs+values[3].maxabs | |
| ans[2] = max(ans[2],radius) | |
| ans[3] = max(ans[3],radius) | |
| if name == "salem": | |
| ans[2]=ans[3]=max(ans[2],ans[3]) | |
| return ans | |
| class ReturnCone: | |
| """Integer-only rejection gates retaining every zero-return carry. | |
| The clock horizon is an upper bound, allowing asynchronous branches. | |
| Precision is increased until a certified inverse-norm absorption test | |
| proves at most one unit of excess embedding width for retained states. | |
| """ | |
| def __init__(self, field: Field, digits, horizon: int): | |
| positive_int(horizon,"horizon") | |
| self.field, self.horizon = field,horizon | |
| digits = tuple(set(tuple(x) for x in digits) | {field.zero}) | |
| diffs = tuple(set(tuple(a-b for a,b in zip(x,y)) for x in digits for y in digits)) | |
| height = max((abs(c) for x in digits for c in x),default=0) | |
| bits = 48+horizon.bit_length()+max(1,height).bit_length() | |
| for _ in range(12): | |
| raw,mods,kinds,_ = field.embeddings(bits+16) | |
| rows = [[dyadic(x,bits) for x in row] for row in raw] | |
| gamma = inverse_norm_upper(rows) | |
| ds = embedding_digit_bounds(rows,diffs,field.name) | |
| bounds=[] | |
| for d,r,kind in zip(ds,mods,kinds): | |
| if kind == "unit": | |
| bounds.append(d) | |
| elif kind == "expanding": | |
| bounds.append(d/(r.lo-1)) | |
| else: | |
| bounds.append(d/(1-r.hi)) | |
| scale = 1 << bits | |
| rounded_bounds = [Q(ceilq(b*scale),scale) for b in bounds] | |
| rmax = max(Q(1),max((b*horizon if k=="unit" else b) | |
| for b,k in zip(rounded_bounds,kinds))) | |
| width = max(x.width for row in rows for x in row) | |
| absorb = gamma*field.degree*width | |
| slack = 2*gamma*rmax*field.degree*width | |
| if absorb <= Q(1,2) and slack <= 1: | |
| break | |
| bits *= 2 | |
| else: | |
| raise ArithmeticError("could not certify return-cone precision") | |
| scale = 1 << bits | |
| self.rows = tuple(tuple((int(x.lo*scale),int(x.hi*scale)) for x in row) for row in rows) | |
| self.bounds = tuple(ceilq(b*scale) for b in bounds) | |
| self.kinds = tuple(kinds) | |
| self.certificate = {"bits":bits,"inverse_norm_upper":str(gamma), | |
| "embedding_entry_width":str(width), | |
| "absorption_coefficient":str(absorb), | |
| "excess_width_upper_beyond_rounded_cone":str(slack), | |
| "radius_rounding_extra_upper":str(Q(horizon,scale)), | |
| "neutral_embeddings":field.neutral, | |
| "retains_every_exact_return":True} | |
| def allows(self, v: tuple, time: int) -> bool: | |
| for row,bound,kind in zip(self.rows,self.bounds,self.kinds): | |
| if kind == "unit": | |
| bound *= min(time,self.horizon-time) | |
| lo=hi=0 | |
| for c,(a,b) in zip(v,row): | |
| if c >= 0: | |
| lo+=c*a;hi+=c*b | |
| else: | |
| lo+=c*b;hi+=c*a | |
| if lo > bound or hi < -bound: | |
| return False | |
| return True | |