Publish Track A and seed1 results and candidate pre-score bindings
This commit is contained in:
1 parent
3e62e08c76
commit
fee71ea677
50 files changed
+87271
No files matched your search
@@ -0,0 +1,117 @@
|
||||
"""Run one exact-reviewed candidate postfit within the original cumulative budgets."""
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import sys
|
||||
import time
|
||||
|
||||
from phase2_h1_worker_v2 import save, sha
|
||||
from phase2_home_freeze_io import freeze
|
||||
from phase3_followup_postfit_common import (
|
||||
CLEANUP_CPU, FOLD_CPU, FOLD_GPU, POSTFIT_CPU, POSTFIT_GPU, SCORE_CPU, SETUP_CPU,
|
||||
TRAINING, budget, config, prediction_identity, read, training_terminal,
|
||||
)
|
||||
from phase3_followup_postfit_guard import run_prediction
|
||||
from r4bc_guard import supervise
|
||||
|
||||
|
||||
def run(root):
|
||||
started_wall = time.monotonic()
|
||||
started_cpu = time.process_time()
|
||||
child_start = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
c, tc, _, by = config(root)
|
||||
item = c['item']
|
||||
evidence = training_terminal(item, tc)
|
||||
if evidence != c['training'] or c['item_gpu_cap'] != tc['gpu_cap']:
|
||||
raise ValueError('Original training-to-postfit evidence changed')
|
||||
lock = (root/'run.lock').open('a')
|
||||
fcntl.flock(lock, fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
gpu_lock = Path(f"/tmp/meltmind-candidate-postfit-{c['gpu_uuid']}.lock").open('a')
|
||||
fcntl.flock(gpu_lock, fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if (root/'started.json').exists():
|
||||
raise FileExistsError('One candidate postfit attempt')
|
||||
os.sched_setaffinity(0,c['coordinator_cpus'])
|
||||
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
|
||||
counters = dict(self_process_time=started_cpu, children_user=child_start.ru_utime,
|
||||
children_system=child_start.ru_stime)
|
||||
train = TRAINING[item][0]
|
||||
prior = evidence['training_gpu_seconds']
|
||||
accrued_gpu = 0.
|
||||
accrued_child = 0.
|
||||
in_flight = None
|
||||
records = []
|
||||
|
||||
def cpu():
|
||||
child = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
reaped = child.ru_utime + child.ru_stime - child_start.ru_utime - child_start.ru_stime
|
||||
return SETUP_CPU + time.process_time() - started_cpu + max(accrued_child,reaped)
|
||||
|
||||
def ledger():
|
||||
return dict(records=records,prediction_gpu_seconds=accrued_gpu,
|
||||
postfit_cpu_seconds=cpu(),training_gpu_seconds_once=prior,
|
||||
cumulative_item_gpu_seconds=prior+accrued_gpu,new_fits=0,new_decodes=0,no_retry=True)
|
||||
|
||||
budget(c,0,cpu(),5)
|
||||
save(root/'started.json',dict(item=item,pid=os.getpid(),unix=time.time(),training_gpu_seconds_once=prior,
|
||||
postfit_gpu_cap=POSTFIT_GPU,postfit_cpu_cap=POSTFIT_CPU,cpu_start_counters=counters,
|
||||
review_sha256=sha(root/'review.json'),new_fits=0,new_decodes=0))
|
||||
try:
|
||||
save(root/'models-adopted.json',evidence)
|
||||
freeze(root,'models',[root/'contract.json',root/'models-adopted.json',train/'complete.json',
|
||||
train/'training-terminal-git-freeze.json',train/'post-terminal-cost.json',
|
||||
*[Path(m[k]) for m in evidence['models'] for k in ('path','standardization')]])
|
||||
predictions = []
|
||||
for fold in range(5):
|
||||
accrued_gpu = max(accrued_gpu,60+time.monotonic()-started_wall)
|
||||
budget(c,accrued_gpu,cpu(),5-fold)
|
||||
(root/'jobs'/str(fold)).mkdir(parents=True,exist_ok=False)
|
||||
in_flight = time.monotonic()
|
||||
guard = run_prediction(root,c,fold,prior+accrued_gpu,FOLD_CPU)
|
||||
elapsed = max(60+time.monotonic()-in_flight,guard['gpu_seconds_charged'])
|
||||
in_flight = None
|
||||
accrued_gpu += elapsed
|
||||
accrued_child += guard['worker']['cpu_seconds'] if guard['worker'] else 0.
|
||||
records.append(dict(fold=fold,charged_gpu_seconds=elapsed,guard=guard))
|
||||
save(root/'resource-progress.json',ledger())
|
||||
if guard['status'] != 'PASS' or guard['monitor_errors'] or elapsed > FOLD_GPU:
|
||||
raise RuntimeError(f'Fold {fold} prediction stop')
|
||||
p = root/'jobs'/str(fold)/'prediction-records/manifest.json'
|
||||
predictions.extend(read(p)['entries'])
|
||||
prediction_identity(root,c,tc,by,predictions)
|
||||
path = root/'predictions-manifest.json'
|
||||
save(path,dict(entries=predictions,test_targets_read=False,new_fits=0))
|
||||
freeze(root,'predictions',[root/'contract.json',root/'models-adopted.json',path,
|
||||
root/'resource-progress.json',*map(Path,c['code_sha256'])])
|
||||
accrued_gpu = max(accrued_gpu,60+time.monotonic()-started_wall)
|
||||
budget(c,accrued_gpu,cpu(),0)
|
||||
g = supervise([sys.executable,'tools/phase3_followup_postfit_worker.py','score',str(root)],
|
||||
root/'score-guard',dict(cpu_seconds=SCORE_CPU,wall_seconds=1200,
|
||||
rss_bytes=16*2**30,disk_bytes=20*2**30))
|
||||
accrued_child += g['cpu_seconds']
|
||||
records.append(dict(mode='score',guard=g))
|
||||
if (g['status']!='PASS' or g['returncode']!=0 or g['monitor_errors']
|
||||
or cpu()+CLEANUP_CPU>POSTFIT_CPU):
|
||||
raise RuntimeError('Score or CPU limit')
|
||||
save(root/'complete.json',dict(status='COMPLETE',**ledger()))
|
||||
freeze(root,'terminal',[root/'contract.json',root/'complete.json',root/'score/result.json',
|
||||
root/'score/target-access.jsonl',root/'review.json'])
|
||||
final = cpu()
|
||||
save(root/'post-terminal-cost.json',dict(**(ledger() | {'postfit_cpu_seconds': final}),
|
||||
within_cap=final<=POSTFIT_CPU,training_complete_sha256=evidence['training_complete_sha256'],
|
||||
cpu_start_counters=counters))
|
||||
if final>POSTFIT_CPU:
|
||||
raise RuntimeError('CPU cap reached during terminal freeze')
|
||||
except BaseException as exc:
|
||||
if in_flight is not None:
|
||||
accrued_gpu += 60+time.monotonic()-in_flight
|
||||
if not any(r.get('mode')=='score' for r in records):
|
||||
accrued_gpu = max(accrued_gpu,60+time.monotonic()-started_wall)
|
||||
if (root/'complete.json').exists():
|
||||
save(root/'pre-failure-complete.json',read(root/'complete.json'))
|
||||
save(root/'complete.json',dict(status='STOPPED',reason=f'{type(exc).__name__}: {exc}',**ledger()))
|
||||
raise
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(Path(sys.argv[1]))
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Frozen candidate, roster, resource and custody checks for phase 3 postfit."""
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import psutil
|
||||
|
||||
from phase2_gate_outcome_review import validate_review
|
||||
from phase2_h1_worker_v2 import checked, sha
|
||||
from phase2_h2_s2_postfit_common import roster
|
||||
from phase2_home_freeze_io import verify
|
||||
from phase3_item_b_shared_common import ROOT as B_TRAIN, config as b_config
|
||||
from phase3_item_c_common import ROOT as C_TRAIN, config as c_config, read
|
||||
from phase3_seed1_postfit_common import normal_identity
|
||||
|
||||
RUNS = C_TRAIN.parent
|
||||
BASELINE = RUNS / 'phase2-h2-s2-postfit-2026-11-17'
|
||||
SEED = RUNS / 'phase3-seed1-postfit-2026-11-18'
|
||||
GPU = 'GPU-f1c9fd5a-e917-56e0-21fb-24035ba44a36'
|
||||
RULING = '1795055299'
|
||||
TRAINING = {
|
||||
'c': (C_TRAIN, c_config, '2ddecef3fac432ccc0267c468d5df4d3203e53ef',
|
||||
'TRAIN_COMPLETE_POSTFIT_REVIEW_PENDING'),
|
||||
'b': (B_TRAIN, b_config, '961ce62360003e7621f4fad6ae58648ef96d82af', 'TRAIN_COMPLETE_POSTFIT_PENDING'),
|
||||
}
|
||||
POSTFIT_GPU = 7200
|
||||
POSTFIT_CPU = 3600
|
||||
FOLD_GPU = 900
|
||||
FOLD_CPU = 300
|
||||
SCORE_CPU = 900
|
||||
SETUP_CPU = 180
|
||||
CLEANUP_CPU = 120
|
||||
|
||||
|
||||
def root_for(item):
|
||||
return RUNS / f'phase3-item-{item}-postfit-2026-11-19'
|
||||
|
||||
|
||||
def frozen_file(proof, path, digest):
|
||||
path = Path(path)
|
||||
if proof['files'].get(str(path.resolve())) != digest:
|
||||
raise ValueError(f'File omitted from the required freeze: {path}')
|
||||
return checked(path, digest)
|
||||
|
||||
|
||||
def training_terminal(item, tc):
|
||||
train, _, commit, expected_status = TRAINING[item]
|
||||
if verify(train, 'implementation')['commit'] != commit:
|
||||
raise ValueError('Candidate training source changed')
|
||||
if (train / 'global-stop.json').exists():
|
||||
raise PermissionError('Original training stopped')
|
||||
for proc in psutil.process_iter(['cmdline']):
|
||||
args = proc.info['cmdline'] or []
|
||||
if str(train) in args and any(Path(a).name.startswith(f'phase3_item_{item}') for a in args):
|
||||
raise RuntimeError('Candidate training process still alive')
|
||||
proof = verify(train, 'training-terminal')
|
||||
complete = train / 'complete.json'
|
||||
done = read(frozen_file(proof, complete, sha(complete)))
|
||||
manifest = train / 'models.json'
|
||||
models = read(frozen_file(proof, manifest, sha(manifest)))
|
||||
tail_path = train / 'post-terminal-cost.json'
|
||||
tail = read(tail_path)
|
||||
entries = {e['id']: e for e in done['entries']}
|
||||
by_fold = {m['fold']: m for m in models}
|
||||
if (done['status'] != expected_status or done['failure'] is not None or done['never_attempted']
|
||||
or any(done[field] is not False for field in ('prediction_started', 'scoring_started', 'test_targets_read'))
|
||||
or len(done['entries']) != 5 or len(models) != 5
|
||||
or set(entries) != set(range(5)) or set(by_fold) != set(range(5))):
|
||||
raise ValueError('Exactly five clean original terminal models required')
|
||||
costs = [entries[i]['gpu_seconds_charged'] for i in range(5)]
|
||||
expected = tc['preparation_charge_gpu_seconds'] + sum(costs)
|
||||
final = tail['cumulative_gpu_seconds']
|
||||
if (not all(math.isfinite(x) and x >= 0 for x in costs + [final])
|
||||
or not math.isclose(expected, done['cumulative_gpu_seconds'], abs_tol=1e-8, rel_tol=0)
|
||||
or not expected - 1e-8 <= final <= tc['gpu_cap'] - POSTFIT_GPU
|
||||
or done['postfit_gpu_reserve'] != POSTFIT_GPU or tail['postfit_gpu_reserve'] != POSTFIT_GPU
|
||||
or tail['training_complete_sha256'] != sha(complete) or tail['within_cap'] is not True
|
||||
or tail['freeze_tail_charged_once'] is not True or tail['postfit_started'] is not False):
|
||||
raise ValueError('Invalid training or freeze-tail accounting')
|
||||
bound_models = []
|
||||
for j in tc['jobs']:
|
||||
i = j['id']
|
||||
jr = train / 'jobs' / str(i)
|
||||
e = entries[i]
|
||||
guard = read(frozen_file(proof, jr / 'complete.json', e['guard_sha256']))
|
||||
receipt = guard['worker']
|
||||
if (e['status'] != 'PASS' or e['returncode'] != 0 or guard['status'] != 'PASS'
|
||||
or guard['reasons'] or guard['monitor_errors'] != [] or receipt['status'] != 'PASS'
|
||||
or receipt['returncode'] != 0 or type(receipt['monitor_errors']) is not int
|
||||
or receipt['monitor_errors'] != 0 or receipt != read(jr / 'guards/train.receipt.json')):
|
||||
raise ValueError(f'Fold {i} guard or worker failure')
|
||||
result = read(frozen_file(proof, jr / 'worker/result.json', guard['worker_result_sha256']))
|
||||
weights = jr / 'worker/last-epoch200.pt'
|
||||
std = jr / 'worker/standardization.json'
|
||||
if (result != by_fold[i] or result['status'] != 'COMPLETE' or result['fold'] != i
|
||||
or result['completed_epochs'] != 200 or result['optimizer_steps'] != j['target_steps']
|
||||
or result['learning_parts'] != len(j['learning'])
|
||||
or result['learning_nodes_per_epoch'] != j['learning_nodes']
|
||||
or any(result[field] is not False for field in
|
||||
('test_prediction_started', 'test_targets_read', 'validation_used_for_selection'))
|
||||
or result['checkpoint'] != str(weights)):
|
||||
raise ValueError(f'Fold {i} final checkpoint identity')
|
||||
frozen_file(proof, weights, result['checkpoint_sha256'])
|
||||
stats = read(frozen_file(proof, std, result['standardization_sha256']))
|
||||
normal_identity(stats, j)
|
||||
if stats['labels_read'] is not False:
|
||||
raise ValueError('Learning normalization may not use labels')
|
||||
if item == 'b':
|
||||
context = stats['context']
|
||||
expected_context = [dict(case=case, nodes=tc['context'][case]['nodes'],
|
||||
valid_nodes=tc['context'][case]['nodes'] if tc['context'][case]['status'] == 'GEOMETRY_COMPLETE' else 0)
|
||||
for case in j['learning']]
|
||||
if (context['parts'] != expected_context or context['labels_read'] is not False
|
||||
or context['valid_nodes'] != sum(r['valid_nodes'] for r in expected_context)
|
||||
or len(context['mean']) != 2 or len(context['scale']) != 2
|
||||
or not np.isfinite(context['mean'] + context['scale']).all() or min(context['scale']) <= 0):
|
||||
raise ValueError('Original learning-only context normalization')
|
||||
bound_models.append(dict(fold=i, path=str(weights), sha256=result['checkpoint_sha256'],
|
||||
standardization=str(std), standardization_sha256=result['standardization_sha256']))
|
||||
return dict(models=bound_models, training_gpu_seconds=final, training_terminal_commit=proof['commit'],
|
||||
training_complete_sha256=sha(complete), training_cost_sha256=sha(tail_path),
|
||||
training_contract_sha256=sha(train / 'contract.json'))
|
||||
|
||||
|
||||
def config(root, *, review=True):
|
||||
c = read(root / 'contract.json')
|
||||
item = c['item']
|
||||
train, load_training, _, _ = TRAINING[item]
|
||||
if (root.resolve() != root_for(item) or c['ruling'] != RULING or c['gpu_uuid'] != GPU
|
||||
or c['no_retry'] is not True or c['new_fits'] != 0 or c['new_decodes'] != 0
|
||||
or c['worker_cpus'] != [2, 3] or c['coordinator_cpus'] != [16, 17]):
|
||||
raise PermissionError('Frozen candidate postfit scope')
|
||||
verify(root, 'implementation')
|
||||
if review:
|
||||
validate_review(root)
|
||||
for path, digest in {**c['source_sha256'], **c['code_sha256']}.items():
|
||||
checked(path, digest)
|
||||
tc, pilot = load_training(train)
|
||||
if c['item_gpu_cap'] != tc['gpu_cap'] or c['postfit_gpu_cap'] != POSTFIT_GPU or c['postfit_cpu_cap'] != POSTFIT_CPU:
|
||||
raise PermissionError('Original item budget required')
|
||||
if c['jobs'] != [dict(id=j['id'], expected_parts=len(j['test'])) for j in tc['jobs']]:
|
||||
raise ValueError('Same five fixed test folds required')
|
||||
by = roster(read(BASELINE / 'contract.json'), pilot)
|
||||
if set(c['seed0_predictions']) != set(by):
|
||||
raise ValueError('Same 552 baseline predictions required')
|
||||
if item == 'b':
|
||||
statuses = [row['status'] for row in tc['context'].values()]
|
||||
if (set(tc['context']) != set(by) or len(statuses) != 552
|
||||
or statuses.count('GEOMETRY_COMPLETE') != 510 or statuses.count('SCIENTIFIC_MISSING') != 42):
|
||||
raise ValueError('Original context coverage and missingness required')
|
||||
return c, tc, pilot, by
|
||||
|
||||
|
||||
def budget(c, gpu, cpu, remaining):
|
||||
if not all(math.isfinite(x) and x >= 0 for x in (gpu, cpu)) or type(remaining) is not int or remaining not in range(6):
|
||||
raise ValueError('Invalid postfit accounting')
|
||||
reserved = gpu + FOLD_GPU * remaining
|
||||
train = c['training']['training_gpu_seconds']
|
||||
other = sum(v for item, v in c['phase_reservations'].items() if item != c['item'])
|
||||
if reserved > POSTFIT_GPU or train + reserved > c['item_gpu_cap'] or other + train + reserved > 720000:
|
||||
raise RuntimeError('Original item/phase 3 GPU envelope exhausted')
|
||||
if cpu + FOLD_CPU * remaining + SCORE_CPU + CLEANUP_CPU > POSTFIT_CPU:
|
||||
raise RuntimeError('Original postfit CPU envelope exhausted')
|
||||
|
||||
|
||||
def checkpoint_identity(blob, job, c):
|
||||
expected = dict(seed=0, fold=job['id'], completed_epochs=200, optimizer_steps=job['target_steps'],
|
||||
contract_sha256=c['training']['training_contract_sha256'], role='last_epoch_only')
|
||||
if any(blob.get(k) != v for k, v in expected.items()):
|
||||
raise ValueError('Candidate last-epoch checkpoint identity')
|
||||
|
||||
|
||||
def prediction_identity(root, c, tc, by, entries):
|
||||
expected = {(j['id'], case) for j in tc['jobs'] for case in j['test']}
|
||||
keys = {(e['fold'], e['case']) for e in entries}
|
||||
if len(entries) != 552 or len(keys) != 552 or keys != expected:
|
||||
raise ValueError('Full same-domain roster requires 552 distinct predictions')
|
||||
for e in entries:
|
||||
case = e['case']
|
||||
base = c['seed0_predictions'][case]
|
||||
row = by[case]
|
||||
expected_path = root / 'jobs' / str(e['fold']) / 'prediction-records' / f'{case}.npz'
|
||||
if (e['component_id'] != row['component_id'] or e['path'] != str(expected_path)
|
||||
or e['nodes'] != row['nodes'] or e['query_nodes'] != base['query_nodes']
|
||||
or e['seed0_sha256'] != base['sha256']
|
||||
or e['raw_ids_sha256'] != row['v5_cache']['output_sha256']['raw_ids.npy']):
|
||||
raise ValueError('Prediction pairing or original raw ID mismatch')
|
||||
for key, count in [('negative_full_predictions', e['nodes']), ('negative_query_predictions', e['query_nodes'])]:
|
||||
if type(e[key]) is not int or not 0 <= e[key] <= count:
|
||||
raise ValueError('Invalid negative count')
|
||||
checked(expected_path, e['sha256'])
|
||||
checked(base['path'], base['sha256'])
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Candidate postfit guard: bounded selected-GPU wait, 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,expected_parts):
|
||||
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 receipt and (type(receipt.get('monitor_errors')) is not int or receipt['monitor_errors'] != 0 or receipt.get('returncode') != 0):add('WORKER_MONITOR_ERRORS')
|
||||
if not result or result.get('status')!='COMPLETE' or result.get('parts')!=expected_parts:add('INCOMPLETE_FOLD')
|
||||
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>900 or cpu_seconds>cpu_cap:add('FINAL_RESOURCE_LIMIT')
|
||||
return out
|
||||
|
||||
def run_prediction(queue,c,fold,prior_gpu,cpu_cap):
|
||||
root=queue/'jobs'/str(fold);gpu_uuid=c['gpu_uuid'];expected_parts=c['jobs'][fold]['expected_parts']
|
||||
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/phase3_followup_postfit_worker.py','predict',str(queue),str(fold)]
|
||||
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/'prediction-records'):reason('RECORDED_VRAM_LIMIT')
|
||||
def watch():
|
||||
while not done.is_set():
|
||||
try:
|
||||
scan();mem,util=device_usage(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(queue)>20*2**30:reason('DISK_LIMIT')
|
||||
if elapsed()>=895: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:
|
||||
wait_start=time.monotonic();waiting=[]
|
||||
while True:
|
||||
mem,util=device_usage(gpu_uuid);waiting.append(dict(unix=time.time(),bytes=mem,utilization=util))
|
||||
save(root/'recovery-idle-wait.json',dict(samples=waiting,limit_seconds=c['idle_wait_seconds'],worker_started=False))
|
||||
if requested:raise RuntimeError('Signal received during idle wait')
|
||||
duration=time.monotonic()-wait_start
|
||||
if duration>c['idle_wait_seconds']:raise RuntimeError('SELECTED_GPU_BUSY_AFTER_BOUNDED_WAIT_NO_RETRY')
|
||||
if mem<=128*2**20 and util==0:break
|
||||
if duration>=c['idle_wait_seconds']:raise RuntimeError('SELECTED_GPU_BUSY_AFTER_BOUNDED_WAIT_NO_RETRY')
|
||||
time.sleep(min(.5,max(0.,c['idle_wait_seconds']-(time.monotonic()-wait_start))))
|
||||
for i in range(3):
|
||||
mem,util=device_usage(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)
|
||||
if requested:raise RuntimeError('Signal received during setup')
|
||||
thread=threading.Thread(target=watch,daemon=True);thread.start()
|
||||
remaining=900-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=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/'prediction-records/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
|
||||
duration=elapsed();reasons=final_reasons(reasons,receipt,result,tracker,duration,totalcpu,cpu_cap,expected_parts)
|
||||
out=dict(status='PASS' if not reasons else 'STOPPED',reasons=reasons,monitor_errors=errors,worker=receipt,recorded_memory=tracker.as_dict(),gpu_seconds_charged=duration,cpu_seconds_charged=totalcpu,cumulative_item_gpu_seconds=prior_gpu+duration,no_retry=True)
|
||||
save(root/'prediction-guard.json',out);return out
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Frozen same-roster component statistics and pre-specified candidate decisions."""
|
||||
import math
|
||||
|
||||
from phase3_seed1_postfit_statistics import comparisons as seed_comparisons
|
||||
from r4bc_common import paired_difference
|
||||
|
||||
|
||||
def comparisons(rows, candidate):
|
||||
# This is the same estimator and bootstrap as the independently reviewed seed result.
|
||||
out = seed_comparisons([dict(row, seed1=row[candidate]) for row in rows])
|
||||
for m in out.values():
|
||||
m['means'][candidate] = m['means'].pop('seed1')
|
||||
m['components'][candidate] = m['components'].pop('seed1')
|
||||
m['part_counts'][candidate] = m['part_counts'].pop('seed1')
|
||||
m['undefined_parts'][candidate] = m['undefined_parts'].pop('seed1')
|
||||
m['candidate_minus_seed0'] = m.pop('seed1_minus_seed0')
|
||||
return out
|
||||
|
||||
|
||||
def decision(item, metrics, seed_metrics):
|
||||
primary = 'last_location' if item == 'c' else 'relative_l2'
|
||||
delta = metrics[primary]['candidate_minus_seed0']
|
||||
field = metrics['relative_l2']['candidate_minus_seed0']
|
||||
if delta['components'] != 204 or field['components'] != 204:
|
||||
return dict(status='INCOMPLETE_PRIMARY_PAIR_SUPPORT', primary=primary)
|
||||
if seed_metrics is None or seed_metrics[primary]['seed1_minus_seed0']['components'] != 204:
|
||||
return dict(status='WAIT_SEED_REFERENCE', primary=primary)
|
||||
noise = seed_metrics[primary]['seed1_minus_seed0']
|
||||
if noise['component_ids'] != delta['component_ids']:
|
||||
raise ValueError('Seed and candidate contrasts must have identical components')
|
||||
magnitude_pass = abs(delta['value']) > abs(noise['value'])
|
||||
if item == 'c':
|
||||
gate = delta['value'] <= -.010 and delta['high'] < 0 and field['high'] < .001
|
||||
else:
|
||||
gate = field['high'] < -.001
|
||||
return dict(status='PASSES_OLD_CORPUS_SCREEN' if gate and magnitude_pass else 'DOES_NOT_PASS_FIXED_SCREEN',
|
||||
primary=primary, registered_metric_gate=gate, exceeds_same_endpoint_seed_difference=magnitude_pass,
|
||||
signed_candidate_delta=delta['value'], signed_seed1_minus_seed0=noise['value'],
|
||||
independent_fresh_family_confirmation=False)
|
||||
|
||||
|
||||
def tail_comparisons(rows, item, include_seed):
|
||||
groups = {}
|
||||
for row in rows:
|
||||
groups.setdefault(row['component_id'], []).append(row)
|
||||
arms = [item, 'seed0'] + (['seed1'] if include_seed else [])
|
||||
values = {}
|
||||
for key in ('E_tail', 'Miss', 'False_alarm'):
|
||||
by_arm = {arm:{g:math.fsum(r['tail']['arms'][arm]['overlap'][key] for r in parts) / len(parts)
|
||||
for g, parts in groups.items()} for arm in arms}
|
||||
values[key] = dict(
|
||||
means={arm:math.fsum(v.values())/len(v) for arm,v in by_arm.items()},
|
||||
candidate_minus_seed0=paired_difference(by_arm[item], by_arm['seed0']),
|
||||
seed1_minus_seed0=paired_difference(by_arm['seed1'], by_arm['seed0']) if include_seed else None,
|
||||
)
|
||||
return dict(metrics=values, parts=len(rows), components=len(groups), secondary_endpoint='E_tail',
|
||||
seed1_regional_status='COMPLETE' if include_seed else 'NOT_COMPUTED',
|
||||
constant_truth_parts=sum(r['tail']['truth']['constant_field'] for r in rows),
|
||||
truth_threshold_tied_parts=sum(r['tail']['truth']['plateau_nodes'] > 1 for r in rows),
|
||||
arms={arm:dict(
|
||||
threshold_tied_parts=sum(r['tail']['arms'][arm]['prediction']['plateau_nodes'] > 1 for r in rows),
|
||||
peak={domain:dict(
|
||||
certified=sum(r['tail']['arms'][arm][domain]['certified'] for r in rows),
|
||||
near_boundary=sum(r['tail']['arms'][arm][domain]['near_boundary'] for r in rows),
|
||||
trivial_radius=sum(r['tail']['arms'][arm][domain]['trivial_radius'] for r in rows),
|
||||
categories={key:sum(r['tail']['arms'][arm][domain]['category'] == key for r in rows)
|
||||
for key in sorted({r['tail']['arms'][arm][domain]['category'] for r in rows})},
|
||||
) for domain in ('query','full')},
|
||||
) for arm in arms})
|
||||
@@ -0,0 +1,269 @@
|
||||
"""Label-free candidate inference and one custody pass after all predictions freeze."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from phase2_b1213_features import cached
|
||||
from phase2_h1_worker_v2 import checked, save, sha
|
||||
from phase2_h2_data import cached as original_cache
|
||||
from phase2_h2_s1_test_data import load_test_part
|
||||
from phase2_home_freeze_io import verify
|
||||
from phase2_residual_math import decode_seconds
|
||||
from phase3_followup_postfit_common import (
|
||||
BASELINE, SEED, checkpoint_identity, config, frozen_file, prediction_identity, read,
|
||||
)
|
||||
from phase3_followup_postfit_statistics import comparisons, decision, tail_comparisons
|
||||
from phase3_item_b_data import encode, read_context
|
||||
from phase3_seed1_postfit_statistics import summary as seed_summary
|
||||
from phase3_seed1_postfit_worker import paired_query
|
||||
from phase3_seed1_v2_common import fold_view
|
||||
from s2_custody_common import prediction_inputs
|
||||
from s2_custody_statistics import part_metrics
|
||||
from s2_tail_diagnostic_math import peak_diagnostic, tail_error, tail_membership, weights
|
||||
|
||||
|
||||
def predict(root, fold):
|
||||
import torch
|
||||
from phase2_h2_data import arguments, to_device
|
||||
from phase2_h2_model import H2Geo
|
||||
from phase3_item_b_model import H2Context
|
||||
|
||||
c, tc, pilot, by = config(root)
|
||||
if fold not in range(5):
|
||||
raise ValueError('Original five prediction folds only')
|
||||
verify(root, 'models')
|
||||
if read(root/'models-adopted.json') != c['training']:
|
||||
raise ValueError('Adopted candidate models differ from binding')
|
||||
view = fold_view(pilot, fold)
|
||||
job = tc['jobs'][fold]
|
||||
m = c['training']['models'][fold]
|
||||
stats = read(checked(m['standardization'], m['standardization_sha256']))
|
||||
if (os.environ.get('CUDA_VISIBLE_DEVICES') != c['gpu_uuid']
|
||||
or os.environ.get('PYTORCH_CUDA_ALLOC_CONF') != 'expandable_segments:True'):
|
||||
raise ValueError('Wrong assigned device or allocator')
|
||||
os.sched_setaffinity(0, c['worker_cpus'])
|
||||
torch.set_num_threads(1)
|
||||
torch.set_num_interop_threads(1)
|
||||
torch.backends.cuda.matmul.allow_tf32 = False
|
||||
torch.backends.cudnn.allow_tf32 = False
|
||||
dest = root/'jobs'/str(fold)/'prediction-records'
|
||||
dest.mkdir(exist_ok=False)
|
||||
torch.cuda.set_device(0)
|
||||
torch.cuda.init()
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
start = time.monotonic()
|
||||
cpu = time.process_time()
|
||||
entries = []
|
||||
|
||||
def record():
|
||||
return dict(fold=fold, parts=len(entries), wall_seconds=time.monotonic()-start,
|
||||
cpu_seconds=time.process_time()-cpu, test_targets_read=False,
|
||||
peak_allocated_bytes=torch.cuda.max_memory_allocated(),
|
||||
peak_reserved_bytes=torch.cuda.max_memory_reserved())
|
||||
|
||||
try:
|
||||
blob = torch.load(checked(m['path'], m['sha256']), map_location='cpu', weights_only=False)
|
||||
checkpoint_identity(blob, job, c)
|
||||
model = (H2Geo() if c['item']=='c' else H2Context()).cuda()
|
||||
model.load_state_dict(blob['model'], strict=True)
|
||||
model.eval()
|
||||
del blob
|
||||
save(dest/'environment.json', dict(fold=fold, checkpoint_sha256=m['sha256'], model_dtype='FP32',
|
||||
gpu_uuid=c['gpu_uuid'], torch=torch.__version__, allocator=str(torch.cuda.memory._snapshot().get('allocator_settings',{}))))
|
||||
with torch.no_grad():
|
||||
for case in job['test']:
|
||||
row = by[case]
|
||||
data = load_test_part(view, case, stats)
|
||||
if c['item'] == 'b':
|
||||
extra, valid = read_context(view, tc, case)
|
||||
context = encode(extra, valid, stats['context'])
|
||||
data['x'] = torch.cat([data['x'], torch.from_numpy(context)], dim=1)
|
||||
data = to_device(data, 'cuda')
|
||||
residual = model(*arguments(data), checkpoint_blocks=False)
|
||||
if not bool(torch.isfinite(residual).all()):
|
||||
raise ValueError('Nonfinite candidate prediction')
|
||||
seconds = decode_seconds(residual.cpu().numpy(), data['F'], job['c'], data['t_set'])
|
||||
torch.cuda.synchronize()
|
||||
q = prediction_inputs(row)
|
||||
base = c['seed0_predictions'][case]
|
||||
with np.load(checked(base['path'],base['sha256']), allow_pickle=False) as old:
|
||||
ix = paired_query(data['raw_ids'], q, old)
|
||||
if len(seconds) != row['nodes'] or len(ix) != base['query_nodes']:
|
||||
raise ValueError('Prediction support mismatch')
|
||||
path = dest/f'{case}.npz'
|
||||
np.savez_compressed(path, seconds=seconds, raw_ids=data['raw_ids'], pred=seconds[ix],
|
||||
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=fold, path=str(path),
|
||||
sha256=sha(path), nodes=row['nodes'], query_nodes=len(ix), seed0_sha256=base['sha256'],
|
||||
raw_ids_sha256=row['v5_cache']['output_sha256']['raw_ids.npy'],
|
||||
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', **record()))
|
||||
del data, residual, seconds
|
||||
save(dest/'manifest.json', dict(entries=entries, test_targets_read=False))
|
||||
save(dest/'result.json', dict(status='COMPLETE', **record()))
|
||||
except BaseException as exc:
|
||||
save(dest/'failure.json', dict(status='FAILED', reason=f'{type(exc).__name__}: {exc}', **record()))
|
||||
raise
|
||||
|
||||
|
||||
def same_rows(rows, by, entries):
|
||||
expected = {(e['case'], e['component_id'], e['fold']) for e in entries}
|
||||
observed = {(r['case'], r['component_id'], r['fold']) for r in rows}
|
||||
if len(rows) != 552 or observed != expected or {r['case'] for r in rows} != set(by):
|
||||
raise ValueError('Reference score roster/pairing differs')
|
||||
return {r['case']:r for r in rows}
|
||||
|
||||
|
||||
def seed_reference(by, entries, old_rows, regional):
|
||||
if not (SEED/'post-terminal-cost.json').exists():
|
||||
return None, {}, None
|
||||
terminal = verify(SEED, 'terminal')
|
||||
pred_proof = verify(SEED, 'predictions')
|
||||
result_path = SEED/'score/result.json'
|
||||
manifest = SEED/'predictions-manifest.json'
|
||||
done_path = SEED/'complete.json'
|
||||
done = read(frozen_file(terminal, done_path, sha(done_path)))
|
||||
cost = read(SEED/'post-terminal-cost.json')
|
||||
if done['status'] != 'COMPLETE' or cost['within_cap'] is not True:
|
||||
return None, {}, None
|
||||
score = read(frozen_file(terminal, result_path, sha(result_path)))
|
||||
if score['status'] != 'COMPLETE' or not score['review_sha256'].startswith('7b4da089'):
|
||||
raise ValueError('Wrong seed1 result or review')
|
||||
srows = same_rows(score['rows'], by, entries)
|
||||
if any(srows[k]['seed0'] != r['H2'] for k,r in old_rows.items()):
|
||||
raise ValueError('Seed1 did not use the same frozen seed0 metrics')
|
||||
pooled = seed_summary(score['rows'])['pooled']
|
||||
if pooled != score['pooled']:
|
||||
raise ValueError('Seed paired summaries differ from frozen result')
|
||||
manifest_entries = read(frozen_file(pred_proof, manifest, sha(manifest)))['entries']
|
||||
s_preds = same_rows(manifest_entries, by, entries) if regional else {}
|
||||
if regional:
|
||||
for e in entries:
|
||||
s = s_preds[e['case']]
|
||||
if any(s[k] != e[k] for k in ('seed0_sha256','raw_ids_sha256','nodes','query_nodes')):
|
||||
raise ValueError('Seed full-domain prediction identity differs')
|
||||
checked(s['path'], s['sha256'])
|
||||
return pooled, s_preds, dict(terminal_commit=terminal['commit'], score_sha256=sha(result_path),
|
||||
prediction_manifest_sha256=sha(manifest))
|
||||
|
||||
|
||||
def full_prediction(z, raw, ix, e):
|
||||
seconds = z['seconds']
|
||||
if (seconds.shape != raw.shape or not np.array_equal(z['raw_ids'],raw)
|
||||
or not np.array_equal(z['pred'], seconds[ix]) or not np.isfinite(seconds).all()
|
||||
or int(np.sum(seconds<0)) != e['negative_full_predictions']
|
||||
or int(np.sum(seconds[ix]<0)) != e['negative_query_predictions']):
|
||||
raise ValueError('Nonfinite or inconsistent frozen full/query prediction')
|
||||
return seconds
|
||||
|
||||
|
||||
def tail_diagnostics(pilot, case, raw, q, ix, truth, predictions):
|
||||
geom = pilot['geometry'][case]
|
||||
with np.load(checked(geom['path'], geom['sha256']), allow_pickle=False) as z:
|
||||
points, mass, rg = z['points'], z['mass'], float(z['rg'])
|
||||
if not np.array_equal(z['raw_ids'],raw) or not np.array_equal(mass,original_cache(pilot,case,'mass')):
|
||||
raise ValueError('Frozen geometry IDs or lumped masses differ')
|
||||
truth = np.asarray(truth, np.float64)
|
||||
w = weights(mass)
|
||||
a, td = tail_membership(truth,w)
|
||||
arms = {}
|
||||
for arm, field in predictions.items():
|
||||
p, pd = tail_membership(field,w)
|
||||
arms[arm] = dict(prediction=pd, overlap=tail_error(a,p,w),
|
||||
full=peak_diagnostic(truth,field,points,raw,rg,w=w,true_tail=a),
|
||||
query=peak_diagnostic(truth[ix],field[ix],points[ix],q['raw_ids'],rg))
|
||||
return dict(truth=td, arms=arms, Rg=rg)
|
||||
|
||||
|
||||
def score(root):
|
||||
c, tc, pilot, by = config(root)
|
||||
verify(root,'models')
|
||||
if read(root/'models-adopted.json') != c['training']:
|
||||
raise ValueError('Adopted model evidence differs')
|
||||
proof = verify(root,'predictions')
|
||||
manifest = root/'predictions-manifest.json'
|
||||
entries = read(frozen_file(proof,manifest,sha(manifest)))['entries']
|
||||
prediction_identity(root,c,tc,by,entries)
|
||||
os.sched_setaffinity(0,c['worker_cpus'])
|
||||
item = c['item']
|
||||
baseline_path = BASELINE/'score/result.json'
|
||||
baseline = read(checked(baseline_path,c['source_sha256'][str(baseline_path)]))
|
||||
if baseline['status'] != 'COMPLETE':
|
||||
raise ValueError('Original seed0 score incomplete')
|
||||
old = same_rows(baseline['rows'],by,entries)
|
||||
seed, seed_preds, seed_evidence = seed_reference(by,entries,old,item=='c')
|
||||
dest = root/'score'
|
||||
dest.mkdir(exist_ok=False)
|
||||
save(dest/'review-consumed.json',dict(unix=time.time(),review_sha256=sha(root/'review.json'),
|
||||
predictions_commit=proof['commit'],before_target_values=True,seed_reference=seed_evidence))
|
||||
rows = []
|
||||
for e in entries:
|
||||
case = e['case']
|
||||
row = by[case]
|
||||
raw = cached(row,'raw_ids')
|
||||
base = c['seed0_predictions'][case]
|
||||
r = dict(case=case, component_id=e['component_id'], fold=e['fold'], seed0=old[case]['H2'])
|
||||
with np.load(e['path'],allow_pickle=False) as z, np.load(base['path'],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 = paired_query(raw,q,original)
|
||||
candidate = full_prediction(z,raw,ix,e)
|
||||
predicted = {item:candidate, 'seed0':full_prediction(original,raw,ix,base)}
|
||||
if seed_preds:
|
||||
s = seed_preds[case]
|
||||
with np.load(s['path'],allow_pickle=False) as replica:
|
||||
if not np.array_equal(paired_query(raw,q,replica),ix):
|
||||
raise ValueError('Seed1 query differs')
|
||||
predicted['seed1'] = full_prediction(replica,raw,ix,s)
|
||||
# Fail closed before opening the one existing full-node target cache.
|
||||
with (dest/'target-access.jsonl').open('a') as receipt:
|
||||
receipt.write(json.dumps(dict(case=case,fold=e['fold'],role='test',
|
||||
target_sha256=row['v5_cache']['output_sha256']['seconds.npy'], unix=time.time()))+'\n')
|
||||
truth = cached(row,'seconds')
|
||||
if truth.shape != raw.shape or not np.isfinite(truth).all():
|
||||
raise ValueError('Wrong full-domain target')
|
||||
r[item] = part_metrics(candidate[ix],truth[ix],q['counts'],q['near_wall'],
|
||||
q['raw_ids'],q['coordinates_over_Rg'],int(case.split('_')[0]))
|
||||
if item == 'c':
|
||||
scale = pilot['parts'][case]['t_set']
|
||||
if not np.isfinite(scale) or scale <= 0:
|
||||
raise ValueError('Original positive time scale required')
|
||||
r['tail'] = tail_diagnostics(pilot,case,raw,q,ix,np.asarray(truth,np.float64)/scale,
|
||||
{a:np.asarray(p,np.float64)/scale for a,p in predicted.items()})
|
||||
else:
|
||||
r['context_valid'] = tc['context'][case]['status']=='GEOMETRY_COMPLETE'
|
||||
rows.append(r)
|
||||
save(dest/'progress.json',dict(parts=len(rows),unique_test_target_reads=len(rows)))
|
||||
metrics = comparisons(rows,item)
|
||||
result = dict(status='COMPLETE',item=item,parts=552,components=204,rows=rows,pooled=metrics,
|
||||
per_fold={str(f):comparisons([r for r in rows if r['fold']==f],item) for f in range(5)},
|
||||
decision=decision(item,metrics,seed),same_endpoint_seed_reference=seed,seed_evidence=seed_evidence,
|
||||
unique_test_target_reads=552,new_decodes=0,new_fits=0,negative_clipping=False,
|
||||
negative_predictions={arm:dict(full_nodes=sum(e['negative_full_predictions'] for e in es),
|
||||
query_nodes=sum(e['negative_query_predictions'] for e in es)) for arm,es in
|
||||
[(item,entries),('seed0',list(c['seed0_predictions'].values()))]})
|
||||
if item == 'c':
|
||||
result['tail'] = tail_comparisons(rows,item,bool(seed_preds))
|
||||
else:
|
||||
result['context_strata'] = {}
|
||||
for valid in (True,False):
|
||||
subset = [r for r in rows if r['context_valid'] is valid]
|
||||
result['context_strata'][str(valid)] = dict(parts=len(subset),
|
||||
components=len({r['component_id'] for r in subset}),metrics=comparisons(subset,item))
|
||||
result['uncached_partition_runtime'] = 'NOT_MEASURED'
|
||||
save(dest/'result.json',result)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
mode, root = sys.argv[1], Path(sys.argv[2])
|
||||
if mode=='predict' and len(sys.argv)==4:
|
||||
predict(root,int(sys.argv[3]))
|
||||
elif mode=='score' and len(sys.argv)==3:
|
||||
score(root)
|
||||
else:
|
||||
raise ValueError('Use predict root fold or score root')
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Prepare one candidate review binding with metadata and opaque hash checks."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
from phase2_h1_worker_v2 import save, sha
|
||||
from phase2_home_freeze_io import freeze, verify
|
||||
from phase3_followup_postfit_common import (
|
||||
BASELINE, GPU, RULING, SEED, TRAINING, budget, config, frozen_file, read,
|
||||
root_for, roster, training_terminal,
|
||||
)
|
||||
from track_a_h2_prepare import local_code_closure
|
||||
|
||||
BASE = Path(__file__).resolve().parents[1]
|
||||
TOOLS = BASE/'tools'
|
||||
B_TRAIN = TRAINING['b'][0]
|
||||
|
||||
|
||||
def prepare(item):
|
||||
start = time.process_time()
|
||||
root = root_for(item)
|
||||
if root.exists():
|
||||
raise FileExistsError('Inspect existing binding rather than duplicate it')
|
||||
train, load_training, _, _ = TRAINING[item]
|
||||
tc, pilot = load_training(train)
|
||||
evidence = training_terminal(item, tc)
|
||||
old = read(BASELINE/'contract.json')
|
||||
by = roster(old,pilot)
|
||||
baseline_proof = verify(BASELINE,'predictions')
|
||||
verify(BASELINE,'terminal')
|
||||
path = BASELINE/'predictions-manifest.json'
|
||||
entries = read(frozen_file(baseline_proof,path,sha(path)))['entries']
|
||||
seed0 = {r['case']:r for r in entries}
|
||||
for job in tc['jobs']:
|
||||
for case in job['test']:
|
||||
e, r = seed0[case], by[case]
|
||||
if (e['fold'],e['component_id'],e['nodes']) != (job['id'],r['component_id'],r['nodes']):
|
||||
raise ValueError('Original H2 seed0 identity')
|
||||
if len(entries)!=552 or set(by)!=set(seed0):
|
||||
raise ValueError('Complete baseline prediction support')
|
||||
sources={}
|
||||
paths = [train/n for n in ('contract.json','training-terminal-git-freeze.json','training-terminal-authorization.json',
|
||||
'complete.json','models.json','post-terminal-cost.json')]
|
||||
paths += [BASELINE/n for n in ('contract.json','predictions-manifest.json','predictions-git-freeze.json',
|
||||
'terminal-git-freeze.json','score/result.json')]
|
||||
paths += [Path(tc['comparison_contract']), B_TRAIN/'contract.json']
|
||||
# Include the actual same-domain seed completion when already available.
|
||||
seed_cost = SEED/'post-terminal-cost.json'
|
||||
if seed_cost.exists() and read(seed_cost)['within_cap'] is True:
|
||||
seed_done = read(SEED/'complete.json')
|
||||
if seed_done['status'] == 'COMPLETE':
|
||||
t = verify(SEED,'terminal')
|
||||
p = SEED/'score/result.json'
|
||||
frozen_file(t,p,sha(p))
|
||||
paths += [seed_cost, SEED/'complete.json', SEED/'terminal-git-freeze.json',
|
||||
SEED/'predictions-git-freeze.json', SEED/'predictions-manifest.json', p]
|
||||
spec_dir = BASE/'references/2026-11-18'/f'phase3-item-{item}'
|
||||
paths += sorted(spec_dir.glob('*.md'))
|
||||
for p in paths:
|
||||
sources[str(p)] = sha(p)
|
||||
codes=local_code_closure([*TOOLS.glob('phase3_followup_postfit*.py'),Path(__file__),
|
||||
TOOLS/'test_phase3_followup_postfit.py',*(TOOLS/'s2_models').glob('*.py')])
|
||||
source_comparison=read(tc['comparison_contract'])
|
||||
comparison = dict(ruling=RULING,item=item,parts=552,components=204,folds=list(range(5)),source_comparison_sha256=tc['comparison_contract_sha256'],candidate_seed=0,baseline_seed=0,
|
||||
seed_noise='frozen same-domain seed1 minus seed0 with full 204-pair support',
|
||||
candidate_contrast=f'{item} minus H2 seed0',bootstrap=2000,bootstrap_seed=2026111408,
|
||||
query='original unique raw IDs, multiplicity, Rg, hard maximum, no clipping',
|
||||
new_fits=0,new_decodes=0,target_cache_reads=552,
|
||||
prospective_gate=source_comparison['old_corpus_gate' if item=='c' else 'test'],
|
||||
secondary='05344bac full-node final 1 percent volume and peak diagnostics' if item=='c' else None,
|
||||
context_missingness='report original valid and scientific-missing strata' if item=='b' else None,
|
||||
full_predictions_frozen_before_target_access=True,fresh_family_confirmation=False)
|
||||
# b's accepted static ledger is the later phase 3 allocation. Prior and later item
|
||||
# reservations stay intact. Replace only the current item's cost with its actual
|
||||
# training including freeze tail and its 7200-second postfit reservation.
|
||||
reservations=read(B_TRAIN/'contract.json')['phase_reservations']
|
||||
c=dict(item=item,ruling=RULING,gpu_uuid=GPU,worker_cpus=[2,3],coordinator_cpus=[16,17],
|
||||
training=evidence,item_gpu_cap=tc['gpu_cap'],phase_reservations=reservations,
|
||||
jobs=[dict(id=j['id'],expected_parts=len(j['test'])) for j in tc['jobs']],
|
||||
seed0_predictions=seed0,source_sha256=sources,code_sha256=codes,comparison_contract=str(root/'comparison-contract.json'),
|
||||
no_retry=True,no_auto_launch=True,new_fits=0,new_decodes=0,
|
||||
postfit_gpu_cap=7200,postfit_cpu_cap=3600)
|
||||
budget(c,0,180,5)
|
||||
root.mkdir()
|
||||
save(root/'comparison-contract.json',comparison)
|
||||
c['comparison_contract_sha256']=sha(root/'comparison-contract.json')
|
||||
save(root/'contract.json',c)
|
||||
receipt=root/'preparation-receipt.json'
|
||||
save(receipt,dict(status='PREPARED_PENDING_EXACT_PRE_SCORE_REVIEW',item=item,training=evidence,
|
||||
contract_sha256=sha(root/'contract.json'),code_files=len(codes),source_files=len(sources),
|
||||
setup_cpu_seconds=time.process_time()-start,launched=False,model_weights_decoded=False,
|
||||
prediction_started=False,scoring_started=False,test_targets_read=False))
|
||||
freeze(root,'implementation',[root/'contract.json',root/'comparison-contract.json',receipt,*map(Path,codes)])
|
||||
proof=root/'implementation-git-freeze.json'
|
||||
binding=dict(reviewed_commit=read(proof)['commit'],contract_sha256=sha(root/'contract.json'),
|
||||
implementation_proof_sha256=sha(proof),comparison_contract_sha256=c['comparison_contract_sha256'],
|
||||
code_sha256=codes)
|
||||
save(root/'expected-review-binding.json',binding)
|
||||
config(root,review=False)
|
||||
print(root, {k:v for k,v in binding.items() if k!='code_sha256'}, sha(root/'expected-review-binding.json'))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
prepare(sys.argv[1])
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Synthetic decision directions, matching domains and custody failures."""
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from phase3_followup_postfit_common import budget, checkpoint_identity, prediction_identity
|
||||
from phase3_followup_postfit_statistics import comparisons, decision
|
||||
from phase3_followup_postfit_worker import full_prediction, same_rows, score
|
||||
|
||||
|
||||
def contrast(value, high, n=204, ids=None):
|
||||
return dict(value=value, high=high, components=n, component_ids=ids or ['same'])
|
||||
|
||||
|
||||
def score_metrics(last, last_high, field, field_high):
|
||||
return dict(last_location=dict(candidate_minus_seed0=contrast(last,last_high)),
|
||||
relative_l2=dict(candidate_minus_seed0=contrast(field,field_high)))
|
||||
|
||||
|
||||
def seed_metrics(last, field):
|
||||
return dict(last_location=dict(seed1_minus_seed0=contrast(last,last)),
|
||||
relative_l2=dict(seed1_minus_seed0=contrast(field,field)))
|
||||
|
||||
|
||||
class PostfitContractTests(unittest.TestCase):
|
||||
def test_item_c_uses_hard_location_and_field_noninferiority(self):
|
||||
noise = seed_metrics(.004,.0002)
|
||||
self.assertEqual(decision('c',score_metrics(-.010,-.001,-.002,.00099),noise)['status'],
|
||||
'PASSES_OLD_CORPUS_SCREEN')
|
||||
for m in [score_metrics(-.00999,-.001,-.002,.0001),
|
||||
score_metrics(-.010,0,-.002,.0001),
|
||||
score_metrics(-.010,-.001,-.002,.001)]:
|
||||
self.assertEqual(decision('c',m,noise)['status'],'DOES_NOT_PASS_FIXED_SCREEN')
|
||||
|
||||
def test_item_b_uses_field_and_strict_seed_magnitude(self):
|
||||
noise = seed_metrics(.2,-.002)
|
||||
self.assertEqual(decision('b',score_metrics(.5,.6,-.003,-.00101),noise)['status'],
|
||||
'PASSES_OLD_CORPUS_SCREEN')
|
||||
for m in [score_metrics(.5,.6,-.003,-.001),score_metrics(.5,.6,-.002,-.00101)]:
|
||||
self.assertEqual(decision('b',m,noise)['status'],'DOES_NOT_PASS_FIXED_SCREEN')
|
||||
|
||||
def test_missing_or_different_seed_domain(self):
|
||||
m = score_metrics(-.02,-.01,-.003,-.002)
|
||||
self.assertEqual(decision('c',m,None)['status'],'WAIT_SEED_REFERENCE')
|
||||
seed = seed_metrics(.001,.002)
|
||||
seed['last_location']['seed1_minus_seed0']['component_ids'] = ['different']
|
||||
with self.assertRaises(ValueError):
|
||||
decision('c',m,seed)
|
||||
|
||||
def test_incomplete_components_hold(self):
|
||||
m=score_metrics(-.02,-.01,-.003,-.002)
|
||||
m['last_location']['candidate_minus_seed0']['components']=203
|
||||
self.assertEqual(decision('c',m,seed_metrics(.001,.002))['status'],'INCOMPLETE_PRIMARY_PAIR_SUPPORT')
|
||||
|
||||
def test_bootstrap_component_equal_and_signed(self):
|
||||
def arm(v):
|
||||
return {k:dict(value=v) for k in ('last_location','relative_l2','kendall_tau_b')}
|
||||
rows = [dict(case=f'p{i}',component_id=g,c=arm(d),seed0=arm(1.))
|
||||
for i,(g,d) in enumerate([('a',0.),('a',0.),('b',1.)])]
|
||||
self.assertEqual(comparisons(rows,'c')['relative_l2']['candidate_minus_seed0']['value'],-.5)
|
||||
|
||||
def test_checkpoint_seed_fold_epoch_and_contract(self):
|
||||
c=dict(training=dict(training_contract_sha256='fixed'))
|
||||
j=dict(id=1,target_steps=60000)
|
||||
ref=dict(seed=0,fold=1,completed_epochs=200,optimizer_steps=60000,
|
||||
contract_sha256='fixed',role='last_epoch_only')
|
||||
checkpoint_identity(ref,j,c)
|
||||
for field,bad in [('seed',1),('fold',0),('completed_epochs',199),('contract_sha256','foreign')]:
|
||||
with self.assertRaises(ValueError):
|
||||
checkpoint_identity(dict(ref,**{field:bad}),j,c)
|
||||
|
||||
def test_full_prediction_identity_rejects_short_or_bad_query(self):
|
||||
raw=np.array([1,3,4])
|
||||
ix=np.array([0,2])
|
||||
seconds=np.array([0.,-1.,2.])
|
||||
z=dict(raw_ids=raw,seconds=seconds,pred=seconds[ix])
|
||||
e=dict(negative_full_predictions=1,negative_query_predictions=0)
|
||||
np.testing.assert_equal(full_prediction(z,raw,ix,e),seconds)
|
||||
for bad in [dict(z,pred=np.zeros(2)),dict(z,raw_ids=raw[::-1]),dict(z,seconds=seconds[:2])]:
|
||||
with self.assertRaises(ValueError):
|
||||
full_prediction(bad,raw,ix,e)
|
||||
|
||||
def test_duplicate_or_wrong_fold_before_file_access(self):
|
||||
entries=[dict(fold=i%5,case=f'p{i}',component_id=f'g{i}') for i in range(552)]
|
||||
by={e['case']:e for e in entries}
|
||||
self.assertEqual(same_rows(entries,by,entries),by)
|
||||
with self.assertRaises(ValueError):
|
||||
same_rows([entries[0]]+entries[:-1],by,entries)
|
||||
jobs=[dict(id=i,test=[e['case'] for e in entries if e['fold']==i]) for i in range(5)]
|
||||
with patch('phase3_followup_postfit_common.checked',side_effect=AssertionError('early read')):
|
||||
with self.assertRaises(ValueError):
|
||||
prediction_identity(Path('/unused'),{},dict(jobs=jobs),by,[entries[0]]+entries[:-1])
|
||||
|
||||
def test_score_missing_review_or_predictions_stops_before_target_reader(self):
|
||||
root = Path('/unused')
|
||||
with patch('phase3_followup_postfit_worker.config',side_effect=PermissionError), \
|
||||
patch('phase3_followup_postfit_worker.cached') as targets:
|
||||
with self.assertRaises(PermissionError):
|
||||
score(root)
|
||||
targets.assert_not_called()
|
||||
with patch('phase3_followup_postfit_worker.config',return_value=({'training': {}}, {}, {}, {})), \
|
||||
patch('phase3_followup_postfit_worker.read',return_value={}), \
|
||||
patch('phase3_followup_postfit_worker.verify',side_effect=[{},FileNotFoundError]), \
|
||||
patch('phase3_followup_postfit_worker.cached') as targets:
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
score(root)
|
||||
targets.assert_not_called()
|
||||
|
||||
def test_budget_charges_existing_cost_once(self):
|
||||
c=dict(item='c',training=dict(training_gpu_seconds=105364.2),
|
||||
phase_reservations=dict(c=205200,b=172908),item_gpu_cap=205200)
|
||||
budget(c,2700,180,5)
|
||||
for gpu,cpu in [(2700.001,180),(2700,1080.001)]:
|
||||
with self.assertRaises(RuntimeError):
|
||||
budget(c,gpu,cpu,5)
|
||||
with self.assertRaises(RuntimeError):
|
||||
budget(dict(c,phase_reservations=dict(c=205200,b=700000)),0,180,5)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user