SORILUN-RSI / research /tests /verify.py
PureOne's picture
Add SORILUN research dataset release
aff9293 verified
Raw History Blame Contribute Delete
6.59 kB
"""Executed exact checks. This is not a Lean/Coq formalization."""
from __future__ import annotations
import copy
import json
import math
from pathlib import Path
import sys
import tempfile
import time
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'src'))
from synthesis import discover, verify_tensor, digest
from arithmetic import Kernel, NTTKernel, load_program, P
from native import NativeKernel, NativeNTTKernel
from tasks import (reciprocal, reference_reciprocal, exponential, reference_exp,
catalan, reference_catalan, reversion, composition)
from audit import CreditAccount, AnytimeGate, atomic_save, read_checkpoint
def run(native_library=None):
start = time.perf_counter()
checks = {}
def check(group, condition):
checks[group] = checks.get(group, 0)+1
if not condition:
raise AssertionError('Failed check in '+group)
def rejects(group, function):
try:
function()
except (ValueError, RuntimeError):
check(group, True)
else:
check(group, False)
discovery = discover()
law = discovery['law']
check('finite_search', discovery['counts']['candidates']==560)
check('finite_search', discovery['counts']['valid']==2)
check('tensor', verify_tensor(law)[0])
# Every single coefficient mutation is checked independently.
for key in ('A','B','C'):
for i,row in enumerate(law[key]):
for j,x in enumerate(row):
bad=copy.deepcopy(law);bad[key][i][j]=0 if x else 1
check('malformed_tensor', not verify_tensor(bad)[0])
rng=np.random.default_rng(80361108)
kernels=[Kernel(law,d) for d in range(8)]
for n in range(1,49):
for m in range(1,49):
values=[k.cost(n,m) for k in kernels]
check('envelope_monotonicity', all(x>=y for x,y in zip(values,values[1:])))
shapes=[(1,1),(1,31),(3,19),(7,8),(17,37),(65,33),(127,129),(256,256),(511,513)]
shapes += [(int(rng.integers(1,130)),int(rng.integers(1,130))) for _ in range(40)]
for n,m in shapes:
a=rng.integers(0,P,n,dtype=np.int64);b=rng.integers(0,P,m,dtype=np.int64)
expected=np.convolve(a,b)%P
for d in range(7):
k=Kernel(law,d);pm,pa,_=k.plan(n,m);out=k.mul(a,b)
check('polynomial_correctness', np.array_equal(out,expected))
check('exact_cost_counts', pm==k.meter.mul and pa==k.meter.add)
if native_library:
kn=NativeKernel(law,d,native_library);out=kn.mul(a,b)
check('native_correctness',np.array_equal(out,expected))
check('native_cost_contract', kn.meter.mul==pm and kn.meter.add==pa)
check('ntt_correctness', np.array_equal(NTTKernel(law).mul(a,b),expected))
if native_library:
check('native_ntt_correctness',np.array_equal(NativeNTTKernel(law,native_library).mul(a,b),expected))
# Universal tensor identity tested on noncommuting integer 2x2 matrices.
for rep in range(100):
a=[rng.integers(-4,5,(2,2),dtype=np.int64) for _ in range(2)]
b=[rng.integers(-4,5,(2,2),dtype=np.int64) for _ in range(2)]
products=[]
for ar,br in zip(law['A'],law['B']):
products.append(sum(c*x for c,x in zip(ar,a)) @ sum(c*x for c,x in zip(br,b)))
actual=[sum(c*x for c,x in zip(row,products)) for row in law['C']]
expected=[a[0]@b[0],a[0]@b[1]+a[1]@b[0],a[1]@b[1]]
check('noncommutative_transfer',all(np.array_equal(x,y) for x,y in zip(actual,expected)))
for n in [2,3,5,8,16,17,31,32,65,128,257]:
for rep in range(3):
f=rng.integers(0,P,n,dtype=np.int64);f[0]=1
for d in [0,2,6]:
check('reciprocal_learning',np.array_equal(reciprocal(f,n,Kernel(law,d)),reference_reciprocal(f,n)))
f[0]=0
check('heldout_exponential',np.array_equal(exponential(f,n,Kernel(law,6)),reference_exp(f,n)))
check('heldout_catalan',np.array_equal(catalan(n,Kernel(law,6)),reference_catalan(n)))
fshort=np.array([0,1,rep+1,2*rep+3],dtype=np.int64)
g=reversion(fshort,n,Kernel(law,6))
fg=composition(fshort,g,n,Kernel(law,0));expected=np.zeros(n,dtype=np.int64);expected[1]=1
check('heldout_reversion',np.array_equal(fg,expected))
k=Kernel(law,4)
p=k.program();check('program_roundtrip',load_program(p).cap==4)
bad=copy.deepcopy(p);bad['cap']=5
rejects('program_mutations',lambda:load_program(bad))
bad=copy.deepcopy(p);bad['field']=5;bad['sha256']=digest({a:b for a,b in bad.items() if a!='sha256'})
rejects('program_mutations',lambda:load_program(bad))
rejects('contracts',lambda:Kernel(law,-1))
rejects('contracts',lambda:Kernel(law,100))
rejects('contracts',lambda:k.mul(np.array([-1]),np.array([1])))
rejects('contracts',lambda:reciprocal(np.zeros(8,dtype=np.int64),8,k))
rejects('contracts',lambda:exponential(np.ones(8,dtype=np.int64),8,k))
rejects('contracts',lambda:reversion(np.array([0,2,1]),8,k))
account=CreditAccount(100)
for i in range(100):
account.service(100,80);check('solvency',account.invest(19));account.check()
check('solvency',not account.invest(100000))
check('solvency',account.credit==200)
for j in range(1,20):
gate=AnytimeGate(j)
for t in range(100):
gate.update(1)
check('anytime_gate',gate.accepted)
losing=AnytimeGate(j)
for t in range(100):
losing.update(-1)
check('anytime_gate',not losing.accepted)
check('alpha_spending',abs(sum(1/(j*(j+1)) for j in range(1,1000))-.999)<1e-12)
with tempfile.TemporaryDirectory() as d:
path=Path(d)/'state.json';atomic_save(path,{'program':p,'generation':4})
check('checkpoints',read_checkpoint(path)['generation']==4)
bad=json.loads(path.read_text());bad['payload']['generation']=5;path.write_text(json.dumps(bad))
rejects('checkpoints',lambda:read_checkpoint(path))
return {'passed':True,'assertions':sum(checks.values()),'groups':checks,
'wall_seconds':time.perf_counter()-start,
'scope':'Exact finite tests and hand-written mathematical proofs; not proof-assistant verification'}
if __name__=='__main__':
native=ROOT/'native_build/discovered_kernel.so'
result=run(str(native) if native.exists() else None)
print(json.dumps(result,indent=2))
(ROOT/'results/verification.json').write_text(json.dumps(result,indent=2))