ISORYTH-Lily-v5 / research /code /benchmark_sampling.py
PureOne's picture
Publish ISORYTH-Lily v5.0.0 research release
474e218 verified
Raw History Blame Contribute Delete
5.11 kB
#!/usr/bin/env python3
"""Executed synthetic sampling benchmark. Timings are not an RSI benchmark.
The enormous rejection counts are exact theoretical expectations, NOT simulated
runs and NOT observed wall-clock speedups. All compared samplers target exactly
the same normalized retained law.
"""
import argparse,json,time,math,platform,statistics,csv
from fractions import Fraction as F
from pathlib import Path
from certified_compiler import BitSource,RationalCategorical
from tail_collapse import fixture,collapse_certificate,TailGenerator
ROOT=Path(__file__).resolve().parents[1]
def iid_entropy(source,n,tail):
p=source.initial
mass=tail['mass'];law=tail['count_law'];accept=tail['acceptance']
expected=sum((F(j)*P*a/mass for j,(P,a) in enumerate(zip(law,accept))),F(0))
mean_counts=[(n-expected)*p[a]/(1-p[3]) for a in range(3)]+[expected]
H=-sum(float(c)*math.log2(float(pa)) for c,pa in zip(mean_counts,p))
H-=sum(float(P*a/mass)*math.log2(float(a)) for P,a in zip(law,accept) if a)
H+=math.log2(float(mass))
return H
def run_case(n,repeats,seeds):
source,tasks=fixture();start=time.perf_counter()
tail=collapse_certificate(source,tasks,n,F(1,4))
certify_seconds=time.perf_counter()-start
start=time.perf_counter();generator=TailGenerator(source,n,tail['acceptance'])
setup_seconds=time.perf_counter()-start
H=iid_entropy(source,n,tail)
rows=[]
for seed in seeds:
for method in ('global_interval','fresh_interval_per_step'):
bits=BitSource(seed);counts=[];consumption=[];start=time.perf_counter()
for _ in range(repeats):
before=bits.bits
if method=='global_interval':word=generator.draw(bits)
else:
prefix=[];count=0;state=None
for i in range(n):
q=generator._conditional(i,count,state)
state=RationalCategorical(q).draw(bits)
count+=source.useful[state];prefix.append(state)
word=tuple(prefix)
counts.append(word.count(3));consumption.append(bits.bits-before)
seconds=time.perf_counter()-start
rows.append({'method':method,'seed':seed,'samples':repeats,'seconds':seconds,
'milliseconds_per_sample':1000*seconds/repeats,
'mean_bits':statistics.mean(consumption),
'bits_sample_stdev':statistics.stdev(consumption) if repeats>1 else None,
'mean_useful_count':statistics.mean(counts)})
return {'depth':n,'certification_seconds':certify_seconds,'setup_seconds':setup_seconds,
'source_retention_mass_exact':str(tail['mass']),
'minimum_expected_raw_proposals_exact':str(1/tail['mass']),
'minimum_expected_raw_proposals_display':float(1/tail['mass']),
'target_entropy_bits_display':H,'global_interval_expected_bits_upper_display':H+3,
'exact_target_mean_useful_count':str(F(n,4)),
'backward_table_scalar_entries':sum(len(row)*source.d for row in generator.H[1:]),
'runs':rows}
def main():
ap=argparse.ArgumentParser();ap.add_argument('--samples-per-seed',type=int,default=100)
ap.add_argument('--depths',default='16,32,64,128');args=ap.parse_args()
results=[run_case(n,args.samples_per_seed,(17,71,127)) for n in map(int,args.depths.split(','))]
report={'version':'5.0.0','scope':'Synthetic exact-distribution samplers; no neural training, physical experiment, or practical RSI test.',
'environment':{'python':platform.python_version(),'platform':platform.platform()},
'provenance':'Elapsed timings and random bits were measured here. Entropy decimal values are display approximations. Rejection counts are exact mathematical expectations, not executed rejection experiments.',
'cases':results}
out=ROOT/'results'/'SAMPLING_BENCHMARK.json';out.write_text(json.dumps(report,indent=2)+'\n')
with (ROOT/'results'/'sampling_runs.csv').open('w',newline='') as f:
columns=['depth','method','seed','samples','seconds','milliseconds_per_sample','mean_bits','bits_sample_stdev','mean_useful_count']
writer=csv.DictWriter(f,fieldnames=columns);writer.writeheader()
for c in results:
for r in c['runs']:writer.writerow({'depth':c['depth'],**r})
for c in results:
print(json.dumps({'depth':c['depth'],'entropy_bits':c['target_entropy_bits_display'],
'expected_raw_proposals':c['minimum_expected_raw_proposals_display'],
'global_mean_bits':statistics.mean(r['mean_bits'] for r in c['runs'] if r['method']=='global_interval'),
'fresh_step_mean_bits':statistics.mean(r['mean_bits'] for r in c['runs'] if r['method']=='fresh_interval_per_step'),
'global_ms':statistics.mean(r['milliseconds_per_sample'] for r in c['runs'] if r['method']=='global_interval')},indent=2))
if __name__=='__main__':main()