Download experiments/run_all.py from PureOne/Infinite-Players: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/datasets/PureOne/Infinite-Players/resolve/main/experiments/run_all.py
- Command line
-
hf download hf://datasets/PureOne/Infinite-Players/experiments/run_all.py
-
curl -L -o run_all.py https://huggingface.co/datasets/PureOne/Infinite-Players/resolve/main/experiments/run_all.py
14 kB
| """Fixed-design finite studies: no network, human data, or downloaded model.""" | |
| from __future__ import annotations | |
| import argparse,csv,itertools,json,math,time | |
| from pathlib import Path | |
| import numpy as np | |
| from scipy.special import logsumexp | |
| from scipy.stats import t as student_t | |
| from infinite_players.temporal import signs,trajectory_products,lag_moments | |
| from infinite_players.evidence_tree import EvidenceTree,paired_emission_factors,forward_log_likelihoods | |
| from infinite_players.memory_contract import confusability_graph,exact_coloring,retrospective_memory_lower_bits | |
| from infinite_players.fidelity import policy_iteration,project_improvement,semantic_law,signature_residual,solve_fiber | |
| from infinite_players.arena import make_arena,calibration_fixture | |
| from infinite_players.promotion import budget | |
| SEED=1860317 | |
| def save_json(path,value):path.write_text(json.dumps(value,indent=2,sort_keys=True,allow_nan=False)+"\n") | |
| def save_csv(path,rows): | |
| with path.open('w',newline='') as f: | |
| w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows) | |
| def wilson(correct,n): | |
| p=correct/n;z=1.959963984540054;d=1+z*z/n | |
| mid=(p+z*z/(2*n))/d;half=z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/d | |
| return mid-half,mid+half | |
| def lag_study(out): | |
| rng=np.random.default_rng(SEED);rows=[];raw=[] | |
| n=64;trials=16000;alpha=.6;beta=.75;rho=.72 | |
| for lag in (0,1,2,3,4,6,9): | |
| u=trajectory_products(rng,trials,n,lag,alpha,beta,rho) | |
| scores=u.sum(1);correct=(scores>0)|((scores==0)&(rng.random(trials)<.5)) | |
| mean,var,bound=lag_moments(n,lag,alpha*beta,rho);lo,hi=wilson(int(correct.sum()),trials) | |
| rows.append(dict(lag=lag,n=n,trials=trials,correct=int(correct.sum()),accuracy=float(correct.mean()),ci_low=lo,ci_high=hi,mean_score=float(scores.mean()),theory_mean=mean,variance=float(scores.var(ddof=1)),theory_variance=var,error_bound=bound)) | |
| raw.extend(dict(lag=lag,trial=i,score=int(s),correct=int(c)) for i,(s,c) in enumerate(zip(scores,correct))) | |
| save_csv(out/'continuous_lag.csv',rows);save_csv(out/'continuous_lag_trials.csv',raw);return rows | |
| def hmm_study(out): | |
| rng=np.random.default_rng(SEED+1);hyp=np.array(list(itertools.product([-1,1],repeat=2))) | |
| rows=[];raw=[];max_difference=0.;pre_diff=0. | |
| for n in (8,16,32): | |
| trials=1000;full_correct=0;replay_correct=0;product_correct=0 | |
| for trial in range(trials): | |
| theta,world=signs(rng,0.,2);z=np.empty(n,dtype=np.int8);z[0]=signs(rng,0.,1)[0] | |
| z[1:]=z[0]*np.cumprod(signs(rng,.72,n-1)) | |
| a=theta*world*z*signs(rng,.6,n);b=z*signs(rng,.75,n) | |
| factors=paired_emission_factors(a,b,hyp) | |
| tree=EvidenceTree(factors,[str(i) for i in range(n)],model_id="paired-HMM-v1") | |
| prior=tree.posterior([.5,.5]);pre_diff=max(pre_diff,abs(prior[hyp[:,0]==1].sum()-.5)) | |
| probe=(hyp[:,1]==world).astype(float);p=tree.posterior([.5,.5],probe=probe) | |
| ll=forward_log_likelihoods(factors,[.5,.5]);ll[hyp[:,1]!=world]=-np.inf;baseline=np.exp(ll-logsumexp(ll)) | |
| max_difference=max(max_difference,float(np.max(np.abs(p-baseline)))) | |
| prob=float(p[hyp[:,0]==1].sum());tie=1 if rng.random()<.5 else -1 | |
| prediction=1 if prob>.5+1e-12 else (-1 if prob<.5-1e-12 else tie) | |
| baseline_prob=float(baseline[hyp[:,0]==1].sum()); replay_prediction=1 if baseline_prob>.5+1e-12 else (-1 if baseline_prob<.5-1e-12 else tie) | |
| score=int(world*np.sum(a.astype(int)*b));product=1 if score>0 else (-1 if score<0 else tie) | |
| hit=int(prediction==theta);replay_hit=int(replay_prediction==theta);hitprod=int(product==theta);full_correct+=hit;replay_correct+=replay_hit;product_correct+=hitprod | |
| raw.append(dict(n=n,trial=trial,theta=int(theta),world=int(world),posterior_positive=prob,tree_correct=hit,full_replay_correct=replay_hit,product_correct=hitprod)) | |
| for name,correct in (("operator_tree",full_correct),("full_HMM_replay",replay_correct),("paired_product",product_correct)): | |
| lo,hi=wilson(correct,trials);rows.append(dict(events=n,method=name,trials=trials,correct=correct,accuracy=correct/trials,ci_low=lo,ci_high=hi)) | |
| save_csv(out/'sequence_inference.csv',rows);save_csv(out/'sequence_inference_trials.csv',raw) | |
| report=dict(maximum_tree_replay_posterior_error=max_difference,maximum_precalibration_identity_error_from_half=pre_diff,independent_records=3000) | |
| save_json(out/'sequence_inference_audit.json',report);return rows,report | |
| def revision_study(out): | |
| rng=np.random.default_rng(SEED+2);hyp=np.array(list(itertools.product([-1,1],repeat=2)));rows=[];timings=[];raw=[] | |
| for n in (256,2048,16384): | |
| a=signs(rng,0.,n);b=signs(rng,0.,n);factors=paired_emission_factors(a,b,hyp) | |
| begin=time.perf_counter();tree=EvidenceTree(factors,[str(i) for i in range(n)],model_id="m");build=time.perf_counter()-begin | |
| maximum=0.;max_centered_logerror=0.;tree_seconds=0.;replay_seconds=0. | |
| for revision,index in enumerate(rng.choice(n,size=16,replace=False)): | |
| b[index]*=-1;new=paired_emission_factors(a[index:index+1],b[index:index+1],hyp)[0];factors[index]=new | |
| t=time.perf_counter();tree.replace(str(index),new,model_id="m",revision_id=str(revision));tp=tree.posterior([.5,.5],probe=[0,1,0,1]);tree_seconds+=time.perf_counter()-t | |
| t=time.perf_counter();ll=forward_log_likelihoods(factors,[.5,.5]);ll[[0,2]]=-np.inf;fp=np.exp(ll-logsumexp(ll));replay_seconds+=time.perf_counter()-t | |
| err=float(np.max(np.abs(tp-fp)));maximum=max(maximum,err) | |
| tll=tree.log_likelihoods([.5,.5]); fll=forward_log_likelihoods(factors,[.5,.5]); logerr=float(np.max(np.abs((tll-tll[0])-(fll-fll[0])))); max_centered_logerror=max(max_centered_logerror,logerr) | |
| raw.append(dict(events=n,revision=revision,index=int(index),posterior_max_error=err,centered_logscore_error=logerr,tree_compositions=tree.last_update_compositions,forward_steps=n)) | |
| depth=(n-1).bit_length() | |
| rows.append(dict(events=n,hypotheses=4,hidden_states=2,revisions=16,tree_compositions_per_revision=depth,replay_steps_per_revision=n,tree_payload_bytes=tree.allocated_array_bytes,raw_two_sign_payload_bytes=2*n,max_posterior_error=maximum,max_centered_logscore_error=max_centered_logerror)) | |
| timings.append(dict(events=n,build_seconds=build,tree_16_revisions_seconds=tree_seconds,replay_16_revisions_seconds=replay_seconds,measured_revision_speed_ratio=replay_seconds/tree_seconds)) | |
| save_csv(out/'local_revisions.csv',rows);save_csv(out/'local_revision_trials.csv',raw);save_json(out/'runtime_telemetry.json',timings);return rows | |
| def memory_study(out): | |
| rows=[] | |
| for n in range(1,5): | |
| records=np.array(list(itertools.product([0,1],repeat=n))) | |
| for prefix in sorted(set((1,n))): | |
| k,_=exact_coloring(confusability_graph(records[:,:prefix]));rows.append(dict(record_bits=n,queried_coordinates=prefix,records=2**n,minimum_memory_states=k,minimum_fixed_bits=int(math.ceil(math.log2(k))))) | |
| save_csv(out/'memory_graphs.csv',rows) | |
| rng=np.random.default_rng(SEED+3);n=256;trials=16000 | |
| d=signs(rng,0.,(trials,n));theta=signs(rng,0.,trials);j=rng.integers(n,size=trials);actual=d[np.arange(trials),j];w=theta*actual;guess=signs(rng,0.,trials);result=[] | |
| for b in (0,8,32,64,128,256): | |
| answer=w*np.where(j<b,actual,guess);correct=int(np.sum(answer==theta));lo,hi=wilson(correct,trials) | |
| result.append(dict(history_bits=n,retained_prefix_bits=b,trials=trials,correct=correct,accuracy=correct/trials,ci_low=lo,ci_high=hi,analytic_accuracy=.5+.5*b/n,evidential_coverage=b/n)) | |
| save_csv(out/'retrospective_memory.csv',result);save_json(out/'lossy_memory_bound.json',{"history_bits":n,"bounds":[{"average_error":e,"minimum_bits_lower_bound":retrospective_memory_lower_bits(n,e)} for e in (0,.01,.05,.1,.25,.5)]});return result | |
| def shield_study(out): | |
| rows=[];curves=[];policies=[];horizon_rows=[] | |
| for seed in range(16): | |
| mdp,anchor,targets=make_arena(4100+seed,theta=(-1 if seed%2 else 1));basevalue,_=mdp.evaluate(anchor);reference=semantic_law(mdp,anchor,6) | |
| methods={"source_anchor":anchor};audits={} | |
| for kind,name in (("path","path_shield_LP"),("class","conditional_class_only"),("none","unconstrained")): | |
| pi,v,check=policy_iteration(mdp,targets,kind);methods[name]=pi;audits[name]=check | |
| projected,hist=project_improvement(mdp,anchor,targets,steps=24);methods['nullspace_24_updates']=projected;curves.extend(dict(seed=seed,**x) for x in hist) | |
| for name,pi in methods.items(): | |
| v,_=mdp.evaluate(pi);law=semantic_law(mdp,pi,6) | |
| class_error=max(np.max(np.abs(np.array([pi[s,mdp.semantic_action[s]==c].sum() for c in range(mdp.C)])-targets[mdp.semantic_state[s]].sum(axis=1))) for s in range(mdp.S)) | |
| rows.append(dict(seed=seed,method=name,discounted_value=float(v.mean()),normalized_value=float((1-mdp.gamma)*v.mean()),normalized_gain=float((1-mdp.gamma)*(v-basevalue).mean()),minimum_state_value_gain=float(np.min(v-basevalue)),class_probability_error=float(class_error),signature_error=signature_residual(mdp,pi,targets),semantic_path_TV_h6=float(np.abs(law-reference).sum()/2))) | |
| if seed<3:policies.append(dict(seed=seed,method=name,policy=pi.tolist(),audit=audits.get(name))) | |
| if seed==0 and name in ('source_anchor','path_shield_LP','conditional_class_only','unconstrained'): | |
| for h in range(1,9): | |
| r=semantic_law(mdp,anchor,h);q=semantic_law(mdp,pi,h);horizon_rows.append(dict(method=name,horizon=h,semantic_path_TV=float(np.abs(r-q).sum()/2))) | |
| summary=[] | |
| for name in dict.fromkeys(x['method'] for x in rows): | |
| subset=[x for x in rows if x['method']==name];g=np.array([x['normalized_gain'] for x in subset]);m=float(g.mean());half=float(student_t.ppf(.975,15)*g.std(ddof=1)/4) | |
| summary.append(dict(method=name,seeds=16,normalized_value=float(np.mean([x['normalized_value'] for x in subset])),normalized_gain=m,paired_gain_ci_low=m-half,paired_gain_ci_high=m+half,semantic_path_TV_h6=float(np.mean([x['semantic_path_TV_h6'] for x in subset])),max_signature_error=float(max(x['signature_error'] for x in subset)))) | |
| save_csv(out/'shield_arena.csv',rows);save_csv(out/'shield_summary.csv',summary);save_csv(out/'nullspace_updates.csv',curves);save_csv(out/'semantic_horizons.csv',horizon_rows);save_json(out/'policy_examples.json',policies) | |
| d0,d1,k,reward=calibration_fixture();cal=[] | |
| for name,D,K in (("before_calibration_robust",np.vstack([d0,d1]),np.tile(k,2)),("true_world_0",d0,k),("true_world_1",d1,k)): | |
| pi,a=solve_fiber(reward,D,K);cal.append(dict(stage=name,policy=pi.tolist(),reward=float(reward@pi),rank=int(np.linalg.matrix_rank(D)),nullity=int(3-np.linalg.matrix_rank(D)),audit=a)) | |
| mdp,anchor,k=make_arena(781,no_headroom=True);p,v,a=policy_iteration(mdp,k) | |
| report={"calibration":cal,"no_headroom_max_absolute_gain":float(np.max(np.abs(v-mdp.evaluate(anchor)[0])))} | |
| save_json(out/'calibration_unlock.json',report);return summary,report | |
| def approximation_study(out): | |
| rng=np.random.default_rng(SEED+4);rows=[] | |
| for trial in range(1000): | |
| n,H,K=8,4,2;factors=rng.uniform(.01,.7,(n,H,K,K));eps=rng.uniform(.001,.02,n);tilde=factors*np.exp(rng.uniform(-1,1,factors.shape)*eps[:,None,None,None]) | |
| initial=rng.dirichlet(np.ones(K));terminal=rng.uniform(.1,1.,(H,K));prior=rng.dirichlet(np.ones(H));probe=np.exp(rng.uniform(-650,0,H)) | |
| x=EvidenceTree(factors,[str(i) for i in range(n)],model_id="x");y=EvidenceTree(tilde,[str(i) for i in range(n)],model_id="x") | |
| p=x.posterior(initial,prior,terminal,probe);q=y.posterior(initial,prior,terminal,probe);error=float(np.abs(p-q).sum()/2);bound=math.tanh(float(eps.sum())/2) | |
| if error>bound+1e-12:raise AssertionError("approximation bound violation") | |
| rows.append(dict(trial=trial,log_error_budget=float(eps.sum()),posterior_TV=error,uniform_bound=bound)) | |
| save_csv(out/'approximation_trials.csv',rows);result={"trials":1000,"violations":0,"maximum_posterior_TV":max(x['posterior_TV'] for x in rows),"maximum_error_bound_ratio":max(x['posterior_TV']/x['uniform_bound'] for x in rows)};save_json(out/'approximation_summary.json',result);return result | |
| def lifetime_study(out): | |
| rng=np.random.default_rng(SEED+5);trials=10000;versions=40;n=256;delta=.05;rows=[] | |
| for true_gain in (0.,.3): | |
| sums=2*rng.binomial(n,(1+true_gain)/2,(trials,versions))-n;radii=np.sqrt(2*np.log([1/budget(delta,j) for j in range(1,versions+1)])/n);accepted=sums/n>radii[None,:] | |
| any_count=int(np.sum(accepted.any(1)));lo,hi=wilson(any_count,trials) | |
| rows.append(dict(true_gain=true_gain,trials=trials,versions=versions,audit_sessions_per_version=n,lifetime_budget=delta,any_promotion_count=any_count,any_promotion_rate=any_count/trials,ci_low=lo,ci_high=hi,mean_promotions=float(accepted.sum(1).mean()))) | |
| save_csv(out/'lifetime_audit.csv',rows);return rows | |
| def main(): | |
| p=argparse.ArgumentParser();p.add_argument('--output',type=Path,default=Path('results'));args=p.parse_args();out=args.output;out.mkdir(parents=True,exist_ok=True) | |
| config={"seed":SEED,"scope":"synthetic finite known-model studies","lag_trials_per_lag":16000,"lag_events":64,"hmm_records_per_size":1000,"sizes":[8,16,32],"revision_lengths":[256,2048,16384],"local_corrections":16,"arena_seeds":16,"projection_updates":24,"horizon":6,"positive_circuit_trials":1000,"lifetime_runs_per_condition":10000};save_json(out/'config.json',config) | |
| report={} | |
| for name,fn in [('lag',lag_study),('sequence',hmm_study),('revisions',revision_study),('memory',memory_study),('shield',shield_study),('approximation',approximation_study),('lifetime',lifetime_study)]: | |
| print('RUN',name,flush=True);report[name]=fn(out) | |
| save_json(out/'summary.json',report);print('Finite studies completed',flush=True) | |
| if __name__=='__main__':main() | |