SORILUN-RSI / research /src /arithmetic.py
PureOne's picture
Add SORILUN research dataset release
aff9293 verified
Raw History Blame Contribute Delete
9.87 kB
"""Exact polynomial arithmetic, explicit cost vectors, and certified programs.
The field is F_65537. NumPy computes exact int64 schoolbook convolutions;
the configured size bound prevents integer overflow before modular reduction.
Field-operation counts model arithmetic, not machine instructions or time.
"""
from __future__ import annotations
from dataclasses import dataclass, asdict
from collections import Counter
import numpy as np
from synthesis import verify_tensor, linear_adds, digest
P = 65537
MAX_LENGTH = 8192
@dataclass
class Meter:
add: int = 0
mul: int = 0
calls: int = 0
plan_states: int = 0
certificate_ops: int = 0
allocations: int = 0
def snapshot(self):
d = asdict(self)
d['field_ops'] = self.add + self.mul
# Declared abstract ledger, not a measured instruction count.
d['ledger_units'] = (self.add + self.mul + self.calls +
32*self.plan_states + self.certificate_ops)
return d
def validate(a):
a = np.asarray(a, dtype=np.int64)
if a.ndim != 1 or len(a) < 1 or len(a) > MAX_LENGTH:
raise ValueError('Polynomial lengths must be in [1, 8192]')
if np.any(a < 0) or np.any(a >= P):
raise ValueError('Coefficients must be canonical residues modulo 65537')
return a
def base_cost(n, m):
return n*m, n*m - (n+m-1)
class Kernel:
"""Interprets a finite, proof-carrying, depth-bounded arithmetic program.
Every available program includes the schoolbook fallback. Selection is by
exact dense field-operation cost, independent of coefficient values.
"""
def __init__(self, law, cap=0):
if type(cap) is not int or not 0 <= cap <= 20:
raise ValueError('Invalid program depth')
ok, work = verify_tensor(law)
if not ok:
raise ValueError('Rejected unsound bilinear tensor certificate')
self.law = law
self.cap = cap
self.meter = Meter(certificate_ops=work)
self.plans = {}
self.trace = Counter()
self.input_adds = sum(linear_adds(r) for r in law['A']+law['B'])
self.output_adds = sum(linear_adds(r) for r in law['C'])
def plan(self, n, m, cap=None):
cap = self.cap if cap is None else cap
key = (n, m, cap)
if key in self.plans:
return self.plans[key]
self.meter.plan_states += 1
bm, ba = base_cost(n, m)
best = (bm, ba, 0)
if cap > 0 and max(n, m) > 1 and min(n, m) > 1:
h = (max(n, m)+1)//2
cm, ca, _ = self.plan(h, h, cap-1)
overhead = self.input_adds*h + (self.output_adds+2)*(2*h-1)
candidate = (3*cm, 3*ca+overhead, 1)
if candidate[0]+candidate[1] < bm+ba:
best = candidate
# A longer operand is split without permuting coefficient order.
# This repairs the padding penalty on 2:1 Newton-lifting products.
if max(n, m) >= 2*min(n, m):
h = max(n, m)//2
if n >= m:
x = self.plan(h, m, cap)
y = self.plan(n-h, m, cap)
extra = n-h+m-1
else:
x = self.plan(n, h, cap)
y = self.plan(n, m-h, cap)
extra = n+m-h-1
rectangular = (x[0]+y[0], x[1]+y[1]+extra, 2)
if sum(rectangular[:2]) < sum(best[:2]):
best = rectangular
self.plans[key] = best
return best
def cost(self, n, m):
a, b, _ = self.plan(n, m)
return a+b
def _lin(self, arrays, row):
nz = [(a, c) for a, c in zip(arrays, row) if c]
if not nz:
return np.zeros(len(arrays[0]), dtype=np.int64)
a, c = nz[0]
z = a.copy()
self.meter.allocations += len(z)
if c == -1:
z = (-z) % P
self.meter.add += len(z)
for a, c in nz[1:]:
z = (z + a) % P if c == 1 else (z - a) % P
self.meter.add += len(z)
return z
def _mul(self, a, b, cap):
n, m = len(a), len(b)
self.meter.calls += 1
_, _, split = self.plan(n, m, cap)
if not split:
cm, ca = base_cost(n, m)
self.meter.mul += cm
self.meter.add += ca
self.meter.allocations += n+m-1
# max coefficient sum <= 8192 * 65536**2 < 2**63.
return np.convolve(a, b) % P
if split == 2:
h = max(n, m)//2
if n >= m:
left = self._mul(a[:h], b, cap)
right = self._mul(a[h:], b, cap)
else:
left = self._mul(a, b[:h], cap)
right = self._mul(a, b[h:], cap)
out = np.zeros(n+m-1, dtype=np.int64)
out[:len(left)] = left
out[h:h+len(right)] = (out[h:h+len(right)]+right) % P
self.meter.add += len(right)
self.meter.allocations += len(out)
return out
h = (max(n, m)+1)//2
aa = np.pad(a, (0, 2*h-n))
bb = np.pad(b, (0, 2*h-m))
av, bv = [aa[:h], aa[h:]], [bb[:h], bb[h:]]
products = []
for ar, br in zip(self.law['A'], self.law['B']):
products.append(self._mul(self._lin(av, ar),
self._lin(bv, br), cap-1))
c = [self._lin(products, row) for row in self.law['C']]
out = np.zeros(4*h-1, dtype=np.int64)
out[:2*h-1] = c[0]
for k in (1, 2):
sl = slice(k*h, k*h+2*h-1)
out[sl] = (out[sl]+c[k]) % P
self.meter.add += 2*h-1
self.meter.allocations += len(out)
return out[:n+m-1]
def mul(self, a, b):
a, b = validate(a), validate(b)
self.trace[(len(a), len(b))] += 1
return self._mul(a, b, self.cap)
def program(self, parent=None):
body = {'schema': 1, 'kind': 'certified_bilinear_envelope',
'field': P, 'cap': self.cap, 'law': self.law,
'parent_sha256': parent, 'max_length': MAX_LENGTH}
return {**body, 'sha256': digest(body)}
def load_program(data):
if type(data) is not dict:
raise ValueError('Invalid program envelope')
body = {k: v for k, v in data.items() if k != 'sha256'}
if digest(body) != data.get('sha256'):
raise ValueError('Program integrity check failed')
if body.get('field') != P or body.get('schema') != 1:
raise ValueError('Unsupported program contract')
if body.get('kind') != 'certified_bilinear_envelope':
raise ValueError('Unsupported program language')
return Kernel(body['law'], body['cap'])
class NTTKernel:
"""Conventional cached radix-two transform baseline, not a learned program.
Roots, their construction, and modular inverse powers are charged. All
transforms use exact field arithmetic. Schoolbook is selected whenever
its predicted field-operation count is lower than a cached NTT estimate.
"""
def __init__(self, law):
self.meter = Meter()
self.trace = Counter()
self.roots = {}
self.base = Kernel(law, 0)
def _pow(self, a, k):
y = 1
while k:
if k & 1:
y = y*a % P
self.meter.mul += 1
k >>= 1
if k:
a = a*a % P
self.meter.mul += 1
return y
def _roots(self, size, inverse):
key = (size, inverse)
if key in self.roots:
return self.roots[key]
w = self._pow(3, (P-1)//size)
if inverse:
w = self._pow(w, P-2)
r = np.ones(size//2, dtype=np.int64)
for j in range(1, len(r)):
r[j] = r[j-1]*w % P
self.meter.mul += 1
self.roots[key] = r
return r
def _transform(self, a, inverse=False):
n = len(a)
bits = n.bit_length()-1
# Integer indexing work is not included in field operation counts.
rev = np.array([int(format(i, '0%db' % bits)[::-1], 2)
for i in range(n)], dtype=np.int64)
out = a[rev].copy()
size = 2
while size <= n:
r = self._roots(size, inverse)
view = out.reshape(-1, size)
left = view[:, :size//2].copy()
right = view[:, size//2:]*r % P
view[:, :size//2] = (left+right) % P
view[:, size//2:] = (left-right) % P
self.meter.mul += n//2
self.meter.add += n
size *= 2
if inverse:
inv = self._pow(n, P-2)
out = out*inv % P
self.meter.mul += n
self.meter.allocations += n
return out
def mul(self, a, b):
a, b = validate(a), validate(b)
nout = len(a)+len(b)-1
n = 1 << (nout-1).bit_length()
if n > P-1:
raise ValueError('Transform exceeds field root-of-unity contract')
self.trace[(len(a), len(b))] += 1
self.meter.calls += 1
bm, ba = base_cost(len(a), len(b))
estimate = (9*n*(n.bit_length()-1))//2 + 2*n
if bm+ba <= estimate:
self.meter.mul += bm
self.meter.add += ba
return np.convolve(a, b) % P
aa = np.pad(a, (0, n-len(a)))
bb = np.pad(b, (0, n-len(b)))
c = self._transform(aa)*self._transform(bb) % P
self.meter.mul += n
return self._transform(c, True)[:nout]
def inv_scalar(x, backend):
if not x % P:
raise ValueError('Constant term is not a unit')
k, a, out = P-2, int(x), 1
while k:
if k & 1:
out = out*a % P
backend.meter.mul += 1
k >>= 1
if k:
a = a*a % P
backend.meter.mul += 1
return out