Datasets:
Formats:
json
Languages:
English
Size:
< 1K
Tags:
recursive-self-improvement
program-synthesis
term-rewriting
automated-reasoning
formal-methods
benchmark
Download research/experiment.py from PureOne/Nhais-DQ-Recursive-Search-Contraction: direct link, hf CLI and curl.
- Browser
- Download file 9.45 kB
-
https://huggingface.co/datasets/PureOne/Nhais-DQ-Recursive-Search-Contraction/resolve/main/research/experiment.py
- Command line
-
hf download hf://datasets/PureOne/Nhais-DQ-Recursive-Search-Contraction/research/experiment.py
-
curl -L -o experiment.py https://huggingface.co/datasets/PureOne/Nhais-DQ-Recursive-Search-Contraction/resolve/main/research/experiment.py
9.45 kB
| #!/usr/bin/env python3 | |
| """Locked confirmatory experiments; standard library only. | |
| No target is used to choose rules, stop training, or change parameters. | |
| All training, checking, compilation, and deployment times are retained separately. | |
| A conventional semantic BFS is the strongest non-learned primary control. | |
| """ | |
| from __future__ import annotations | |
| import argparse, copy, hashlib, json, math, platform, random, statistics, sys, time | |
| from pathlib import Path | |
| from engine import Improver, Rule, family, cold_search, ref_eval | |
| from verifier import verify | |
| ROOT=Path(__file__).resolve().parent | |
| PROTOCOL={ | |
| 'version':'1.0','status':'locked before confirmatory seeds', | |
| 'training_seeds':list(range(81200,81208)), 'widths':[8,10,12], | |
| 'rounds':8,'semantic_products_per_round':600,'max_rules':1500, | |
| 'deployment_semantic_budget':12000,'deployment_expansion_budget':6000, | |
| 'timing_repeats':5,'target_count':256,'target_word_lengths':[8,16], | |
| 'wall_probe_seconds':0.025,'wall_probe_repeats':3, | |
| 'primary_outcome':'additional exact semantic discoveries per 12000 semantic products', | |
| 'secondary_outcomes':['canonical-prefix wall time','full training cost', | |
| 'cold wall-budget discoveries','held-out target coverage','causal continuation'], | |
| 'important':'A semantic product is not a FLOP or equal-wall-clock budget. ' | |
| 'Primitive maps and grammar are supplied; no unrestricted code invention.', | |
| 'sources_locked':['engine.py','verifier.py','experiment.py'] | |
| } | |
| def dump(path, data): | |
| path.parent.mkdir(parents=True,exist_ok=True) | |
| path.write_text(json.dumps(data,indent=2,sort_keys=True)+'\n') | |
| def targets(gs,seed): | |
| rng=random.Random(seed+19000003); out={} | |
| while len(out)<PROTOCOL['target_count']: | |
| word=tuple(rng.randrange(len(gs)) for _ in range(rng.randint(8,16))) | |
| val=ref_eval(word,gs) | |
| out.setdefault(val,word) | |
| return out | |
| def scalar_result(result, goals): | |
| return {**{k:v for k,v in result.items() if k!='best'}, | |
| 'targets_solved':sum(t in result['best'] for t in goals)} | |
| def run_case(seed,n,save=True): | |
| gs=family(seed,n); engine=Improver(gs,semantic_dedup=True) | |
| history=[]; first=None; fork=None; snapshots=[] | |
| full_start=time.perf_counter() | |
| for generation in range(1,PROTOCOL['rounds']+1): | |
| growth=engine.advance(100000,product_budget=PROTOCOL['semantic_products_per_round']) | |
| upgrade=engine.install(PROTOCOL['max_rules']) | |
| history.append({'generation':generation,'growth':growth,'upgrade':upgrade, | |
| 'stats':engine.stats.copy()}) | |
| snapshots.append(engine.export()) | |
| if generation==1:first=engine.rules.copy() | |
| if generation==3:fork=copy.deepcopy(engine) | |
| full_train=time.perf_counter()-full_start | |
| # The training wall above INCLUDES instrumented snapshots and one deep copy. | |
| final=engine.export(); receipt=verify(final) | |
| assert receipt['accepted'] | |
| # Target generation occurs strictly after the optimizer has stopped. | |
| goals=targets(gs,seed+100*n) | |
| trial={'seed':seed,'width':n,'history':history,'final_receipt':receipt, | |
| 'training_wall_seconds':full_train,'final_stats':engine.stats.copy(), | |
| 'final_rules':len(engine.rules),'final_automaton_states':len(engine.guard.next), | |
| 'methods':{},'causal_fork':{}} | |
| choices={'semantic_bfs':([],True), 'one_shot':(first,True), | |
| 'recursive':(engine.rules,True), 'frozen_syntax':([],False)} | |
| # Rotate ordering deterministically to reduce a systematic timing-order effect. | |
| names=list(choices); shift=seed % len(names); names=names[shift:]+names[:shift] | |
| for name in names: | |
| laws,dedup=choices[name] | |
| fixed_products=cold_search(gs,laws,100000,dedup, | |
| product_budget=PROTOCOL['deployment_semantic_budget']) | |
| for sig,word in fixed_products['best'].items(): | |
| if sig in goals: assert ref_eval(word,gs)==sig | |
| samples=[cold_search(gs,laws,PROTOCOL['deployment_expansion_budget'],dedup) | |
| for _ in range(PROTOCOL['timing_repeats'])] | |
| wall_samples=[cold_search(gs,laws,100000,dedup, | |
| wall_budget=PROTOCOL['wall_probe_seconds']) | |
| for _ in range(PROTOCOL['wall_probe_repeats'])] | |
| trial['methods'][name]={ | |
| 'fixed_products':scalar_result(fixed_products,goals), | |
| 'fixed_prefix':scalar_result(samples[0],goals), | |
| 'prefix_timing_samples':[r['wall_seconds'] for r in samples], | |
| 'median_prefix_seconds':statistics.median(r['wall_seconds'] for r in samples), | |
| 'wall_probes':[scalar_result(r,goals) for r in wall_samples]} | |
| # Match all state, archives, primitives and old learned rules at the causal fork. | |
| common=hashlib.sha256(json.dumps(fork.export(),sort_keys=True).encode()).hexdigest() | |
| for name,active in [('continue_self_updates',True),('freeze_meta_only',False)]: | |
| branch=copy.deepcopy(fork); before=len(branch.best); start=time.perf_counter();trace=[] | |
| for i in range(3): | |
| growth=branch.advance(100000,product_budget=600) | |
| upgrade=branch.install(1500) if active else {'accepted':0,'wall_seconds':0.0} | |
| if not active: branch.pending={} | |
| trace.append({'growth':growth,'upgrade':upgrade}) | |
| trial['causal_fork'][name]={'common_certificate_hash':common, | |
| 'additional_semantics':len(branch.best)-before, | |
| 'wall_seconds':time.perf_counter()-start,'trace':trace, | |
| 'rules':len(branch.rules)} | |
| if save: | |
| dump(ROOT/'results'/f'case_{n}_{seed}.json',trial) | |
| for i,s in enumerate(snapshots,1): | |
| dump(ROOT/'snapshots'/f'n{n}_seed{seed}_g{i}.json',s) | |
| dump(ROOT/'results'/f'targets_{n}_{seed}.json', | |
| [{'map':list(m),'witness':list(w)} for m,w in goals.items()]) | |
| return trial | |
| def summarize(trials): | |
| rows={} | |
| for name in ['semantic_bfs','one_shot','recursive','frozen_syntax']: | |
| entries=[x['methods'][name] for x in trials] | |
| rows[name]={ | |
| 'mean_semantics_fixed_products':statistics.mean(x['fixed_products']['known_semantics'] for x in entries), | |
| 'total_targets_solved':sum(x['fixed_products']['targets_solved'] for x in entries), | |
| 'targets_total':len(trials)*PROTOCOL['target_count'], | |
| 'median_prefix_seconds':statistics.median(x['median_prefix_seconds'] for x in entries), | |
| 'mean_products_fixed_prefix':statistics.mean(x['fixed_prefix']['semantic_products'] for x in entries), | |
| 'median_wall_probe_semantics':statistics.median(statistics.median(r['known_semantics'] for r in x['wall_probes']) for x in entries)} | |
| paired={} | |
| for control in ['semantic_bfs','one_shot','frozen_syntax']: | |
| ratios=[x['methods']['recursive']['fixed_products']['known_semantics']/x['methods'][control]['fixed_products']['known_semantics'] for x in trials] | |
| speeds=[x['methods'][control]['median_prefix_seconds']/x['methods']['recursive']['median_prefix_seconds'] for x in trials] | |
| margins=[x['methods'][control]['median_prefix_seconds']-x['methods']['recursive']['median_prefix_seconds'] for x in trials] | |
| break_even=[math.ceil(x['training_wall_seconds']/m) if m>0 else None for x,m in zip(trials,margins)] | |
| paired[control]={'mean_discovery_ratio':statistics.mean(ratios), | |
| 'min_discovery_ratio':min(ratios),'max_discovery_ratio':max(ratios), | |
| 'median_prefix_speedup':statistics.median(speeds), | |
| 'wall_wins':sum(s>1 for s in speeds),'trials':len(trials), | |
| 'break_even_full_training_queries':break_even} | |
| causal=[x['causal_fork']['continue_self_updates']['additional_semantics']/max(1,x['causal_fork']['freeze_meta_only']['additional_semantics']) for x in trials] | |
| return {'protocol':PROTOCOL,'case_count':len(trials),'methods':rows,'paired':paired, | |
| 'causal_additional_discovery_mean_ratio':statistics.mean(causal), | |
| 'causal_additional_discovery_min_ratio':min(causal), | |
| 'causal_additional_discovery_max_ratio':max(causal), | |
| 'causal_wins':sum(r>1 for r in causal), | |
| 'median_training_seconds':statistics.median(t['training_wall_seconds'] for t in trials), | |
| 'total_nonempty_updates':sum(sum(h['upgrade']['accepted']>0 for h in t['history']) for t in trials), | |
| 'total_final_rules':sum(t['final_rules'] for t in trials), | |
| 'all_cases_eight_nonempty_updates':all(sum(h['upgrade']['accepted']>0 for h in t['history'])==8 for t in trials), | |
| 'environment':{'python':sys.version,'platform':platform.platform()}, | |
| 'disclaimer':'Finite symbolic demonstration. Timings are hardware-specific. ' | |
| 'No independence or general-AI transfer claim. Ratios are not intelligence multipliers.'} | |
| def main(): | |
| p=argparse.ArgumentParser();p.add_argument('--lock',action='store_true') | |
| p.add_argument('--width',type=int);p.add_argument('--summarize',action='store_true');a=p.parse_args() | |
| if a.lock: | |
| lock={**PROTOCOL,'source_sha256':{x:hashlib.sha256((ROOT/x).read_bytes()).hexdigest() for x in PROTOCOL['sources_locked']}} | |
| dump(ROOT/'PROTOCOL_LOCK.json',lock);print('Protocol locked');return | |
| lock=json.loads((ROOT/'PROTOCOL_LOCK.json').read_text()) | |
| for f,digest in lock['source_sha256'].items(): | |
| assert hashlib.sha256((ROOT/f).read_bytes()).hexdigest()==digest,'source changed after lock' | |
| if a.summarize: | |
| trials=[json.loads(p.read_text()) for p in sorted((ROOT/'results').glob('case_*.json'))] | |
| result=summarize(trials);dump(ROOT/'results'/'SUMMARY.json',result) | |
| print(json.dumps(result,indent=2));return | |
| widths=[a.width] if a.width else PROTOCOL['widths'] | |
| for n in widths: | |
| for seed in PROTOCOL['training_seeds']: | |
| r=run_case(seed,n) | |
| print(n,seed,r['final_rules'],[h['upgrade']['accepted'] for h in r['history']],flush=True) | |
| if __name__=='__main__': main() | |