SORILUN-RSI / research /src /experiments.py
PureOne's picture
Add SORILUN research dataset release
aff9293 verified
Raw History Blame Contribute Delete
17.7 kB
"""Auditable, bounded experiments; all favorable and unfavorable controls saved."""
from __future__ import annotations
import copy
import hashlib
import json
import math
from pathlib import Path
import platform
import sys
import time
import numpy as np
from synthesis import discover, digest, verify_tensor
from arithmetic import Kernel, NTTKernel, P
from native import build, NativeKernel, NativeNTTKernel
from tasks import reciprocal, exponential, reversion, catalan
from audit import CreditAccount, AnytimeGate, atomic_save
ROOT = Path(__file__).resolve().parents[1]
def arrayhash(x):
return hashlib.sha256(np.asarray(x,dtype='<i8').tobytes()).hexdigest()
def vector(seed,n,constant=1):
r=np.random.default_rng(seed).integers(0,P,n,dtype=np.int64)
r[0]=constant
return r
class Lab:
def __init__(self,root=ROOT,native=True):
self.root=Path(root)
self.config=json.loads((self.root/'experiment_config.json').read_text())
self.discovery=discover()
self.law=self.discovery['law']
self.native=build(self.law,self.root/'native_build') if native else {'available':False,'wall_seconds':0}
self.files={}
self.backend='native C++' if self.native['available'] else 'portable NumPy'
def save(self,name,data):
path=self.root/'results'/name
path.parent.mkdir(parents=True,exist_ok=True)
path.write_text(json.dumps(data,indent=2,sort_keys=True))
def kernel(self,cap=0,ntt=False):
if self.native['available']:
return NativeNTTKernel(self.law,self.native['library']) if ntt else NativeKernel(self.law,cap,self.native['library'])
return NTTKernel(self.law) if ntt else Kernel(self.law,cap)
def run_job(self,family,n,seed,cap=0,ntt=False):
# Generate task inputs outside the solver timer; this cost is shared and
# not called learning. Kernel construction and checking ARE inside.
f=vector(seed,n,0 if family=='exponential' else 1)
fshort=np.array([0,1,seed%19+1,seed%23+2,seed%13+1],dtype=np.int64)
b=vector(seed+9871,n,2)
start=time.perf_counter_ns()
k=self.kernel(cap,ntt)
if family=='reciprocal':
out=reciprocal(f,n,k)
elif family=='exponential':
out=exponential(f,n,k)
elif family=='reversion':
out=reversion(fshort,n,k)
elif family=='implicit_catalan':
out=catalan(n,k)
elif family=='convolution':
out=k.mul(f,b)
else:
raise ValueError('Unknown task family')
elapsed=time.perf_counter_ns()-start
record={'family':family,'length':n,'input_seed':seed,'cap':cap,'ntt':ntt,
'wall_ns':elapsed,'output_sha256':arrayhash(out),
'meter':k.meter.snapshot(),
'trace':[[a,b,count] for (a,b),count in sorted(k.trace.items())]}
return out,record
def train(self):
cfg=self.config
account=CreditAccount(cfg['bootstrap_ledger_units'])
disc=self.discovery['counts']
startup_charge=disc['rational_ops']+disc['pivot_tests']+disc['certificate_ops']
if not account.invest(startup_charge):
raise RuntimeError('Insufficient bootstrap credit')
cap=0
state=self.kernel(0).program()
records=[];service=[];audit=[]
training_wall_start=time.perf_counter()
for stage,n in enumerate(cfg['training_lengths']):
stage_start=time.perf_counter()
for rep in range(cfg['service_jobs_per_stage']):
seed=cfg['master_seed']+stage*1000+rep
out,live=self.run_job('reciprocal',n,seed,cap)
ref,base=self.run_job('reciprocal',n,seed,0)
if not np.array_equal(out,ref):
raise ArithmeticError('Service semantics changed')
account.service(base['meter']['ledger_units'],live['meter']['ledger_units'])
service.append({'stage':stage,'live':live,'reference':base})
seed=cfg['master_seed']+stage*1000+999
child_kernel=self.kernel(cap+1)
proposed=child_kernel.program(state['sha256'])
before,old=self.run_job('reciprocal',n,seed,cap)
after,new=self.run_job('reciprocal',n,seed,cap+1)
if not np.array_equal(before,after):
raise ArithmeticError('Candidate changed learning result')
# Validation work is an explicit cost of producing a successor.
checks=verify_tensor(self.law)[1]
investment=old['meter']['ledger_units']+new['meter']['ledger_units']+checks+len(json.dumps(proposed))
improvement=new['meter']['field_ops']<old['meter']['field_ops']
paid=account.invest(investment)
committed=paid and improvement
if committed:
cap+=1;state=proposed
event={'stage':stage,'length':n,'before_cap':cap-int(committed),'after_cap':cap,
'committed':committed,'candidate_sha256':proposed['sha256'],
'state_sha256':state['sha256'],'investment_units':investment,
'strict_arithmetic_gain':improvement,'paid':paid,
'parent_evaluation':old,'candidate_evaluation':new,
'account':account.snapshot(),'stage_wall_seconds':time.perf_counter()-stage_start}
records.append(event)
audit.append({'stage':stage,'candidate':proposed})
atomic_save(self.root/'results/checkpoint.json',
{'generation':stage+1,'program':state,'account':account.snapshot(),
'protocol_sha256':digest(cfg),'next_request':'bounded external job'})
atomic_save(self.root/f'results/checkpoint_{stage:02d}.json',
{'generation':stage+1,'program':state,'account':account.snapshot()})
result={'mode':'arithmetic objective; timings are diagnostic, not the promotion criterion',
'final_cap':cap,'commits':sum(x['committed'] for x in records),
'startup_discovery_units':startup_charge,'records':records,'service':service,
'programs':audit,'final_account':account.snapshot(),
'loop_wall_seconds_including_reference_audit':time.perf_counter()-training_wall_start,
'production_wall_seconds':sum(x['live']['wall_ns'] for x in service)/1e9+
sum((x['parent_evaluation']['wall_ns']+x['candidate_evaluation']['wall_ns'])/1e9 for x in records)+
self.discovery['wall_seconds']+self.native['wall_seconds'],
'reference_service_wall_seconds':sum(x['reference']['wall_ns'] for x in service)/1e9,
'accounting_note':'Production time includes discovery, native compilation, service and paired validation; reference reruns are research-only audit costs and are logged separately.'}
self.save('training.json',result)
return result
def same_child(self,final_cap):
cfg=self.config;rows=[]
for n in cfg['same_child_lengths']:
for rep in range(cfg['same_child_replicates']):
seed=710000+n*10+rep
child,child_record=self.run_job('reciprocal',n,seed,final_cap)
artifact=self.kernel(final_cap).program('counterfactual-fixed-parent-metadata')
for cap in range(final_cap+1):
old,record=self.run_job('reciprocal',n,seed,cap)
if not np.array_equal(old,child):
raise ArithmeticError('Same-child output mismatch')
fixed=verify_tensor(self.law)[1]+len(json.dumps(artifact))
rows.append({'length':n,'replicate':rep,'parent_cap':cap,
'candidate_cap':final_cap,'candidate_sha256':artifact['sha256'],
'identical_learned_output':True,
'parent_evaluation':record,'candidate_evaluation':child_record,
'meta_field_ops':record['meter']['field_ops']+child_record['meter']['field_ops'],
'meta_ledger_units':record['meter']['ledger_units']+child_record['meter']['ledger_units']+fixed,
'meta_wall_ns':record['wall_ns']+child_record['wall_ns']})
result={'definition':'Same fixed candidate artifact and task. Only the inherited arithmetic implementation used by the incumbent validation arm is intervened on.',
'not_a_claim':'This does not show that the proposal grammar or proof strategy improved.',
'rows':rows}
self.save('same_child.json',result)
return result
def holdout(self,final_cap,wall_cap):
cfg=self.config;rows=[]
methods=[('frozen_schoolbook',0,False),('arithmetic_lineage',final_cap,False),
('wall_gated_lineage',wall_cap,False),('static_cap4',4,False),
('static_full_envelope',20,False),('conventional_NTT',0,True)]
order_rng=np.random.default_rng(22012027)
for family in ['exponential','reversion','implicit_catalan','convolution']:
for n in cfg['holdout_lengths']:
for rep in range(cfg['holdout_replicates']):
seed=cfg['holdout_seed']+n*100+rep
expected=None
for j in order_rng.permutation(len(methods)):
name,cap,ntt=methods[int(j)]
out,row=self.run_job(family,n,seed,cap,ntt)
if expected is None:expected=out
elif not np.array_equal(out,expected):
raise ArithmeticError('Held-out algorithm disagreement')
row.update({'method':name,'replicate':rep,'correct_vs_other_algorithms':True})
rows.append(row)
result={'status':'Fresh coefficient instances and control-flow families, but the same finite-field arithmetic contract.',
'families_not_used_for_promotion':['exponential','reversion','implicit_catalan','convolution'],
'rows':rows}
self.save('holdout.json',result)
return result
def hardware_gate(self):
cfg=self.config;cap=0;records=[]
rng=np.random.default_rng(813411)
for proposal,n in enumerate(cfg['hardware_audit_lengths'],1):
gate=AnytimeGate(proposal,cfg['hardware_alpha'])
pairs=[];parent_cap=cap
for t in range(cfg['hardware_audit_max_pairs']):
seed=8800000+proposal*10000+t
order=list(map(int,rng.permutation(2)));data={};outs={}
for j in order:
outs[int(j)],data[int(j)]=self.run_job('reciprocal',n,seed,cap+int(j))
if not np.array_equal(outs[0],outs[1]):
raise ArithmeticError('Hardware gate saw a semantic difference')
a,b=data[0]['wall_ns'],data[1]['wall_ns']
sign=1 if b<a else (-1 if b>a else 0)
gate.update(sign)
pairs.append({'trial':t,'order':order,'parent_ns':a,'candidate_ns':b,
'sign':sign,'parent_units':data[0]['meter']['ledger_units'],
'candidate_units':data[1]['meter']['ledger_units']})
if gate.accepted and t+1>=16:
break
if gate.accepted:cap+=1
records.append({'proposal':proposal,'length':n,'parent_cap':parent_cap,
'candidate_cap':parent_cap+1,'accepted':gate.accepted,
'after_cap':cap,'evidence':gate.snapshot(),'pairs':pairs})
result={'final_cap':cap,'accepted_proposals':sum(r['accepted'] for r in records),
'alpha':cfg['hardware_alpha'],'records':records,
'null':'For a proposal, conditional probability of a candidate timing win is at most one half on the sampled reciprocal workload.',
'limitations':'No distribution-free guarantee for future wall time; hardware-dependent outcomes; this gate is separate from the arithmetic lineage.'}
self.save('hardware_gate.json',result)
return result
def payback(self,cap):
cfg=self.config;rows=[];rng=np.random.default_rng(199903)
for rep in range(cfg['payback_jobs']):
seed=9100000+rep
pair={};outs={}
for j in rng.permutation(2):
outs[int(j)],pair[int(j)]=self.run_job('reciprocal',cfg['payback_length'],seed,cap if j else 0)
if not np.array_equal(outs[0],outs[1]):
raise ArithmeticError('Payback task mismatch')
rows.append({'replicate':rep,'frozen':pair[0],'evolved':pair[1]})
result={'deployed_cap':cap,'rows':rows,
'frozen_seconds':sum(r['frozen']['wall_ns'] for r in rows)/1e9,
'evolved_seconds':sum(r['evolved']['wall_ns'] for r in rows)/1e9,
'note':'A measured finite deployment workload, not a forecast. Subtract separately recorded discovery, compilation and all relevant proposal-validation costs before claiming net payback.'}
self.save('payback.json',result)
return result
def fixed_budget(self,cap,wall_cap):
cfg=self.config;rows=[]
methods=[('frozen_schoolbook',0,False),('arithmetic_lineage',cap,False),
('wall_gated_lineage',wall_cap,False),('static_cap4',4,False),
('static_full_envelope',20,False),('conventional_NTT',0,True)]
for name,d,ntt in methods:
spent=0;completed=0;wall=0.;hashes=[]
# Exact shape model makes cost constant for non-NTT methods. NTT
# root setup is separately charged through measured counters.
while completed<1000:
out,r=self.run_job('reciprocal',cfg['budget_length'],9300000+completed,d,ntt)
units=r['meter']['ledger_units']
if spent+units>cfg['budget_ledger_units']:
# This look-ahead run belongs to audit, not the service
# budget; its full cost is explicitly disclosed.
lookahead={'units':units,'wall_ns':r['wall_ns']};break
spent+=units;wall+=r['wall_ns']/1e9;completed+=1;hashes.append(r['output_sha256'])
rows.append({'method':name,'completed':completed,'budget':cfg['budget_ledger_units'],
'spent_units':spent,'service_seconds':wall,'output_hashes':hashes,
'research_only_lookahead':lookahead})
result={'scope':'Equal warm-service abstract resource budgets; separate from end-to-end training budgets.',
'rows':rows}
self.save('fixed_budget.json',result)
return result
def e_simulation(self):
cfg=self.config;rng=np.random.default_rng(319127)
result=[]
for probability in [0.5,0.65,0.8]:
successes=0;stops=[]
for simulation in range(cfg['null_simulations']):
gate=AnytimeGate(1,cfg['hardware_alpha'])
for t in range(cfg['null_horizon']):
if gate.update(1 if rng.random()<probability else -1):
successes+=1;stops.append(t+1);break
result.append({'win_probability':probability,'accepted':successes,
'runs':cfg['null_simulations'],'horizon':cfg['null_horizon'],
'acceptance_fraction':successes/cfg['null_simulations'],
'mean_stopping_trial_if_accepted':float(np.mean(stops)) if stops else None})
output={'proposal':1,'allocated_alpha':cfg['hardware_alpha']/2,'results':result,
'interpretation':'Monte Carlo check of a proved gate, not evidence of AI capability.'}
self.save('e_simulation.json',output)
return output
def run(self):
totalstart=time.perf_counter()
self.save('discovery.json',self.discovery)
self.save('native_build.json',self.native)
self.save('environment.json',{'python':sys.version,'platform':platform.platform(),
'numpy':np.__version__,'backend':self.backend,
'hardware_scope':'Container CPU only; no GPU or user-PC benchmark',
'protocol_sha256':digest(self.config)})
training=self.train()
print('Training',training['commits'],'commits; cap',training['final_cap'],flush=True)
same=self.same_child(training['final_cap'])
hardware=self.hardware_gate()
print('Hardware gate',hardware['accepted_proposals'],'accepted; cap',hardware['final_cap'],flush=True)
holdout=self.holdout(training['final_cap'],hardware['final_cap'])
payback=self.payback(hardware['final_cap'])
budget=self.fixed_budget(training['final_cap'],hardware['final_cap'])
e=self.e_simulation()
self.save('experiment_run.json',{'completed':True,'wall_seconds':time.perf_counter()-totalstart,
'training_commits':training['commits'],'hardware_commits':hardware['accepted_proposals'],
'heldout_method_runs':len(holdout['rows']),'same_child_runs':len(same['rows']),
'payback_jobs':len(payback['rows']),'note':'All reported outcomes, including regressions and stronger conventional controls, are retained.'})
print('Completed experiments',time.perf_counter()-totalstart,flush=True)
if __name__=='__main__':
Lab(native='--portable' not in sys.argv).run()