Freeze H2 final200 prediction and scoring entry for semantic review
This commit is contained in:
1 parent
0a45935ee4
commit
7c6ea4f312
31 files changed
+291058
-3
No files matched your search
@@ -0,0 +1,123 @@
|
||||
"""Frozen final-only H2-S1 prediction/score; no fitting or additional GPU stages."""
|
||||
import argparse,fcntl,json,os,resource,sys,time
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from phase2_fixed_io import BASE
|
||||
from phase2_h1_worker_v2 import checked,sha,save
|
||||
from phase2_home_freeze_io import verify,freeze
|
||||
from phase2_gate_outcome_review import validate_review
|
||||
from phase2_h2_s1_common import gate
|
||||
from phase2_residual_math import decode_seconds
|
||||
from s2_custody_common import prediction_inputs
|
||||
from s2_custody_statistics import part_metrics
|
||||
from phase2_b13_e1b import pooled
|
||||
from phase2_b1213_features import cached
|
||||
from r4bc_guard import supervise
|
||||
|
||||
def read(p):return json.loads(Path(p).read_text())
|
||||
def h2_execution_command(args):
|
||||
return any(Path(x).name in {'phase2_h2_s1_guard.py','phase2_h2_s1_worker.py','phase2_h2_s1_postfit.py'} for x in args)
|
||||
def config(root):
|
||||
c=read(root/'contract.json');verify(root,'implementation');verify(Path(c['checkpoint_root']),'checkpoint')
|
||||
if c['approval']!='1794921374.599419' or c['prediction_gpu_seconds']!=600 or c['postfit_cpu_seconds']!=3600 or c['total_h2_gpu_seconds']!=144000 or c['new_fits']!=0:raise PermissionError('Fixed H2-S1 scope')
|
||||
for p,h in {**c['code_sha256'],**c['source_sha256']}.items():checked(p,h)
|
||||
pilot=read(c['pilot_contract']);train=read(c['training_contract']);done=read(c['training_complete']);result=read(c['training_result'])
|
||||
if done['status']!='PASS' or done['reasons'] or result['completed_epochs']!=200 or result['optimizer_steps']!=64000 or result['checkpoint_sha256']!=c['checkpoint_sha256']:raise PermissionError('Original last200 training PASS required')
|
||||
if done['cumulative_h2_gpu_seconds']!=c['prior_gpu_seconds'] or c['prior_gpu_seconds']+600>144000:raise ValueError('Original pilot/train cumulative cost')
|
||||
stats=read(c['standardization']);fold=pilot['folds'][0]
|
||||
if stats['parts']!=fold['learning'] or stats['nodes']!=fold['learning_nodes'] or sha(c['standardization'])!=train['standardization_sha256']:raise ValueError('Training normalization identity')
|
||||
if len(c['rows'])!=121 or len({r['case'] for r in c['rows']})!=121 or {r['case'] for r in c['rows']}!=set(fold['test']):raise ValueError('Original fold0 test121')
|
||||
if len({r['component_id'] for r in c['rows']})!=37:raise ValueError('Original37 test components')
|
||||
for row in c['rows']:
|
||||
case=row['case'];pr=pilot['parts'][case];tests=[a['fold'] for a in row['assignments'] if a['role']=='test']
|
||||
if tests!=[0] or row['component_id']!=pr['clock_group'] or row['v5_cache']['output_sha256']!=pr['output_sha256'] or row['preparation']['t_set']!=pr['t_set']:raise ValueError('H2/A cached role identity')
|
||||
return c,pilot,stats
|
||||
|
||||
def query_index(raw,q,baseline):
|
||||
if raw.ndim!=1 or np.any(np.diff(raw)<=0) or q['raw_ids'].ndim!=1 or not len(q['raw_ids']) or np.any(np.diff(q['raw_ids'])<=0):raise ValueError('Ascending unique raw/query IDs required')
|
||||
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 outside original full nodes')
|
||||
for name in ['raw_ids','counts','coordinates_over_Rg','near_wall']:
|
||||
if not np.array_equal(q[name],baseline[name]):raise ValueError('Original A query identity: '+name)
|
||||
return ix
|
||||
|
||||
def checkpoint_identity(blob,c):
|
||||
if blob['completed_epochs']!=200 or blob['optimizer_steps']!=64000 or blob['seed']!=0 or blob['fold']!=0 or blob['role']!='last_epoch_only' or blob['contract_sha256']!=c['source_sha256'][c['training_contract']]:raise ValueError('Wrong final checkpoint, not pilot/best epoch')
|
||||
|
||||
def predict(root):
|
||||
import torch
|
||||
from phase2_h2_model import H2Geo
|
||||
from phase2_h2_data import to_device,arguments
|
||||
from phase2_h2_s1_test_data import load_test_part
|
||||
c,pilot,stats=config(root);validate_review(root);verify(root,'model');dest=root/'predictions';dest.mkdir(exist_ok=False)
|
||||
if torch.__version__!=pilot['versions']['torch'] or np.__version__!=pilot['versions']['numpy']:raise ValueError('Scientific library version')
|
||||
if os.environ.get('CUDA_VISIBLE_DEVICES')!=c['gpu_uuid'] or os.environ.get('PYTORCH_CUDA_ALLOC_CONF')!='expandable_segments:True':raise ValueError('GPU/allocator binding')
|
||||
os.sched_setaffinity(0,[0,1]);torch.set_num_threads(1);torch.set_num_interop_threads(1);torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
|
||||
torch.cuda.set_device(0);torch.cuda.init();torch.cuda.reset_peak_memory_stats();start=time.monotonic();cpu=time.process_time();entries=[]
|
||||
def peaks():return dict(peak_allocated_bytes=int(torch.cuda.max_memory_allocated()),peak_reserved_bytes=int(torch.cuda.max_memory_reserved()))
|
||||
try:
|
||||
blob=torch.load(checked(c['checkpoint'],c['checkpoint_sha256']),map_location='cpu',weights_only=False);checkpoint_identity(blob,c);model=H2Geo().cuda();model.load_state_dict(blob['model'],strict=True);model.eval();del blob
|
||||
save(dest/'environment.json',dict(torch=torch.__version__,gpu_uuid=c['gpu_uuid'],allocator_settings=str(torch.cuda.memory._snapshot().get('allocator_settings',{})),model_dtype='FP32',autocast=False,checkpoint_sha256=c['checkpoint_sha256']))
|
||||
with torch.no_grad():
|
||||
for row in c['rows']:
|
||||
case=row['case'];data=to_device(load_test_part(pilot,case,stats),'cuda');residual=model(*arguments(data),checkpoint_blocks=False)
|
||||
if not bool(torch.isfinite(residual).all()):raise ValueError('Nonfinite H2 residual')
|
||||
seconds=decode_seconds(residual.cpu().numpy(),data['F'],pilot['folds'][0]['c'],data['t_set']);torch.cuda.synchronize();q=prediction_inputs(row);a=c['A_predictions'][case]
|
||||
with np.load(checked(a['path'],a['sha256']),allow_pickle=False) as old:
|
||||
ix=query_index(data['raw_ids'],q,old);A=old['A'].copy()
|
||||
if not np.isfinite(A).all() or len(seconds)!=row['nodes']:raise ValueError('Full-node coverage or A prediction')
|
||||
path=dest/(case+'.npz');np.savez_compressed(path,seconds=seconds,raw_ids=data['raw_ids'],pred=seconds[ix],A=A,query_raw_ids=q['raw_ids'],counts=q['counts'],coordinates_over_Rg=q['coordinates_over_Rg'],near_wall=q['near_wall'])
|
||||
entries.append(dict(case=case,component_id=row['component_id'],fold=0,path=str(path),sha256=sha(path),nodes=row['nodes'],query_nodes=len(ix),A_source_sha256=a['sha256'],negative_full_predictions=int(np.sum(seconds<0)),negative_query_predictions=int(np.sum(seconds[ix]<0))))
|
||||
save(dest/'progress.json',dict(stage='TEST_PREDICTION_NO_TARGETS',parts=len(entries),wall_seconds=time.monotonic()-start,cpu_seconds=time.process_time()-cpu,**peaks()));del data,residual,seconds
|
||||
save(dest/'manifest.json',dict(entries=entries,test_targets_read=False,new_fits=0,full_nodes=sum(e['nodes'] for e in entries)))
|
||||
save(dest/'result.json',dict(status='COMPLETE',parts=len(entries),test_targets_read=False,wall_seconds=time.monotonic()-start,cpu_seconds=time.process_time()-cpu,**peaks()))
|
||||
except BaseException as exc:
|
||||
save(dest/'failure.json',dict(status='FAILED',reason=type(exc).__name__+': '+str(exc),completed_parts=len(entries),wall_seconds=time.monotonic()-start,cpu_seconds=time.process_time()-cpu,**peaks()));raise
|
||||
|
||||
def score(root):
|
||||
c,pilot,stats=config(root);verify(root,'predictions');validate_review(root) # Must precede every target and old-score read.
|
||||
dest=root/'score';dest.mkdir(exist_ok=False);manifest=read(root/'predictions-manifest.json')['entries'];by={r['case']:r for r in c['rows']}
|
||||
if len(manifest)!=121 or {e['case'] for e in manifest}!=set(by):raise ValueError('All121 frozen predictions required')
|
||||
save(dest/'review-consumed.json',dict(unix=time.time(),review_sha256=sha(root/'review.json'),verdict='PASS',before_target_access=True))
|
||||
prior={r['case']:r for r in read(checked(c['A_score'],c['source_sha256'][c['A_score']]))['rows']};rows=[];access=[]
|
||||
for e in manifest:
|
||||
row=by[e['case']];case=row['case'];old=prior[case]
|
||||
if e['fold']!=0 or old['fold']!=0 or e['component_id']!=row['component_id'] or old['component_id']!=row['component_id']:raise ValueError('Paired fold/component')
|
||||
access.append(dict(case=case,fold=0,role='test',target_sha256=row['v5_cache']['output_sha256']['seconds.npy']));save(dest/'target-access.json',access)
|
||||
truth=cached(row,'seconds');raw=cached(row,'raw_ids');base=c['A_predictions'][case]
|
||||
with np.load(checked(e['path'],e['sha256']),allow_pickle=False) as z,np.load(checked(base['path'],base['sha256']),allow_pickle=False) as original:
|
||||
q={k:z['query_raw_ids' if k=='raw_ids' else k] for k in ['raw_ids','counts','coordinates_over_Rg','near_wall']};ix=query_index(raw,q,original)
|
||||
if not np.array_equal(z['raw_ids'],raw) or not np.array_equal(z['pred'],z['seconds'][ix]) or not np.array_equal(z['A'],original['A']):raise ValueError('Full/query/A frozen array identity')
|
||||
m=part_metrics(z['pred'],truth[ix],q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'],int(case.split('_')[0]))
|
||||
rows.append(dict(case=case,component_id=row['component_id'],fold=0,new=m,A=old['A']));save(dest/'progress.json',dict(parts=len(rows)))
|
||||
metrics=pooled(rows);eligible=gate(metrics['relative_l2']['new_minus_A']['high'],metrics['last_location']['new_minus_A']['high'])
|
||||
save(dest/'result.json',dict(status='COMPLETE',parts=121,components=37,metrics=metrics,rows=rows,s2_eligible_by_original_gate=eligible,gate='field H2-A CI upper<+.005 OR last-location/Rg H2-A CI upper<0; strict bounds',s2_started=False,data_sufficiency_started=False,checkpoint_epoch=200,validation_used_for_selection=False,negative_predictions_clipped=False,new_decodes=0,new_fits=0,review_sha256=sha(root/'review.json'),interpretation='Single fixed fold/seed conditional component uncertainty; not pure connectivity causality'))
|
||||
|
||||
def run(root):
|
||||
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);c,pilot,stats=config(root);validate_review(root);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if (root/'started.json').exists():raise FileExistsError('Single H2-S1 postfit attempt')
|
||||
import psutil
|
||||
for p in psutil.process_iter(['pid','cmdline']):
|
||||
args=p.info['cmdline'] or []
|
||||
if p.pid!=os.getpid() and h2_execution_command(args):raise RuntimeError('Existing H2 train/postfit process')
|
||||
os.sched_setaffinity(0,[2]);os.environ['PYTORCH_CUDA_ALLOC_CONF']='expandable_segments:True';save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),training_complete_sha256=c['source_sha256'][c['training_complete']],checkpoint_sha256=c['checkpoint_sha256'],new_fits=0));gpu=0.;charged=0.;records=[];prediction_start=None
|
||||
def cpu():
|
||||
u=resource.getrusage(resource.RUSAGE_CHILDREN);return c['setup_cpu_seconds']+time.process_time()-start+max(charged,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)
|
||||
try:
|
||||
if cpu()+1200+600+120>3600:raise RuntimeError('Postfit CPU reservation')
|
||||
from phase2_h2_s1_prediction_guard import run_prediction
|
||||
prediction_start=time.monotonic();receipt=run_prediction(root,c,1200);gpu=receipt['gpu_seconds_charged'];prediction_start=None;charged+=receipt['worker']['cpu_seconds'] if receipt['worker'] else 0.;records.append(dict(mode='predict',receipt=receipt))
|
||||
if receipt['status']!='PASS' or gpu>600 or c['prior_gpu_seconds']+gpu>144000:raise RuntimeError('Prediction not PASS')
|
||||
m=read(root/'predictions/manifest.json');assert len(m['entries'])==121 and m['full_nodes']==pilot['folds'][0]['test_nodes']
|
||||
for e in m['entries']:checked(e['path'],e['sha256'])
|
||||
save(root/'predictions-manifest.json',m);freeze(root,'predictions',[root/'contract.json',root/'predictions-manifest.json',root/'prediction-guard.json',*[Path(p) for p in c['code_sha256']]])
|
||||
if cpu()+600+120>3600:raise RuntimeError('Score CPU reservation')
|
||||
g=supervise([sys.executable,'tools/phase2_h2_s1_postfit.py','score',str(root)],root/'score-guard',dict(cpu_seconds=600,wall_seconds=780,rss_bytes=16*2**30,disk_bytes=2*2**30));charged+=g['cpu_seconds'];records.append(dict(mode='score',guard=g))
|
||||
if g['status']!='PASS' or cpu()>3600:raise RuntimeError('Score not PASS')
|
||||
save(root/'complete.json',dict(status='COMPLETE',records=records,postfit_cpu_seconds=cpu(),prediction_gpu_seconds=gpu,cumulative_h2_gpu_seconds=c['prior_gpu_seconds']+gpu,prior_pilot_and_train_gpu_once=c['prior_gpu_seconds'],s2_eligible_by_original_gate=read(root/'score/result.json')['s2_eligible_by_original_gate'],new_fits=0,s2_started=False,data_sufficiency_started=False,retry=False))
|
||||
freeze(root,'terminal',[root/'contract.json',root/'complete.json',root/'score/result.json',root/'review.json']);save(root/'post-terminal-cost.json',dict(postfit_cpu_seconds=cpu(),prediction_gpu_seconds=gpu,cumulative_h2_gpu_seconds=c['prior_gpu_seconds']+gpu,within_cap=cpu()<=3600 and gpu<=600 and c['prior_gpu_seconds']+gpu<=144000))
|
||||
except BaseException as exc:
|
||||
if prediction_start is not None:gpu=max(gpu,60+time.monotonic()-prediction_start)
|
||||
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),records=records,postfit_cpu_seconds=cpu(),prediction_gpu_seconds=gpu,cumulative_h2_gpu_seconds=c['prior_gpu_seconds']+gpu,new_fits=0,retry=False));raise
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('action',choices=['run','predict','score']);p.add_argument('root',type=Path);a=p.parse_args();{'run':run,'predict':predict,'score':score}[a.action](a.root)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Bounded600 GPU-second inference, final failure peaks retained; no retries."""
|
||||
import json,os,signal,sys,threading,time
|
||||
import psutil
|
||||
from phase2_h1_worker_v2 import save
|
||||
from s2_main_memory_guard import PeakRecords
|
||||
from s2_precision_continuation_guard import device_usage
|
||||
from s2_recovery_gpu_supervisor import supervise,tree_usage,stop_group,disk_usage
|
||||
|
||||
def final_reasons(reasons,receipt,result,tracker,gpu_seconds,cpu_seconds,cpu_cap):
|
||||
out=list(reasons)
|
||||
def add(s):
|
||||
if s not in out:out.append(s)
|
||||
if not receipt or receipt['status']!='PASS':add('WORKER_NOT_PASS')
|
||||
if not result or result.get('status')!='COMPLETE' or result.get('parts')!=121:add('INCOMPLETE121')
|
||||
if not all(k in tracker.witnesses for k in ['peak_allocated_bytes','peak_reserved_bytes']):add('MISSING_PEAKS')
|
||||
if any(v>15*2**30 for v in tracker.maxima.values()):add('RECORDED_VRAM_LIMIT')
|
||||
if gpu_seconds>600 or cpu_seconds>cpu_cap:add('FINAL_RESOURCE_LIMIT')
|
||||
return out
|
||||
|
||||
def run_prediction(root,c,cpu_cap):
|
||||
start=time.monotonic();cpu=time.process_time();requested=[];reasons=[];errors=[];samples=[];done=threading.Event();tracker=PeakRecords();receipt=None
|
||||
def elapsed():return 60+time.monotonic()-start
|
||||
def reason(x):
|
||||
if x not in reasons:reasons.append(x)
|
||||
command=[sys.executable,'tools/phase2_h2_s1_postfit.py','predict',str(root)]
|
||||
def kill():
|
||||
for p in psutil.Process().children(recursive=True):
|
||||
try:
|
||||
if p.cmdline()==command:stop_group(p.pid)
|
||||
except psutil.NoSuchProcess:pass
|
||||
def scan():
|
||||
if tracker.scan(root/'predictions'):reason('RECORDED_VRAM_LIMIT')
|
||||
def watch():
|
||||
while not done.is_set():
|
||||
try:
|
||||
scan();mem,util=device_usage(c['gpu_uuid']);_,rss,_=tree_usage(os.getpid())
|
||||
if mem>15*2**30:reason('DEVICE_VRAM_LIMIT')
|
||||
if rss>16*2**30:reason('TREE_RSS_LIMIT')
|
||||
if disk_usage(root)>20*2**30:reason('DISK_LIMIT')
|
||||
if elapsed()>=595:reason('PREDICTION_TIME_LIMIT')
|
||||
for x in requested:reason(x)
|
||||
save(root/'prediction-live.json',dict(gpu_seconds_charged=elapsed(),device_bytes=mem,device_utilization=util,rss_bytes=rss,peaks=tracker.maxima,reasons=reasons,unix=time.time()))
|
||||
except Exception as exc:reason('MONITOR_ERROR');errors.append(str(exc))
|
||||
if reasons:kill()
|
||||
done.wait(.5)
|
||||
old={s:signal.signal(s,lambda signum,frame:requested.append('COORDINATOR_SIGNAL_'+str(signum))) for s in [signal.SIGTERM,signal.SIGINT]};thread=None
|
||||
try:
|
||||
for i in range(3):
|
||||
mem,util=device_usage(c['gpu_uuid']);samples.append(dict(unix=time.time(),bytes=mem,utilization=util))
|
||||
if mem>128*2**20 or util!=0:raise RuntimeError('SELECTED_GPU_BUSY_NO_RETRY')
|
||||
if i<2:time.sleep(2)
|
||||
save(root/'prediction-idle-polls.json',samples);thread=threading.Thread(target=watch,daemon=True);thread.start()
|
||||
remaining=600-elapsed()-10
|
||||
if remaining<=0:raise RuntimeError('Setup exhausted prediction budget')
|
||||
receipt=supervise(command,root/'prediction-guard','predict',dict(total_cpu_seconds=cpu_cap-60,job_cpu_seconds=cpu_cap-60,job_wall_seconds=remaining,tree_rss_bytes=16*2**30,disk_bytes=20*2**30,max_processes=1),poll=.2,gpu_uuid=c['gpu_uuid'])
|
||||
except BaseException as exc:reason(type(exc).__name__+': '+str(exc));kill()
|
||||
finally:
|
||||
done.set()
|
||||
if thread:thread.join(timeout=4)
|
||||
if thread and thread.is_alive():reason('MONITOR_DID_NOT_EXIT')
|
||||
try:scan()
|
||||
except Exception as exc:reason('FINAL_SCAN_ERROR');errors.append(str(exc))
|
||||
for s,h in old.items():signal.signal(s,h)
|
||||
result=None;p=root/'predictions/result.json'
|
||||
try:
|
||||
if p.exists():result=json.loads(p.read_text())
|
||||
except Exception as exc:reason('FINAL_RESULT_READ_ERROR');errors.append(str(exc))
|
||||
totalcpu=60+(receipt['cpu_seconds'] if receipt else 0)+time.process_time()-cpu
|
||||
reasons=final_reasons(reasons,receipt,result,tracker,elapsed(),totalcpu,cpu_cap)
|
||||
out=dict(status='PASS' if not reasons else 'STOPPED',reasons=reasons,monitor_errors=errors,worker=receipt,recorded_memory=tracker.as_dict(),gpu_seconds_charged=elapsed(),cpu_seconds_charged=totalcpu,cumulative_h2_gpu_seconds=c['prior_gpu_seconds']+elapsed(),no_retry=True)
|
||||
save(root/'prediction-guard.json',out);return out
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Original H2 geometry/features preprocessing with explicit test-only scope; no targets."""
|
||||
import numpy as np
|
||||
import torch
|
||||
from scipy.sparse import csr_matrix
|
||||
from scipy.sparse.csgraph import connected_components
|
||||
from phase2_h1_worker_v2 import checked
|
||||
from phase2_h2_data import cached
|
||||
from phase2_h2_model import edge_attributes
|
||||
|
||||
def load_test_part(c,case,stats):
|
||||
if case not in c['folds'][0]['test']:raise PermissionError('Frozen fold0 test role required')
|
||||
r=c['parts'][case];g=c['geometry'][case]
|
||||
with np.load(checked(g['path'],g['sha256']),allow_pickle=False) as z:
|
||||
points=z['points'].copy();raw=z['raw_ids'].copy();mass=z['mass'].copy()
|
||||
indptr=z['indptr'].copy();sender=z['indices'].astype(np.int64);old_rg=float(z['rg'])
|
||||
n=len(raw);receiver=np.repeat(np.arange(n,dtype=np.int64),np.diff(indptr))
|
||||
if not np.array_equal(raw,cached(c,case,'raw_ids')) or not np.array_equal(mass,cached(c,case,'mass')):raise ValueError('Frozen geometry/node mass identity')
|
||||
if n!=r['nodes'] or len(sender)!=g['directed_edges']:raise ValueError('Frozen graph counts')
|
||||
a,rg=edge_attributes(points,mass,receiver,sender)
|
||||
if not np.isclose(rg,old_rg,rtol=1e-10,atol=1e-12):raise ValueError('Original mass Rg differs')
|
||||
graph=csr_matrix((np.ones(len(sender)),sender,indptr),shape=(n,n));count,comp=connected_components(graph,directed=False)
|
||||
x=cached(c,case,'features');F=cached(c,case,'Vf')
|
||||
if F.dtype!=np.float64 or F.shape!=(n,) or not np.isfinite(F).all():raise ValueError('Original F must be FP64')
|
||||
x=((np.asarray(x,np.float64)-np.asarray(stats['mean']))/np.asarray(stats['scale'])).astype(np.float32)
|
||||
if not np.isfinite(x).all():raise ValueError('Standardized feature overflow')
|
||||
result=dict(x=torch.from_numpy(x),mass=torch.from_numpy(mass.astype(np.float32)),receiver=torch.from_numpy(receiver),sender=torch.from_numpy(sender),attributes=torch.from_numpy(a),component_ids=torch.from_numpy(comp.astype(np.int64)),
|
||||
F=F,raw_ids=raw,physical_components=int(count),nodes=n,directed_edges=len(sender),Rg=rg,t_set=r['t_set'])
|
||||
return result
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Prepare/freeze the one H2-S1 postfit entry; never starts prediction or scoring."""
|
||||
import json,time,shutil
|
||||
from pathlib import Path
|
||||
import psutil
|
||||
from phase2_fixed_io import BASE
|
||||
from phase2_h1_worker_v2 import sha,checked,save
|
||||
from phase2_home_freeze_io import freeze,verify
|
||||
from phase2_h2_s1_postfit import config,h2_execution_command
|
||||
|
||||
def read(p):return json.loads(Path(p).read_text())
|
||||
def main():
|
||||
root=Path('/home/frank14f/MeltMind-runs/phase2-h2-s1-postfit-2026-11-17')
|
||||
if root.exists():raise FileExistsError('Existing H2 postfit; inspect instead of duplicate')
|
||||
trainroot=BASE/'artifacts/phase2-h2-s1-2026-11-17';pilotroot=BASE/'artifacts/phase2-h2-pilot-2026-11-17';checkpointroot=Path('/home/frank14f/MeltMind-runs/phase2-h2-s1-checkpoint-2026-11-17');aroot=BASE/'artifacts/phase2-b13-e1b-2026-11-17';hroot=BASE/'artifacts/phase2-h1-execution-2026-11-17'
|
||||
cp=verify(checkpointroot,'checkpoint');train=read(trainroot/'contract.json');pilot=read(pilotroot/'contract.json');done=read(trainroot/'complete.json');result=read(checked(trainroot/'worker/result.json',done['worker_result_sha256']));a=read(aroot/'contract.json');h=read(hroot/'contract.json');f=pilot['folds'][0];af=a['folds'][0];hj=h['jobs'][0]
|
||||
if done['status']!='PASS' or done['reasons'] or done['monitor_errors'] or done['worker']['returncode']!=0 or result['test_targets_read'] is not False:raise ValueError('Training PASS required')
|
||||
if train['prediction_gpu_reserve']!=600 or train['postfit_cpu_cap']!=3600 or train['total_h2_gpu_seconds']!=144000:raise ValueError('Original budget mismatch')
|
||||
if hj['baseline_model']!=af['A_baseline'] or set(hj['learning'])!=set(f['learning']) or set(hj['test'])!=set(f['test']):raise ValueError('H1/A baseline model/roles differ')
|
||||
if {r['case'] for r in af['rows']['learning']}!=set(f['learning']) or {r['case'] for r in af['rows']['test']}!=set(f['test']):raise ValueError('H2/A learning/test mismatch')
|
||||
by={r['case']:r for r in af['rows']['test']};rows=[by[k] for k in f['test']]
|
||||
if len(rows)!=121 or len({r['component_id'] for r in rows})!=37 or sum(r['nodes'] for r in rows)!=3125278:raise ValueError('Fixed test roster')
|
||||
entries=[e for e in read(aroot/'predictions-manifest.json')['entries'] if e['fold']==0]
|
||||
if len(entries)!=121 or {e['case'] for e in entries}!=set(f['test']):raise ValueError('A prediction manifest coverage')
|
||||
A={e['case']:e for e in entries}
|
||||
for row in rows:
|
||||
case=row['case'];pr=pilot['parts'][case];entry=A[case]
|
||||
if pr['output_sha256']!=row['v5_cache']['output_sha256'] or pr['t_set']!=row['preparation']['t_set'] or pr['clock_group']!=row['component_id'] or entry['component_id']!=row['component_id'] or entry['A_source_sha256']!=a['A_predictions'][case]['sha256']:raise ValueError('A/H2 cache/clock/component/prediction identity')
|
||||
active=[]
|
||||
for proc in psutil.process_iter(['pid','cmdline']):
|
||||
if h2_execution_command(proc.info['cmdline'] or []):active.append(proc.info['pid'])
|
||||
if active:raise RuntimeError('H2 active processes: '+str(active))
|
||||
sources={str(BASE/p):digest for p,digest in train['source_sha256'].items()}
|
||||
source_paths=[trainroot/'contract.json',trainroot/'complete.json',trainroot/'worker/result.json',trainroot/'worker/standardization.json',pilotroot/'contract.json',aroot/'contract.json',aroot/'predictions-manifest.json',aroot/'score/result.json',checkpointroot/'contract.json',checkpointroot/'checkpoint-git-freeze.json',checkpointroot/'checkpoint-authorization.json',Path(result['checkpoint'])]
|
||||
sources.update({str(p):sha(p) for p in source_paths});sources[hj['baseline_model']['path']]=hj['baseline_model']['sha256']
|
||||
sources.update({e['path']:e['sha256'] for e in entries})
|
||||
for p,digest in sources.items():checked(p,digest) # Opaque hashes only; old score/target values not parsed.
|
||||
codes={}
|
||||
for old in [train,a]:
|
||||
for p,digest in old['code_sha256'].items():
|
||||
p=str(BASE/p)
|
||||
if p in codes and codes[p]!=digest:raise ValueError('Conflicting source pin: '+p)
|
||||
checked(p,digest);codes[p]=digest
|
||||
extra=['phase2_h2_s1_test_data.py','phase2_h2_s1_postfit.py','phase2_h2_s1_prediction_guard.py','prepare_phase2_h2_s1_postfit.py','test_phase2_h2_s1_postfit.py','phase2_home_freeze_io.py','phase2_local_freeze_io.py','phase2_gate_outcome_review.py','test_phase2_gate_outcome_postfit.py','phase2_gate_outcome_statistics.py','phase2_gate_outcome_postfit.py']
|
||||
for name in extra:codes[str(BASE/'tools'/name)]=sha(BASE/'tools'/name)
|
||||
doc=BASE/'docs/phase2-h2-s1-postfit-2026-11-17.md';codes[str(doc)]=sha(doc)
|
||||
root.mkdir()
|
||||
comparison=dict(approval='1794921374.599419',fold=0,seed=0,checkpoint_epoch=200,learning_parts=320,validation_parts=111,test_parts=121,test_components=37,full_nodes=3125278,roles_unchanged=True,A_model=hj['baseline_model'],normalization_sha256=train['standardization_sha256'],clock=dict(c=f['c'],path=f['clock_path'],sha256=f['clock_sha256']),metrics=['relative_l2','last_location','kendall_tau_b'],query='Original eligible S2 query; multiplicities once; raw-ID minimum tie rule; last distance/Rg',pooling='Original E1b pooled(): per-arm components require all constituent part metrics defined, component means equally weighted, paired intersection',bootstrap=dict(replicates=2000,seed=2026111408),S2_gate='field H2-A CI upper < +0.005 OR last-location/Rg H2-A CI upper < 0; strict, finite bounds',S2_automatic_launch=False,next_stage='Data sufficiency only after S1 scored; no additional stage launch in this entry',new_fits=0,new_decodes=0,negative_clipping=False,actual_semantic_PASS_before_any_target=True)
|
||||
save(root/'comparison-contract.json',comparison)
|
||||
c=dict(version='H2-S1-final200-postfit-v1',approval='1794921374.599419',checkpoint_root=str(checkpointroot),checkpoint_commit=cp['commit'],checkpoint=result['checkpoint'],checkpoint_sha256=result['checkpoint_sha256'],training_contract=str(trainroot/'contract.json'),training_complete=str(trainroot/'complete.json'),training_result=str(trainroot/'worker/result.json'),pilot_contract=str(pilotroot/'contract.json'),standardization=str(trainroot/'worker/standardization.json'),prior_gpu_seconds=done['cumulative_h2_gpu_seconds'],prior_training_cpu_seconds=done['cpu_seconds_charged'],prediction_gpu_seconds=600,postfit_cpu_seconds=3600,total_h2_gpu_seconds=144000,setup_cpu_seconds=120,gpu_uuid=train['gpu_uuid'],worker_cpus=[0,1],coordinator_cpus=[2],vram_bytes=15*2**30,rss_bytes=16*2**30,disk_bytes=20*2**30,rows=rows,A_predictions=A,A_score=str(aroot/'score/result.json'),A_model=hj['baseline_model'],source_sha256=sources,code_sha256=codes,comparison_contract=str(root/'comparison-contract.json'),comparison_contract_sha256=sha(root/'comparison-contract.json'),new_fits=0,new_decodes=0,no_retry=True,actual_semantic_PASS_required=True,predictions_freeze_before_score=True,validation_used_for_selection=False)
|
||||
save(root/'contract.json',c)
|
||||
shutil.copyfile('/tmp/h2-postfit-synthetic-attempt1.log',root/'synthetic-attempt1.log')
|
||||
shutil.copyfile('/tmp/h2-postfit-synthetic-attempt2.log',root/'synthetic-attempt2.log')
|
||||
save(root/'preparation-attempt1-failure.json',dict(status='STOPPED_BEFORE_ROOT_CREATION',reason='Process suffix match falsely identified preparer PID686575 as H2 execution',fix='Exact Path(arg).name match; regression test added',real_predictions=0,target_values_read=False))
|
||||
log=(root/'synthetic-attempt2.log').read_text()
|
||||
if 'Ran 21 tests' not in log or not log.rstrip().endswith('OK'):raise ValueError('Actual synthetic acceptance missing')
|
||||
save(root/'acceptance.json',dict(status='PASS',tests=21,elapsed_seconds=1.056,command='python -m unittest tools.test_phase2_h2_s1_postfit -v',log_sha256=sha(root/'synthetic-attempt2.log'),scope='15 input/identity/science/failure synthetic checks plus 6 actual file/Git semantic review checks; CPU only, no real target/prediction/GPU',test_source_sha256=sha(BASE/'tools/test_phase2_h2_s1_postfit.py'),setup_cpu_charge=120,unix=time.time()))
|
||||
save(root/'preparation-audit.json',dict(status='PREPARED_NOT_LAUNCHED',unix=time.time(),h2_active_pids=active,checkpoint_commit=cp['commit'],test_parts=121,test_components=37,test_nodes=3125278,original_H2_A_roles_equal=True,baseline_model_hash_equal=True,A_predictions_hash_checked=121,training_sources_verified=True,test_target_values_read=False,old_score_values_read=False,new_predictions=0,new_scores=0,gate_queue_untouched=True))
|
||||
freeze(root,'model',[root/'contract.json',Path(c['checkpoint']),Path(c['standardization']),trainroot/'worker/result.json',checkpointroot/'checkpoint-git-freeze.json'])
|
||||
freeze(root,'implementation',[root/'contract.json',root/'comparison-contract.json',root/'acceptance.json',root/'synthetic-attempt1.log',root/'synthetic-attempt2.log',root/'preparation-attempt1-failure.json',root/'preparation-audit.json',*[Path(p) for p in codes]])
|
||||
proof=verify(root,'implementation');save(root/'expected-review-binding.json',dict(reviewed_commit=proof['commit'],contract_sha256=sha(root/'contract.json'),implementation_proof_sha256=sha(root/'implementation-git-freeze.json'),comparison_contract_sha256=c['comparison_contract_sha256'],code_sha256=codes))
|
||||
freeze(root,'review-binding',[root/'contract.json',root/'expected-review-binding.json',root/'implementation-git-freeze.json',root/'implementation-authorization.json']);config(root)
|
||||
print(json.dumps(dict(root=str(root),implementation=proof['commit'],contract_sha256=sha(root/'contract.json'),binding_sha256=sha(root/'expected-review-binding.json'),code_files=len(codes),review_pending=True,launched=False)))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Synthetic CPU acceptance only; never opens real test targets or invokes CUDA."""
|
||||
import ast,copy,inspect,json,tempfile,unittest
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from phase2_h1_worker_v2 import sha
|
||||
from phase2_h2_data import load_part
|
||||
from phase2_h2_s1_test_data import load_test_part
|
||||
from phase2_h2_model import edge_attributes
|
||||
from phase2_h2_s1_postfit import query_index,checkpoint_identity,predict,score,h2_execution_command
|
||||
from phase2_h2_s1_common import gate
|
||||
from phase2_residual_math import decode_seconds
|
||||
from phase2_b13_e1b import pooled
|
||||
from phase2_h2_s1_prediction_guard import final_reasons
|
||||
from s2_main_memory_guard import PeakRecords
|
||||
# The exact shared validator is exercised against real temporary Git files.
|
||||
from test_phase2_gate_outcome_postfit import SemanticReview
|
||||
|
||||
class InputScope(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name)
|
||||
raw=np.array([10,20,30,40]);mass=np.array([1.,1.,2.,2.]);points=np.array([[0.,0,0],[1,0,0],[0,2,0],[1,2,0]])
|
||||
receiver=np.arange(4);sender=np.array([1,0,3,2]);_,rg=edge_attributes(points,mass,receiver,sender)
|
||||
geometry=self.root/'geometry.npz';np.savez(geometry,points=points,raw_ids=raw,mass=mass,indptr=np.arange(5),indices=sender,rg=rg)
|
||||
self.F=np.array([.1,.2,.3,.4],np.float64)+1e-10;features=np.arange(76,dtype=float).reshape(4,19)
|
||||
hashes={}
|
||||
for name,array in dict(raw_ids=raw,mass=mass,features=features,Vf=self.F).items():
|
||||
p=self.root/(name+'.npy');np.save(p,array);hashes[p.name]=sha(p)
|
||||
self.c=dict(folds=[dict(test=['test'],learning=['learn'],validation=['val'])],parts={'test':dict(output=str(self.root),output_sha256=hashes,nodes=4,t_set=.4)},geometry={'test':dict(path=str(geometry),sha256=sha(geometry),directed_edges=4)})
|
||||
self.stats=dict(mean=[1.]*19,scale=[2.]*19)
|
||||
def tearDown(self):self.tmp.cleanup()
|
||||
def test_test_loader_succeeds_with_no_target_files(self):
|
||||
d=load_test_part(self.c,'test',self.stats);self.assertEqual(d['physical_components'],2);self.assertEqual(d['nodes'],4);self.assertEqual(d['F'].dtype,np.float64);np.testing.assert_array_equal(d['F'],self.F);self.assertNotIn('target',d)
|
||||
np.testing.assert_array_equal(d['x'].numpy(),((np.arange(76).reshape(4,19)-1)/2).astype(np.float32))
|
||||
def test_reject_learning_validation_unknown_before_file_access(self):
|
||||
for case in ['learn','val','unknown']:
|
||||
with self.assertRaises(PermissionError):load_test_part(self.c,case,self.stats)
|
||||
def test_original_preprocessing_ast_identical(self):
|
||||
old=ast.parse(inspect.getsource(load_part)).body[0].body;new=ast.parse(inspect.getsource(load_test_part)).body[0].body
|
||||
self.assertEqual([ast.dump(x) for x in old[2:-2]+old[-1:]],[ast.dump(x) for x in new[1:]])
|
||||
def test_fp32_skip_rejected(self):
|
||||
p=self.root/'Vf.npy';np.save(p,self.F.astype(np.float32));self.c['parts']['test']['output_sha256'][p.name]=sha(p)
|
||||
with self.assertRaises(ValueError):load_test_part(self.c,'test',self.stats)
|
||||
def test_full_graph_not_query_subgraph(self):
|
||||
d=load_test_part(self.c,'test',self.stats);q=dict(raw_ids=np.array([20,40]),counts=np.array([3,1]),coordinates_over_Rg=np.zeros((2,3)),near_wall=np.array([True,False]));ix=query_index(d['raw_ids'],q,q)
|
||||
np.testing.assert_array_equal(ix,[1,3]);self.assertEqual(d['directed_edges'],4)
|
||||
|
||||
class IdentitiesAndScience(unittest.TestCase):
|
||||
def test_query_requires_counts_coordinates_wall_and_raw_identity(self):
|
||||
raw=np.array([1,3,5]);q=dict(raw_ids=np.array([1,5]),counts=np.array([2,3]),coordinates_over_Rg=np.zeros((2,3)),near_wall=np.array([True,False]))
|
||||
for k in q:
|
||||
bad={a:b.copy() for a,b in q.items()};bad[k].flat[0]=not bad[k].flat[0] if k=='near_wall' else bad[k].flat[0]+1
|
||||
with self.assertRaises(ValueError):query_index(raw,q,bad)
|
||||
with self.assertRaises(ValueError):query_index(raw,dict(q,raw_ids=np.array([1,9])),q)
|
||||
with self.assertRaises(ValueError):query_index(raw[::-1],q,q)
|
||||
def test_final_checkpoint_identity(self):
|
||||
c=dict(training_contract='/train',source_sha256={'/train':'fixed'});blob=dict(completed_epochs=200,optimizer_steps=64000,seed=0,fold=0,role='last_epoch_only',contract_sha256='fixed');checkpoint_identity(blob,c)
|
||||
for k,v in dict(completed_epochs=199,optimizer_steps=63999,seed=1,fold=1,role='best',contract_sha256='other').items():
|
||||
with self.assertRaises(ValueError):checkpoint_identity(dict(blob,**{k:v}),c)
|
||||
def test_fp64_clock_and_no_negative_clipping(self):
|
||||
f=np.array([.123456789123,.75],np.float64);r=np.array([-1.,.1],np.float32);actual=decode_seconds(r,f,1.026602777749673,.4)
|
||||
np.testing.assert_array_equal(actual,(f*1.026602777749673+r.astype(np.float64))*.4);self.assertLess(actual[0],0)
|
||||
def test_original_strict_or_gate(self):
|
||||
for f,l,expected in [(.005,0,False),(.004999,None,True),(None,-1e-8,True),(.1,-.001,True),(float('nan'),0,False),(None,None,False),(.006,.001,False)]:self.assertEqual(gate(f,l),expected)
|
||||
def test_original_whole_component_and_equal_component_pooling(self):
|
||||
def row(group,new,old):return dict(component_id=group,**{arm:{k:dict(value=v) for k in ['relative_l2','last_location','kendall_tau_b']} for arm,v in [('new',new),('A',old)]})
|
||||
d=pooled([row('x',2,1),row('x',2,1),row('y',1,1)])['relative_l2'];self.assertEqual(d['new_minus_A']['value'],.5)
|
||||
d=pooled([row('x',2,1),row('x',None,1),row('y',1,1)])['relative_l2'];self.assertEqual(d['components'],dict(new=1,A=2));self.assertEqual(d['new_minus_A']['value'],0)
|
||||
def test_review_precedes_target_reads_in_entry(self):
|
||||
source=inspect.getsource(score);self.assertLess(source.index('validate_review(root)'),source.index("c['A_score']"));self.assertLess(source.index('validate_review(root)'),source.index("cached(row,'seconds')"))
|
||||
for f in [load_test_part,predict]:
|
||||
tree=ast.parse(inspect.getsource(f));calls=[n for n in ast.walk(tree) if isinstance(n,ast.Call) and isinstance(n.func,ast.Name) and n.func.id=='cached']
|
||||
self.assertFalse(any(isinstance(n.args[-1],ast.Constant) and n.args[-1].value in ['target','seconds'] for n in calls))
|
||||
|
||||
class FailureAccounting(unittest.TestCase):
|
||||
def test_process_identity_excludes_preparer_and_tests(self):
|
||||
for script in ['prepare_phase2_h2_s1_postfit.py','test_phase2_h2_s1_postfit.py']:
|
||||
self.assertFalse(h2_execution_command(['python','tools/'+script]))
|
||||
for script in ['phase2_h2_s1_postfit.py','phase2_h2_s1_worker.py','phase2_h2_s1_guard.py']:
|
||||
self.assertTrue(h2_execution_command(['python','tools/'+script]))
|
||||
def test_failed_worker_peak_still_fails_after_result_peak_regresses(self):
|
||||
with tempfile.TemporaryDirectory() as p:
|
||||
root=Path(p);(root/'failure.json').write_text(json.dumps(dict(peak_allocated_bytes=10,peak_reserved_bytes=16*2**30)))
|
||||
t=PeakRecords();self.assertTrue(t.scan(root));(root/'failure.json').unlink();(root/'result.json').write_text(json.dumps(dict(peak_allocated_bytes=10,peak_reserved_bytes=10)));t.scan(root)
|
||||
reasons=final_reasons([],{'status':'FAILED'},dict(status='COMPLETE',parts=121),t,100,100,1200);self.assertIn('WORKER_NOT_PASS',reasons);self.assertIn('RECORDED_VRAM_LIMIT',reasons)
|
||||
def test_missing_peaks_and_incomplete_coverage_fail(self):
|
||||
r=final_reasons([],{'status':'PASS'},dict(status='COMPLETE',parts=120),PeakRecords(),100,100,1200);self.assertIn('MISSING_PEAKS',r);self.assertIn('INCOMPLETE121',r)
|
||||
def test_final_gpu_and_cpu_caps_enforced(self):
|
||||
t=PeakRecords();t.witnesses=dict(peak_allocated_bytes={},peak_reserved_bytes={})
|
||||
for gpu,cpu in [(600.01,1),(1,1200.01)]:self.assertIn('FINAL_RESOURCE_LIMIT',final_reasons([],{'status':'PASS'},dict(status='COMPLETE',parts=121),t,gpu,cpu,1200))
|
||||
self.assertEqual(final_reasons([],{'status':'PASS'},dict(status='COMPLETE',parts=121),t,600,1200,1200),[])
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user