Record ten-part results and fix bounded pilot timing and AMP handling

This commit is contained in:
Frank14f committed 2026-11-15 03:02:29 +08:00
1 parent f8a6ed3f81
commit cdb52988c3
42 files changed
+31677 -77

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
"""Finalize all 499 terminal preparation attempts and freeze one pilot plan."""
import argparse
import json
from pathlib import Path
import numpy as np
from freeze_g1_components import sha
from s2_e1_supervisor import save
from s2_pilot_data import permitted_role
def quantile_probe(records,roles):
learning=sorted((r for r in records if permitted_role(roles,r['case'])=='learning'),key=lambda r:(r['nodes'],r['case']))
if len(learning)<20:raise ValueError('Need 20 distinct successful learning parts')
return [learning[int(i)]['case'] for i in np.linspace(0,len(learning)-1,20,dtype=int)]
def finalize(source,root,gpu_uuid):
c=json.loads((source/'contract.json').read_text());batch=json.loads((source/'batch-complete.json').read_text())
assert batch['status']=='ATTEMPTS_COMPLETE' and batch['stop_reason'] is None
assert len(batch['jobs'])==len(c['cases'])==499 and not batch['not_run_indices']
assert sorted(r['index'] for r in batch['jobs'])==list(range(499))
assert not root.exists(),'No overwrite or retry of an existing pilot'
roles=json.loads((source/'role-manifest.json').read_text());assert sha(source/'role-manifest.json')==c['role_manifest_sha256']
ready=[];failed=[]
for job in sorted(batch['jobs'],key=lambda r:r['index']):
spec=c['cases'][job['index']];case=spec['case'];role=permitted_role(roles,case)
assert job['case']==case
dest=source/'ready'/case
if job['worker']['status']!='PASS':
failed.append(dict(case=case,role=role,component_id=spec['component_id'],guard=job['worker'],
failure=json.loads((dest/'failure.json').read_text()) if (dest/'failure.json').exists() else None))
continue
r=json.loads((dest/'receipt.json').read_text());assert r['status']=='READY' and r['role']==role and r['case']==case
prep=Path(r['preparation_root']);assert sha(prep/'result.json')==r['preparation_result_sha256']
pr=json.loads((prep/'result.json').read_text());assert pr['status']=='COMPLETE'
hashes={name:sha(prep/name) for name in ['base.npy','queries.npz']}
assert all(hashes[name]==pr['output_sha256'][name] for name in hashes)
label=dest/'labels.npz';hashes['labels.npz']=sha(label);assert hashes['labels.npz']==r['label_sha256']
assert r['nodes']==spec['tet_nodes'] and r['component_id']==spec['component_id'] and r['t_set']==spec['t_set']
ready.append(dict(case=case,role=role,component_id=r['component_id'],nodes=r['nodes'],t_set=r['t_set'],
preparation_root=str(prep),label_path=str(label),input_sha256=hashes,ready_receipt_sha256=sha(dest/'receipt.json')))
planned={role:sum(s['tet_nodes'] for s in c['cases'] if permitted_role(roles,s['case'])==role) for role in ['learning','validation']}
successful={role:dict(parts=sum(r['role']==role for r in ready),nodes=sum(r['nodes'] for r in ready if r['role']==role)) for role in planned}
assert planned==dict(learning=11863762,validation=3330152)
if not all(successful[k]['parts'] for k in successful):raise ValueError('Empty successful role')
probe=quantile_probe(ready,roles)
paths=['tools/prepare_s2_pilot_training.py','tools/run_s2_pilot.py','tools/run_s2_pilot_probe.py',
'tools/run_s2_pilot_training.py','tools/s2_pilot_train.py','tools/s2_pilot_gpu_guard.py','tools/s2_gpu_process_supervisor.py',
'tools/s2_e1_supervisor.py','tools/s2_pilot_data.py','tools/freeze_g1_components.py']
paths+=sorted(str(p) for p in Path('tools/s2_models').glob('*.py'))
code={p:sha(p) for p in paths}
root.mkdir();save(root/'success-manifest.json',dict(ready_parts=ready,failed_parts=failed,successful=successful,
preparation_batch_sha256=sha(source/'batch-complete.json'),preparation_contract_sha256=sha(source/'contract.json')))
plan=dict(fold=0,pool=100,seed=0,gpu_uuid=gpu_uuid,code_sha256=code,role_manifest=str(source/'role-manifest.json'),
role_manifest_sha256=sha(source/'role-manifest.json'),success_manifest=str(root/'success-manifest.json'),
success_manifest_sha256=sha(root/'success-manifest.json'),probe_cases=probe,
probe_selection='20 equally spaced ranks in successful learning node-count order; includes min/max; tie by case',
learning_nodes=planned['learning'],validation_nodes=planned['validation'],successful=successful,
extrapolation='Train rate * all 387 planned learning nodes + FP32 inference rate * all 112 planned validation nodes; conservative if failed parts dropped',
runs=[dict(name=f'{arm}{width}-seed0',arm=arm,width=width,seed=0) for width in [128,256] for arm in ['N','E']],
limits=dict(total_gpu_wall_seconds=7200,probe_wall_seconds=300,run_wall_seconds=1800,host_rss_bytes=16*2**30,vram_bytes=15*2**30,disk_bytes=5*2**30),
authorizing_rulings=['1794680129.303719','1794681576.845789','1794681807.376669'],test_labels_read=False)
save(root/'pilot-plan.json',plan);return plan
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('source',type=Path);p.add_argument('root',type=Path);p.add_argument('gpu_uuid');a=p.parse_args()
plan=finalize(a.source,a.root,a.gpu_uuid);print(json.dumps(dict(successful=plan['successful'],probe_cases=plan['probe_cases'])))
+51
View File
@@ -0,0 +1,51 @@
"""One irreversible attempt: bounded timing probe, frozen E_max, then four runs."""
import argparse
import fcntl
import json
from pathlib import Path
import sys
import time
import traceback
from freeze_g1_components import sha
from s2_e1_supervisor import save
from s2_pilot_gpu_guard import guarded_worker,run as train_runs
from s2_pilot_train import common_epoch_limit
def freeze_training_contract(root,plan,probe):
assert probe['status']=='COMPLETE' and probe['labels_read'] is False and probe['metrics_evaluated'] is False
assert [r['case'] for r in probe['rows']]==plan['probe_cases']
nodes=sum(r['nodes'] for r in probe['rows']);assert nodes==probe['probe_nodes']
timing=common_epoch_limit(sum(r['training_seconds'] for r in probe['rows'])/nodes,
sum(r['inference_seconds'] for r in probe['rows'])/nodes,plan['learning_nodes'],plan['validation_nodes'])
assert all(probe[k]==v for k,v in timing.items())
c=dict(plan,**timing,timing_probe_receipt=str(root/'timing-probe/result.json'),timing_probe_sha256=sha(root/'timing-probe/result.json'),
timing_probe_guard_sha256=sha(root/'timing-probe-guard-receipt.json'),
probe_guard_wall_seconds=json.loads((root/'timing-probe-guard-receipt.json').read_text())['total_run_wall_seconds'],
standardizer_fingerprint=probe['standardizer_fingerprint'])
with (root/'training-contract.json').open('x') as f:json.dump(c,f,indent=2);f.write('\n')
return c
def run(root):
with (root/'orchestrator.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
assert not (root/'orchestrator-started.json').exists(),'No automatic probe/pilot retry'
plan=json.loads((root/'pilot-plan.json').read_text())
for p,h in plan['code_sha256'].items():assert sha(p)==h,p
start=time.monotonic();save(root/'orchestrator-started.json',dict(started_unix=time.time(),plan_sha256=sha(root/'pilot-plan.json')))
try:
receipt,probe=guarded_worker(root,dict(name='timing-probe'),-1,plan['gpu_uuid'],300,
[sys.executable,'tools/run_s2_pilot_probe.py',str(root)])
if receipt['status']!='PASS' or not probe or probe['status']!='COMPLETE':raise RuntimeError('Timing probe failed; no training, no retry')
freeze_training_contract(root,plan,probe)
train_runs(root,prior_wall_seconds=time.monotonic()-start)
result=json.loads((root/'pilot-complete.json').read_text())
save(root/'orchestrator-complete.json',dict(status=result['status'],total_wall_seconds=time.monotonic()-start,
selected_global_width=result['selected_global_width'],test_labels_read=False,probe_included_in_7200_seconds=True))
except Exception as exc:
save(root/'orchestrator-failure.json',dict(status='FAILED_NO_RETRY',error=str(exc),traceback=traceback.format_exc(),total_wall_seconds=time.monotonic()-start));raise
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();run(a.root)
+60
View File
@@ -0,0 +1,60 @@
"""One bounded E256 timing probe, learning geometry and synthetic zero targets only."""
import argparse
from collections import Counter
import json
from pathlib import Path
import time
import traceback
import numpy as np
import torch
from freeze_g1_components import sha
from s2_e1_supervisor import save
from s2_models.network import QueryModel
from s2_models.normalization import fit_base_standardizer
from s2_pilot_data import permitted_role
from s2_pilot_train import train_part,part_weights,SkipPolicy,common_epoch_limit
from run_s2_pilot_training import LearningBases,read_part_arrays,to_device
def run(root):
started=time.monotonic();dest=root/'timing-probe';dest.mkdir(exist_ok=False)
rows=[];policy=SkipPolicy()
try:
c=json.loads((root/'pilot-plan.json').read_text())
for p,h in c['code_sha256'].items():assert sha(p)==h,p
assert sha(c['success_manifest'])==c['success_manifest_sha256'] and sha(c['role_manifest'])==c['role_manifest_sha256']
roles=json.loads(Path(c['role_manifest']).read_text());records={r['case']:r for r in json.loads(Path(c['success_manifest']).read_text())['ready_parts']}
learning=sorted(p for p in records if permitted_role(roles,p)=='learning');probe=c['probe_cases']
assert len(probe)==len(set(probe))==20 and set(probe)<=set(learning)
torch.set_num_threads(1);torch.manual_seed(0);np.random.seed(0)
if not torch.cuda.is_available() or torch.cuda.device_count()!=1 or 'V100' not in torch.cuda.get_device_name():raise RuntimeError('Exactly one visible V100 required')
device=torch.device('cuda:0');torch.cuda.manual_seed_all(0);torch.cuda.reset_peak_memory_stats();torch.backends.cuda.matmul.allow_tf32=False
stats=fit_base_standardizer(LearningBases(records,learning,roles),learning_part_ids=learning,fold='0',pool='100')
cache={case:read_part_arrays(records[case],roles,synthetic_targets=True) for case in probe}
model=QueryModel('E',256,standardizer=stats).to(device);optimizer=torch.optim.AdamW(model.parameters(),lr=1e-3,weight_decay=1e-5)
scaler=torch.amp.GradScaler('cuda');groups=Counter(records[p]['component_id'] for p in learning)
for case in probe:
torch.cuda.synchronize();start=time.monotonic();model.train();data=to_device(cache[case],device)
weights=torch.tensor(part_weights(data['counts'],groups[records[case]['component_id']],len(groups),len(learning)),dtype=torch.float32,device=device)
info={};train_part(model,optimizer,data['base'],data['ids'],data['gaps'],data['edge'],data['target'],weights,scaler=scaler,amp=True,step_info=info)
policy.observe(info['step_skipped']);del data,weights;torch.cuda.synchronize();train_seconds=time.monotonic()-start
start=time.monotonic();model.eval()
with torch.no_grad(),torch.autocast(device_type='cuda',enabled=False):
data=to_device(cache[case],device);prediction=model(data['base'],data['ids'],data['gaps'],data['edge'])
# Include prediction device-to-host cost; discard values, no metrics.
prediction.float().cpu().numpy();del prediction,data
torch.cuda.synchronize();inference_seconds=time.monotonic()-start
rows.append(dict(case=case,nodes=records[case]['nodes'],training_seconds=train_seconds,inference_seconds=inference_seconds,amp=info))
save(dest/'progress.json',dict(rows=rows,amp=policy.summary(),elapsed_seconds=time.monotonic()-started))
nodes=sum(r['nodes'] for r in rows)
timing=common_epoch_limit(sum(r['training_seconds'] for r in rows)/nodes,sum(r['inference_seconds'] for r in rows)/nodes,c['learning_nodes'],c['validation_nodes'])
result=dict(status='COMPLETE',**timing,rows=rows,probe_nodes=nodes,amp=policy.summary(),standardizer_fingerprint=stats.fingerprint,
synthetic_zero_targets=True,labels_read=False,metrics_evaluated=False,model_discarded=True,
wall_seconds=time.monotonic()-started,peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved())
save(dest/'result.json',result);print(json.dumps({k:v for k,v in result.items() if k!='rows'}),flush=True)
except Exception as exc:
save(dest/'failure.json',dict(status='FAILED_NO_RETRY',error=str(exc),traceback=traceback.format_exc(),amp=policy.summary(),rows=rows,wall_seconds=time.monotonic()-started));raise
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();run(a.root)
+49 -25
View File
@@ -15,34 +15,49 @@ from s2_models.network import QueryModel,TRAINING_CONTRACT
from s2_models.normalization import BaseStandardizer,fit_base_standardizer
from s2_models.objectives import relative_l2
from s2_pilot_data import permitted_role
from s2_pilot_train import part_weights,train_part,component_score
from s2_pilot_train import part_weights,train_part,component_score,SkipPolicy
class LearningBases(Mapping):
def __init__(self,records,ids,roles):self.records=records;self.ids=tuple(ids);self.roles=roles
def __init__(self,records,ids,roles,cache=None):self.records=records;self.ids=tuple(ids);self.roles=roles;self.cache=cache
def __iter__(self):return iter(self.ids)
def __len__(self):return len(self.ids)
def __getitem__(self,case):
if case not in self.ids or permitted_role(self.roles,case)!='learning':raise PermissionError('Learning-only normalization')
if self.cache is not None:return self.cache[case]['base']
assert sha(Path(self.records[case]['preparation_root'])/'base.npy')==self.records[case]['input_sha256']['base.npy']
return np.load(Path(self.records[case]['preparation_root'])/'base.npy',allow_pickle=False,mmap_mode='r')
def load_part(record,roles,device):
case=record['case'];permitted_role(roles,case)
def read_part_arrays(record,roles,*,synthetic_targets=False):
case=record['case'];role=permitted_role(roles,case)
if synthetic_targets and role!='learning':raise PermissionError('Timing probe accepts only learning parts')
root=Path(record['preparation_root']);label=Path(record['label_path'])
assert sha(root/'base.npy')==record['input_sha256']['base.npy']
assert sha(root/'queries.npz')==record['input_sha256']['queries.npz']
assert sha(label)==record['input_sha256']['labels.npz']
with np.load(root/'queries.npz',allow_pickle=False) as q:
mask=q['eligible_s2'];ids=q['anchor_ids'][mask];g=q['g'][mask];edge=q['edge_summary'][mask];counts=q['multiplicity'][mask]
with np.load(label,allow_pickle=False) as z:
assert np.array_equal(ids,z['anchor_ids']) and np.array_equal(counts,z['multiplicity'])
target=z['target_t_star'];seconds=z['seconds']
if synthetic_targets:
target=np.zeros(len(ids));seconds=None
else:
assert sha(label)==record['input_sha256']['labels.npz']
with np.load(label,allow_pickle=False) as z:
assert np.array_equal(ids,z['anchor_ids']) and np.array_equal(counts,z['multiplicity'])
target=z['target_t_star'];seconds=z['seconds']
base=np.load(root/'base.npy',allow_pickle=False)
if len(base)!=record['nodes']:raise ValueError('Full-node base size mismatch')
tensor=lambda a,dtype=torch.float32:torch.as_tensor(np.array(a,copy=True),dtype=dtype,device=device)
return dict(base=tensor(base),ids=tensor(ids,torch.long),gaps=tensor(g),edge=tensor(edge),target=tensor(target),
counts=counts,truth_seconds=seconds)
return dict(base=base,ids=ids,gaps=g,edge=edge,target=target,counts=counts,truth_seconds=seconds)
def to_device(data,device):
result={k:v for k,v in data.items() if k not in ['base','ids','gaps','edge','target']}
for key in ['base','ids','gaps','edge','target']:
result[key]=torch.as_tensor(np.array(data[key],copy=True),dtype=torch.long if key=='ids' else torch.float32,device=device)
return result
def load_part(record,roles,device):
return to_device(read_part_arrays(record,roles),device)
def run(root,index):
@@ -63,42 +78,50 @@ def run(root,index):
device=torch.device('cuda:0');torch.cuda.manual_seed_all(run['seed']);torch.cuda.reset_peak_memory_stats()
torch.backends.cuda.matmul.allow_tf32=False
if 'V100' not in torch.cuda.get_device_name():raise RuntimeError('Frozen pilot requires one V100')
# Every base statistics calculation is learning-only and inside this run's wall guard.
stats=fit_base_standardizer(LearningBases(records,learning,roles),learning_part_ids=learning,fold='0',pool='100')
# Check hashes once, cache raw FP64 arrays, and fit only the learning subset.
cache={case:read_part_arrays(records[case],roles) for case in sorted(records)}
stats=fit_base_standardizer(LearningBases(records,learning,roles,cache),learning_part_ids=learning,fold='0',pool='100')
assert stats.fingerprint==c['standardizer_fingerprint'],'Probe and actual runs must share learning statistics'
save(dest/'standardizer.json',dict(**stats.as_dict(),fingerprint=stats.fingerprint))
shared=root/'shared-standardizer-fingerprint.json'
if shared.exists():assert json.loads(shared.read_text())['fingerprint']==stats.fingerprint
else:save(shared,dict(fingerprint=stats.fingerprint,learning_parts=learning))
model=QueryModel(run['arm'],run['width'],standardizer=stats).to(device)
optimizer=torch.optim.AdamW(model.parameters(),lr=1e-3,weight_decay=1e-5)
scheduler=torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,T_max=200)
epoch_limit=int(c['E_max']);assert 1<=epoch_limit<=200 and c['cosine_T_max']==epoch_limit
assert sha(c['timing_probe_receipt'])==c['timing_probe_sha256']
scheduler=torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,T_max=epoch_limit)
scaler=torch.amp.GradScaler('cuda');rng=np.random.Generator(np.random.PCG64(run['seed']))
group_counts=Counter(records[p]['component_id'] for p in learning);group_number=len(group_counts)
val_groups={p:records[p]['component_id'] for p in validation}
best=float('inf');best_epoch=None;stale=0;history=[];updates=0
for epoch in range(200):
model.train();loss_sum=0.
best=float('inf');best_epoch=None;stale=0;history=[];updates=0;attempted_updates=0;skip_policy=SkipPolicy()
for epoch in range(epoch_limit):
model.train();loss_sum=0.;skip_policy.start_epoch()
order=[learning[int(j)] for j in rng.permutation(len(learning))]
for j,case in enumerate(order):
record=records[case];data=load_part(record,roles,device)
record=records[case];data=to_device(cache[case],device)
weights=torch.tensor(part_weights(data['counts'],group_counts[record['component_id']],group_number,len(learning)),dtype=torch.float32,device=device)
loss=train_part(model,optimizer,data['base'],data['ids'],data['gaps'],data['edge'],data['target'],weights,scaler=scaler,amp=True)
loss_sum+=loss/len(learning);updates+=1
step_info={}
loss=train_part(model,optimizer,data['base'],data['ids'],data['gaps'],data['edge'],data['target'],weights,scaler=scaler,amp=True,step_info=step_info)
loss_sum+=loss/len(learning);attempted_updates+=1;updates+=int(not step_info['step_skipped'])
skip_policy.observe(step_info['step_skipped'])
del data,weights
if j%16==0:
torch.cuda.synchronize();save(dest/'progress.json',dict(stage='training',epoch=epoch,parts_done=j+1,parts_total=len(learning),updates=updates,elapsed_seconds=time.monotonic()-started,
peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved()))
amp_summary=skip_policy.summary();save(dest/f'epoch-{epoch:03d}-amp.json',amp_summary)
skip_policy.finish_epoch(epoch)
model.eval();errors={}
with torch.no_grad():
for case in validation:
data=load_part(records[case],roles,device)
with torch.autocast(device_type='cuda',dtype=torch.float16):
data=to_device(cache[case],device)
with torch.autocast(device_type='cuda',enabled=False):
pred=model(data['base'],data['ids'],data['gaps'],data['edge'] if run['arm']=='E' else None)
predicted_seconds=pred.float().cpu().numpy().astype(np.float64)*records[case]['t_set']
score=relative_l2(predicted_seconds,data['truth_seconds'],data['counts'],np.ones(len(data['counts']),bool))
errors[case]=score['value'];del data,pred
value=component_score(errors,val_groups);torch.cuda.synchronize()
row=dict(epoch=epoch,training_global_weighted_mse=loss_sum,validation_component_equal_relative_l2=value,updates=updates,elapsed_seconds=time.monotonic()-started,
row=dict(epoch=epoch,amp=amp_summary,attempted_updates=attempted_updates,training_global_weighted_mse=loss_sum,validation_component_equal_relative_l2=value,updates=updates,elapsed_seconds=time.monotonic()-started,
peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved())
history.append(row);save(dest/'history.json',history)
if value<best:
@@ -111,14 +134,15 @@ def run(root,index):
save(dest/'progress.json',dict(stage='epoch_complete',**row,patience_count=stale))
if stale>=20:break
torch.cuda.synchronize()
result=dict(status='COMPLETE',run=run,epochs=len(history),updates=updates,best_epoch=best_epoch,best_validation_score=best,
result=dict(status='COMPLETE',run=run,E_max=epoch_limit,cosine_T_max=epoch_limit,epochs=len(history),attempted_updates=attempted_updates,updates=updates,best_epoch=best_epoch,best_validation_score=best,
learning_parts=len(learning),validation_parts=len(validation),learning_components=group_number,validation_components=len(set(val_groups.values())),
failed_preparation_parts_dropped=manifest['failed_parts'],standardizer_fingerprint=stats.fingerprint,
wall_seconds=time.monotonic()-started,peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved(),
test_labels_read=False,test_predictions=False,capacity_selected=False,checkpoint_sha256=sha(dest/'best.pt'))
save(dest/'result.json',result);print(json.dumps(result),flush=True);return 0
except Exception as exc:
save(dest/'failure.json',dict(status='FAILED_NO_RETRY',error_type=type(exc).__name__,message=str(exc),traceback=traceback.format_exc(),wall_seconds=time.monotonic()-started))
save(dest/'failure.json',dict(status='FAILED_NO_RETRY',error_type=type(exc).__name__,message=str(exc),traceback=traceback.format_exc(),wall_seconds=time.monotonic()-started,
epoch=locals().get('epoch'),amp=skip_policy.summary() if 'skip_policy' in locals() else None))
raise
+50 -42
View File
@@ -36,69 +36,77 @@ def active_training_pids(parent,root,index):
for p in children:
try:
cmd=p.cmdline()
if 'tools/run_s2_pilot_training.py' in cmd and str(root) in cmd and str(index)==cmd[-1]:ids.append(p.pid)
if str(root) in cmd and (('tools/run_s2_pilot_training.py' in cmd and str(index)==cmd[-1]) or (index==-1 and 'tools/run_s2_pilot_probe.py' in cmd)):ids.append(p.pid)
except psutil.NoSuchProcess:pass
return ids
def run(root):
def guarded_worker(root,spec,i,uuid,wall_limit,command):
run_start=time.monotonic();initial,util=device_usage(uuid)
if initial>128*2**20 or util>0:raise RuntimeError('SELECTED_GPU_BUSY_BEFORE_RUN')
done=threading.Event();monitor=dict(peak_device_memory_bytes=initial,peak_whole_run_tree_rss_bytes=0,max_poll_gap_seconds=0.,reason=None,samples=0)
def watch():
previous=time.monotonic()
while not done.is_set():
now=time.monotonic();monitor['max_poll_gap_seconds']=max(monitor['max_poll_gap_seconds'],now-previous);previous=now
try:
used,_=device_usage(uuid);monitor['samples']+=1;monitor['peak_device_memory_bytes']=max(monitor['peak_device_memory_bytes'],used)
if used>15*2**30:monitor['reason']='DEVICE_VRAM_LIMIT'
_,rss,_=tree_usage(os.getpid());monitor['peak_whole_run_tree_rss_bytes']=max(monitor['peak_whole_run_tree_rss_bytes'],rss)
if rss>16*2**30:monitor['reason']='WHOLE_RUN_HOST_RSS_LIMIT'
if disk_usage(root)>=5*2**30:monitor['reason']='PILOT_DISK_LIMIT'
except Exception as exc:monitor['reason']='GPU_MONITOR_FAILED';monitor['error']=str(exc)
if monitor['reason']:
for pid in active_training_pids(os.getpid(),root,i):stop_group(pid)
done.wait(.5)
thread=threading.Thread(target=watch,daemon=True);thread.start()
try:
wall=wall_limit-(time.monotonic()-run_start)-2.5
if wall<=0:raise RuntimeError('No budget left before spawn')
r=supervise(command,root/'guards',spec['name'],dict(total_cpu_seconds=7200,job_cpu_seconds=wall_limit,job_wall_seconds=wall,
tree_rss_bytes=16*2**30,disk_bytes=5*2**30,max_processes=2),poll=.1,gpu_uuid=uuid)
finally:
done.set();thread.join(timeout=3)
total_wall=time.monotonic()-run_start
result_path=root/spec['name']/'result.json'
result=json.loads(result_path.read_text()) if result_path.exists() else None
if monitor['reason']:r.update(status='STOPPED_OR_FAILED',stop_reason=monitor['reason'])
if total_wall>wall_limit:r.update(status='STOPPED_OR_FAILED',stop_reason='TOTAL_RUN_WALL_LIMIT')
if result and max(result['peak_allocated_bytes'],result['peak_reserved_bytes'])>15*2**30:r.update(status='STOPPED_OR_FAILED',stop_reason='RECORDED_VRAM_LIMIT')
r.update(gpu_visible=True,gpu_uuid=uuid,device_monitor=monitor,total_run_wall_seconds=total_wall,
result_sha256=sha(result_path) if result else None)
save(root/(spec['name']+'-guard-receipt.json'),r)
return r,result
def run(root,prior_wall_seconds=0.):
with (root/'pilot.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
return run_locked(root)
return run_locked(root,prior_wall_seconds)
def run_locked(root):
def run_locked(root,prior_wall_seconds=0.):
c=json.loads((root/'training-contract.json').read_text());uuid=c['gpu_uuid']
prior_wall_seconds=max(prior_wall_seconds,c.get('probe_guard_wall_seconds',0.))
assert [(r['arm'],r['width'],r['seed']) for r in c['runs']]==[('N',128,0),('E',128,0),('N',256,0),('E',256,0)]
for p,h in c['code_sha256'].items():assert sha(p)==h,p
assert not (root/'pilot-started.json').exists(),'No automatic pilot retry'
start=time.monotonic();save(root/'pilot-started.json',dict(started_unix=time.time(),contract_sha256=sha(root/'training-contract.json')))
rows=[];scores={};reason=None
for i,spec in enumerate(c['runs']):
remaining=7200-(time.monotonic()-start)
remaining=7200-prior_wall_seconds-(time.monotonic()-start)
if remaining<=3:reason='TOTAL_PILOT_WALL_LIMIT';break
run_start=time.monotonic();initial,util=device_usage(uuid)
if initial>128*2**20 or util>0:reason='SELECTED_GPU_BUSY_BEFORE_RUN';break
done=threading.Event();monitor=dict(peak_device_memory_bytes=initial,peak_whole_run_tree_rss_bytes=0,max_poll_gap_seconds=0.,reason=None,samples=0)
def watch():
previous=time.monotonic()
while not done.is_set():
now=time.monotonic();monitor['max_poll_gap_seconds']=max(monitor['max_poll_gap_seconds'],now-previous);previous=now
try:
used,_=device_usage(uuid);monitor['samples']+=1;monitor['peak_device_memory_bytes']=max(monitor['peak_device_memory_bytes'],used)
if used>15*2**30:monitor['reason']='DEVICE_VRAM_LIMIT'
_,rss,_=tree_usage(os.getpid());monitor['peak_whole_run_tree_rss_bytes']=max(monitor['peak_whole_run_tree_rss_bytes'],rss)
if rss>16*2**30:monitor['reason']='WHOLE_RUN_HOST_RSS_LIMIT'
if disk_usage(root)>=5*2**30:monitor['reason']='PILOT_DISK_LIMIT'
except Exception as exc:monitor['reason']='GPU_MONITOR_FAILED';monitor['error']=str(exc)
if monitor['reason']:
for pid in active_training_pids(os.getpid(),root,i):stop_group(pid)
done.wait(.5)
thread=threading.Thread(target=watch,daemon=True);thread.start()
try:
wall=min(1800,remaining)-(time.monotonic()-run_start)-2.5
if wall<=0:raise RuntimeError('No budget left before spawn')
command=[sys.executable,'tools/run_s2_pilot_training.py',str(root),str(i)]
r=supervise(command,root/'guards',spec['name'],dict(total_cpu_seconds=7200,job_cpu_seconds=1800,job_wall_seconds=wall,
tree_rss_bytes=16*2**30,disk_bytes=5*2**30,max_processes=2),poll=.1,gpu_uuid=uuid)
finally:
done.set();thread.join(timeout=3)
total_wall=time.monotonic()-run_start
result_path=root/spec['name']/'result.json'
result=json.loads(result_path.read_text()) if result_path.exists() else None
if monitor['reason']:r.update(status='STOPPED_OR_FAILED',stop_reason=monitor['reason'])
if total_wall>min(1800,remaining):r.update(status='STOPPED_OR_FAILED',stop_reason='TOTAL_RUN_WALL_LIMIT')
if result and max(result['peak_allocated_bytes'],result['peak_reserved_bytes'])>15*2**30:r.update(status='STOPPED_OR_FAILED',stop_reason='RECORDED_VRAM_LIMIT')
r.update(gpu_visible=True,gpu_uuid=uuid,device_monitor=monitor,total_run_wall_seconds=total_wall,
result_sha256=sha(result_path) if result else None)
save(root/(spec['name']+'-guard-receipt.json'),r);rows.append(dict(run=spec,**r))
command=[sys.executable,'tools/run_s2_pilot_training.py',str(root),str(i)]
try:r,result=guarded_worker(root,spec,i,uuid,min(1800,remaining),command)
except Exception as exc:reason=str(exc);break
rows.append(dict(run=spec,**r))
if r['status']!='PASS' or not result or result['status']!='COMPLETE':reason='PILOT_RUN_FAILED_NO_RETRY';break
scores[(spec['arm'],spec['width'])]=result['best_validation_score']
if time.monotonic()-start>7200:reason='TOTAL_PILOT_WALL_LIMIT_AFTER_EXIT'
if prior_wall_seconds+time.monotonic()-start>7200:reason='TOTAL_PILOT_WALL_LIMIT_AFTER_EXIT'
selected=select_capacity(scores) if len(scores)==4 and reason is None else None
summary=dict(status='FOUR_RUNS_COMPLETE' if selected else 'PILOT_INCOMPLETE',reason=reason,runs=rows,selected_global_width=selected,
selection_rule='mean of N/E validation error at each width, ties smaller; all four runs required',
pilot_wall_seconds=time.monotonic()-start,test_labels_read=False,test_predictions=False,retries=0)
pilot_wall_seconds=prior_wall_seconds+time.monotonic()-start,probe_and_setup_wall_seconds=prior_wall_seconds,test_labels_read=False,test_predictions=False,retries=0)
save(root/'pilot-complete.json',summary);print(json.dumps(summary),flush=True)
+33 -2
View File
@@ -14,24 +14,55 @@ def part_weights(counts, parts_in_component, component_count, learning_parts):
return c/c.sum()/parts_in_component/component_count*learning_parts
def train_part(model,optimizer,base,ids,gaps,edge,target,weights,*,scaler=None,amp=False):
def train_part(model,optimizer,base,ids,gaps,edge,target,weights,*,scaler=None,amp=False,step_info=None):
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type=base.device.type,dtype=torch.float16,enabled=amp):
prediction=model(base,ids,gaps,edge if model.arm=='E' else None)
loss=weighted_mse(prediction,target,weights)
if not torch.isfinite(loss):raise FloatingPointError('Nonfinite training loss')
scale_before=float(scaler.get_scale()) if scaler is not None else None
if scaler is None:
loss.backward()
else:
scaler.scale(loss).backward();scaler.unscale_(optimizer)
if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
if scaler is None and any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
raise FloatingPointError('Nonfinite gradient; no silent retry or precision fallback')
if scaler is None:optimizer.step()
else:scaler.step(optimizer);scaler.update()
scale_after=float(scaler.get_scale()) if scaler is not None else None
skipped=scaler is not None and scale_after<scale_before
if step_info is not None:
step_info.update(step_skipped=skipped,scale_before=scale_before,scale_after=scale_after)
if any(not torch.isfinite(p).all() for p in model.parameters()):raise FloatingPointError('Nonfinite updated parameter')
return float(loss.detach())
class SkipPolicy:
"""Claude 1794681576: epoch 0 exempt from fraction, never from streak cap."""
def __init__(self):self.consecutive=0;self.start_epoch()
def start_epoch(self):self.attempted=0;self.skipped=0
def observe(self,skipped):
self.attempted+=1;self.skipped+=int(skipped)
self.consecutive=self.consecutive+1 if skipped else 0
if self.consecutive>20:raise FloatingPointError('More than 20 consecutive AMP skipped steps')
def summary(self):
return dict(attempted_steps=self.attempted,skipped_steps=self.skipped,successful_updates=self.attempted-self.skipped,
skipped_fraction=self.skipped/self.attempted if self.attempted else 0.,consecutive_skipped=self.consecutive)
def finish_epoch(self,epoch):
if epoch>0 and self.skipped>self.attempted*.01:raise FloatingPointError('AMP skipped steps exceed 1 percent after epoch 0')
def common_epoch_limit(training_seconds_per_node,inference_seconds_per_node,learning_nodes,validation_nodes):
if min(training_seconds_per_node,inference_seconds_per_node,learning_nodes,validation_nodes)<=0:raise ValueError('Positive per-node timing and node counts required')
epoch=training_seconds_per_node*learning_nodes+inference_seconds_per_node*validation_nodes
if not math.isfinite(epoch):raise ValueError('Nonfinite epoch time')
limit=min(200,math.floor(25*60/epoch))
if limit<1:raise ValueError('One projected epoch exceeds the 25-minute run reserve')
return dict(E_max=limit,cosine_T_max=limit,projected_epoch_seconds=epoch,projected_epochs_seconds=limit*epoch,
training_seconds_per_node=training_seconds_per_node,inference_seconds_per_node=inference_seconds_per_node,
learning_nodes=learning_nodes,validation_nodes=validation_nodes)
def component_score(part_errors,component_ids):
if not part_errors or set(part_errors)!=set(component_ids):raise ValueError('Incomplete validation roster')
groups={}
+21 -1
View File
@@ -2,7 +2,10 @@ import unittest
from unittest.mock import patch
import numpy as np
import torch
from run_s2_pilot_training import LearningBases,load_part
from run_s2_pilot_training import LearningBases,load_part,read_part_arrays
import tempfile
from pathlib import Path
from freeze_g1_components import sha
class PilotEntrySealTests(unittest.TestCase):
@@ -17,6 +20,23 @@ class PilotEntrySealTests(unittest.TestCase):
with patch('run_s2_pilot_training.sha') as hasher,patch('run_s2_pilot_training.np.load') as loader:
with self.assertRaises(PermissionError):load_part(dict(case='c'),self.roles,torch.device('cpu'))
hasher.assert_not_called();loader.assert_not_called()
def test_probe_uses_zero_target_without_opening_missing_label(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);np.save(root/'base.npy',np.ones((3,10),dtype=np.float64))
np.savez(root/'queries.npz',eligible_s2=[True,False,True],anchor_ids=[0,1,2],g=np.ones((3,2)),edge_summary=np.ones((3,4)),multiplicity=[2,3,4])
record=dict(case='a',nodes=3,preparation_root=str(root),label_path=str(root/'must-not-exist.npz'),
input_sha256={p:sha(root/p) for p in ['base.npy','queries.npz']})
data=read_part_arrays(record,self.roles,synthetic_targets=True)
self.assertIsNone(data['truth_seconds']);np.testing.assert_array_equal(data['target'],[0.,0.])
self.assertEqual(data['base'].dtype,np.float64)
record['case']='b'
with patch('run_s2_pilot_training.sha') as hasher:
with self.assertRaises(PermissionError):read_part_arrays(record,self.roles,synthetic_targets=True)
hasher.assert_not_called()
def test_learning_standardizer_uses_cached_full_precision_array(self):
values=np.array([[1.+2**-40]*10]);bases=LearningBases({},['a'],self.roles,cache={'a':{'base':values}})
with patch('run_s2_pilot_training.np.load') as loader:
self.assertIs(bases['a'],values);loader.assert_not_called()
if __name__=='__main__':unittest.main(verbosity=2)
+58
View File
@@ -0,0 +1,58 @@
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from prepare_s2_pilot_training import quantile_probe,finalize
from s2_pilot_train import common_epoch_limit
from run_s2_pilot import freeze_training_contract,run
import s2_pilot_gpu_guard as guard
class OrchestrationTests(unittest.TestCase):
def test_quantiles_only_learning_and_include_size_extremes(self):
records=[dict(case=str(i),nodes=i+1) for i in range(40)]
roles=dict(learning_parts=[str(i) for i in range(30)],validation_parts=[str(i) for i in range(30,40)],sealed_test_parts=['test'])
ids=quantile_probe(records,roles)
self.assertEqual(len(set(ids)),20);self.assertEqual(ids[0],'0');self.assertEqual(ids[-1],'29')
self.assertTrue(set(ids)<=set(roles['learning_parts']))
def test_partial_preparation_never_starts_pilot(self):
with tempfile.TemporaryDirectory() as tmp:
source=Path(tmp);(source/'contract.json').write_text('{}');(source/'batch-complete.json').write_text('{"status":"STOPPED"}')
with self.assertRaises(AssertionError):finalize(source,source/'never-created','synthetic')
self.assertFalse((source/'never-created').exists())
def test_contract_records_two_node_rates_totals_and_cannot_overwrite(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);(root/'timing-probe').mkdir()
rows=[dict(case=str(i),nodes=(i+1)*100,training_seconds=(i+1)*.1,inference_seconds=(i+1)*.05) for i in range(20)]
nodes=sum(r['nodes'] for r in rows)
train=sum(r['training_seconds'] for r in rows)/nodes;infer=sum(r['inference_seconds'] for r in rows)/nodes
plan=dict(probe_cases=[r['case'] for r in rows],learning_nodes=38700,validation_nodes=11200)
probe=dict(status='COMPLETE',rows=rows,probe_nodes=nodes,labels_read=False,metrics_evaluated=False,standardizer_fingerprint='synthetic',
**common_epoch_limit(train,infer,38700,11200))
(root/'timing-probe/result.json').write_text(json.dumps(probe));(root/'timing-probe-guard-receipt.json').write_text('{"total_run_wall_seconds":10}')
c=freeze_training_contract(root,plan,probe)
self.assertEqual(c['E_max'],33);self.assertEqual(c['cosine_T_max'],33)
self.assertEqual(c['learning_nodes'],38700);self.assertEqual(c['validation_nodes'],11200)
self.assertAlmostEqual(c['training_seconds_per_node'],.001);self.assertAlmostEqual(c['inference_seconds_per_node'],.0005)
with self.assertRaises(FileExistsError):freeze_training_contract(root,plan,probe)
def test_failed_probe_stops_before_training(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);(root/'pilot-plan.json').write_text('{"code_sha256":{},"gpu_uuid":"synthetic"}')
with patch('run_s2_pilot.guarded_worker',return_value=({'status':'FAIL'},None)),patch('run_s2_pilot.train_runs') as train:
with self.assertRaises(RuntimeError):run(root)
train.assert_not_called()
self.assertTrue((root/'orchestrator-failure.json').exists());self.assertFalse((root/'training-contract.json').exists())
def test_probe_time_reduces_total_budget(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);c=dict(gpu_uuid='synthetic',code_sha256={},probe_guard_wall_seconds=7190.,
runs=[dict(name=f'{arm}{width}',arm=arm,width=width,seed=0) for width in [128,256] for arm in ['N','E']])
(root/'training-contract.json').write_text(json.dumps(c))
with patch.object(guard,'guarded_worker',return_value=({'status':'FAIL'},None)) as worker:
guard.run(root)
self.assertEqual(worker.call_count,1);self.assertLessEqual(worker.call_args.args[4],10.)
result=json.loads((root/'pilot-complete.json').read_text());self.assertGreaterEqual(result['pilot_wall_seconds'],7190.)
self.assertIsNone(result['selected_global_width'])
if __name__=='__main__':unittest.main(verbosity=2)
+28 -1
View File
@@ -2,7 +2,7 @@ import unittest
import numpy as np
import torch
from torch import nn
from s2_pilot_train import part_weights,train_part,component_score,select_capacity
from s2_pilot_train import part_weights,train_part,component_score,select_capacity,SkipPolicy,common_epoch_limit
class TinyQueryModel(nn.Module):
@@ -12,6 +12,33 @@ class TinyQueryModel(nn.Module):
class PilotTrainChecks(unittest.TestCase):
def test_one_forced_amp_overflow_skips_then_continues(self):
torch.manual_seed(0);m=TinyQueryModel();o=torch.optim.AdamW(m.parameters(),lr=1e-3)
scaler=torch.amp.GradScaler('cpu',init_scale=2.)
b=torch.tensor([[1.,2.],[2.,3.]]);ids=torch.tensor([0,1]);g=torch.zeros(2,2);w=torch.tensor([.5,.5]);target=torch.ones(2)
before=m.linear.weight.detach().clone();hook=m.linear.weight.register_hook(lambda grad:torch.full_like(grad,float('inf')))
first={};train_part(m,o,b,ids,g,None,target,w,scaler=scaler,step_info=first);hook.remove()
self.assertTrue(first['step_skipped']);self.assertLess(first['scale_after'],first['scale_before']);self.assertTrue(torch.equal(before,m.linear.weight))
second={};train_part(m,o,b,ids,g,None,target,w,scaler=scaler,step_info=second)
self.assertFalse(second['step_skipped']);self.assertFalse(torch.equal(before,m.linear.weight))
def test_skip_fraction_end_of_epoch_and_consecutive_limit(self):
p=SkipPolicy()
for i in range(100):p.observe(i==0)
p.finish_epoch(1)
p.start_epoch()
for i in range(100):p.observe(i in [0,2])
p.finish_epoch(0)
with self.assertRaises(FloatingPointError):p.finish_epoch(1)
p=SkipPolicy()
for _ in range(20):p.observe(True)
with self.assertRaises(FloatingPointError):p.observe(True)
def test_common_timing_epoch_limit_frozen_for_all_runs(self):
result=common_epoch_limit(.001,.0005,38700,11200)
self.assertEqual(result['E_max'],33);self.assertEqual(result['cosine_T_max'],33)
self.assertAlmostEqual(result['projected_epoch_seconds'],44.3)
self.assertEqual(result['learning_nodes'],38700);self.assertEqual(result['validation_nodes'],11200)
self.assertEqual(common_epoch_limit(.001,.001,387,112)['E_max'],200)
with self.assertRaises(ValueError):common_epoch_limit(10,1,387,112)
def test_step_weights_expectation_and_component_balance(self):
# Two components with 1 and 2 parts; total global contribution is one.
weights=[part_weights([1,3],n,2,3) for n in [1,2,2]]