H1 approved bounded execution and synthetic acceptance
This commit is contained in:
1 parent
1153cd8c34
commit
ef7fe68833
20 files changed
+119566
No files matched your search
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"tests": 15,
|
||||
"cpu_seconds": 2.4609499999999995,
|
||||
"receipts": {
|
||||
"artifacts/phase2-h1-acceptance-2026-11-17/attempt-01/worker.receipt.json": "4fe8d682d6ad39c9bbd6496c11c9d92a63c9bd9fcf77d2dac59f0546c0bb93f6",
|
||||
"artifacts/phase2-h1-acceptance-2026-11-17/attempt-02-new-boundaries/worker.receipt.json": "7210fbb76072a0ab818fedac4aebd4512af8272babb7014d026ce91a2554d121"
|
||||
},
|
||||
"code_sha256": {
|
||||
"tools/phase2_h1_execution.py": "0eefd4031a928b709d133ae80a02223edf6066e1b6171753f6f9d7d32367a8b6",
|
||||
"tools/phase2_h1_worker_v2.py": "1543df85b615bb69b79bacd572074a7c77ae19dab110197601573a7e5805ed20",
|
||||
"tools/phase2_h1_geometry.py": "9f576322da3a6c62afda5ff26ad741c99c13ec86f73d9d45c3c4f0f9cfb058ac",
|
||||
"tools/phase2_h1_topology.py": "f8c9b5d68d04b65a2f7015c2af79a303d4d1b0146899bac0ee229ce1381bbf2d",
|
||||
"tools/phase2_h1_postfit.py": "e41ec6fc23dacd2bf086115b29813b98cda05db948574edc48a1c416774bd206",
|
||||
"tools/phase2_h1_decision.py": "96546522b7684205bb148b3503fe535f23ff70ef5acd1728ea512b848c84fb9c",
|
||||
"tools/phase2_residual_math.py": "ffbd9624dec79bdaabf95244fe87209055908f31a977e73ea4377045d6f8fe62",
|
||||
"tools/test_phase2_h1_execution.py": "c5621d2ea0045bf38129789410397cfe7303f96a8bd59e4146014f845bd12140"
|
||||
},
|
||||
"scope": "new synthetic integration, topology and coordinator boundaries; no real project arrays or model fit",
|
||||
"old_pure_math_tests_rerun": false,
|
||||
"reporting_coverage_reason_addition": "metadata-only reason field added after the tested scoring gate; no changed numerical calculation"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"cpu_seconds_charged": 1.319427,
|
||||
"attempts": [
|
||||
{
|
||||
"name": "worker",
|
||||
"status": "PASS",
|
||||
"cpu_seconds": 1.319427
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
test_branch_units_sign_and_strict_boundaries (__main__.PolicyTests) ... ok
|
||||
test_cost_gate_counts_failed_first_cell_and_factor (__main__.PolicyTests) ... ok
|
||||
test_failed_worker_peak_checked_and_retry_denied (__main__.PolicyTests) ... ok
|
||||
test_all_equal_no_finite_events_and_separate_infinite_classes (__main__.TopologyTests) ... ok
|
||||
test_empty_matching_denominators_undefined (__main__.TopologyTests) ... ok
|
||||
test_matching_is_maximum_one_to_one_and_lexicographic (__main__.TopologyTests) ... ok
|
||||
test_three_peaks_compound_multiplicity_and_increasing_map (__main__.TopologyTests) ... ok
|
||||
test_tie_plateau_is_one_merge_and_position_mass_weighted (__main__.TopologyTests) ... ok
|
||||
test_true_tet_graph_no_cross_component_shortcut (__main__.TopologyTests) ... ok
|
||||
test_real_tiny_xgb_clock_fp64_and_prediction_target_denial (__main__.WorkerIntegrationTests) ... ok
|
||||
test_role_overlap_is_rejected_before_access (__main__.WorkerIntegrationTests) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 11 tests in 1.054s
|
||||
|
||||
OK
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"command": [
|
||||
"/home/frank14f/optane/MeltMind/artifacts/gre24-reproduction-2026-11-15/environment/venv/bin/python",
|
||||
"tools/test_phase2_h1_execution.py",
|
||||
"-v"
|
||||
],
|
||||
"returncode": 0,
|
||||
"stop_reason": null,
|
||||
"cpu_seconds": 1.319427,
|
||||
"wall_seconds": 1.6363972519757226,
|
||||
"peak_tree_rss_bytes": 154644480,
|
||||
"peak_process_count": 2,
|
||||
"output_disk_bytes_before_receipt": 8192,
|
||||
"max_poll_gap_seconds": 0.21419689297908917,
|
||||
"poll_target_seconds": 0.05,
|
||||
"reaped_orphan_cpu_seconds": 0.0,
|
||||
"supervision": "sampled process-tree monitoring; wait4 final CPU/HWM; overshoot retained as failure",
|
||||
"gpu_visible": false,
|
||||
"cuda_device": "",
|
||||
"numerical_threads": 1,
|
||||
"retry": false,
|
||||
"monitor_errors": 0,
|
||||
"last_monitor_error": null
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"command": [
|
||||
"/home/frank14f/optane/MeltMind/artifacts/gre24-reproduction-2026-11-15/environment/venv/bin/python",
|
||||
"tools/test_phase2_h1_execution.py",
|
||||
"-v"
|
||||
],
|
||||
"limits": {
|
||||
"job_wall_seconds": 50,
|
||||
"job_cpu_seconds": 50,
|
||||
"total_cpu_seconds": 50,
|
||||
"tree_rss_bytes": 2147483648,
|
||||
"max_processes": 8,
|
||||
"disk_bytes": 104857600
|
||||
},
|
||||
"started_unix": 1794889239.2523327
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"cpu_seconds_charged": 1.1415229999999998,
|
||||
"attempts": [
|
||||
{
|
||||
"name": "worker",
|
||||
"status": "PASS",
|
||||
"cpu_seconds": 1.1415229999999998
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
test_missing_guard_receipt_marks_incomplete_and_closes_children (test_phase2_h1_execution.CoordinatorBoundaryTests) ... ok
|
||||
test_monitor_failure_stops_before_spawn (test_phase2_h1_execution.CoordinatorBoundaryTests) ... ok
|
||||
test_reservation_stop_never_spawns (test_phase2_h1_execution.CoordinatorBoundaryTests) ... ok
|
||||
test_scoring_tamper_rejected_before_target_access (test_phase2_h1_execution.CoordinatorBoundaryTests) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 4 tests in 0.491s
|
||||
|
||||
OK
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"command": [
|
||||
"/home/frank14f/optane/MeltMind/artifacts/gre24-reproduction-2026-11-15/environment/venv/bin/python",
|
||||
"-m",
|
||||
"unittest",
|
||||
"-v",
|
||||
"test_phase2_h1_execution.CoordinatorBoundaryTests"
|
||||
],
|
||||
"returncode": 0,
|
||||
"stop_reason": null,
|
||||
"cpu_seconds": 1.1415229999999998,
|
||||
"wall_seconds": 1.1895454719779082,
|
||||
"peak_tree_rss_bytes": 111964160,
|
||||
"peak_process_count": 1,
|
||||
"output_disk_bytes_before_receipt": 8192,
|
||||
"max_poll_gap_seconds": 0.17457875597756356,
|
||||
"poll_target_seconds": 0.05,
|
||||
"reaped_orphan_cpu_seconds": 0.0,
|
||||
"supervision": "sampled process-tree monitoring; wait4 final CPU/HWM; overshoot retained as failure",
|
||||
"gpu_visible": false,
|
||||
"cuda_device": "",
|
||||
"numerical_threads": 1,
|
||||
"retry": false,
|
||||
"monitor_errors": 0,
|
||||
"last_monitor_error": null
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"command": [
|
||||
"/home/frank14f/optane/MeltMind/artifacts/gre24-reproduction-2026-11-15/environment/venv/bin/python",
|
||||
"-m",
|
||||
"unittest",
|
||||
"-v",
|
||||
"test_phase2_h1_execution.CoordinatorBoundaryTests"
|
||||
],
|
||||
"limits": {
|
||||
"job_wall_seconds": 50,
|
||||
"job_cpu_seconds": 45,
|
||||
"total_cpu_seconds": 45,
|
||||
"tree_rss_bytes": 2147483648,
|
||||
"max_processes": 8,
|
||||
"disk_bytes": 104857600
|
||||
},
|
||||
"started_unix": 1794889315.4383507
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"unix": 1794889549.0574343,
|
||||
"active_related_processes": [],
|
||||
"logical_cpus": 32,
|
||||
"available_memory_bytes": 63746785280,
|
||||
"workspace_free_bytes": 67314515968,
|
||||
"writer_free_bytes": 38155005952,
|
||||
"earlier_system_python_probe": "psutil unavailable; no process assertion made by that failed probe"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"status": "PASS_METADATA_ONLY",
|
||||
"actual_cpu_seconds": 0.402164184,
|
||||
"setup_charge_seconds": 60.0,
|
||||
"synthetic_cpu_seconds": 2.4609499999999995,
|
||||
"project_targets_read": false,
|
||||
"contract_sha256": "416183a09272714a179af790e5b7be85e5a92f1395afa6a5b9fe123a184b44b2"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# B1 主审批准及执行实现接续
|
||||
|
||||
Claude1794888554.440209已对固定合同e751e5b261820b6c2df1dc1f218cde7275b2ebec作唯一主审,批准其输入、实际组件键/权重、FP64 F、物理tet端点、v4件等权、新Rg、完整A/H1预测、Mold规范性附件及20CPUh预算。原合同与审阅包字节不变。本记录落实新增树判据及实现状态,不重开主审。
|
||||
|
||||
判据只用grouped100%池、组件配对bootstrap,方向全部为**H1−A**,原始relative L2差的+0.001等于+0.10个百分点:场差区间上界<0.001,且末位置/Rg差上界<0或tau差下界>0,记EXPAND;否则若场差下界>0且上述两项均无区间支持的改善,记PRUNE;其余PARK(inconclusive)。区间未定义时PARK,不把缺失当无改善。EXPAND按上述顺序优先,边界等号不满足严格不等式。旧展示A−H1可保留但必须明确变号;拓扑和v4均仅描述。该决定是向Claude研究树提交的结果,不自动发起H2或其他目标训练。
|
||||
|
||||
原worker初稿及原接口/时钟PASS完整保留。独立`phase2_h1_worker_v2.py`将时钟改为max(seconds)/t_set、核对FP32首列与原FP64 F、核target与seconds/t_set;新执行、网格、拓扑、评分和树判据模块与旧源码分开。新运行根为`artifacts/phase2-h1-execution-2026-11-17`;旧队列不重启。
|
||||
|
||||
新增11项集成/拓扑/守卫合成PASS,CPU1.319427秒;随后仅执行4项新增协调器边界检查PASS,CPU1.141523秒。没有重跑旧纯数学6项。验收包括实际极小合成XGB拟合和无测试真值文件的预测;不把该合成模型称为项目拟合。原验收日志/资源回执在`artifacts/phase2-h1-acceptance-2026-11-17`。失败路径显存不适用于本CPU流程;本次实际检查CPU树RSS失败峰值、等待/终态账、缺guard回执、源文件篡改评分屏障、不可重复尝试和预算不足不派发。
|
||||
|
||||
执行先单worker准备全部grouped552和v4成功615的原域网格/Rg,冻结manifest后才读取learning端点和拟合;几何无目标解码。先grouped fold0/100与v4 split0,不通过首格即停止;通过后grouped至多4个单线程、v4固定8线程且顺序派发(低于最多2个上限)。20拟合全终态后Git冻结模型、无标签全tet预测、冻结全部预测manifest和评分来源,随后才缓存测试真场评分。完整场评分在每件拓扑前写独立回执,拓扑超300秒保留场评分并标诊断缺测;summary预留120CPU秒。所有失败和真实超量保留,无重试。
|
||||
|
||||
准备预算3600秒中先保守计入60秒用于已知合成/元数据/接口及发布编排开销,余3540秒用于几何worker。60是保守计费而不是实际测得60秒;原已知准备0.570199085秒和本次新增合成2.46095秒包含其中、不重复计入。阶段guard CPU与协调CPU另累计,全总额仍72000秒;没有额外GPU。具体运行源码、合同、验收、PID及进度以随后固定的launch/started/guard回执为准;本文件本身不证明已经启动。
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Claude1794888554 fixed tree rule, raw metric units, candidate minus A."""
|
||||
import math
|
||||
|
||||
|
||||
def branch_decision(field, location, tau):
|
||||
intervals=(field,location,tau)
|
||||
if any(v is None or v.get('low') is None or v.get('high') is None for v in intervals):
|
||||
return dict(decision='PARK',reason='inconclusive: undefined paired interval')
|
||||
if any(not math.isfinite(v[k]) for v in intervals for k in ('low','high')):
|
||||
raise ValueError('Nonfinite interval')
|
||||
if any(v['low']>v['high'] for v in intervals): raise ValueError('Reversed interval')
|
||||
improve_location=location['high']<0; improve_tau=tau['low']>0
|
||||
if field['high']<.001 and (improve_location or improve_tau):
|
||||
decision='EXPAND';reason='field noninferiority and at least one ordering/location interval excludes zero'
|
||||
elif field['low']>0 and not improve_location and not improve_tau:
|
||||
decision='PRUNE';reason='field clearly worse without interval-supported ordering/location improvement'
|
||||
else:decision='PARK';reason='inconclusive'
|
||||
return dict(decision=decision,reason=reason,field_margin_raw=.001,field_margin_percentage_points=.10,
|
||||
sign='H1 minus A',location_improves=improve_location,tau_improves=improve_tau,
|
||||
scope='grouped100 paired components; topology and v4 descriptive only')
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Single H1 execution, bounded guards, actual Git barriers, no retries."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import psutil
|
||||
from r4bc_guard import supervise
|
||||
from s2_recovery_supervisor import tree_usage
|
||||
from s2_recovery_monitoring import disk_usage
|
||||
from phase2_h1_worker_v2 import contract,sha,checked,save
|
||||
|
||||
BASE=Path('/home/frank14f/optane/MeltMind')
|
||||
WRITER=Path('/tmp/meltmind-git-review-20261114-v1-29ebglg8')
|
||||
ROOT=BASE/'artifacts/phase2-h1-execution-2026-11-17'
|
||||
|
||||
|
||||
def read(p):return json.loads(Path(p).read_text())
|
||||
|
||||
|
||||
def prepare(acceptance):
|
||||
start=time.process_time();packet=read(BASE/'artifacts/phase2-h1-planning-2026-11-17/b1-review-packet-v1.json')
|
||||
for p,h in packet['files'].items():checked(BASE/p,h)
|
||||
for p,h in packet['legacy_source_sha256'].items():checked(BASE/p,h)
|
||||
tests=read(acceptance)
|
||||
if tests['status']!='PASS' or tests['cpu_seconds']>=50:raise ValueError('Synthetic acceptance/bounded setup missing')
|
||||
frozen=read(BASE/'artifacts/phase2-h1-planning-2026-11-17/clock-freeze-v1/membership-and-sources.json')
|
||||
for p,h in frozen['source_sha256'].items():checked(BASE/p,h)
|
||||
grouped=read(BASE/'artifacts/r4bc-execution-2026-11-16/contract.json')
|
||||
prior_path='artifacts/r4bc-final-postfit-2026-11-17/predictions-freeze.json';prior=read(BASE/prior_path)
|
||||
c=dict(version='phase2-h1-res-v1',main_review='1794888554.440209',reviewed_contract_commit='e751e5b261820b6c2df1dc1f218cde7275b2ebec',
|
||||
parts=frozen['parts'],jobs=frozen['cells'],grouped_rows={r['case']:r for r in grouped['parts']},
|
||||
source_sha256={**frozen['source_sha256'],**packet['legacy_source_sha256'],prior_path:sha(BASE/prior_path)},
|
||||
baseline_predictions={},archives={},initial_setup_charge_seconds=60.,setup_charge_kind='conservative metadata/synthetic reserve, not measured worker use',
|
||||
synthetic_acceptance_path=str(acceptance),synthetic_acceptance_sha256=sha(acceptance),
|
||||
budget=dict(total=72000.,geometry=3540.,fit=43200.,postfit=25200.,disk_bytes=20*1024**3,total_rss_bytes=36*1024**3),
|
||||
tree_rule=dict(sign='H1-A',field_noninferiority_margin=.001,field_margin_percentage_points=.10,scope='grouped100'),new_decodes=0,gpu=False,retry=False)
|
||||
for job in c['jobs']:
|
||||
checked(job['baseline_model']['path'],job['baseline_model']['sha256'])
|
||||
if job['protocol']=='grouped':
|
||||
entries=[e for e in prior['entries'] if e['arm']=='A' and e['fold']==job['fold'] and e['pool']==job['pool']]
|
||||
if {e['case'] for e in entries}!=set(job['test']):raise ValueError('Original A prediction roster mismatch')
|
||||
c['baseline_predictions'][str(job['index'])]={e['case']:e for e in entries}
|
||||
for protocol,version in [('grouped','v5'),('v4_random','v4')]:
|
||||
archive=packet['archive_metadata'][version];c['archives'][protocol]=dict(path=archive['path'],stat=archive['original_archive_stat'])
|
||||
new=['phase2_h1_execution','phase2_h1_worker_v2','phase2_h1_geometry','phase2_h1_topology','phase2_h1_postfit','phase2_h1_decision','phase2_residual_math']
|
||||
old=['gre24_models','gre24_prepare_v2','gre24_features_v2','audit_samples','r4bc_guard','r4bc_common','s2_custody_common','s2_custody_statistics','s2_recovery_supervisor','s2_recovery_monitoring']
|
||||
c['code_sha256']={f'tools/{name}.py':sha(BASE/f'tools/{name}.py') for name in new+old}
|
||||
for p,h in tests['code_sha256'].items():checked(BASE/p,h)
|
||||
if time.process_time()-start+tests['cpu_seconds']+.570199085>=60:raise ValueError('Setup reserve exceeded')
|
||||
ROOT.mkdir(exist_ok=False);save(ROOT/'contract.json',c)
|
||||
save(ROOT/'preparation-receipt.json',dict(status='PASS_METADATA_ONLY',actual_cpu_seconds=time.process_time()-start,
|
||||
setup_charge_seconds=60.,synthetic_cpu_seconds=tests['cpu_seconds'],project_targets_read=False,
|
||||
contract_sha256=sha(ROOT/'contract.json')))
|
||||
print(ROOT,flush=True)
|
||||
|
||||
|
||||
def freeze(root,name,relative_names,extra_paths=()):
|
||||
with Path('/tmp/meltmind-single-writer.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
def git(*args):return subprocess.check_output(['git','-C',str(WRITER),*args],text=True).strip()
|
||||
if git('branch','--show-current')!='codex/s2-execution-diff-20261114' or git('status','--porcelain'):raise RuntimeError('Single writer not clean on approved branch')
|
||||
files=[root/n for n in relative_names]+[Path(p) for p in extra_paths]
|
||||
for p in files:
|
||||
rel=p.resolve().relative_to(BASE);dest=WRITER/rel;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(p,dest)
|
||||
paths=[str(p.resolve().relative_to(BASE)) for p in files]
|
||||
subprocess.run(['git','-C',str(WRITER),'add','--',*paths],check=True)
|
||||
if git('diff','--cached','--name-only'):
|
||||
subprocess.run(['git','-C',str(WRITER),'commit','-m','H1 '+name+' immutable evidence'],check=True)
|
||||
commit=git('rev-parse','HEAD')
|
||||
for p,rel in zip(files,paths):
|
||||
data=subprocess.check_output(['git','-C',str(WRITER),'show',commit+':'+rel])
|
||||
if hashlib.sha256(data).hexdigest()!=sha(p):raise RuntimeError('Git byte freeze mismatch')
|
||||
proof=dict(commit=commit,checkout=str(WRITER),sha256={n:sha(root/n) for n in relative_names},
|
||||
extra_sha256={str(p):sha(p) for p in extra_paths},remote_published=False)
|
||||
save(root/(name+'-git-freeze.json'),proof)
|
||||
return proof
|
||||
|
||||
|
||||
def guard(root,task_path):
|
||||
c=contract(root);task=read(task_path);os.sched_setaffinity(0,task['cpus']);start=time.process_time()
|
||||
dest=root/'guards'/task['name']
|
||||
result=supervise(task['command'],dest,task['limits'],global_stop=root/'global-stop.json')
|
||||
result['guard_cpu_seconds']=time.process_time()-start
|
||||
save(dest/'guard-result.json',result)
|
||||
return 0 if result['status']=='PASS' else 1
|
||||
|
||||
|
||||
def projected_fits(c,records):
|
||||
by={r['job_index']:r for r in records};remaining=0.
|
||||
for first in (0,15):
|
||||
if first not in by or by[first]['guard']['status']!='PASS':return dict(pass_gate=False,reason='FIRST_CELL_FAILED_OR_MISSING')
|
||||
reference=c['jobs'][first]
|
||||
for job in c['jobs']:
|
||||
if job['protocol']==reference['protocol'] and job['index'] not in by:
|
||||
remaining+=1.25*by[first]['guard']['cpu_seconds']*job['learning_nodes']/reference['learning_nodes']
|
||||
spent=sum(r['guard']['cpu_seconds']+r['guard']['guard_cpu_seconds'] for r in records)
|
||||
return dict(pass_gate=spent+remaining<=c['budget']['fit'],spent=spent,remaining_projection=remaining,
|
||||
full_fit_projection=spent+remaining,postfit_reserved=c['budget']['postfit'],factor=1.25)
|
||||
|
||||
|
||||
class Runner:
|
||||
def __init__(self,root,c):
|
||||
self.root=root;self.c=c;self.charges={'geometry':0.,'fit':0.,'postfit':0.};self.records=[];self.stop=None
|
||||
self.active={};self.accounting_complete=True
|
||||
self.stage_seconds={};self.start_cpu=time.process_time()
|
||||
for sig in (signal.SIGTERM,signal.SIGINT):signal.signal(sig,self.interrupt)
|
||||
def interrupt(self,sig,frame):self.stop='COORDINATOR_SIGNAL_'+str(sig)
|
||||
def total(self):return 60+sum(self.charges.values())+time.process_time()-self.start_cpu
|
||||
def jobs(self,stage,items,parallel=1):
|
||||
try:return self._jobs(stage,items,parallel)
|
||||
except BaseException:
|
||||
self.stop=self.stop or 'COORDINATOR_EXCEPTION'
|
||||
save(self.root/'global-stop.json',dict(reason=self.stop))
|
||||
for proc,_,_ in self.active.values():
|
||||
if proc.poll() is None:proc.send_signal(signal.SIGTERM)
|
||||
for proc,task,log in self.active.values():
|
||||
try:proc.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.accounting_complete=False
|
||||
for child in psutil.Process(proc.pid).children(recursive=True):child.kill()
|
||||
proc.kill();proc.wait()
|
||||
p=self.root/'guards'/task['name']/'guard-result.json'
|
||||
if p.exists():
|
||||
g=read(p);self.charges[stage]+=g['cpu_seconds']+g['guard_cpu_seconds']
|
||||
self.records.append(dict(name=task['name'],stage=stage,job_index=task.get('job_index'),guard=g))
|
||||
else:self.accounting_complete=False
|
||||
log.close()
|
||||
self.active={}
|
||||
raise
|
||||
def _jobs(self,stage,items,parallel=1):
|
||||
active={};pending=list(items);finished=[];cap=self.c['budget'][stage]
|
||||
self.active=active
|
||||
if stage=='postfit' and not (len(items)==1 and items[0]['name']=='summary'):cap-=120.
|
||||
while pending or active:
|
||||
for key,(proc,task,log) in list(active.items()):
|
||||
code=proc.poll()
|
||||
if code is None:continue
|
||||
receipt=self.root/'guards'/task['name']/'guard-result.json'
|
||||
if not receipt.exists():self.stop='MISSING_GUARD_ACCOUNTING';self.accounting_complete=False;raise RuntimeError(self.stop)
|
||||
g=read(receipt);charged=g['cpu_seconds']+g['guard_cpu_seconds'];self.charges[stage]+=charged
|
||||
record=dict(name=task['name'],stage=stage,job_index=task.get('job_index'),protocol=task.get('protocol'),case=task.get('case'),guard=g)
|
||||
finished.append(record);self.records.append(record);log.close();del active[key]
|
||||
if g['monitor_errors']:self.stop='MONITOR_ERROR'
|
||||
if g['status']!='PASS' and g['stop_reason'] is None and stage!='postfit':self.stop='WORKER_EXCEPTION_REQUIRES_REVIEW'
|
||||
print('TERMINAL',task['name'],g['status'],flush=True)
|
||||
try:
|
||||
usage=[tree_usage(proc.pid) for proc,_,_ in active.values()]
|
||||
used_disk=disk_usage(self.root)
|
||||
except Exception:
|
||||
self.stop='GLOBAL_MONITOR_ERROR';usage=[];used_disk=0
|
||||
live=sum(x[0] for x in usage)
|
||||
if self.charges[stage]+live>=cap or self.total()+live>=72000:self.stop='CUMULATIVE_CPU_LIMIT'
|
||||
if sum(x[1] for x in usage)+psutil.Process().memory_info().rss>self.c['budget']['total_rss_bytes']:self.stop='GLOBAL_RSS_LIMIT'
|
||||
if used_disk>=self.c['budget']['disk_bytes']:self.stop='GLOBAL_DISK_LIMIT'
|
||||
if self.stop:
|
||||
if not (self.root/'global-stop.json').exists():save(self.root/'global-stop.json',dict(reason=self.stop))
|
||||
pending=[]
|
||||
for proc,_,_ in active.values():
|
||||
if proc.poll() is None:proc.send_signal(signal.SIGTERM)
|
||||
while pending and len(active)<parallel and not self.stop:
|
||||
task=pending[0];reserved=sum(t['limits']['cpu_seconds'] for _,t,_ in active.values())
|
||||
if self.charges[stage]+reserved+task['limits']['cpu_seconds']>cap:
|
||||
if active:break
|
||||
self.stop='STAGE_RESERVATION_LIMIT';break
|
||||
pending.pop(0);p=self.root/'tasks'/(task['name']+'.json');p.parent.mkdir(exist_ok=True);save(p,task)
|
||||
log=(self.root/'tasks'/(task['name']+'.log')).open('x')
|
||||
env=dict(os.environ,CUDA_VISIBLE_DEVICES='',OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1')
|
||||
proc=subprocess.Popen([sys.executable,'tools/phase2_h1_execution.py','guard',str(self.root),str(p)],stdout=log,stderr=subprocess.STDOUT,env=env)
|
||||
active[task['name']]=(proc,task,log)
|
||||
save(self.root/'live-progress.json',dict(unix=time.time(),stage=stage,charges=self.charges,total_cpu_charge=self.total(),
|
||||
active=[dict(name=t['name'],guard_pid=p.pid) for p,t,_ in active.values()],terminal=len(self.records),stop=self.stop))
|
||||
if not active and not pending:break
|
||||
time.sleep(.5)
|
||||
return finished
|
||||
|
||||
|
||||
def task(name,command,cpus,cap=1800.,**kw):
|
||||
return dict(name=name,command=[sys.executable,*command],cpus=cpus,
|
||||
limits=dict(cpu_seconds=cap,wall_seconds=cap,rss_bytes=8*1024**3,disk_bytes=20*1024**3),**kw)
|
||||
|
||||
|
||||
def run(root):
|
||||
with (root/'run.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if (root/'started.json').exists():raise FileExistsError('Never restart an H1 run')
|
||||
c=contract(root);launch=read(root/'launch-freeze.json');checked(root/'contract.json',launch['contract_sha256'])
|
||||
os.sched_setaffinity(0,[30,31]);runner=Runner(root,c)
|
||||
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),implementation_commit=launch['commit']))
|
||||
try:
|
||||
rec=runner.jobs('geometry',[task('geometry',['tools/phase2_h1_geometry.py',str(root)],[8],3540.)])
|
||||
if runner.stop or not rec or rec[0]['guard']['status']!='PASS':raise RuntimeError('Geometry preparation not complete')
|
||||
freeze(root,'geometry',['contract.json','geometry/manifest.json','geometry/complete.json'])
|
||||
def fit_task(i):
|
||||
j=c['jobs'][i];cpus=[8+2*(i%4)] if j['protocol']=='grouped' else list(range(8,16))
|
||||
return task(f'fit-{i:02d}',['tools/phase2_h1_worker_v2.py',str(root),'fit',str(i)],cpus,job_index=i)
|
||||
fits=runner.jobs('fit',[fit_task(0)])
|
||||
if runner.stop or fits[0]['guard']['status']!='PASS':raise RuntimeError('First grouped cell stopped')
|
||||
fits+=runner.jobs('fit',[fit_task(15)])
|
||||
cost=projected_fits(c,fits);save(root/'first-cell-cost-check.json',cost)
|
||||
if not cost['pass_gate'] or runner.stop:raise RuntimeError('First-cell gate stopped')
|
||||
fits+=runner.jobs('fit',[fit_task(i) for i in range(15) if i!=0],parallel=4)
|
||||
if not runner.stop:fits+=runner.jobs('fit',[fit_task(i) for i in range(16,20)],parallel=1)
|
||||
models=[];by={r['job_index']:r for r in fits};extras=[]
|
||||
for j in c['jobs']:
|
||||
i=j['index'];d=root/'fits'/f'job-{i:02d}';r=by.get(i);result=read(d/'result.json') if (d/'result.json').exists() else None
|
||||
valid=bool(r and r['guard']['status']=='PASS' and result)
|
||||
item=dict(index=i,status='PASS' if valid else 'NA',reason=None if valid else 'FAILED_OR_UNATTEMPTED')
|
||||
if valid:
|
||||
checked(result['checkpoint'],result['checkpoint_sha256']);item.update(checkpoint=result['checkpoint'],checkpoint_sha256=result['checkpoint_sha256'],clock_path=str(d/'clock.json'),clock_sha256=result['clock_sha256'])
|
||||
extras += [d/'model.ubj',d/'clock.json',d/'result.json']
|
||||
models.append(item)
|
||||
save(root/'models-terminal.json',dict(models=models));save(root/'batch-complete.json',dict(attempted=len(fits),global_stop=runner.stop,accounting_complete=True,records=fits))
|
||||
if runner.stop or len(fits)!=20:raise RuntimeError('Full fit barrier not met')
|
||||
freeze(root,'models',['contract.json','batch-complete.json','models-terminal.json'],extras)
|
||||
predtasks=[task(f"predict-{m['index']:02d}",['tools/phase2_h1_worker_v2.py',str(root),'predict',str(m['index'])],[8+2*(m['index']%4)],job_index=m['index']) for m in models if m['status']=='PASS']
|
||||
predictions=runner.jobs('postfit',predtasks,parallel=4);entries=[]
|
||||
for r in predictions:
|
||||
if r['guard']['status']!='PASS':continue
|
||||
j=c['jobs'][r['job_index']];d=root/'predictions'/f"job-{j['index']:02d}"
|
||||
result=read(d/'result.json');checked(d/'index.json',result['index_sha256'])
|
||||
for entry in read(d/'index.json'):
|
||||
checked(entry['path'],entry['sha256']);entries.append(dict(**entry,index=j['index'],protocol=j['protocol'],fold=j['fold'],pool=j['pool']))
|
||||
if runner.stop:raise RuntimeError('Prediction stop')
|
||||
save(root/'predictions-freeze.json',dict(entries=entries,all_prediction_attempts_terminal=len(predictions)==len(predtasks),accounting_complete=True,
|
||||
attempts=predictions,models=models,contract_sha256=sha(root/'contract.json')))
|
||||
freeze(root,'scoring',['contract.json','predictions-freeze.json','geometry/manifest.json'])
|
||||
pairs=sorted({(e['protocol'],e['case']) for e in entries})
|
||||
scoretasks=[task(f'score-{k:04d}',['tools/phase2_h1_postfit.py',str(root),'part',p,case],[8+2*(k%4)],300.,protocol=p,case=case) for k,(p,case) in enumerate(pairs)]
|
||||
runner.jobs('postfit',scoretasks,parallel=4)
|
||||
# A budget stop preserves every completed field; summary is launched
|
||||
# only if a separately reserved 120 CPU seconds remains.
|
||||
if runner.stop:raise RuntimeError('Scoring stopped; partial evidence preserved')
|
||||
last=runner.jobs('postfit',[task('summary',['tools/phase2_h1_postfit.py',str(root),'summary'],[8],120.)])
|
||||
if runner.stop or last[0]['guard']['status']!='PASS':raise RuntimeError('Summary failed')
|
||||
save(root/'complete.json',dict(status='COMPLETE',accounting_complete=runner.accounting_complete,charges=runner.charges,total_cpu_charge=runner.total(),records=runner.records,new_decodes=0))
|
||||
except BaseException as exc:
|
||||
runner.stop=runner.stop or type(exc).__name__+': '+str(exc)
|
||||
save(root/'complete.json',dict(status='STOPPED',reason=runner.stop,accounting_complete=runner.accounting_complete,charges=runner.charges,total_cpu_charge=runner.total(),records=runner.records,new_decodes=0))
|
||||
raise
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('mode',choices=['prepare','run','guard']);p.add_argument('path',type=Path);p.add_argument('task',type=Path,nargs='?');a=p.parse_args()
|
||||
if a.mode=='prepare':prepare(a.path)
|
||||
elif a.mode=='guard':raise SystemExit(guard(a.path,a.task))
|
||||
else:run(a.path)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Label-free H1 graph/Rg freeze before fitting or scoring."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import numpy as np
|
||||
from phase2_h1_worker_v2 import contract,checked,sha,save
|
||||
from phase2_h1_topology import graph
|
||||
from gre24_prepare_v2 import read_geometry
|
||||
|
||||
|
||||
def run(root):
|
||||
c=contract(root); dest=root/'geometry';dest.mkdir(exist_ok=False)
|
||||
start=time.process_time();records=[]
|
||||
for protocol in ('grouped','v4_random'):
|
||||
for case,row in sorted(c['parts'][protocol].items()):
|
||||
out=dest/protocol;out.mkdir(exist_ok=True)
|
||||
save(dest/'progress.json',dict(protocol=protocol,case=case,completed=len(records),cpu_seconds=time.process_time()-start))
|
||||
raw=np.load(checked(Path(row['output'])/'raw_ids.npy',row['output_sha256']['raw_ids.npy']),allow_pickle=False)
|
||||
mass=np.load(checked(Path(row['output'])/'mass.npy',row['output_sha256']['mass.npy']),allow_pickle=False)
|
||||
if protocol=='grouped':
|
||||
old=c['grouped_rows'][case];prep=old['preparation'];p=Path(prep['preparation_root'])
|
||||
meta=json.loads(checked(p/'result.json',prep['result_sha256']).read_text())
|
||||
with np.load(checked(p/'geometry.npz',prep['output_sha256']['geometry.npz']),allow_pickle=False) as z:
|
||||
x=z['points_raw'].copy();t=z['tetra'].copy();ids=z['raw_node_ids'].copy()
|
||||
rg=float(meta['scales']['Rg'])
|
||||
else:
|
||||
archive=c['archives'][protocol];st=Path(archive['path']).stat();expected=archive['stat']
|
||||
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(expected['bytes'],expected['mtime_ns'],expected['inode']):raise ValueError('Archive identity changed')
|
||||
x,t,ids,_=read_geometry(archive['path'],case)
|
||||
center=np.sum(x*mass[:,None],axis=0)/mass.sum()
|
||||
rg=float(np.sqrt(np.sum(mass*np.sum((x-center)**2,axis=1))/mass.sum()))
|
||||
if not np.array_equal(ids,raw) or mass.shape!=raw.shape or np.any(mass<=0) or not np.isfinite(mass).all():raise ValueError('Graph domain/mass mismatch')
|
||||
if not np.isfinite(rg) or rg<=0:raise ValueError('Invalid Rg')
|
||||
a=graph(x,t);path=out/(case+'.npz')
|
||||
np.savez_compressed(path,points=x,raw_ids=raw,mass=mass,rg=np.array(rg),
|
||||
indptr=a.indptr,indices=a.indices,data=a.data)
|
||||
records.append(dict(protocol=protocol,case=case,path=str(path),sha256=sha(path),nodes=len(raw),directed_edges=a.nnz,Rg=rg))
|
||||
save(dest/'manifest.json',dict(records=records,contract_sha256=sha(root/'contract.json'),target_arrays_read=False,
|
||||
field_arrays_decoded=False,cpu_seconds=time.process_time()-start))
|
||||
save(dest/'complete.json',dict(status='PASS',parts=len(records),manifest_sha256=sha(dest/'manifest.json'),
|
||||
cpu_seconds=time.process_time()-start,target_arrays_read=False))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('root',type=Path);run(p.parse_args().root)
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Frozen predictions -> per-part fields/topology -> frozen descriptive report."""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from scipy.sparse import csr_matrix
|
||||
from phase2_h1_worker_v2 import contract,sha,checked,save
|
||||
from phase2_h1_topology import events,match
|
||||
from phase2_h1_decision import branch_decision
|
||||
from s2_custody_common import prediction_inputs
|
||||
from s2_custody_statistics import part_metrics,kendall_pairs,last_location
|
||||
from gre24_features_v2 import per_geometry_metrics,appendix_summary
|
||||
from r4bc_common import paired_difference
|
||||
|
||||
ARMS=('A','H1','cF','EIK')
|
||||
ARRAYS=dict(A='A_seconds',H1='seconds',cF='cF_seconds',EIK='EIK_seconds')
|
||||
|
||||
|
||||
def scoring_gate(root):
|
||||
c=contract(root);proof=json.loads((root/'scoring-git-freeze.json').read_text())
|
||||
for name in ['contract.json','predictions-freeze.json','geometry/manifest.json']:
|
||||
path=root/name;expected=proof['sha256'][name];checked(path,expected)
|
||||
rel=str(path.resolve().relative_to(Path.cwd()))
|
||||
data=subprocess.check_output(['git','show',proof['commit']+':'+rel],cwd=proof['checkout'])
|
||||
import hashlib
|
||||
if hashlib.sha256(data).hexdigest()!=expected:raise PermissionError('Score Git proof differs')
|
||||
frozen=json.loads((root/'predictions-freeze.json').read_text())
|
||||
if not frozen['all_prediction_attempts_terminal'] or not frozen['accounting_complete']:raise PermissionError('Prediction barrier missing')
|
||||
return c,frozen
|
||||
|
||||
|
||||
def score_part(root,protocol,case):
|
||||
c,frozen=scoring_gate(root);row=c['parts'][protocol][case]
|
||||
dest=root/'scores'/protocol/case;dest.mkdir(parents=True,exist_ok=False);start=time.process_time()
|
||||
entries=[e for e in frozen['entries'] if e['protocol']==protocol and e['case']==case]
|
||||
# Verify every field for this part before opening its target; global freeze
|
||||
# already verified every prediction file before permitting this worker.
|
||||
for e in entries:checked(e['path'],e['sha256'])
|
||||
gm=json.loads((root/'geometry/manifest.json').read_text())
|
||||
ge=next(e for e in gm['records'] if e['protocol']==protocol and e['case']==case)
|
||||
with np.load(checked(ge['path'],ge['sha256']),allow_pickle=False) as z:
|
||||
raw=z['raw_ids'].copy();x=z['points'].copy();mass=z['mass'].copy();rg=float(z['rg'])
|
||||
adjacency=csr_matrix((z['data'],z['indices'],z['indptr']),shape=(len(raw),len(raw)))
|
||||
source=Path(row['output']);save(dest/'target-access.json',dict(protocol=protocol,case=case,role='test_scoring',
|
||||
path=str(source/'seconds.npy'),sha256=row['output_sha256']['seconds.npy'],predictions_freeze_sha256=sha(root/'predictions-freeze.json')))
|
||||
truth=np.load(checked(source/'seconds.npy',row['output_sha256']['seconds.npy']),allow_pickle=False)
|
||||
cacheids=np.load(checked(source/'raw_ids.npy',row['output_sha256']['raw_ids.npy']),allow_pickle=False)
|
||||
if not np.array_equal(raw,cacheids) or truth.shape!=raw.shape or not np.isfinite(truth).all():raise ValueError('Score domain mismatch')
|
||||
if protocol=='grouped':
|
||||
q=prediction_inputs(c['grouped_rows'][case]);ix=np.searchsorted(raw,q['raw_ids'])
|
||||
if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],q['raw_ids']):raise ValueError('Query raw ID mismatch')
|
||||
label=c['grouped_rows'][case]['label']
|
||||
with np.load(checked(label['path'],label['sha256']),allow_pickle=False) as z:
|
||||
if not np.array_equal(z['raw_ids'],q['raw_ids']) or not np.array_equal(z['counts'],q['counts']) or not np.array_equal(z['seconds'],truth[ix]):raise ValueError('Frozen query truth differs from tet truth')
|
||||
else:ix=np.arange(len(raw));q=None
|
||||
rows=[]
|
||||
for e in entries:
|
||||
with np.load(e['path'],allow_pickle=False) as z:
|
||||
if not np.array_equal(z['raw_ids'],raw):raise ValueError('Prediction raw ID mismatch')
|
||||
for arm in ARMS:
|
||||
pred=z[ARRAYS[arm]]
|
||||
if protocol=='grouped':metrics=part_metrics(pred[ix],truth[ix],q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'],int(case.split('_')[0]))
|
||||
else:
|
||||
met=per_geometry_metrics(truth,pred)
|
||||
metrics=dict(relative_l2=dict(value=met['rrmse_rms'],reason=None if met['rrmse_rms'] is not None else 'zero truth denominator'),
|
||||
kendall_tau_b=kendall_pairs(truth,pred,int(case.split('_')[0])),
|
||||
last_location=dict(value=last_location(truth,pred,raw,x/rg),reason=None),paper=met)
|
||||
rows.append(dict(case=case,protocol=protocol,fold=e['fold'],pool=e['pool'],arm=arm,**metrics))
|
||||
# Field scores survive a later topology resource stop; their provenance is
|
||||
# independent and the guard must report topology as incomplete, never PASS.
|
||||
save(dest/'core.json',dict(status='FIELD_SCORES_COMPLETE',rows=rows,cpu_seconds=time.process_time()-start))
|
||||
ref=events(truth,mass,raw,x,adjacency);save(dest/'truth-events.json',ref);topo=[]
|
||||
for e in entries:
|
||||
with np.load(e['path'],allow_pickle=False) as z:
|
||||
for arm in ARMS:
|
||||
pred=events(z[ARRAYS[arm]],mass,raw,x,adjacency)
|
||||
detail=dict(case=case,protocol=protocol,fold=e['fold'],pool=e['pool'],arm=arm,predicted=pred,
|
||||
match=match(ref,pred,adjacency,rg))
|
||||
save(dest/f"events-{e['index']:02d}-{arm}.json",detail);topo.append(detail)
|
||||
save(dest/'topology.json',dict(status='TOPOLOGY_COMPLETE',rows=topo,cpu_seconds=time.process_time()-start))
|
||||
|
||||
|
||||
def intervals(rows,c,pool,metric):
|
||||
lookup={(r['case'],r['arm']):r for r in rows if r['protocol']=='grouped' and r['pool']==pool}
|
||||
groups={}
|
||||
for case,row in c['parts']['grouped'].items():groups.setdefault(row['clock_group'],[]).append(case)
|
||||
values={arm:{} for arm in ARMS};missing={arm:{} for arm in ARMS}
|
||||
for arm in ARMS:
|
||||
for g,cases in sorted(groups.items()):
|
||||
block=[];bad=[]
|
||||
for case in cases:
|
||||
r=lookup.get((case,arm));v=None if r is None else r.get(metric,{}).get('value')
|
||||
if v is None:bad.append(case)
|
||||
else:block.append(v)
|
||||
if bad:missing[arm][g]=bad
|
||||
else:values[arm][g]=float(np.mean(block))
|
||||
# Existing helper is before-after: pass H1 first for the approved H1-A sign.
|
||||
delta=paired_difference(values['H1'],values['A'])
|
||||
return dict(means={a:float(np.mean(list(v.values()))) if v else None for a,v in values.items()},
|
||||
components={a:len(v) for a,v in values.items()},values=values,missing=missing,H1_minus_A=delta)
|
||||
|
||||
|
||||
def summarize(root):
|
||||
c,frozen=scoring_gate(root);rows=[];topo=[];coverage=[]
|
||||
guard_by_part={}
|
||||
for path in (root/'tasks').glob('score-*.json'):
|
||||
desc=json.loads(path.read_text());g=root/'guards'/desc['name']/'guard-result.json'
|
||||
guard_by_part[(desc['protocol'],desc['case'])]=json.loads(g.read_text()) if g.exists() else None
|
||||
for protocol in ('grouped','v4_random'):
|
||||
for case in c['parts'][protocol]:
|
||||
d=root/'scores'/protocol/case;core=d/'core.json';tp=d/'topology.json'
|
||||
if core.exists():rows.extend(json.loads(core.read_text())['rows'])
|
||||
if tp.exists():topo.extend(json.loads(tp.read_text())['rows'])
|
||||
g=guard_by_part.get((protocol,case));reason=None if tp.exists() else ('not requested/no valid test prediction' if (protocol,case) not in guard_by_part else 'missing guard receipt' if g is None else g.get('stop_reason') or 'worker failure before topology completed')
|
||||
coverage.append(dict(protocol=protocol,case=case,field_complete=core.exists(),topology_complete=tp.exists(),
|
||||
missing_topology_reason=reason,guard_status=None if g is None else g['status']))
|
||||
grouped={str(p):{metric:intervals(rows,c,p,metric) for metric in ('relative_l2','last_location','kendall_tau_b')} for p in (100,50,25)}
|
||||
decision=branch_decision(*(grouped['100'][m]['H1_minus_A'] for m in ('relative_l2','last_location','kendall_tau_b')))
|
||||
v4={}
|
||||
for arm in ARMS:
|
||||
v4[arm]={}
|
||||
for denominator in ('rms','maximum','mean'):
|
||||
key='rrmse_'+denominator;blocks=[[r['paper'][key] for r in rows if r['protocol']=='v4_random' and r['arm']==arm and r['fold']==f and r['paper'][key] is not None] for f in range(5)]
|
||||
v4[arm][key]=dict(summary=appendix_summary(blocks) if all(blocks) else None,
|
||||
defined=[len(v) for v in blocks],fraction_below_point1=[float(np.mean(np.asarray(v)<.1)) if v else None for v in blocks])
|
||||
totals={}
|
||||
for r in topo:
|
||||
key=f"{r['protocol']}/{r['pool']}/{r['fold']}/{r['arm']}";m=r['match']
|
||||
t=totals.setdefault(key,dict(TP=0,FP=0,FN=0,distances=[],empty_classes={},parts=0))
|
||||
for k in ('TP','FP','FN'):t[k]+=m[k]
|
||||
t['distances'].extend(m['matched_distance_over_Rg']);t['parts']+=1
|
||||
category=m['empty_class'];t['empty_classes'][category]=t['empty_classes'].get(category,0)+1
|
||||
for t in totals.values():
|
||||
t['precision']=t['TP']/(t['TP']+t['FP']) if t['TP']+t['FP'] else None
|
||||
t['recall']=t['TP']/(t['TP']+t['FN']) if t['TP']+t['FN'] else None
|
||||
t['median_distance_over_Rg']=float(np.median(t['distances'])) if t['distances'] else None
|
||||
save(root/'summary.json',dict(status='SCORED_DESCRIPTIVE',grouped=grouped,v4=v4,tree_decision=decision,
|
||||
topology=totals,coverage=coverage,field_rows=len(rows),topology_rows=len(topo),
|
||||
topology_interpretation='auxiliary; B3 stability gate must pass before treating as usable diagnostic',
|
||||
new_decodes=0,full_training_matrix=False))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('mode',choices=['part','summary']);p.add_argument('protocol',nargs='?');p.add_argument('case',nargs='?');a=p.parse_args()
|
||||
(score_part(a.root,a.protocol,a.case) if a.mode=='part' else summarize(a.root))
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Mold91ecc62f dry H0 on original tet-edge graphs; array-only implementation."""
|
||||
import math
|
||||
import numpy as np
|
||||
from scipy.sparse import csr_matrix
|
||||
from scipy.sparse.csgraph import dijkstra
|
||||
from scipy.optimize import linear_sum_assignment
|
||||
|
||||
|
||||
def graph(points, tetra):
|
||||
x=np.asarray(points,dtype=np.float64); t=np.asarray(tetra)
|
||||
if x.ndim!=2 or x.shape[1]!=3 or not np.isfinite(x).all(): raise ValueError('Invalid geometry')
|
||||
if t.ndim!=2 or t.shape[1]!=4 or t.dtype.kind not in 'iu' or t.min()<0 or t.max()>=len(x): raise ValueError('Invalid tet IDs')
|
||||
edges=np.concatenate([t[:,[a,b]] for a,b in [(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)]])
|
||||
edges=np.unique(np.sort(edges,axis=1),axis=0)
|
||||
length=np.linalg.norm(x[edges[:,0]]-x[edges[:,1]],axis=1)
|
||||
if not np.isfinite(length).all() or np.any(length<=0): raise ValueError('Nonpositive original edge')
|
||||
a=np.r_[edges[:,0],edges[:,1]]; b=np.r_[edges[:,1],edges[:,0]]
|
||||
return csr_matrix((np.r_[length,length],(a,b)),shape=(len(x),len(x)))
|
||||
|
||||
|
||||
def events(field,mass,raw_ids,points,adjacency,persistence=.01):
|
||||
s=np.asarray(field,dtype=np.float64); m=np.asarray(mass,dtype=np.float64); raw=np.asarray(raw_ids)
|
||||
n=len(s); x=np.asarray(points,dtype=np.float64)
|
||||
if s.shape!=m.shape or raw.shape!=s.shape or x.shape!=(n,3) or adjacency.shape!=(n,n): raise ValueError('Event domain mismatch')
|
||||
if not np.isfinite(s).all() or not np.isfinite(m).all() or np.any(m<=0) or len(np.unique(raw))!=n: raise ValueError('Invalid event input')
|
||||
order=np.argsort(-s,kind='stable'); boundaries=np.r_[0,np.flatnonzero(np.diff(s[order])!=0)+1,n]
|
||||
parent=np.arange(n); active=np.zeros(n,bool); birth=np.zeros(n); birth_id=raw.copy()
|
||||
def find(i):
|
||||
while parent[i]!=i:
|
||||
parent[i]=parent[parent[i]];i=int(parent[i])
|
||||
return i
|
||||
total=math.fsum(map(float,m)); passed=0.; output=[]; infinite=None
|
||||
for lo,hi in zip(boundaries[:-1],boundaries[1:]):
|
||||
layer=order[lo:hi]; level=passed/total; pending=set(map(int,layer)); blocks=[]
|
||||
while pending:
|
||||
first=next(iter(pending));pending.remove(first);todo=[first];nodes=[];old=set()
|
||||
while todo:
|
||||
i=todo.pop();nodes.append(i)
|
||||
for jj in adjacency.indices[adjacency.indptr[i]:adjacency.indptr[i+1]]:
|
||||
j=int(jj)
|
||||
if active[j]: old.add(find(j))
|
||||
elif j in pending:
|
||||
pending.remove(j);todo.append(j)
|
||||
blocks.append((nodes,old))
|
||||
# Bipartite connected components, using shared old roots to join blocks.
|
||||
bp=list(range(len(blocks)));owner={}
|
||||
def bf(i):
|
||||
while bp[i]!=i: bp[i]=bp[bp[i]];i=bp[i]
|
||||
return i
|
||||
for k,(_,old) in enumerate(blocks):
|
||||
for g in old:
|
||||
if g in owner:bp[bf(k)]=bf(owner[g])
|
||||
else:owner[g]=k
|
||||
compound={}
|
||||
for k in range(len(blocks)):compound.setdefault(bf(k),[]).append(k)
|
||||
for keys in compound.values():
|
||||
nodes=[i for k in keys for i in blocks[k][0]]
|
||||
olds=set().union(*(blocks[k][1] for k in keys))
|
||||
if olds:
|
||||
survivor=min(olds,key=lambda i:(birth[i],int(birth_id[i])))
|
||||
dying=sorted(olds-{survivor},key=lambda i:(birth[i],int(birth_id[i])))
|
||||
bars=[dict(birth=float(birth[i]),death=float(level),persistence=float(level-birth[i]),birth_raw_id=int(birth_id[i])) for i in dying]
|
||||
if any(b['persistence']>=persistence and b['persistence']>0 for b in bars):
|
||||
support=np.array([i for k in keys if len(blocks[k][1])>=2 for i in blocks[k][0]],dtype=int)
|
||||
if not len(support): raise ValueError('Compound merge has no positional support')
|
||||
center=np.sum(x[support]*m[support,None],axis=0)/m[support].sum()
|
||||
distance=np.linalg.norm(x[support]-center,axis=1)
|
||||
rep=int(support[np.lexsort((raw[support],distance))[0]])
|
||||
output.append(dict(node=rep,raw_id=int(raw[rep]),death=float(level),
|
||||
support_nodes=len(support),support_radius=float(np.linalg.norm(x[support]-x[rep],axis=1).max()),
|
||||
multiplicity=len(dying),bars=bars))
|
||||
for g in olds:parent[g]=survivor
|
||||
else:
|
||||
survivor=min(nodes,key=lambda i:int(raw[i]));birth[survivor]=level;birth_id[survivor]=raw[survivor]
|
||||
for i in nodes:parent[i]=survivor;active[i]=True
|
||||
passed=math.fsum((passed,math.fsum(map(float,m[layer]))))
|
||||
infinite=len({find(i) for i in range(n)})
|
||||
output.sort(key=lambda e:(e['death'],e['raw_id']))
|
||||
return dict(events=output,infinite_classes=infinite,nodes=n,total_mass=total,
|
||||
precision='frozen scalar values converted to FP64; exact equality ties',persistence=persistence)
|
||||
|
||||
|
||||
def _assignment(cost, forced=(), excluded=frozenset()):
|
||||
n,m=cost.shape; fr={i for i,j in forced}; fc={j for i,j in forced}
|
||||
if len(fr)!=len(forced) or len(fc)!=len(forced): return None
|
||||
rows=[i for i in range(n) if i not in fr];cols=[j for j in range(m) if j not in fc]
|
||||
nr,nc=len(rows),len(cols);penalty=float(n+m+1)
|
||||
a=np.full((nr+nc,nr+nc),penalty*4)
|
||||
if nr and nc:
|
||||
sub=cost[np.ix_(rows,cols)].copy()
|
||||
for ii,i in enumerate(rows):
|
||||
for jj,j in enumerate(cols):
|
||||
if (i,j) in excluded:sub[ii,jj]=np.inf
|
||||
a[:nr,:nc]=np.where(np.isfinite(sub),sub,penalty*4)
|
||||
a[:nr,nc:]=penalty;a[nr:,:nc]=penalty;a[nr:,nc:]=0.
|
||||
rr,cc=linear_sum_assignment(a)
|
||||
pairs=list(forced)+[(rows[i],cols[j]) for i,j in zip(rr,cc) if i<nr and j<nc and np.isfinite(cost[rows[i],cols[j]]) and (rows[i],cols[j]) not in excluded]
|
||||
return pairs,math.fsum(float(cost[i,j]) for i,j in pairs)
|
||||
|
||||
|
||||
def match(reference,predicted,adjacency,rg):
|
||||
if not math.isfinite(rg) or rg<=0:raise ValueError('Invalid frozen Rg')
|
||||
truth=reference['events'];pred=predicted['events'];cost=np.full((len(truth),len(pred)),np.inf)
|
||||
for i,a in enumerate(truth):
|
||||
eligible=[j for j,b in enumerate(pred) if abs(a['death']-b['death'])<=.05]
|
||||
if not eligible:continue
|
||||
dist=dijkstra(adjacency,directed=False,indices=a['node'],limit=.10*rg)
|
||||
for j in eligible:
|
||||
d=float(dist[pred[j]['node']])
|
||||
if math.isfinite(d) and d<=.10*rg:cost[i,j]=d/rg
|
||||
best,target=_assignment(cost);count=len(best);forced=[];excluded=set()
|
||||
candidates=sorted(zip(*np.where(np.isfinite(cost))),key=lambda p:(truth[p[0]]['raw_id'],pred[p[1]]['raw_id']))
|
||||
for edge in candidates:
|
||||
i,j=map(int,edge)
|
||||
if any(i==a or j==b for a,b in forced):continue
|
||||
attempt=_assignment(cost,forced+[(i,j)],frozenset(excluded))
|
||||
if attempt is not None and len(attempt[0])==count and attempt[1]==target:forced.append((i,j))
|
||||
else:excluded.add((i,j))
|
||||
if len(forced)==count:break
|
||||
if len(forced)!=count: raise ValueError('Exact-cost lexicographic matching could not be certified')
|
||||
distances=[float(cost[i,j]) for i,j in forced]
|
||||
return dict(TP=count,FP=len(pred)-count,FN=len(truth)-count,
|
||||
precision=count/len(pred) if pred else None,recall=count/len(truth) if truth else None,
|
||||
matched_distance_over_Rg=distances,median_distance_over_Rg=float(np.median(distances)) if distances else None,
|
||||
empty_class='both_empty' if not truth and not pred else 'truth_empty' if not truth else 'prediction_empty' if not pred else 'both_nonempty',
|
||||
pairs=[dict(truth_raw_id=truth[i]['raw_id'],prediction_raw_id=pred[j]['raw_id'],distance_over_Rg=float(cost[i,j])) for i,j in forced])
|
||||
@@ -0,0 +1,179 @@
|
||||
"""H1-RES fixed-XGB worker. No queue or implicit execution approval.
|
||||
|
||||
The reviewed contract binds training/test roles, source metadata, precision,
|
||||
clock weighting and source hashes. Test predictions never load target arrays.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import numpy as np
|
||||
from threadpoolctl import threadpool_limits
|
||||
from gre24_models import xgb_model
|
||||
from phase2_residual_math import learning_clock, residual_target, decode_seconds
|
||||
|
||||
|
||||
def sha(path):
|
||||
h = hashlib.sha256()
|
||||
with Path(path).open('rb') as source:
|
||||
for block in iter(lambda: source.read(4*1024**2), b''): h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
path = Path(path); tmp = path.with_suffix(path.suffix+'.tmp')
|
||||
tmp.write_text(json.dumps(value, indent=2, allow_nan=False)+'\n'); tmp.replace(path)
|
||||
|
||||
|
||||
def checked(path, digest):
|
||||
if sha(path) != digest: raise ValueError('Pinned file mismatch: '+str(path))
|
||||
return Path(path)
|
||||
|
||||
|
||||
def contract(root):
|
||||
import xgboost
|
||||
if np.__version__ != '1.26.4' or xgboost.__version__ != '2.1.4':
|
||||
raise ValueError('Frozen library version differs')
|
||||
c = json.loads((root/'contract.json').read_text())
|
||||
if c.get('version') != 'phase2-h1-res-v1' or not c.get('main_review'):
|
||||
raise PermissionError('No fixed reviewed H1 contract')
|
||||
for p, h in c['code_sha256'].items(): checked(p, h)
|
||||
for p, h in c['source_sha256'].items(): checked(p, h)
|
||||
return c
|
||||
|
||||
|
||||
def role_rows(c, job, role):
|
||||
if role not in ('learning', 'test'): raise ValueError('Unknown role')
|
||||
if set(job['learning']) & set(job['test']): raise PermissionError('Training/test overlap')
|
||||
if len(job[role]) != len(set(job[role])): raise ValueError('Repeated case')
|
||||
# Contract builder must cross-check these frozen roles against original
|
||||
# source contracts. Here a role cannot be expanded through row metadata.
|
||||
return [c['parts'][job['protocol']][case] for case in job[role]]
|
||||
|
||||
|
||||
def load_features(row):
|
||||
source = Path(row['output']); hashes = row['output_sha256']
|
||||
f = np.load(checked(source/'Vf.npy', hashes['Vf.npy']), allow_pickle=False)
|
||||
x = np.load(checked(source/'features.npy', hashes['features.npy']), mmap_mode='r', allow_pickle=False)
|
||||
ids = np.load(checked(source/'raw_ids.npy', hashes['raw_ids.npy']), allow_pickle=False)
|
||||
if x.shape != (row['nodes'], 19) or f.shape != (row['nodes'],) or ids.shape != f.shape:
|
||||
raise ValueError('Feature/node identity shape mismatch')
|
||||
if f.dtype != np.dtype('float64') or not np.array_equal(np.asarray(x[:, 0],dtype=np.float32), f.astype(np.float32)):
|
||||
raise ValueError('Original float64 F differs from frozen first column')
|
||||
if np.any(np.diff(ids) <= 0) or not np.isfinite(x).all(): raise ValueError('Bad IDs/features')
|
||||
return np.asarray(x, dtype=np.float32), f, ids
|
||||
|
||||
|
||||
def fit(root, c, job):
|
||||
out = root/'fits'/f"job-{job['index']:02d}"; out.mkdir(parents=True, exist_ok=False)
|
||||
save(out/'started.json', {'unix': time.time(), 'job': job, 'contract_sha256': sha(root/'contract.json')})
|
||||
cpu = time.process_time(); access = []; rows = role_rows(c, job, 'learning')
|
||||
end_ratios, groups = [], []
|
||||
# First pass: only learning-role retained-tet targets for this cell's clock.
|
||||
for row in rows:
|
||||
path = Path(row['output'])/'seconds.npy'
|
||||
access.append({'case': row['case'], 'role': 'learning', 'purpose': 'clock', 'path': str(path)})
|
||||
save(out/'target-access.json', access)
|
||||
y = np.load(checked(path, row['output_sha256']['seconds.npy']), mmap_mode='r', allow_pickle=False)
|
||||
if y.shape != (row['nodes'],) or not np.isfinite(y).all() or np.any(y < 0): raise ValueError('Invalid learning target')
|
||||
if y.dtype != np.dtype('float64') or not np.isfinite(row['t_set']) or row['t_set']<=0: raise ValueError('Endpoint precision/scale mismatch')
|
||||
raw=np.load(checked(Path(row['output'])/'raw_ids.npy',row['output_sha256']['raw_ids.npy']),allow_pickle=False)
|
||||
if raw.shape!=y.shape or np.any(np.diff(raw)<=0): raise ValueError('Endpoint raw ID mismatch')
|
||||
end_ratios.append(float(y.max())/float(row['t_set'])); groups.append(row['clock_group'])
|
||||
clock = learning_clock(end_ratios, groups)
|
||||
save(out/'clock.json', {'c': clock, 'source': 'learning retained-tet max(T)/t_set, mean within component then mean across components',
|
||||
'parts': [row['case'] for row in rows], 'end_ratios': end_ratios, 'groups': groups})
|
||||
n = sum(row['nodes'] for row in rows); x = np.empty((n, 19), np.float32); y = np.empty(n, np.float32); cursor = 0
|
||||
for row in rows:
|
||||
xx, f, ids = load_features(row)
|
||||
path = checked(Path(row['output'])/'target.npy', row['output_sha256']['target.npy'])
|
||||
target = np.load(path, mmap_mode='r', allow_pickle=False)
|
||||
physical=np.load(checked(Path(row['output'])/'seconds.npy',row['output_sha256']['seconds.npy']),mmap_mode='r',allow_pickle=False)
|
||||
if not np.array_equal(target,physical/row['t_set']): raise ValueError('Frozen normalized target differs from physical seconds/t_set')
|
||||
count = len(f); x[cursor:cursor+count] = xx
|
||||
y[cursor:cursor+count] = residual_target(target, f, clock, fit_dtype='float32'); cursor += count
|
||||
access.append({'case': row['case'], 'role': 'learning', 'purpose': 'residual_fit', 'path': str(path)})
|
||||
save(out/'target-access.json', access)
|
||||
with threadpool_limits(job['threads']):
|
||||
model = xgb_model(job['seed'], job['threads'])
|
||||
save(out/'progress.json', {'stage': 'FIT', 'nodes': n, 'clock': clock})
|
||||
model.fit(x, y, verbose=False)
|
||||
checkpoint = out/'model.ubj'; model.save_model(checkpoint)
|
||||
(out/'xgboost-config.json').write_text(model.get_booster().save_config())
|
||||
save(out/'result.json', {'status': 'FIT_COMPLETE_NO_TEST_SCORES', 'checkpoint': str(checkpoint),
|
||||
'checkpoint_sha256': sha(checkpoint), 'clock_sha256': sha(out/'clock.json'), 'c': clock,
|
||||
'learning_nodes': n, 'learning_parts': len(rows), 'cpu_seconds': time.process_time()-cpu,
|
||||
'test_labels_read': False, 'new_decodes': 0, 'retry': False})
|
||||
|
||||
|
||||
def predict(root, c, job):
|
||||
import joblib
|
||||
import xgboost
|
||||
proof = json.loads((root/'models-git-freeze.json').read_text())
|
||||
if not proof.get('commit') or not proof.get('checkout'):
|
||||
raise PermissionError('All-terminal model Git freeze missing or mismatched')
|
||||
for rel in ['contract.json', 'batch-complete.json', 'models-terminal.json']:
|
||||
path = root/rel; expected = proof['sha256'][rel]; checked(path, expected)
|
||||
repository_path = str(path.resolve().relative_to(Path.cwd()))
|
||||
raw = subprocess.check_output(['git', 'show', proof['commit']+':'+repository_path], cwd=proof['checkout'])
|
||||
if hashlib.sha256(raw).hexdigest() != expected: raise PermissionError('Git freeze differs from local files')
|
||||
terminal = json.loads((root/'batch-complete.json').read_text())
|
||||
if terminal['global_stop'] or not terminal['accounting_complete'] or terminal['attempted'] != len(c['jobs']):
|
||||
raise PermissionError('Fit queue not complete')
|
||||
freeze = json.loads((root/'models-terminal.json').read_text())
|
||||
if len(freeze['models']) != len(c['jobs']): raise PermissionError('Incomplete model manifest')
|
||||
entry = next(r for r in freeze['models'] if r['index'] == job['index'])
|
||||
if entry['status'] != 'PASS': raise ValueError('No checkpoint for failed cell')
|
||||
out = root/'predictions'/f"job-{job['index']:02d}"; out.mkdir(parents=True, exist_ok=False)
|
||||
model = xgboost.XGBRegressor(); model.load_model(checked(entry['checkpoint'], entry['checkpoint_sha256']))
|
||||
old = job['baseline_model']; checked(old['path'], old['sha256'])
|
||||
if old['format'] == 'joblib':
|
||||
baseline = joblib.load(old['path'])
|
||||
elif old['format'] == 'ubj':
|
||||
baseline = xgboost.XGBRegressor(); baseline.load_model(old['path'])
|
||||
else:
|
||||
raise ValueError('Unsupported frozen A checkpoint format')
|
||||
clock = json.loads(checked(entry['clock_path'], entry['clock_sha256']).read_text())['c']
|
||||
index = []; cpu = time.process_time()
|
||||
with threadpool_limits(job['threads']):
|
||||
for row in role_rows(c, job, 'test'):
|
||||
x, f, ids = load_features(row) # No target.npy load on this path.
|
||||
seconds = decode_seconds(model.predict(x), f, clock, row['t_set'])
|
||||
old_seconds = np.asarray(baseline.predict(x), dtype=np.float64)*row['t_set']
|
||||
if old_seconds.shape != seconds.shape or not np.isfinite(old_seconds).all(): raise ValueError('Invalid A prediction')
|
||||
if job['protocol']=='grouped':
|
||||
prior=c['baseline_predictions'][str(job['index'])][row['case']]
|
||||
with np.load(checked(prior['path'],prior['sha256']),allow_pickle=False) as z:
|
||||
iq=np.searchsorted(ids,z['raw_ids'])
|
||||
if np.any(iq>=len(ids)) or not np.array_equal(ids[iq],z['raw_ids']):raise ValueError('Historical A query identity differs')
|
||||
if not np.array_equal(old_seconds[iq],z[prior['array']]):raise ValueError('Historical A query prediction differs')
|
||||
path = out/(row['case']+'.npz')
|
||||
np.savez_compressed(path, seconds=seconds, A_seconds=old_seconds, cF_seconds=clock*f*row['t_set'],
|
||||
EIK_seconds=f*row['t_set'], raw_ids=ids)
|
||||
index.append({'case': row['case'], 'path': str(path), 'sha256': sha(path),
|
||||
'negative_predictions': int(np.sum(seconds < 0)), 'nodes': len(ids)})
|
||||
save(out/'progress.json', {'parts': len(index), 'cpu_seconds': time.process_time()-cpu})
|
||||
save(out/'index.json', index)
|
||||
save(out/'result.json', {'status': 'PREDICTIONS_COMPLETE_NO_SCORES', 'index_sha256': sha(out/'index.json'),
|
||||
'cpu_seconds': time.process_time()-cpu, 'target_values_read': False})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(); parser.add_argument('root', type=Path)
|
||||
parser.add_argument('mode', choices=['fit', 'predict']); parser.add_argument('index', type=int)
|
||||
args = parser.parse_args(); start = time.process_time()
|
||||
try:
|
||||
config = contract(args.root); selected = config['jobs'][args.index]
|
||||
if selected['index'] != args.index: raise ValueError('Job index mismatch')
|
||||
(fit if args.mode == 'fit' else predict)(args.root, config, selected)
|
||||
except Exception as exc:
|
||||
dest = args.root/'failures'; dest.mkdir(exist_ok=True)
|
||||
save(dest/f'{args.mode}-{args.index:02d}.json', {'type': type(exc).__name__, 'message': str(exc),
|
||||
'traceback': traceback.format_exc(), 'pid': os.getpid(), 'cpu_seconds': time.process_time()-start,
|
||||
'retry': False})
|
||||
raise
|
||||
@@ -0,0 +1,152 @@
|
||||
"""New integration/topology/guard tests; synthetic inputs only, no old test rerun."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import Mock
|
||||
import signal
|
||||
import numpy as np
|
||||
from scipy.sparse import csr_matrix
|
||||
from phase2_h1_topology import graph,events,match
|
||||
from phase2_h1_decision import branch_decision
|
||||
from phase2_h1_execution import projected_fits,Runner,task
|
||||
import phase2_h1_worker_v2 as worker
|
||||
from r4bc_guard import supervise
|
||||
|
||||
|
||||
def line(n):
|
||||
a=np.arange(n-1);b=a+1
|
||||
return csr_matrix((np.ones(2*(n-1)),(np.r_[a,b],np.r_[b,a])),shape=(n,n))
|
||||
|
||||
|
||||
class TopologyTests(unittest.TestCase):
|
||||
def test_tie_plateau_is_one_merge_and_position_mass_weighted(self):
|
||||
s=np.array([4.,1.,1.,3.]);m=np.array([1.,1.,3.,1.]);raw=np.arange(10,14);x=np.c_[np.arange(4),np.zeros((4,2))]
|
||||
r=events(s,m,raw,x,line(4));self.assertEqual(len(r['events']),1)
|
||||
e=r['events'][0];self.assertEqual(e['raw_id'],12);self.assertEqual(e['support_nodes'],2);self.assertEqual(e['multiplicity'],1)
|
||||
self.assertEqual(r['infinite_classes'],1);self.assertAlmostEqual(e['bars'][0]['persistence'],1/6)
|
||||
perm=np.array([3,1,0,2]);a=line(4)[perm][:,perm]
|
||||
q=events(s[perm],m[perm],raw[perm],x[perm],a)
|
||||
self.assertEqual(q['events'][0]['raw_id'],12)
|
||||
self.assertEqual(q['events'][0]['death'],e['death'])
|
||||
def test_three_peaks_compound_multiplicity_and_increasing_map(self):
|
||||
a=csr_matrix((np.ones(6),([0,0,0,1,2,3],[1,2,3,0,0,0])),shape=(4,4));s=np.array([0.,4.,3.,2.]);x=np.c_[np.arange(4),np.zeros((4,2))]
|
||||
e=events(s,np.ones(4),np.arange(4),x,a)
|
||||
self.assertEqual(len(e['events']),1);self.assertEqual(e['events'][0]['multiplicity'],2)
|
||||
self.assertEqual(e,events(s*2+1,np.ones(4),np.arange(4),x,a))
|
||||
def test_all_equal_no_finite_events_and_separate_infinite_classes(self):
|
||||
a=csr_matrix((4,4));r=events(np.ones(4),np.ones(4),np.arange(4),np.zeros((4,3)),a)
|
||||
self.assertEqual(r['events'],[]);self.assertEqual(r['infinite_classes'],4)
|
||||
def test_true_tet_graph_no_cross_component_shortcut(self):
|
||||
x=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1],[.1,.1,.1],[1.1,.1,.1],[.1,1.1,.1],[.1,.1,1.1]])
|
||||
a=graph(x,np.array([[0,1,2,3],[4,5,6,7]]));self.assertEqual(a.nnz,24);self.assertEqual(a[:4,4:].nnz,0)
|
||||
def test_matching_is_maximum_one_to_one_and_lexicographic(self):
|
||||
a=line(4);truth=dict(events=[dict(node=0,raw_id=10,death=.5),dict(node=3,raw_id=13,death=.5)])
|
||||
pred=dict(events=[dict(node=1,raw_id=11,death=.5),dict(node=2,raw_id=12,death=.5)])
|
||||
r=match(truth,pred,a,30.);self.assertEqual(r['TP'],2);self.assertEqual([(x['truth_raw_id'],x['prediction_raw_id']) for x in r['pairs']],[(10,11),(13,12)])
|
||||
# Same objective and cardinality: representative IDs define the tie.
|
||||
tied=csr_matrix((np.ones(8),([0,0,3,3,1,2,1,2],[1,2,1,2,0,0,3,3])),shape=(4,4))
|
||||
r=match(truth,pred,tied,20.);self.assertEqual([(x['truth_raw_id'],x['prediction_raw_id']) for x in r['pairs']],[(10,11),(13,12)])
|
||||
pred['events'][0]['death']=.56;r=match(truth,pred,a,30.);self.assertEqual(r['TP'],1)
|
||||
def test_empty_matching_denominators_undefined(self):
|
||||
r=match(dict(events=[]),dict(events=[]),line(2),1.)
|
||||
self.assertIsNone(r['precision']);self.assertIsNone(r['recall']);self.assertEqual(r['empty_class'],'both_empty')
|
||||
|
||||
|
||||
class PolicyTests(unittest.TestCase):
|
||||
def test_branch_units_sign_and_strict_boundaries(self):
|
||||
interval=lambda a,b:dict(low=a,high=b)
|
||||
self.assertEqual(branch_decision(interval(-.01,.0009),interval(-.2,-.1),interval(-.1,.1))['decision'],'EXPAND')
|
||||
self.assertEqual(branch_decision(interval(-.01,.001),interval(-.2,-.1),interval(-.1,.1))['decision'],'PARK')
|
||||
self.assertEqual(branch_decision(interval(.001,.002),interval(-.1,.1),interval(-.1,.1))['decision'],'PRUNE')
|
||||
self.assertEqual(branch_decision(interval(.001,.002),interval(-.1,0),interval(.01,.02))['decision'],'PARK')
|
||||
self.assertEqual(branch_decision(interval(0,1),None,None)['decision'],'PARK')
|
||||
def test_cost_gate_counts_failed_first_cell_and_factor(self):
|
||||
jobs=[dict(index=i,protocol='grouped' if i<15 else 'v4_random',learning_nodes=10) for i in range(20)]
|
||||
c=dict(jobs=jobs,budget=dict(fit=100,postfit=50))
|
||||
r=[dict(job_index=i,guard=dict(status='PASS',cpu_seconds=10,guard_cpu_seconds=0)) for i in (0,15)]
|
||||
q=projected_fits(c,r);self.assertFalse(q['pass_gate']);self.assertEqual(q['remaining_projection'],225)
|
||||
r[0]['guard']['status']='FAILED';self.assertFalse(projected_fits(c,r)['pass_gate'])
|
||||
def test_failed_worker_peak_checked_and_retry_denied(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
limits=dict(cpu_seconds=5,wall_seconds=5,rss_bytes=40*1024**2,disk_bytes=1024**3)
|
||||
receipt=supervise([sys.executable,'-c','x=bytearray(80*1024*1024); raise RuntimeError("synthetic numerical failure")'],Path(d)/'guard',limits,poll=.2)
|
||||
self.assertEqual(receipt['status'],'FAILED');self.assertGreater(receipt['peak_tree_rss_bytes'],limits['rss_bytes'])
|
||||
self.assertTrue(receipt['stop_reason']);self.assertGreater(receipt['cpu_seconds'],0)
|
||||
with self.assertRaises(FileExistsError):supervise([sys.executable,'-c','pass'],Path(d)/'guard',limits)
|
||||
|
||||
|
||||
class WorkerIntegrationTests(unittest.TestCase):
|
||||
def test_real_tiny_xgb_clock_fp64_and_prediction_target_denial(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base=Path(tmp);root=base/'execution';root.mkdir();parts={}
|
||||
for k in range(4):
|
||||
case=f'p{k}';out=base/case;out.mkdir();f=np.array([0.,.10000000001,.5,.9]);x=np.zeros((4,19),np.float32);x[:,0]=f
|
||||
physical=np.array([0.,1.,2.,float(k+3)])*2
|
||||
for name,value in [('Vf',f),('features',x),('raw_ids',np.arange(4)),('seconds',physical),('target',physical/2)]:np.save(out/(name+'.npy'),value)
|
||||
parts[case]=dict(case=case,output=str(out),nodes=4,t_set=2.,clock_group='g0' if k<2 else 'g1',output_sha256={p.name:worker.sha(p) for p in out.glob('*.npy')})
|
||||
job=dict(index=0,protocol='v4_random',learning=['p0','p1','p2'],test=['p3'],seed=0,threads=1)
|
||||
c=dict(parts={'v4_random':parts},jobs=[job]);worker.save(root/'contract.json',c)
|
||||
worker.fit(root,c,job);d=root/'fits/job-00';result=json.loads((d/'result.json').read_text())
|
||||
self.assertEqual(result['c'],4.25) # mean(mean(3,4),5)
|
||||
job['baseline_model']=dict(path=result['checkpoint'],sha256=result['checkpoint_sha256'],format='ubj')
|
||||
worker.save(root/'contract.json',c)
|
||||
worker.save(root/'batch-complete.json',dict(global_stop=None,accounting_complete=True,attempted=1))
|
||||
worker.save(root/'models-terminal.json',dict(models=[dict(index=0,status='PASS',checkpoint=result['checkpoint'],checkpoint_sha256=result['checkpoint_sha256'],clock_path=str(d/'clock.json'),clock_sha256=result['clock_sha256'])]))
|
||||
# Remove test truth; prediction must succeed without opening it.
|
||||
for name in ('target.npy','seconds.npy'):(Path(parts['p3']['output'])/name).unlink()
|
||||
repo=base/'git';repo.mkdir();subprocess.run(['git','init','-q',str(repo)],check=True)
|
||||
names=['contract.json','batch-complete.json','models-terminal.json']
|
||||
for name in names:
|
||||
dest=repo/'execution'/name;dest.parent.mkdir(exist_ok=True);shutil.copyfile(root/name,dest)
|
||||
subprocess.run(['git','-C',str(repo),'add','.'],check=True)
|
||||
subprocess.run(['git','-C',str(repo),'-c','user.name=Synthetic','-c','user.email=synthetic@localhost','commit','-qm','synthetic barrier'],check=True)
|
||||
commit=subprocess.check_output(['git','-C',str(repo),'rev-parse','HEAD'],text=True).strip()
|
||||
worker.save(root/'models-git-freeze.json',dict(commit=commit,checkout=str(repo),sha256={name:worker.sha(root/name) for name in names}))
|
||||
with patch.object(Path,'cwd',return_value=base):worker.predict(root,c,job)
|
||||
index=json.loads((root/'predictions/job-00/index.json').read_text());self.assertEqual(len(index),1)
|
||||
with np.load(index[0]['path']) as z:np.testing.assert_array_equal(z['cF_seconds'],4.25*f*2)
|
||||
def test_role_overlap_is_rejected_before_access(self):
|
||||
with self.assertRaises(PermissionError):worker.role_rows({},dict(learning=['same'],test=['same']),'learning')
|
||||
|
||||
|
||||
class CoordinatorBoundaryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.signals={s:signal.getsignal(s) for s in (signal.SIGTERM,signal.SIGINT)}
|
||||
self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name)
|
||||
self.c=dict(budget=dict(fit=100.,geometry=100.,postfit=1000.,disk_bytes=10**9,total_rss_bytes=10**9))
|
||||
def tearDown(self):
|
||||
for s,h in self.signals.items():signal.signal(s,h)
|
||||
self.tmp.cleanup()
|
||||
def test_reservation_stop_never_spawns(self):
|
||||
r=Runner(self.root,self.c);item=task('oversized',['-c','pass'],[8],101.)
|
||||
with patch('phase2_h1_execution.subprocess.Popen') as spawn,patch('phase2_h1_execution.time.sleep'):
|
||||
self.assertEqual(r.jobs('fit',[item]),[]);spawn.assert_not_called()
|
||||
self.assertEqual(r.stop,'STAGE_RESERVATION_LIMIT')
|
||||
def test_missing_guard_receipt_marks_incomplete_and_closes_children(self):
|
||||
r=Runner(self.root,self.c);proc=Mock();proc.pid=123456;proc.poll.return_value=0;proc.wait.return_value=0
|
||||
with patch('phase2_h1_execution.subprocess.Popen',return_value=proc),patch('phase2_h1_execution.time.sleep'):
|
||||
with self.assertRaises(RuntimeError):r.jobs('fit',[task('missing',['-c','pass'],[8],1.)])
|
||||
self.assertFalse(r.accounting_complete);self.assertEqual(r.active,{})
|
||||
self.assertTrue((self.root/'global-stop.json').exists())
|
||||
def test_monitor_failure_stops_before_spawn(self):
|
||||
r=Runner(self.root,self.c)
|
||||
with patch('phase2_h1_execution.disk_usage',side_effect=OSError('synthetic monitor failure')),patch('phase2_h1_execution.subprocess.Popen') as spawn:
|
||||
self.assertEqual(r.jobs('fit',[task('never',['-c','pass'],[8],1.)]),[]);spawn.assert_not_called()
|
||||
self.assertEqual(r.stop,'GLOBAL_MONITOR_ERROR')
|
||||
def test_scoring_tamper_rejected_before_target_access(self):
|
||||
import phase2_h1_postfit as post
|
||||
(self.root/'contract.json').write_text('{}')
|
||||
worker.save(self.root/'scoring-git-freeze.json',dict(sha256={'contract.json':'wrong'},commit='fake',checkout='unused'))
|
||||
with patch.object(post,'contract',return_value={}),patch.object(post.np,'load') as load:
|
||||
with self.assertRaises(ValueError):post.scoring_gate(self.root)
|
||||
load.assert_not_called()
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user