Archived
Labelled B1 five-prediction recovery and B11 A H1 continuation with unchanged science
This commit is contained in:
1 parent
d1cfbc8947
commit
bccf1fee9f
30 files changed
+137776
No files matched your search
@@ -0,0 +1,84 @@
|
||||
"""Labelled full-panel A/H1 continuation only; original EIK is never rerun."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import phase2_b11_gate as original
|
||||
from phase2_h1_worker_v2 import sha,checked,save
|
||||
from r4bc_guard import supervise
|
||||
|
||||
BASE=original.BASE
|
||||
OLD=BASE/'artifacts/phase2-b11-gate-2026-11-17'
|
||||
H1V2=BASE/'artifacts/phase2-h1-labelled-recovery-2026-11-17'
|
||||
ROOT=BASE/'artifacts/phase2-b11-labelled-continuation-2026-11-17'
|
||||
def read(p):return json.loads(Path(p).read_text())
|
||||
|
||||
|
||||
def prepare():
|
||||
old=read(OLD/'complete.json')
|
||||
if old['status']!='COMPLETE' or old['completed']!=['eik','models']:raise ValueError('Original B11 not terminal')
|
||||
original.config(OLD);ROOT.mkdir(exist_ok=False);shutil.copyfile(OLD/'contract.json',ROOT/'contract.json')
|
||||
save(ROOT/'engineering-contract.json',dict(approval='1794892722.876299',original_complete_sha256=sha(OLD/'complete.json'),
|
||||
original_cumulative_cpu_seconds=old['cumulative_cpu_seconds'],new_setup_charge_seconds=60,total_cpu_cap=7200,
|
||||
code_sha256={'tools/phase2_b11_continuation.py':sha(BASE/'tools/phase2_b11_continuation.py')},
|
||||
source='B1-v2 canonical full-node100 out-of-fold paired A/H1',arms=['A','H1'],rerun_EIK=False,refit=False,retry=False))
|
||||
|
||||
|
||||
def config(root):
|
||||
e=read(root/'engineering-contract.json')
|
||||
if e['approval']!='1794892722.876299' or e['arms']!=['A','H1'] or e['rerun_EIK']:raise PermissionError('Continuation scope differs')
|
||||
for p,h in e['code_sha256'].items():checked(p,h)
|
||||
checked(OLD/'complete.json',e['original_complete_sha256'])
|
||||
original.H1=H1V2
|
||||
return e,original.config(root)
|
||||
|
||||
|
||||
def run(root):
|
||||
e,c=config(root);os.sched_setaffinity(0,[22]);start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);charged=0.;records=[]
|
||||
def total():
|
||||
u=resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
return e['original_cumulative_cpu_seconds']+60+max(charged,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start
|
||||
with (root/'run.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if (root/'started.json').exists():raise FileExistsError('Only one labelled B11 continuation')
|
||||
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),engineering_sha256=sha(root/'engineering-contract.json')))
|
||||
try:
|
||||
while not (H1V2/'scoring-git-freeze.json').exists():
|
||||
if (H1V2/'complete.json').exists():raise RuntimeError('B1-v2 stopped before canonical freeze')
|
||||
save(root/'live-progress.json',dict(stage='WAIT_B1_V2_FROZEN_PREDICTIONS',unix=time.time(),cumulative_cpu_seconds=total()))
|
||||
if total()>7080:raise RuntimeError('B11 shared CPU cap')
|
||||
time.sleep(15)
|
||||
entries=original.model_entries(check_git=True)
|
||||
for row in c['parts']:original.select_entry(row,entries)
|
||||
save(root/'models-source-authorization.json',dict(freeze_sha256=sha(H1V2/'scoring-git-freeze.json'),manifest_sha256=sha(H1V2/'predictions-freeze.json')))
|
||||
for mode in ['build','score']:
|
||||
name='models-'+mode;dest=root/'phases'/name;dest.mkdir(parents=True,exist_ok=False)
|
||||
if mode=='score':
|
||||
original.freeze(root,'models',[root/'contract.json',root/'engineering-contract.json',root/'phases/models-build/manifest.json',BASE/'tools/phase2_b11_continuation.py',*[BASE/p for p in c['code_sha256']]])
|
||||
original.verify_freeze(root/'models-git-freeze.json');save(root/'models-score-authorization.json',dict(freeze_sha256=sha(root/'models-git-freeze.json')))
|
||||
cap=min(1800,7200-total()-120)
|
||||
if cap<=0:raise RuntimeError('B11 shared budget exhausted')
|
||||
save(root/'live-progress.json',dict(stage=name,unix=time.time(),cumulative_cpu_seconds=total()))
|
||||
g=supervise([sys.executable,'tools/phase2_b11_continuation.py',mode,str(root)],dest,
|
||||
dict(cpu_seconds=cap,wall_seconds=1800,rss_bytes=8*1024**3,disk_bytes=5*1024**3))
|
||||
charged+=g['cpu_seconds'];records.append(dict(phase=name,guard=g))
|
||||
save(root/'phase-ledger.json',dict(records=records,cumulative_cpu_seconds=total()))
|
||||
if g['status']!='PASS' or total()>7200:raise RuntimeError('B11 labelled phase stopped')
|
||||
score=read(root/'phases/models-score/result.json')
|
||||
if score['failures'] or any(v['parts']!=50 for v in score['summaries'].values()):raise RuntimeError('Full50 A/H1 continuation incomplete')
|
||||
save(root/'complete.json',dict(status='COMPLETE',records=records,old_cpu_seconds=e['original_cumulative_cpu_seconds'],cumulative_cpu_seconds=total(),arms=['A','H1'],rerun_EIK=False,retry=False))
|
||||
except BaseException as exc:
|
||||
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),records=records,cumulative_cpu_seconds=total(),original_receipts_preserved=True,retry=False));raise
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('mode',choices=['prepare','run','build','score']);p.add_argument('root',nargs='?',type=Path,default=ROOT);a=p.parse_args()
|
||||
if a.mode=='prepare':prepare()
|
||||
elif a.mode=='run':run(a.root)
|
||||
else:
|
||||
e,c=config(a.root);(original.build if a.mode=='build' else original.score)(a.root,c,'models')
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Claude1794892722: one labelled recovery, no fits or original-source edits."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import signal
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import psutil
|
||||
from phase2_h1_execution import Runner,task,freeze,read,BASE
|
||||
from phase2_h1_worker_v2 import contract,checked,sha,save
|
||||
from phase2_h1_recovery_gate import engineering
|
||||
|
||||
OLD=BASE/'artifacts/phase2-h1-execution-2026-11-17'
|
||||
ROOT=BASE/'artifacts/phase2-h1-labelled-recovery-2026-11-17'
|
||||
FAILED=[0,1,3,4,10]
|
||||
|
||||
|
||||
def authorize(root,phase):
|
||||
proof=read(root/(phase+'-git-freeze.json'))
|
||||
for name,h in proof['sha256'].items():
|
||||
p=root/name;checked(p,h);rel=str(p.relative_to(BASE))
|
||||
data=subprocess.check_output(['git','show',proof['commit']+':'+rel],cwd=proof['checkout'])
|
||||
if hashlib.sha256(data).hexdigest()!=h:raise ValueError('Coordinator Git check failed')
|
||||
for p,h in proof.get('extra_sha256',{}).items():checked(p,h)
|
||||
save(root/(phase+'-authorization.json'),dict(engineering_sha256=sha(root/'engineering-contract.json'),proof_sha256=sha(root/(phase+'-git-freeze.json')),verified_git_commit=proof['commit']))
|
||||
|
||||
|
||||
def failure_scope(frozen):
|
||||
bad=[r['job_index'] for r in frozen['attempts'] if r['guard']['status']!='PASS']
|
||||
if sorted(bad)!=FAILED or len(frozen['attempts'])!=20:raise ValueError('Recovery scope differs from approved five')
|
||||
if any(r['guard']['stop_reason']!='process_count_limit' for r in frozen['attempts'] if r['job_index'] in FAILED):raise ValueError('Recovery cause differs')
|
||||
return bad
|
||||
|
||||
|
||||
def prepare(acceptance):
|
||||
a=read(acceptance)
|
||||
if a['status']!='PASS':raise ValueError('Recovery synthetic acceptance missing')
|
||||
for p,h in a['code_sha256'].items():checked(BASE/p,h)
|
||||
original=read(OLD/'predictions-freeze.json');failure_scope(original);contract(OLD)
|
||||
names=['phase2_h1_recovery','phase2_h1_recovery_gate','phase2_h1_recovery_worker','phase2_h1_recovery_postfit']
|
||||
ROOT.mkdir(exist_ok=False)
|
||||
for name in ['contract.json','batch-complete.json','models-terminal.json','geometry/manifest.json','geometry/complete.json']:
|
||||
p=ROOT/name;p.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(OLD/name,p)
|
||||
save(ROOT/'engineering-contract.json',dict(approval='1794892722.876299',version='B1-labelled-infrastructure-recovery-v1',old_root=str(OLD),failed_prediction_jobs=FAILED,
|
||||
original_model_commit='265fa06518262d8173b229d2cfbe104a36ce19ec',old_predictions_sha256=sha(OLD/'predictions-freeze.json'),
|
||||
original_contract_sha256=sha(OLD/'contract.json'),code_sha256={f'tools/{n}.py':sha(BASE/f'tools/{n}.py') for n in names},
|
||||
acceptance_sha256=sha(acceptance),acceptance_path=str(acceptance),setup_charge_seconds=60,total_cpu_cap=72000,postfit_cpu_cap=25200,
|
||||
original_chain_must_exit_before_workers=True,refit=False,retry=False,new_decodes=0,scope='five failed predictions once, canonical20 freeze, unchanged scoring arithmetic, full decision'))
|
||||
|
||||
|
||||
class RecoveryRunner(Runner):
|
||||
def __init__(self,root,c,baseline,waiting_cpu):
|
||||
super().__init__(root,c);self.baseline=baseline;self.charges['postfit']=baseline['charges']['postfit'];self.waiting_cpu=waiting_cpu
|
||||
u=resource.getrusage(resource.RUSAGE_CHILDREN);self.child_start=u.ru_utime+u.ru_stime
|
||||
def total(self):
|
||||
u=resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
settled=sum(self.charges.values())-self.baseline['charges']['postfit']
|
||||
new=60+self.waiting_cpu+max(settled,u.ru_utime+u.ru_stime-self.child_start)+time.process_time()-self.start_cpu
|
||||
if self.baseline['charges']['postfit']+new>=25200:self.stop=self.stop or 'CUMULATIVE_POSTFIT_CPU_LIMIT'
|
||||
return self.baseline['total_cpu_charge']+new
|
||||
|
||||
|
||||
def run(root):
|
||||
eng=engineering(root);start=time.process_time();os.sched_setaffinity(0,[30,31]);runner=None
|
||||
def interrupted(sig,frame):raise InterruptedError('Recovery waiting coordinator signal '+str(sig))
|
||||
for sig in (signal.SIGTERM,signal.SIGINT):signal.signal(sig,interrupted)
|
||||
import fcntl
|
||||
with (root/'run.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if (root/'started.json').exists():raise FileExistsError('One labelled recovery only')
|
||||
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),engineering_sha256=sha(root/'engineering-contract.json')))
|
||||
while not (OLD/'complete.json').exists():
|
||||
save(root/'live-progress.json',dict(stage='WAIT_ORIGINAL_B1_TERMINAL',unix=time.time(),waiting_cpu_seconds=time.process_time()-start))
|
||||
time.sleep(10)
|
||||
for p in psutil.process_iter(['pid','cmdline']):
|
||||
args=p.info['cmdline'] or []
|
||||
if str(OLD) in args and any(str(x).endswith(('phase2_h1_execution.py','phase2_h1_worker_v2.py','phase2_h1_postfit.py')) for x in args):raise RuntimeError('Original process still live after terminal receipt')
|
||||
baseline=read(OLD/'complete.json')
|
||||
if not baseline['accounting_complete']:raise RuntimeError('Original accounting incomplete')
|
||||
original=read(checked(OLD/'predictions-freeze.json',eng['old_predictions_sha256']));failure_scope(original)
|
||||
c=contract(root);save(root/'baseline.json',dict(original_complete=baseline,original_complete_sha256=sha(OLD/'complete.json'),original_predictions_sha256=eng['old_predictions_sha256'],classification='B1-v1 incomplete; no grouped100 main tree decision'))
|
||||
# Keep a reserve for this coordinator, Git checks, and setup inside the
|
||||
# original postfit cap; the 20 CPU-hour overall cap is not reopened.
|
||||
c['budget']['postfit']=25200-600
|
||||
runner=RecoveryRunner(root,c,baseline,time.process_time()-start)
|
||||
try:
|
||||
oldproof=read(OLD/'models-git-freeze.json')
|
||||
if oldproof['commit']!=eng['original_model_commit']:raise ValueError('Frozen model commit changed')
|
||||
for name,h in oldproof['sha256'].items():
|
||||
checked(OLD/name,h);rel=str((OLD/name).relative_to(BASE));data=subprocess.check_output(['git','show',oldproof['commit']+':'+rel],cwd=oldproof['checkout'])
|
||||
if hashlib.sha256(data).hexdigest()!=h:raise ValueError('Original model Git identity differs')
|
||||
for p,h in oldproof['extra_sha256'].items():checked(p,h)
|
||||
freeze(root,'models',['contract.json','batch-complete.json','models-terminal.json'])
|
||||
authorize(root,'models')
|
||||
predtasks=[task(f'predict-{i:02d}',['tools/phase2_h1_recovery_worker.py',str(root),str(i)],[8+2*(i%4)],job_index=i) for i in FAILED]
|
||||
recovered=runner.jobs('postfit',predtasks,parallel=4)
|
||||
if runner.stop or len(recovered)!=5 or any(r['guard']['status']!='PASS' for r in recovered):raise RuntimeError('Labelled prediction recovery incomplete')
|
||||
entries=list(original['entries'])
|
||||
for rec in recovered:
|
||||
i=rec['job_index'];j=c['jobs'][i];d=root/'predictions'/f'job-{i:02d}';result=read(d/'result.json');checked(d/'index.json',result['index_sha256'])
|
||||
for e in read(d/'index.json'):entries.append(dict(**e,index=i,protocol=j['protocol'],fold=j['fold'],pool=j['pool']))
|
||||
expected={(j['index'],case) for j in c['jobs'] for case in j['test']}
|
||||
if {(e['index'],e['case']) for e in entries}!=expected or len(entries)!=len(expected):raise ValueError('Canonical prediction roster incomplete/duplicate')
|
||||
for e in entries:checked(e['path'],e['sha256'])
|
||||
canonical=[r for r in original['attempts'] if r['job_index'] not in FAILED]+recovered
|
||||
save(root/'predictions-freeze.json',dict(entries=entries,all_prediction_attempts_terminal=True,accounting_complete=True,attempts=canonical,
|
||||
original_failed_attempts=[r for r in original['attempts'] if r['job_index'] in FAILED],labelled_recovery_attempts=recovered,
|
||||
models=original['models'],contract_sha256=sha(root/'contract.json'),version='B1-v2',original_predictions_sha256=eng['old_predictions_sha256']))
|
||||
freeze(root,'scoring',['contract.json','predictions-freeze.json','geometry/manifest.json'])
|
||||
authorize(root,'scoring')
|
||||
pairs=sorted({(e['protocol'],e['case']) for e in entries})
|
||||
scoretasks=[task(f'score-{i:04d}',['tools/phase2_h1_recovery_postfit.py',str(root),'part',p,case],[8+2*(i%4)],300.,protocol=p,case=case) for i,(p,case) in enumerate(pairs)]
|
||||
runner.jobs('postfit',scoretasks,parallel=4)
|
||||
if runner.stop:raise RuntimeError('v2 score budget/monitor stop')
|
||||
summary=runner.jobs('postfit',[task('summary',['tools/phase2_h1_recovery_postfit.py',str(root),'summary'],[8],120.)])
|
||||
if runner.stop or summary[0]['guard']['status']!='PASS':raise RuntimeError('v2 summary failure')
|
||||
total=runner.total();new=total-baseline['total_cpu_charge']
|
||||
if runner.stop or total>72000 or baseline['charges']['postfit']+new>25200:raise RuntimeError('Cumulative recovery cap')
|
||||
save(root/'complete.json',dict(status='COMPLETE',accounting_complete=runner.accounting_complete,old_total_cpu_seconds=baseline['total_cpu_charge'],
|
||||
new_cpu_seconds=new,cumulative_total_cpu_seconds=total,cumulative_postfit_cpu_seconds=baseline['charges']['postfit']+new,records=runner.records,refit=False,retry=False))
|
||||
except BaseException as exc:
|
||||
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),accounting_complete=runner.accounting_complete,
|
||||
cumulative_total_cpu_seconds=runner.total(),records=runner.records,original_receipts_preserved=True,refit=False,retry=False));raise
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('mode',choices=['prepare','run']);p.add_argument('path',type=Path);a=p.parse_args()
|
||||
try:(prepare if a.mode=='prepare' else run)(a.path)
|
||||
except BaseException as exc:
|
||||
if a.mode=='run' and (a.path/'started.json').exists() and not (a.path/'complete.json').exists():
|
||||
save(a.path/'complete.json',dict(status='STOPPED_BEFORE_RECOVERY_WORKERS',reason=type(exc).__name__+': '+str(exc),new_worker_cpu_seconds=0,coordinator_cpu_seconds=time.process_time(),original_receipts_preserved=True))
|
||||
raise
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Coordinator-authorized local hash checks: no worker Git subprocess."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from phase2_h1_worker_v2 import contract,checked,sha
|
||||
|
||||
|
||||
def engineering(root):
|
||||
c=json.loads((Path(root)/'engineering-contract.json').read_text())
|
||||
if c['approval']!='1794892722.876299':raise PermissionError('Missing labelled recovery ruling')
|
||||
for p,h in c['code_sha256'].items():checked(p,h)
|
||||
return c
|
||||
|
||||
|
||||
def verified_gate(root,phase):
|
||||
root=Path(root);engineering(root)
|
||||
authorization=json.loads((root/(phase+'-authorization.json')).read_text())
|
||||
checked(root/'engineering-contract.json',authorization['engineering_sha256'])
|
||||
proof_path=root/(phase+'-git-freeze.json');checked(proof_path,authorization['proof_sha256'])
|
||||
proof=json.loads(proof_path.read_text())
|
||||
if proof['commit']!=authorization['verified_git_commit']:raise PermissionError('Git coordinator authorization differs')
|
||||
for name,digest in proof['sha256'].items():checked(root/name,digest)
|
||||
return proof
|
||||
|
||||
|
||||
def scoring_gate(root):
|
||||
c=contract(root);verified_gate(root,'scoring')
|
||||
frozen=json.loads((Path(root)/'predictions-freeze.json').read_text())
|
||||
if not frozen['all_prediction_attempts_terminal'] or not frozen['accounting_complete']:raise PermissionError('Prediction barrier missing')
|
||||
return c,frozen
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Frozen predictions -> per-part fields/topology -> frozen descriptive report."""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from scipy.sparse import csr_matrix
|
||||
from phase2_h1_worker_v2 import contract,sha,checked,save
|
||||
from phase2_h1_topology import events,match
|
||||
from phase2_h1_decision import branch_decision
|
||||
from s2_custody_common import prediction_inputs
|
||||
from s2_custody_statistics import part_metrics,kendall_pairs,last_location
|
||||
from gre24_features_v2 import per_geometry_metrics,appendix_summary
|
||||
from r4bc_common import paired_difference
|
||||
|
||||
ARMS=('A','H1','cF','EIK')
|
||||
ARRAYS=dict(A='A_seconds',H1='seconds',cF='cF_seconds',EIK='EIK_seconds')
|
||||
|
||||
|
||||
def scoring_gate(root):
|
||||
from phase2_h1_recovery_gate import scoring_gate as verified
|
||||
return verified(root)
|
||||
|
||||
|
||||
def score_part(root,protocol,case):
|
||||
c,frozen=scoring_gate(root);row=c['parts'][protocol][case]
|
||||
dest=root/'scores'/protocol/case;dest.mkdir(parents=True,exist_ok=False);start=time.process_time()
|
||||
entries=[e for e in frozen['entries'] if e['protocol']==protocol and e['case']==case]
|
||||
# Verify every field for this part before opening its target; global freeze
|
||||
# already verified every prediction file before permitting this worker.
|
||||
for e in entries:checked(e['path'],e['sha256'])
|
||||
gm=json.loads((root/'geometry/manifest.json').read_text())
|
||||
ge=next(e for e in gm['records'] if e['protocol']==protocol and e['case']==case)
|
||||
with np.load(checked(ge['path'],ge['sha256']),allow_pickle=False) as z:
|
||||
raw=z['raw_ids'].copy();x=z['points'].copy();mass=z['mass'].copy();rg=float(z['rg'])
|
||||
adjacency=csr_matrix((z['data'],z['indices'],z['indptr']),shape=(len(raw),len(raw)))
|
||||
source=Path(row['output']);save(dest/'target-access.json',dict(protocol=protocol,case=case,role='test_scoring',
|
||||
path=str(source/'seconds.npy'),sha256=row['output_sha256']['seconds.npy'],predictions_freeze_sha256=sha(root/'predictions-freeze.json')))
|
||||
truth=np.load(checked(source/'seconds.npy',row['output_sha256']['seconds.npy']),allow_pickle=False)
|
||||
cacheids=np.load(checked(source/'raw_ids.npy',row['output_sha256']['raw_ids.npy']),allow_pickle=False)
|
||||
if not np.array_equal(raw,cacheids) or truth.shape!=raw.shape or not np.isfinite(truth).all():raise ValueError('Score domain mismatch')
|
||||
if protocol=='grouped':
|
||||
q=prediction_inputs(c['grouped_rows'][case]);ix=np.searchsorted(raw,q['raw_ids'])
|
||||
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],q['raw_ids']):raise ValueError('Query raw ID mismatch')
|
||||
label=c['grouped_rows'][case]['label']
|
||||
with np.load(checked(label['path'],label['sha256']),allow_pickle=False) as z:
|
||||
if not np.array_equal(z['raw_ids'],q['raw_ids']) or not np.array_equal(z['counts'],q['counts']) or not np.array_equal(z['seconds'],truth[ix]):raise ValueError('Frozen query truth differs from tet truth')
|
||||
else:ix=np.arange(len(raw));q=None
|
||||
rows=[]
|
||||
for e in entries:
|
||||
with np.load(e['path'],allow_pickle=False) as z:
|
||||
if not np.array_equal(z['raw_ids'],raw):raise ValueError('Prediction raw ID mismatch')
|
||||
for arm in ARMS:
|
||||
pred=z[ARRAYS[arm]]
|
||||
if protocol=='grouped':metrics=part_metrics(pred[ix],truth[ix],q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'],int(case.split('_')[0]))
|
||||
else:
|
||||
met=per_geometry_metrics(truth,pred)
|
||||
metrics=dict(relative_l2=dict(value=met['rrmse_rms'],reason=None if met['rrmse_rms'] is not None else 'zero truth denominator'),
|
||||
kendall_tau_b=kendall_pairs(truth,pred,int(case.split('_')[0])),
|
||||
last_location=dict(value=last_location(truth,pred,raw,x/rg),reason=None),paper=met)
|
||||
rows.append(dict(case=case,protocol=protocol,fold=e['fold'],pool=e['pool'],arm=arm,**metrics))
|
||||
# Field scores survive a later topology resource stop; their provenance is
|
||||
# independent and the guard must report topology as incomplete, never PASS.
|
||||
save(dest/'core.json',dict(status='FIELD_SCORES_COMPLETE',rows=rows,cpu_seconds=time.process_time()-start))
|
||||
ref=events(truth,mass,raw,x,adjacency);save(dest/'truth-events.json',ref);topo=[]
|
||||
for e in entries:
|
||||
with np.load(e['path'],allow_pickle=False) as z:
|
||||
for arm in ARMS:
|
||||
pred=events(z[ARRAYS[arm]],mass,raw,x,adjacency)
|
||||
detail=dict(case=case,protocol=protocol,fold=e['fold'],pool=e['pool'],arm=arm,predicted=pred,
|
||||
match=match(ref,pred,adjacency,rg))
|
||||
save(dest/f"events-{e['index']:02d}-{arm}.json",detail);topo.append(detail)
|
||||
save(dest/'topology.json',dict(status='TOPOLOGY_COMPLETE',rows=topo,cpu_seconds=time.process_time()-start))
|
||||
|
||||
|
||||
def intervals(rows,c,pool,metric):
|
||||
lookup={(r['case'],r['arm']):r for r in rows if r['protocol']=='grouped' and r['pool']==pool}
|
||||
groups={}
|
||||
for case,row in c['parts']['grouped'].items():groups.setdefault(row['clock_group'],[]).append(case)
|
||||
values={arm:{} for arm in ARMS};missing={arm:{} for arm in ARMS}
|
||||
for arm in ARMS:
|
||||
for g,cases in sorted(groups.items()):
|
||||
block=[];bad=[]
|
||||
for case in cases:
|
||||
r=lookup.get((case,arm));v=None if r is None else r.get(metric,{}).get('value')
|
||||
if v is None:bad.append(case)
|
||||
else:block.append(v)
|
||||
if bad:missing[arm][g]=bad
|
||||
else:values[arm][g]=float(np.mean(block))
|
||||
# Existing helper is before-after: pass H1 first for the approved H1-A sign.
|
||||
delta=paired_difference(values['H1'],values['A'])
|
||||
return dict(means={a:float(np.mean(list(v.values()))) if v else None for a,v in values.items()},
|
||||
components={a:len(v) for a,v in values.items()},values=values,missing=missing,H1_minus_A=delta)
|
||||
|
||||
|
||||
def summarize(root):
|
||||
c,frozen=scoring_gate(root);rows=[];topo=[];coverage=[]
|
||||
guard_by_part={}
|
||||
for path in (root/'tasks').glob('score-*.json'):
|
||||
desc=json.loads(path.read_text());g=root/'guards'/desc['name']/'guard-result.json'
|
||||
guard_by_part[(desc['protocol'],desc['case'])]=json.loads(g.read_text()) if g.exists() else None
|
||||
for protocol in ('grouped','v4_random'):
|
||||
for case in c['parts'][protocol]:
|
||||
d=root/'scores'/protocol/case;core=d/'core.json';tp=d/'topology.json'
|
||||
if core.exists():rows.extend(json.loads(core.read_text())['rows'])
|
||||
if tp.exists():topo.extend(json.loads(tp.read_text())['rows'])
|
||||
g=guard_by_part.get((protocol,case));reason=None if tp.exists() else ('not requested/no valid test prediction' if (protocol,case) not in guard_by_part else 'missing guard receipt' if g is None else g.get('stop_reason') or 'worker failure before topology completed')
|
||||
coverage.append(dict(protocol=protocol,case=case,field_complete=core.exists(),topology_complete=tp.exists(),
|
||||
missing_topology_reason=reason,guard_status=None if g is None else g['status']))
|
||||
grouped={str(p):{metric:intervals(rows,c,p,metric) for metric in ('relative_l2','last_location','kendall_tau_b')} for p in (100,50,25)}
|
||||
decision=branch_decision(*(grouped['100'][m]['H1_minus_A'] for m in ('relative_l2','last_location','kendall_tau_b')))
|
||||
v4={}
|
||||
for arm in ARMS:
|
||||
v4[arm]={}
|
||||
for denominator in ('rms','maximum','mean'):
|
||||
key='rrmse_'+denominator;blocks=[[r['paper'][key] for r in rows if r['protocol']=='v4_random' and r['arm']==arm and r['fold']==f and r['paper'][key] is not None] for f in range(5)]
|
||||
v4[arm][key]=dict(summary=appendix_summary(blocks) if all(blocks) else None,
|
||||
defined=[len(v) for v in blocks],fraction_below_point1=[float(np.mean(np.asarray(v)<.1)) if v else None for v in blocks])
|
||||
totals={}
|
||||
for r in topo:
|
||||
key=f"{r['protocol']}/{r['pool']}/{r['fold']}/{r['arm']}";m=r['match']
|
||||
t=totals.setdefault(key,dict(TP=0,FP=0,FN=0,distances=[],empty_classes={},parts=0))
|
||||
for k in ('TP','FP','FN'):t[k]+=m[k]
|
||||
t['distances'].extend(m['matched_distance_over_Rg']);t['parts']+=1
|
||||
category=m['empty_class'];t['empty_classes'][category]=t['empty_classes'].get(category,0)+1
|
||||
for t in totals.values():
|
||||
t['precision']=t['TP']/(t['TP']+t['FP']) if t['TP']+t['FP'] else None
|
||||
t['recall']=t['TP']/(t['TP']+t['FN']) if t['TP']+t['FN'] else None
|
||||
t['median_distance_over_Rg']=float(np.median(t['distances'])) if t['distances'] else None
|
||||
save(root/'summary.json',dict(status='SCORED_DESCRIPTIVE',grouped=grouped,v4=v4,tree_decision=decision,
|
||||
topology=totals,coverage=coverage,field_rows=len(rows),topology_rows=len(topo),
|
||||
topology_interpretation='auxiliary; B3 stability gate must pass before treating as usable diagnostic',
|
||||
new_decodes=0,full_training_matrix=False))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('mode',choices=['part','summary']);p.add_argument('protocol',nargs='?');p.add_argument('case',nargs='?');a=p.parse_args()
|
||||
(score_part(a.root,a.protocol,a.case) if a.mode=='part' else summarize(a.root))
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Labelled inference-only recovery; original prediction arithmetic unchanged."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import numpy as np
|
||||
from threadpoolctl import threadpool_limits
|
||||
from phase2_h1_worker_v2 import contract,checked,sha,save,role_rows,load_features,decode_seconds
|
||||
from phase2_h1_recovery_gate import verified_gate
|
||||
|
||||
def predict(root, c, job):
|
||||
import joblib
|
||||
import xgboost
|
||||
verified_gate(root,'models')
|
||||
terminal = json.loads((root/'batch-complete.json').read_text())
|
||||
if terminal['global_stop'] or not terminal['accounting_complete'] or terminal['attempted'] != len(c['jobs']):
|
||||
raise PermissionError('Fit queue not complete')
|
||||
freeze = json.loads((root/'models-terminal.json').read_text())
|
||||
if len(freeze['models']) != len(c['jobs']): raise PermissionError('Incomplete model manifest')
|
||||
entry = next(r for r in freeze['models'] if r['index'] == job['index'])
|
||||
if entry['status'] != 'PASS': raise ValueError('No checkpoint for failed cell')
|
||||
out = root/'predictions'/f"job-{job['index']:02d}"; out.mkdir(parents=True, exist_ok=False)
|
||||
model = xgboost.XGBRegressor(); model.load_model(checked(entry['checkpoint'], entry['checkpoint_sha256']))
|
||||
old = job['baseline_model']; checked(old['path'], old['sha256'])
|
||||
if old['format'] == 'joblib':
|
||||
baseline = joblib.load(old['path'])
|
||||
elif old['format'] == 'ubj':
|
||||
baseline = xgboost.XGBRegressor(); baseline.load_model(old['path'])
|
||||
else:
|
||||
raise ValueError('Unsupported frozen A checkpoint format')
|
||||
clock = json.loads(checked(entry['clock_path'], entry['clock_sha256']).read_text())['c']
|
||||
index = []; cpu = time.process_time()
|
||||
with threadpool_limits(job['threads']):
|
||||
for row in role_rows(c, job, 'test'):
|
||||
x, f, ids = load_features(row) # No target.npy load on this path.
|
||||
seconds = decode_seconds(model.predict(x), f, clock, row['t_set'])
|
||||
old_seconds = np.asarray(baseline.predict(x), dtype=np.float64)*row['t_set']
|
||||
if old_seconds.shape != seconds.shape or not np.isfinite(old_seconds).all(): raise ValueError('Invalid A prediction')
|
||||
if job['protocol']=='grouped':
|
||||
prior=c['baseline_predictions'][str(job['index'])][row['case']]
|
||||
with np.load(checked(prior['path'],prior['sha256']),allow_pickle=False) as z:
|
||||
iq=np.searchsorted(ids,z['raw_ids'])
|
||||
if np.any(iq>=len(ids)) or not np.array_equal(ids[iq],z['raw_ids']):raise ValueError('Historical A query identity differs')
|
||||
if not np.array_equal(old_seconds[iq],z[prior['array']]):raise ValueError('Historical A query prediction differs')
|
||||
path = out/(row['case']+'.npz')
|
||||
np.savez_compressed(path, seconds=seconds, A_seconds=old_seconds, cF_seconds=clock*f*row['t_set'],
|
||||
EIK_seconds=f*row['t_set'], raw_ids=ids)
|
||||
index.append({'case': row['case'], 'path': str(path), 'sha256': sha(path),
|
||||
'negative_predictions': int(np.sum(seconds < 0)), 'nodes': len(ids)})
|
||||
save(out/'progress.json', {'parts': len(index), 'cpu_seconds': time.process_time()-cpu})
|
||||
save(out/'index.json', index)
|
||||
save(out/'result.json', {'status': 'PREDICTIONS_COMPLETE_NO_SCORES', 'index_sha256': sha(out/'index.json'),
|
||||
'cpu_seconds': time.process_time()-cpu, 'target_values_read': False})
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('index',type=int);a=p.parse_args()
|
||||
c=contract(a.root);predict(a.root,c,c['jobs'][a.index])
|
||||
@@ -0,0 +1,48 @@
|
||||
import ast
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from phase2_h1_recovery import failure_scope,FAILED
|
||||
from phase2_h1_recovery_gate import verified_gate,scoring_gate
|
||||
|
||||
|
||||
def function(path,name):
|
||||
source=Path(path).read_text();node=next(n for n in ast.parse(source).body if isinstance(n,ast.FunctionDef) and n.name==name)
|
||||
return ast.get_source_segment(source,node)
|
||||
|
||||
|
||||
class RecoveryTests(unittest.TestCase):
|
||||
def test_prediction_arithmetic_is_byte_identical(self):
|
||||
old=function('tools/phase2_h1_worker_v2.py','predict');new=function('tools/phase2_h1_recovery_worker.py','predict')
|
||||
token=' terminal = json.loads'
|
||||
self.assertEqual(old[old.index(token):],new[new.index(token):])
|
||||
self.assertNotIn('subprocess.',new)
|
||||
def test_score_and_statistics_bodies_are_identical(self):
|
||||
for name in ['score_part','intervals','summarize']:
|
||||
self.assertEqual(function('tools/phase2_h1_postfit.py',name),function('tools/phase2_h1_recovery_postfit.py',name))
|
||||
self.assertNotIn('subprocess.',function('tools/phase2_h1_recovery_postfit.py','scoring_gate'))
|
||||
def test_only_exact_five_failed_predictions(self):
|
||||
rows=[dict(job_index=i,guard=dict(status='FAILED' if i in FAILED else 'PASS',stop_reason='process_count_limit' if i in FAILED else None)) for i in range(20)]
|
||||
self.assertEqual(sorted(failure_scope(dict(attempts=rows))),FAILED)
|
||||
rows[2]['guard']['status']='FAILED'
|
||||
with self.assertRaises(ValueError):failure_scope(dict(attempts=rows))
|
||||
|
||||
|
||||
def worker(root):
|
||||
with patch('subprocess.check_output',side_effect=AssertionError('Worker must not spawn Git')):
|
||||
verified_gate(root,'models');c,p=scoring_gate(root)
|
||||
assert p['all_prediction_attempts_terminal'] and c['main_review']=='synthetic'
|
||||
auth=root/'models-authorization.json';old=auth.read_bytes();j=json.loads(old);j['verified_git_commit']='tampered';auth.write_text(json.dumps(j))
|
||||
try:
|
||||
try:verified_gate(root,'models')
|
||||
except PermissionError:pass
|
||||
else:raise AssertionError('Tampered coordinator authorization accepted')
|
||||
finally:auth.write_bytes(old)
|
||||
print('PASS actual one-process worker: coordinator Git freeze accepted; tampering rejected; no subprocess')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv)>1 and sys.argv[1]=='worker':worker(Path(sys.argv[2]))
|
||||
else:unittest.main()
|
||||
Reference in new issue
Block a user