diff --git a/artifacts/r4bc-acceptance-2026-11-16/attempt-01/accepted-source.json b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/accepted-source.json new file mode 100644 index 000000000..9fee1d436 --- /dev/null +++ b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/accepted-source.json @@ -0,0 +1,18 @@ +{ + "tools/r4bc_common.py": "27543fff987975ece767167f9771e6621c825035a053805604e4a696794dfcbd", + "tools/r4bc_guard.py": "437a756ddf10b125dce450f463e76e28df52724f8c5766e0a989dfa536805628", + "tools/r4bc_fit.py": "7827c1dac077baf0659a93c8f992c3243285e4f6c0ab31a5f6b3711a148b5247", + "tools/r4bc_preflight.py": "45136c40d398f4f722125a236842a52eb43ba1f5231268fdb0cc5c673ab5445d", + "tools/run_r4bc.py": "dbe10041a4cafc59467fffaa3008429d5bb30772936505f081e054674c514abc", + "tools/prepare_r4bc.py": "7e1ae070b69a116227fd49cb4f39b5483c34f8b4c8fcf78b831dd382b2c1f80c", + "tools/test_r4bc.py": "93b3de09603d80535a9574bddb3394d80a69f3425f35f34344875d95e19eb84e", + "tools/r4bc_postfit.py": "02df42bc8cc9ce553db5dfbc047cf80955ceee5348faa306c37cab05933d9623", + "tools/gre24_models.py": "53b6fee8b700b9b982b06d29908ce2ce23e0c57512c46dbf74b2aade79e3ac3a", + "tools/s2_models/features.py": "3b34ae61cf8012ebd58b7505a73d7aa43d8ee1890ac54f98d7917b67887a45a4", + "tools/s2_models/objectives.py": "5b6527a45f08690055d572335470ce5979e8bb86e1cab00de594f79ae21316b1", + "tools/s2_recovery_supervisor.py": "f563ca3c2665f5baf0c04f296616e4640423a59b815fbb00479af0f29e57a919", + "tools/s2_recovery_monitoring.py": "442c2a9c75e8c00b30a8f2e91cb52d87c466b19a80aea9128b10c021e61b922e", + "tools/s2_custody_common.py": "588c646101be0d50f505f9a12a1c98361aa3437c8c594eecb7321831f717a741", + "tools/s2_custody_statistics.py": "188565801f6901d0192f79aec0889e632501e672a4149d76d1835efbb9b45447", + "tools/freeze_g1_components.py": "d0cee60d95243ac2c59ef3f2244ba818315718c4e3d1895f2f9f064f1f7f5ecd" +} diff --git a/artifacts/r4bc-acceptance-2026-11-16/attempt-01/ledger.json b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/ledger.json new file mode 100644 index 000000000..ad013b0dc --- /dev/null +++ b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/ledger.json @@ -0,0 +1,10 @@ +{ + "cpu_seconds_charged": 1.9702989999999998, + "attempts": [ + { + "name": "worker", + "status": "PASS", + "cpu_seconds": 1.9702989999999998 + } + ] +} diff --git a/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/access.json b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/access.json new file mode 100644 index 000000000..e33c93021 --- /dev/null +++ b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/access.json @@ -0,0 +1,20 @@ +[ + { + "case": "case-0", + "fold": 0, + "role": "learning", + "full": true, + "cached_label_path": "artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/fixture/case-0/label.npz", + "cached_label_sha256": "59b6af661cbd9d5de786969c96ffe505844819fdc03800e29bb3ef27b93222bc", + "v5_target_sha256": "a1650976faed5ffc51d7982fcc1f40139d66e0012af7fa99fd0ba05b29099366" + }, + { + "case": "case-1", + "fold": 0, + "role": "learning", + "full": true, + "cached_label_path": "artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/fixture/case-1/label.npz", + "cached_label_sha256": "6d9aec17a08c9f9bc2dba9f67eecc81bbe456426acf677ce621b26cdb544b076", + "v5_target_sha256": "f4e08b92f2f3e29c275ddb14c1dbe7a31c9969033869428b321f3c4c8acfb353" + } +] diff --git a/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/next-access.json b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/next-access.json new file mode 100644 index 000000000..bc4e46934 --- /dev/null +++ b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/next-access.json @@ -0,0 +1,6 @@ +{ + "case": "case-1", + "role": "learning", + "fold": 0, + "full": true +} diff --git a/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/training-fingerprints.json b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/training-fingerprints.json new file mode 100644 index 000000000..d03ac4bf6 --- /dev/null +++ b/artifacts/r4bc-acceptance-2026-11-16/attempt-01/synthetic/arrays-A/training-fingerprints.json @@ -0,0 +1,71 @@ +{ + "x": { + "shape": [ + 160, + 19 + ], + "dtype": "60 or initial>=7200: raise ValueError('Setup reserve exhausted') + root.mkdir(parents=True) + jobs = make_jobs(); save(root/'job-list.json', jobs) + c = dict(version='R4bc-shared-roster-five-steps-v1', + main_review=['1794832267.149719','1794833279.817489','1794833544.971179','1794833643.127119'], + reviewed_contract_commit='c98801f90d5c665638028d1aba67b1db0c5f74c0', + parts=parts, jobs=jobs, job_list_sha256=sha(root/'job-list.json'), + excluded_components=inventory['excluded_components'], source_sha256=sources, + code_sha256={str(Path('tools')/n):sha(Path('tools')/n) for n in CODE}, + worker_cpus=[24,26,28,29], coordinator_cpu=25, + initial_setup_cpu_seconds=initial, acceptance=tests, + limits=dict(total_cpu_seconds=144000,setup_cpu_seconds=7200,fit_cpu_seconds=122400, + post_cpu_seconds=14400,setup_wall_seconds=10800,post_wall_seconds=21600, + total_rss_bytes=36*2**30,disk_bytes=100*2**30,workers=4,retries=0), + fit_limits=dict(cpu_seconds=1800,wall_seconds=3600,rss_bytes=8*2**30,disk_bytes=100*2**30), + pool_order=[100,50,25],arm_order=['H0p','H1','H2','H3','H4','A','Q'], + first_cell=2, hist_hpo_configs=12, precision_bridge=False, + postfit_gate='All fit terminal/checkpoints Git frozen; then predictions; then prediction/code Git freeze before cached test scoring', + new_decodes=0,gpu=False,old_sources_unchanged=True) + save(root/'contract.json',c) + save(root/'prepared.json',dict(status='READY_FOR_GUARDED_INPUT_PREFLIGHT_NO_FITS',contract_sha256=sha(root/'contract.json'), + initial_setup_cpu_seconds=initial, parts=552,components=204,jobs=len(jobs))) + print(str(root), sha(root/'contract.json'), flush=True) + + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();prepare(a.root) diff --git a/tools/r4bc_common.py b/tools/r4bc_common.py new file mode 100644 index 000000000..488bae06b --- /dev/null +++ b/tools/r4bc_common.py @@ -0,0 +1,231 @@ +"""R4bc fixed protocol and checked inputs; no archive reader or fitting here.""" +import hashlib +import json +import math +from collections import Counter +from pathlib import Path + +import numpy as np +from s2_models.features import R2_COLUMNS, histgbrt_grid +from s2_recovery_supervisor import save + +ARMS = ('H0p', 'H1', 'H2', 'H3', 'H4', 'A', 'Q') +HIST = ARMS[:5] +POOLS = (100, 50, 25) + + +class InputViolation(ValueError): + """Identity/role/hash failures are global stops, never a failed HPO choice.""" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda: f.read(4 * 1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def checked(path, digest): + if sha(path) != digest: + raise InputViolation('Frozen hash mismatch: ' + str(path)) + return Path(path) + + +def exact(a, b, name): + if not np.array_equal(a, b): + raise InputViolation('Identity mismatch: ' + name) + + +def fingerprint(a): + a = np.ascontiguousarray(a) + return dict(shape=list(a.shape), dtype=a.dtype.str, + sha256=hashlib.sha256(a.tobytes()).hexdigest()) + + +def contract(root, *, inputs=True): + c = read(Path(root) / 'contract.json') + for path, digest in c['code_sha256'].items(): + checked(path, digest) + if inputs: + for path, digest in c['source_sha256'].items(): + checked(path, digest) + return c + + +def require_role(row, fold, role, pool): + a = next(x for x in row['assignments'] if x['fold'] == fold) + if a['role'] != role or (role == 'learning' and str(pool) not in a['learning_pools']): + raise InputViolation('Role denied: ' + row['case'] + '/' + role) + + +def role_rows(c, fold, pool, role): + result = [] + for row in c['parts']: + a = next(x for x in row['assignments'] if x['fold'] == fold) + if a['role'] == role and (role != 'learning' or str(pool) in a['learning_pools']): + result.append(row) + return sorted(result, key=lambda r: r['case']) + + +def make_jobs(): + jobs = [] + for pool in POOLS: + for fold in range(5): + cell = fold * 3 + (25, 50, 100).index(pool) + for arm in ARMS: + for config in (range(12) if arm in HIST else []): + jobs.append(dict(index=len(jobs), cell=cell, fold=fold, pool=pool, + arm=arm, kind='HPO', config_index=config)) + jobs.append(dict(index=len(jobs), cell=cell, fold=fold, pool=pool, + arm=arm, kind='FINAL', config_index=None)) + assert len(jobs) == 1005 + return jobs + + +def spec(arm): + if arm not in ARMS: + raise ValueError(arm) + return dict(columns=20 if arm == 'H0p' else 19, + geometry='historical' if arm in ('H0p', 'H1') else 'tet', + support='all' if arm in ('H4', 'A') else 'query', + weights='hierarchy' if arm in ('H0p', 'H1', 'H2', 'Q') else 'unit', + dtype='float32' if arm in ('A', 'Q') else 'float64', + learner='XGB' if arm in ('A', 'Q') else 'Hist') + + +def hierarchy_weights(counts, components, *, xgb=False): + if len(counts) != len(components) or not counts: + raise InputViolation('Weight parts mismatch') + groups = Counter(components) + ws = [] + for cc, group in zip(counts, components): + cc = np.asarray(cc, dtype=np.float64) + if not len(cc) or not np.isfinite(cc).all() or np.any(cc <= 0): + raise InputViolation('Invalid query counts') + ws.append(cc / cc.sum() / groups[group] / len(groups)) + w = np.concatenate(ws) + if not np.isclose(w.sum(), 1., rtol=0, atol=1e-12): + raise InputViolation('Hierarchy sum differs from one') + return w * len(w) if xgb else w + + +def selection(trials): + if len(trials) != 12 or sorted(t['config_index'] for t in trials) != list(range(12)): + raise InputViolation('Selection requires all 12 terminal HPO attempts') + good = [t for t in trials if t['status'] == 'PASS' and t.get('score') is not None + and math.isfinite(t['score'])] + best = min(good, key=lambda t: (t['score'], t['config_index'])) if good else None + return dict(status='SELECTED' if best else 'NA_ALL_HPO_FAILED', + config_index=best['config_index'] if best else None, trials=trials, + finished_configurations=len(good), failed_configurations=12-len(good)) + + +def can_reserve(spent, active, cap, per_job=1800.): + return math.isfinite(spent) and spent >= 0 and spent + (active + 1) * per_job <= cap + + +def selection_path(root, job): + return Path(root) / 'selections' / f"cell-{job['cell']:02d}-{job['arm']}.json" + + +def job_dir(root, index): + return Path(root) / 'jobs' / f'job-{index:04d}' + + +def relative_l2(pred, truth, counts): + denominator = float(np.sum(counts * truth * truth)) + if denominator <= 0: + return None + return float(np.sqrt(np.sum(counts * (pred - truth)**2) / denominator)) + + +def query_inputs(row): + prep = row['preparation']; source = Path(prep['preparation_root']) + with np.load(checked(source/'queries.npz', prep['output_sha256']['queries.npz']), allow_pickle=False) as z: + keep = z['eligible_s2'] + out = dict(ids=z['anchor_ids'][keep].copy(), raw_ids=z['raw_node_ids'][keep].copy(), + counts=z['multiplicity'][keep].copy(), near_wall=z['near_wall'][keep].copy()) + if not len(out['ids']) or np.any(np.diff(out['raw_ids']) <= 0) or np.any(out['counts'] <= 0): + raise InputViolation('Invalid distinct query IDs/counts') + return out + + +def tet_indices(row, query): + v = row['v5_cache']; path = Path(v['output'])/'raw_ids.npy' + raw = np.load(checked(path, v['output_sha256']['raw_ids.npy']), allow_pickle=False) + if len(raw) != row['nodes'] or np.any(np.diff(raw) <= 0): + raise InputViolation('Tet node identity') + ids = np.searchsorted(raw, query['raw_ids']) + if np.any(ids >= len(raw)): + raise InputViolation('Query outside tet domain') + exact(raw[ids], query['raw_ids'], 'tet queries') + return ids + + +def features(row, arm, *, full=False): + q = query_inputs(row); cfg = spec(arm); v = row['v5_cache']; prep = row['preparation'] + if cfg['geometry'] == 'historical': + with np.load(checked(Path(prep['preparation_root'])/'r2.npz', prep['output_sha256']['r2.npz']), allow_pickle=False) as z: + data = z['features'] + if data.shape != (row['nodes'], 20): + raise InputViolation('Historical 20-column shape') + x = data[q['ids']].copy() + exact(x[:, -1], np.full(len(x), prep['t_set']), 'historical t_set') + if arm == 'H1': + x = x[:, :-1] + else: + path = checked(Path(v['output'])/'features.npy', v['output_sha256']['features.npy']) + data = np.load(path, mmap_mode='r', allow_pickle=False) + if data.shape != (row['nodes'], 19): + raise InputViolation('Tet 19-column shape') + x = data if full else data[tet_indices(row, q)] + x = np.asarray(x, dtype=cfg['dtype']) + if not np.isfinite(x).all(): + raise InputViolation('Nonfinite features') + return x, q + + +def targets(row, job, role, *, full, access): + if role not in ('learning', 'validation') or (role == 'validation' and job['kind'] != 'HPO'): + raise InputViolation('Target role forbidden before prediction freeze') + require_role(row, job['fold'], role, job['pool']) + q = query_inputs(row); v = row['v5_cache']; label = row['label'] + # Record intended accesses before any target values are loaded. + access.append(dict(case=row['case'], fold=job['fold'], role=role, full=full, + cached_label_path=label['path'], cached_label_sha256=label['sha256'], + v5_target_sha256=v['output_sha256']['target.npy'])) + with np.load(checked(label['path'], label['sha256']), allow_pickle=False) as z: + exact(z['raw_ids'], q['raw_ids'], 'label query IDs') + exact(z['counts'], q['counts'], 'label counts') + truth = z['seconds'].copy() + path = checked(Path(v['output'])/'target.npy', v['output_sha256']['target.npy']) + yfull = np.load(path, mmap_mode='r', allow_pickle=False) + iq = tet_indices(row, q) + scale = float(row['preparation']['t_set']) + if scale <= 0 or scale != float(v['t_scale_seconds']): + raise InputViolation('t_set mismatch') + exact(yfull[iq], truth / scale, 'S2 and v5 normalized targets') + y = np.array(yfull if full else truth/scale, dtype=spec(job['arm'])['dtype']) + if not np.isfinite(y).all() or np.any(y < 0): + raise InputViolation('Invalid cached target') + return y, truth + + +def paired_difference(before, after, *, seed=2026111408, replicates=2000): + ids = sorted(set(before) & set(after)) + if not ids: + return dict(value=None, low=None, high=None, components=0, undefined_replicates=replicates) + d = np.array([before[g] - after[g] for g in ids], dtype=np.float64) + if not np.isfinite(d).all(): + raise InputViolation('Undefined component passed to bootstrap') + rng = np.random.default_rng(seed) + values = np.array([d[rng.integers(0, len(d), len(d))].mean() for _ in range(replicates)]) + low, high = np.percentile(values, [2.5, 97.5], method='linear') + return dict(value=float(d.mean()), low=float(low), high=float(high), components=len(ids), + component_ids=ids, replicates=replicates, seed=seed, undefined_replicates=0, + formula='mean(before)-mean(after)', interval='component-paired percentile95; descriptive') diff --git a/tools/r4bc_fit.py b/tools/r4bc_fit.py new file mode 100644 index 000000000..5b46cbffd --- /dev/null +++ b/tools/r4bc_fit.py @@ -0,0 +1,122 @@ +"""One R4bc HPO/final job: cached targets scoped to learning/validation only.""" +import argparse +import json +import os +from pathlib import Path +import time +import traceback + +import joblib +import numpy as np +import sklearn +from sklearn.ensemble import HistGradientBoostingRegressor +from threadpoolctl import threadpool_limits, threadpool_info +from r4bc_common import (ARMS, HIST, InputViolation, contract, read, checked, sha, save, + spec, role_rows, require_role, features, targets, hierarchy_weights, + histgbrt_grid, relative_l2, selection_path, job_dir, fingerprint) +from gre24_models import xgb_model + + +def assemble(c, job, output, access): + rows = role_rows(c, job['fold'], job['pool'], 'learning'); cfg = spec(job['arm']) + full = cfg['support'] == 'all' + n = sum(r['nodes'] if full else r['preparation']['eligible_unique'] for r in rows) + x = np.empty((n, cfg['columns']), dtype=cfg['dtype']); y = np.empty(n, dtype=cfg['dtype']) + cursor = 0; counts = []; groups = []; identities = [] + for row in rows: + require_role(row, job['fold'], 'learning', job['pool']) + save(output/'next-access.json', dict(case=row['case'], role='learning', fold=job['fold'], full=full)) + xx, q = features(row, job['arm'], full=full) + yy, _ = targets(row, job, 'learning', full=full, access=access) + if len(xx) != len(yy): raise InputViolation('Feature/target rows differ') + end = cursor+len(yy); x[cursor:end] = xx; y[cursor:end] = yy; cursor = end + counts.append(q['counts']); groups.append(row['component_id']) + identities.append(dict(case=row['case'], nodes=len(yy), query_raw_ids=fingerprint(q['raw_ids']), + counts=fingerprint(q['counts']))) + save(output/'access.json', access) + if cursor != n or not n: raise InputViolation('Empty/miscounted learning rows') + w = hierarchy_weights(counts, groups, xgb=job['arm']=='Q') if cfg['weights']=='hierarchy' else np.ones(n, dtype=np.float64) + if len(w) != n: raise InputViolation('Weights/support mismatch') + save(output/'training-fingerprints.json', dict(x=fingerprint(x), y=fingerprint(y), weights=fingerprint(w), + order=identities, weight_sum=float(w.sum()), spec=cfg)) + return x, y, w, rows + + +def validate(model, c, job, output, access): + rows = role_rows(c, job['fold'], job['pool'], 'validation'); groups = {}; parts = [] + for row in rows: + require_role(row, job['fold'], 'validation', job['pool']) + save(output/'next-access.json', dict(case=row['case'], role='validation', fold=job['fold'], full=False)) + x, q = features(row, job['arm'], full=False) + _, truth = targets(row, job, 'validation', full=False, access=access) + pred = np.asarray(model.predict(x), dtype=np.float64)*row['preparation']['t_set'] + if not np.isfinite(pred).all(): raise ValueError('Nonfinite validation prediction') + error = relative_l2(pred, truth, q['counts']) + if error is None or not np.isfinite(error): raise ValueError('Undefined validation error') + groups.setdefault(row['component_id'], []).append(error) + parts.append(dict(case=row['case'], error=error)); save(output/'access.json', access) + if not groups: raise InputViolation('No validation components') + save(output/'validation-parts.json', parts) + return float(np.mean([np.mean(v) for v in groups.values()])) + + +def run(root, index): + start = time.monotonic(); cpu = time.process_time(); c = contract(root); job = c['jobs'][index] + output = job_dir(root, index)/'output'; output.mkdir(exist_ok=False); access = [] + save(output/'started.json', dict(pid=os.getpid(), unix=time.time(), job=job, contract_sha256=sha(root/'contract.json'))) + try: + if sklearn.__version__ != '1.7.2' or np.__version__ != '1.26.4': + raise InputViolation('Frozen library version differs') + config_index = job['config_index']; selected = None + if job['arm'] in HIST and job['kind']=='FINAL': + path = selection_path(root, job); selected = read(path) + if selected['status'] != 'SELECTED': raise InputViolation('Final without completed selection') + for trial in selected['trials']: checked(trial['receipt_path'], trial['receipt_sha256']) + config_index = selected['config_index']; save(output/'selection.json', dict(path=str(path), sha256=sha(path), **selected)) + with threadpool_limits(1): + pools = threadpool_info() + if any(p['num_threads']!=1 for p in pools): raise InputViolation('Thread limit violated') + save(output/'progress.json', dict(stage='LOAD_LEARNING', job=job)) + x, y, weights, rows = assemble(c, job, output, access) + loaded_cpu = time.process_time()-cpu + if job['arm'] in HIST: + params = histgbrt_grid()[config_index]; model = HistGradientBoostingRegressor(**params) + else: + import xgboost + if xgboost.__version__ != '2.1.4': raise InputViolation('XGBoost version differs') + model = xgb_model(0, 1); params = {k:('NaN library missing marker' if isinstance(v,float) and np.isnan(v) else v) for k,v in model.get_params().items()} + save(output/'progress.json', dict(stage='FIT', job=job, rows=len(y), load_cpu_seconds=loaded_cpu)) + before = time.process_time() + model.fit(x, y, sample_weight=weights) + fitted_cpu = time.process_time()-before + if job['arm'] in HIST and model.n_iter_ != params['max_iter']: raise InputViolation('Unplanned early stop') + learning_nodes = len(y); del x, y, weights + score = None + if job['kind']=='HPO': + save(output/'progress.json', dict(stage='VALIDATION', job=job, fit_cpu_seconds=fitted_cpu)) + score = validate(model, c, job, output, access) + path = output/'model.joblib' + joblib.dump(model, path, compress=3) + if job['arm'] not in HIST: (output/'xgboost-config.json').write_text(model.get_booster().save_config()) + result = dict(status='COMPLETE', job=job, config_index=config_index, params=params, + validation_score=score, model_path=str(path), model_sha256=sha(path), + load_cpu_seconds=loaded_cpu, fit_cpu_seconds=fitted_cpu, + worker_cpu_seconds=time.process_time()-cpu, wall_seconds=time.monotonic()-start, + learning_nodes=learning_nodes, learning_parts=len(rows), + learning_components=len({r['component_id'] for r in rows}), + access_sha256=sha(output/'access.json'), threadpools=pools, + cpu_affinity=sorted(os.sched_getaffinity(0)), test_labels_read=False, + new_decodes=0, retry=False, final_learning_only=job['kind']=='FINAL') + save(output/'result.json', result); save(output/'progress.json', dict(stage='COMPLETE', job=job)) + return 0 + except Exception as exc: + save(output/'access.json', access) + save(output/'failure.json', dict(type=type(exc).__name__, message=str(exc), traceback=traceback.format_exc(), + global_stop=isinstance(exc, InputViolation), cpu_seconds=time.process_time()-cpu, + wall_seconds=time.monotonic()-start, retry=False)) + raise + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(); parser.add_argument('root', type=Path); parser.add_argument('index', type=int) + args = parser.parse_args(); raise SystemExit(run(args.root, args.index)) diff --git a/tools/r4bc_guard.py b/tools/r4bc_guard.py new file mode 100644 index 000000000..c7f2a09af --- /dev/null +++ b/tools/r4bc_guard.py @@ -0,0 +1,118 @@ +"""Single attempt CPU guard; global stop requests retain wait4 accounting.""" +import argparse +import ctypes +import fcntl +import json +import math +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + +from s2_recovery_supervisor import save, tree_usage, stop_group +from s2_recovery_monitoring import disk_usage + + +def supervise(command, dest, limits, *, global_stop=None, poll=.2): + dest = Path(dest); dest.mkdir(parents=True, exist_ok=True) + if any(not math.isfinite(v) or v <= 0 for v in limits.values()): + raise ValueError('Invalid guard limit') + with (dest/'execution.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (dest/'worker.started.json').exists() or (dest/'worker.receipt.json').exists(): + raise FileExistsError('Single attempt; no restart') + save(dest/'worker.started.json', dict(command=command, limits=limits, unix=time.time())) + requested = [None] + def stop(signum, frame): + requested[0] = 'GUARD_SIGNAL_'+str(signum) + prior = {s: signal.signal(s, stop) for s in (signal.SIGTERM, signal.SIGINT)} + libc = ctypes.CDLL(None, use_errno=True); previous = ctypes.c_int() + if libc.prctl(37, ctypes.byref(previous), 0, 0, 0) or libc.prctl(36, 1, 0, 0, 0): + raise OSError('Cannot enable descendant accounting') + start = time.monotonic(); last = start; reason = None; errors = [] + cpu_peak = rss_peak = proc_peak = gap = 0; usage = None; exit_status = None + env = dict(os.environ, OMP_NUM_THREADS='1', OPENBLAS_NUM_THREADS='1', MKL_NUM_THREADS='1', + NUMEXPR_NUM_THREADS='1', CUDA_VISIBLE_DEVICES='') + try: + with (dest/'worker.log').open('x') as log: + child = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True) + save(dest/'worker-pid.json', dict(pid=child.pid, unix=time.time(), guard_pid=os.getpid())) + try: + while True: + now = time.monotonic(); gap = max(gap, now-last); last = now + try: + cpu, rss, count = tree_usage(child.pid) + disk = disk_usage(dest) + cpu_peak = max(cpu_peak, cpu); rss_peak = max(rss_peak, rss); proc_peak = max(proc_peak, count) + except Exception as exc: + errors.append(dict(type=type(exc).__name__, message=str(exc))) + reason = 'MONITOR_ERROR' + if requested[0]: reason = reason or requested[0] + if global_stop and Path(global_stop).exists(): reason = reason or 'GLOBAL_STOP_REQUEST' + if now-start >= limits['wall_seconds']: reason = reason or 'wall_limit' + if cpu_peak >= limits['cpu_seconds']: reason = reason or 'cpu_limit' + if rss_peak > limits['rss_bytes']: reason = reason or 'rss_limit' + if proc_peak > 1: reason = reason or 'process_count_limit' + if not errors and disk >= limits['disk_bytes']: reason = reason or 'disk_limit' + if reason: stop_group(child.pid) + pid, status, current_usage = os.wait4(child.pid, 0 if reason else os.WNOHANG) + if pid: + usage = current_usage; exit_status = status; break + time.sleep(poll) + finally: + stop_group(child.pid) + if exit_status is None: + _, exit_status, usage = os.wait4(child.pid, 0) + child.returncode = os.waitstatus_to_exitcode(exit_status) + orphan_cpu = 0.; orphan_rss = 0 + while True: + try: _, _, u = os.wait4(-child.pid, 0) + except ChildProcessError: break + orphan_cpu += u.ru_utime + u.ru_stime + orphan_rss = max(orphan_rss, u.ru_maxrss*1024) + wall = time.monotonic()-start + charged = max(cpu_peak, usage.ru_utime+usage.ru_stime+orphan_cpu) + rss_peak = max(rss_peak, usage.ru_maxrss*1024, orphan_rss) + # Inspect final peaks even when a numerical exception returned nonzero. + if charged > limits['cpu_seconds']: reason = reason or 'cpu_limit_after_exit' + if wall > limits['wall_seconds']: reason = reason or 'wall_limit_after_exit' + if rss_peak > limits['rss_bytes']: reason = reason or 'rss_limit_after_exit' + result = dict(status='PASS' if child.returncode == 0 and reason is None else 'FAILED', + returncode=child.returncode, stop_reason=reason, cpu_seconds=charged, + wall_seconds=wall, peak_tree_rss_bytes=rss_peak, peak_process_count=proc_peak, + monitor_errors=errors, max_poll_gap_seconds=gap, reaped_orphan_cpu_seconds=orphan_cpu, + limits=limits, retry=False, gpu_visible=False) + save(dest/'worker.receipt.json', result) + return result + finally: + libc.prctl(36, previous.value, 0, 0, 0) + for signum, handler in prior.items(): signal.signal(signum, handler) + + +def run(root, index, slot): + from r4bc_common import contract, job_dir, read, sha + c = contract(root); os.sched_setaffinity(0, [c['worker_cpus'][slot]]) + dest = job_dir(root, index) + receipt = supervise([sys.executable, 'tools/r4bc_fit.py', str(root), str(index)], dest, + c['fit_limits'], global_stop=Path(root)/'global-stop.json') + result_path = dest/'output/result.json'; failure_path = dest/'output/failure.json' + if receipt['status'] == 'PASS' and not result_path.exists(): + receipt.update(status='FAILED', stop_reason='MISSING_RESULT') + failure = read(failure_path) if failure_path.exists() else None + global_failure = bool(receipt['monitor_errors']) or bool(failure and failure.get('global_stop')) + if global_failure and not (Path(root)/'global-stop.json').exists(): + save(Path(root)/'global-stop.json', dict(reason='WORKER_INPUT_OR_MONITOR_FAILURE', job=index, failure=failure)) + record = dict(index=index, job=c['jobs'][index], worker=receipt, global_failure=global_failure, + guard_cpu_seconds=time.process_time(), result_path=str(result_path) if result_path.exists() else None, + result_sha256=sha(result_path) if result_path.exists() else None) + save(dest/'guard-result.json', record) + return 0 if receipt['status'] == 'PASS' else 1 + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(); parser.add_argument('root', type=Path) + parser.add_argument('index', type=int); parser.add_argument('slot', type=int) + args = parser.parse_args(); raise SystemExit(run(args.root, args.index, args.slot)) diff --git a/tools/r4bc_postfit.py b/tools/r4bc_postfit.py new file mode 100644 index 000000000..a79cbe18e --- /dev/null +++ b/tools/r4bc_postfit.py @@ -0,0 +1,156 @@ +"""Postfit stages require actual Git-frozen manifests; never launch fits or decode VTU.""" +import argparse +from pathlib import Path +import subprocess +import time +import hashlib + +import joblib +import numpy as np +from threadpoolctl import threadpool_limits +from r4bc_common import (contract, read, checked, sha, save, role_rows, require_role, features, + query_inputs, exact, InputViolation, paired_difference, ARMS) +from s2_custody_common import prediction_inputs +from s2_custody_statistics import part_metrics + +METRICS=('relative_l2','kendall_tau_b','last_location','near_wall') + + +def git_gate(root, name, required): + proof=read(root/name) + if not proof.get('commit') or not proof.get('checkout'):raise InputViolation('No Git freeze evidence') + for rel in required: + path=root/rel;expected=proof['sha256'][rel];checked(path,expected) + repository_path=str(path.relative_to(Path.cwd())) if path.is_absolute() else str(path) + raw=subprocess.check_output(['git','show',proof['commit']+':'+repository_path],cwd=proof['checkout']) + if hashlib.sha256(raw).hexdigest()!=expected:raise InputViolation('Git object differs from local freeze') + return proof + + +def training_gate(root): + c=contract(root);git_gate(root,'training-git-freeze.json',['contract.json','batch-complete.json','models-terminal.json']) + done=read(root/'batch-complete.json') + if done['global_stop'] or not done['accounting_complete'] or done['postfit_state']!='READY_FOR_GIT_CHECKPOINT_FREEZE': + raise InputViolation('Training terminal gate not satisfied') + checked(root/'models-terminal.json',done['model_manifest_sha256']) + return c,read(root/'models-terminal.json')['models'] + + +def predict(root,cell,arm): + c,models=training_gate(root) + m=next(m for m in models if m['cell']==cell and m['arm']==arm) + if m['status']!='PASS':raise InputViolation('No valid final checkpoint') + dest=root/'predictions'/f'cell-{cell:02d}-{arm}';dest.mkdir(parents=True,exist_ok=False) + start=time.process_time();index={} + with threadpool_limits(1): + model=joblib.load(checked(m['model_path'],m['model_sha256'])) + for row in role_rows(c,m['fold'],m['pool'],'test'): + require_role(row,m['fold'],'test',m['pool']) + x,q=features(row,arm,full=False) + pred=np.asarray(model.predict(x),dtype=np.float64)*row['preparation']['t_set'] + if pred.shape!=q['raw_ids'].shape or not np.isfinite(pred).all():raise ValueError('Invalid test prediction') + path=dest/(row['case']+'.npz') + np.savez_compressed(path,seconds=pred,raw_ids=q['raw_ids'],counts=q['counts']) + index[row['case']]=dict(path=str(path),sha256=sha(path),array='seconds') + save(dest/'progress.json',dict(parts=len(index),cpu_seconds=time.process_time()-start)) + save(dest/'index.json',index) + save(dest/'result.json',dict(status='COMPLETE',cell=cell,arm=arm,index_sha256=sha(dest/'index.json'), + model_sha256=m['model_sha256'],cpu_seconds=time.process_time()-start, + target_values_read=False,new_decodes=0,model_fit=False)) + + +def freeze_predictions(root): + c,models=training_gate(root);entries=[];missing=[] + for m in models: + dest=root/'predictions'/f"cell-{m['cell']:02d}-{m['arm']}" + guard=root/'prediction-guards'/f"cell-{m['cell']:02d}-{m['arm']}"/'worker.receipt.json' + if m['status']!='PASS' or not guard.exists() or read(guard)['status']!='PASS': + missing.append(dict(cell=m['cell'],arm=m['arm'],reason=m['reason'] or 'PREDICTION_NOT_PASS'));continue + result=read(dest/'result.json');checked(dest/'index.json',result['index_sha256']) + index=read(dest/'index.json') + expected={r['case'] for r in role_rows(c,m['fold'],m['pool'],'test')} + if set(index)!=expected:raise InputViolation('Prediction domain incomplete') + for case,v in index.items(): + checked(v['path'],v['sha256']);entries.append(dict(pool=m['pool'],fold=m['fold'],arm=m['arm'],case=case,**v)) + for row in c['parts']: + fold=next(a['fold'] for a in row['assignments'] if a['role']=='test') + for pool in (100,50,25): + h=row['historical_predictions'][str(pool)];checked(h['path'],h['sha256']) + entries.append(dict(pool=pool,fold=fold,arm='H0',case=row['case'],array='seconds',**h)) + e=row['r4a'];checked(e['predictions'],e['predictions_sha256']) + entries.append(dict(pool=pool,fold=fold,arm='EIK',case=row['case'],array='F',path=e['predictions'],sha256=e['predictions_sha256'])) + save(root/'predictions-freeze.json',dict(contract_sha256=sha(root/'contract.json'), + models_terminal_sha256=sha(root/'models-terminal.json'),entries=entries,missing=missing, + target_values_read=False,new_decodes=0,common_parts=552,common_components=204)) + + +def component_table(rows, roster, arms, metric): + by={(r['case'],r['arm']):r for r in rows};groups={} + for r in roster:groups.setdefault(r['component_id'],[]).append(r['case']) + values={a:{} for a in arms};excluded={} + for group,cases in groups.items(): + missing=[(case,a) for case in cases for a in arms + if by.get((case,a),{}).get(metric,{}).get('value') is None + or not np.isfinite(by.get((case,a),{}).get(metric,{}).get('value',np.nan))] + if missing:excluded[group]=missing;continue + for arm in arms:values[arm][group]=float(np.mean([by[case,arm][metric]['value'] for case in cases])) + ids=sorted(next(iter(values.values()))) + return dict(components=len(ids),parts=sum(len(groups[g]) for g in ids),component_ids=ids, + means={a:float(np.mean(list(v.values()))) if v else None for a,v in values.items()}, + values=values,excluded_components=excluded) + + +def score(root): + c,_=training_gate(root) + git_gate(root,'scoring-git-freeze.json',['contract.json','predictions-freeze.json']) + frozen=read(root/'predictions-freeze.json') + if frozen['contract_sha256']!=sha(root/'contract.json'):raise InputViolation('Prediction contract mismatch') + for e in frozen['entries']:checked(e['path'],e['sha256']) + # Every prediction is verified before the first cached test target value. + entries={} + for e in frozen['entries']:entries.setdefault(e['case'],[]).append(e) + out=root/'scores';out.mkdir(exist_ok=False);start=time.process_time();rows=[];access=[] + for row in c['parts']: + case=row['case'];q=prediction_inputs(row);label=row['label'] + with np.load(checked(label['path'],label['sha256']),allow_pickle=False) as z: + exact(z['raw_ids'],q['raw_ids'],'scoring target IDs');exact(z['counts'],q['counts'],'scoring target counts') + truth=z['seconds'].copy() + access.append(dict(case=case,path=label['path'],sha256=label['sha256'])) + for entry in entries[case]: + with np.load(entry['path'],allow_pickle=False) as z: + exact(z['raw_ids'],q['raw_ids'],'scoring prediction IDs');exact(z['counts'],q['counts'],'scoring prediction counts') + metrics=part_metrics(z[entry['array']],truth,q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'],int(case.split('_')[0])) + rows.append(dict(case=case,component_id=row['component_id'],pool=entry['pool'],fold=entry['fold'],arm=entry['arm'],**metrics)) + save(out/'progress.json',dict(parts=len(access),cpu_seconds=time.process_time()-start)) + summary={} + edges=[('H0','H0p'),('H0p','H1'),('H1','H2'),('H2','H3'),('H3','H4'),('H4','A')] + for pool in (100,50,25): + selected=[r for r in rows if r['pool']==pool];info={} + for metric in METRICS: + b=component_table(selected,c['parts'],('EIK','A','Q'),metric) + chain=component_table(selected,c['parts'],('H0p','H1','H2','H3','H4','A'),metric) + edge_reports={} + for before,after in edges: + item=component_table(selected,c['parts'],(before,after),metric) + if metric=='relative_l2':item['difference']=paired_difference(item['values'][before],item['values'][after]) + edge_reports[before+'->'+after]=item + if metric=='relative_l2': + b['differences']={a+'->'+z:paired_difference(b['values'][a],b['values'][z]) for a,z in [('EIK','A'),('EIK','Q'),('Q','A')]} + info[metric]=dict(primary=b,chain_common=chain,edges=edge_reports) + folds={a:sorted({r['fold'] for r in selected if r['arm']==a}) for a in ARMS} + summary[str(pool)]=dict(metrics=info,valid_prediction_folds=folds, + complete_five_fold_all_arms=all(len(v)==5 for v in folds.values())) + save(out/'part-scores.json',rows);save(out/'target-access.json',access) + save(out/'summary.json',dict(status='SCORED_DESCRIPTIVE',pools=summary, + predictions_freeze_sha256=sha(root/'predictions-freeze.json'),new_decodes=0,new_fits=0, + part_scores_sha256=sha(out/'part-scores.json'),cpu_seconds=time.process_time()-start, + limitations=['Fixed grouped v5 domain; not fresh blind evaluation','Failure domains reported per comparison', + 'H0 reference only; H0 to H0p includes roster/HPO response','Final learner step includes float32 and training policy'])) + + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('mode',choices=['predict','freeze','score']) + p.add_argument('--cell',type=int);p.add_argument('--arm',choices=ARMS);a=p.parse_args() + if a.mode=='predict':predict(a.root,a.cell,a.arm) + elif a.mode=='freeze':freeze_predictions(a.root) + else:score(a.root) diff --git a/tools/r4bc_preflight.py b/tools/r4bc_preflight.py new file mode 100644 index 000000000..c41b3a2b6 --- /dev/null +++ b/tools/r4bc_preflight.py @@ -0,0 +1,62 @@ +"""Hash and geometry/query identity preflight, with zero target-value reads.""" +import argparse +from pathlib import Path +import time +import numpy as np +from r4bc_common import (contract, checked, read, sha, save, exact, fingerprint, + query_inputs, tet_indices, R2_COLUMNS, InputViolation) + + +def run(root): + start=time.process_time(); c=contract(root); out=root/'input-preflight'; out.mkdir(exist_ok=False) + index={}; records=[] + def check(p,h): + checked(p,h);index[str(p)]=h;return Path(p) + for row in c['parts']: + case=row['case'];p=row['preparation'];v=row['v5_cache'];s=Path(p['preparation_root']);t=Path(v['output']) + old=read(check(s/'result.json',p['result_sha256']));new=read(check(t/'result.json',v['result_sha256'])) + if old['case']!=case or new['case']!=case or new['status']!='PASS':raise InputViolation('Preparation case/status') + if old['r2']['columns']!=list(R2_COLUMNS) or new['features']['columns']!=list(R2_COLUMNS[:-1]):raise InputViolation('Feature columns') + if p['t_set']!=v['t_scale_seconds'] or new['t_scale_seconds']!=p['t_set']:raise InputViolation('t_set provenance') + for name in ('queries.npz','r2.npz','geometry.npz','base.npy'): + check(s/name,p['output_sha256'][name]) + # Hash target files as bytes only; no target values are opened in this phase. + for name in ('features.npy','raw_ids.npy','target.npy','seconds.npy'): + check(t/name,v['output_sha256'][name]) + check(row['label']['path'],row['label']['sha256']) + q=query_inputs(row);iq=tet_indices(row,q) + if len(iq)!=p['eligible_unique']:raise InputViolation('Query count differs from manifest') + r4a=read(check(row['r4a']['result'],row['r4a']['result_sha256'])) + check(row['r4a']['predictions'],row['r4a']['predictions_sha256']) + if not r4a['cache_identity_verified'] or r4a['case']!=case:raise InputViolation('R4a cache identity unavailable') + with np.load(s/'geometry.npz',allow_pickle=False) as z: + raw=np.load(t/'raw_ids.npy',allow_pickle=False) + exact(z['raw_node_ids'],raw,'full raw IDs') + for key,field in [('points_raw','mesh_x'),('tetra','mesh_t')]: + if fingerprint(z[key])!=r4a['fingerprints'][field]:raise InputViolation('Geometry/frame fingerprint') + exact(z['gate_location_raw'],new['geometry']['inlet_config']['inlet_location'],'gate metadata') + for key,field in [('raw_ids','query_raw_ids'),('counts','query_counts')]: + if fingerprint(q[key])!=r4a['fingerprints'][field]:raise InputViolation('Query identity fingerprint') + with np.load(s/'r2.npz',allow_pickle=False) as z: + x=z['features'];h=x[q['ids']] + if x.shape!=(row['nodes'],20) or not np.isfinite(h).all():raise InputViolation('Historical query features') + exact(h[:,-1],np.full(len(h),p['t_set']),'historical process column') + x=np.load(t/'features.npy',mmap_mode='r',allow_pickle=False) + if x.shape!=(row['nodes'],19) or not np.isfinite(x).all():raise InputViolation('Tet feature coverage') + for oldpred in row['historical_predictions'].values(): + with np.load(check(oldpred['path'],oldpred['sha256']),allow_pickle=False) as z: + exact(z['raw_ids'],q['raw_ids'],'historical prediction IDs') + exact(z['counts'],q['counts'],'historical prediction counts') + if not np.isfinite(z['seconds']).all():raise InputViolation('Nonfinite historical prediction') + records.append(dict(case=case,nodes=row['nodes'],query_rows=len(iq),geometry_identity=True, + historical_dtype=str(h.dtype),tet_dtype=str(x.dtype),targets_values_read=False)) + save(out/'progress.json',dict(parts=len(records),total=len(c['parts']),cpu_seconds=time.process_time()-start)) + save(root/'input-freeze.json',dict(contract_sha256=sha(root/'contract.json'),files=index,parts=records, + label_values_read=False,new_decodes=0,new_features=0)) + save(out/'result.json',dict(status='COMPLETE',parts=len(records),files=len(index), + input_freeze_sha256=sha(root/'input-freeze.json'),cpu_seconds=time.process_time()-start, + target_values_read=False,model_fit=False)) + + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();run(a.root) diff --git a/tools/run_r4bc.py b/tools/run_r4bc.py new file mode 100644 index 000000000..5937ea15c --- /dev/null +++ b/tools/run_r4bc.py @@ -0,0 +1,227 @@ +"""One detached R4bc fit queue. Pool barriers, reserved budgets and immutable attempts.""" +import argparse +import fcntl +import math +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +import psutil + +from r4bc_common import (ARMS,HIST,POOLS,contract,read,sha,checked,save,selection,selection_path, + job_dir,can_reserve,role_rows,histgbrt_grid) +from s2_recovery_supervisor import tree_usage +from s2_recovery_monitoring import disk_usage + + +def tracks(c): + return {cell:[j['index'] for j in c['jobs'] if j['cell']==cell] for cell in range(15)} + + +def eligible_cells(c, cursors, *, checkpoint_passed, active_cells=()): + by=tracks(c) + if not checkpoint_passed:return [c['first_cell']] if cursors[c['first_cell']]c['limits']['setup_cpu_seconds']:raise ValueError('Setup budget already exceeded') + accounting_complete=True;monitor_errors=[];waiting=None + env=dict(os.environ,OMP_NUM_THREADS='1',MKL_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',NUMEXPR_NUM_THREADS='1',CUDA_VISIBLE_DEVICES='') + try: + while True: + for slot,item in list(active.items()): + code=item['process'].poll() + if code is None:continue + p=job_dir(root,item['index'])/'guard-result.json' + if not p.exists(): + accounting_complete=False;reason='MISSING_GUARD_RECEIPT' + save(root/'missing-guard.json',dict(index=item['index'],returncode=code,accounting_complete=False)) + else: + r=read(p) + if not math.isfinite(r['worker']['cpu_seconds']) or r['worker']['cpu_seconds']<0: + accounting_complete=False;reason='INVALID_ACCOUNTING' + records.append(dict(**r,attempted=True)) + if r['global_failure']:reason='WORKER_GLOBAL_FAILURE' + item['log'].close();del active[slot] + print('TERMINAL',item['index'],code,len(records),flush=True) + spent=sum(r['worker']['cpu_seconds'] for r in records) + if signal_request[0]:reason=reason or signal_request[0] + if (root/'global-stop.json').exists():reason=reason or read(root/'global-stop.json')['reason'] + try: + usage=[tree_usage(v['process'].pid) for v in active.values()] + live_cpu=sum(u[0] for u in usage);rss=sum(u[1] for u in usage)+psutil.Process().memory_info().rss + disk=disk_usage(root);available=psutil.virtual_memory().available + if rss>c['limits']['total_rss_bytes']:reason='GLOBAL_RSS_LIMIT' + if disk>=c['limits']['disk_bytes']:reason='GLOBAL_DISK_LIMIT' + # Live process-tree CPU includes guards: conservative, never an undercount. + if spent+live_cpu>c['limits']['fit_cpu_seconds']:reason='GLOBAL_FIT_CPU_LIMIT' + except Exception as exc: + monitor_errors.append(dict(type=type(exc).__name__,message=str(exc)));reason='GLOBAL_MONITOR_ERROR' + live_cpu=rss=disk=available=0 + if reason: + if not (root/'global-stop.json').exists():save(root/'global-stop.json',dict(reason=reason,unix=time.time())) + # Signal the guard, not the worker, to preserve final CPU/peak accounting. + for item in active.values(): + if not item.get('stop_sent'): + try:item['process'].send_signal(signal.SIGTERM) + except ProcessLookupError:pass + item['stop_sent']=True + if not checkpoint and not active and cursors[c['first_cell']]==len(by[c['first_cell']]) and not reason: + check=cost_check(c,records);save(root/'first-cell-cost-check.json',check) + checkpoint=check['continue_within_cap'] + if not checkpoint:cut='FIRST_CELL_COST_OR_FAILURE_STOP' + if not reason and not cut: + cells=eligible_cells(c,cursors,checkpoint_passed=checkpoint,active_cells={v['cell'] for v in active.values()}) + busy={v['cell'] for v in active.values()};waiting=None + for cell in cells: + if cell in busy or len(active)>=c['limits']['workers']:continue + if not checkpoint and active:break + i=by[cell][cursors[cell]];job=c['jobs'][i] + if job['kind']=='FINAL' and job['arm'] in HIST: + candidates=[r for r in records if r['job']['cell']==cell and r['job']['arm']==job['arm'] and r['job']['kind']=='HPO'] + trials=[] + for r in candidates: + value=read(checked(r['result_path'],r['result_sha256'])).get('validation_score') if r['worker']['status']=='PASS' else None + path=job_dir(root,r['index'])/'guard-result.json' + trials.append(dict(config_index=r['job']['config_index'],status=r['worker']['status'],score=value, + receipt_path=str(path),receipt_sha256=sha(path))) + decision=selection(trials);p=selection_path(root,job);p.parent.mkdir(exist_ok=True) + if not p.exists():save(p,decision) + elif read(p)!=decision:raise ValueError('Selection changed') + if decision['status']!='SELECTED': + records.append(dict(index=i,job=job,attempted=False,result_path=None,result_sha256=None, + guard_cpu_seconds=0,worker=dict(status='NA',cpu_seconds=0.,stop_reason='ALL_HPO_FAILED',monitor_errors=[]))) + cursors[cell]+=1;continue + if not can_reserve(spent,len(active),c['limits']['fit_cpu_seconds']): + if not active:cut='NOT_RUN_BUDGET' + else:waiting='WAIT_ACTIVE_SETTLEMENT_FOR_BUDGET' + break + if available<10*2**30: + waiting='WAIT_RESOURCES_V4_PRIORITY';break + contract(root) + slot=next(k for k in range(4) if k not in active);dest=job_dir(root,i);dest.mkdir(parents=True,exist_ok=True) + if (dest/'worker.started.json').exists():raise ValueError('Attempt already started') + log=(dest/'guard.log').open('x') + process=subprocess.Popen([sys.executable,'tools/r4bc_guard.py',str(root),str(i),str(slot)], + env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True) + active[slot]=dict(process=process,log=log,index=i,cell=cell);cursors[cell]+=1 + available-=8*2**30 + save(root/'progress.json',dict(terminal_attempts=sum(r.get('attempted',True) for r in records),logical_terminal=len(records), + active={str(k):dict(job=v['index'],cell=v['cell'],guard_pid=v['process'].pid) for k,v in active.items()}, + fit_cpu_seconds=spent,setup_cpu_seconds=initial_setup,live_guard_and_worker_cpu_seconds=live_cpu, + reserved_active_cpu_seconds=len(active)*1800,total_rss_bytes=rss,disk_bytes=disk, + checkpoint_passed=checkpoint,cut=cut,global_stop=reason,waiting=waiting, + monitor_errors=monitor_errors,wall_seconds=time.monotonic()-start)) + if not active and (reason or cut or (checkpoint and not eligible_cells(c,cursors,checkpoint_passed=True))):break + time.sleep(.5) + except Exception as exc: + reason='COORDINATOR_EXCEPTION';save(root/'coordinator-failure.json',dict(type=type(exc).__name__,message=str(exc))) + save(root/'global-stop.json',dict(reason=reason)) + finally: + for item in active.values(): + try:item['process'].send_signal(signal.SIGTERM) + except ProcessLookupError:pass + for item in active.values(): + item['process'].wait();item['log'].close();p=job_dir(root,item['index'])/'guard-result.json' + if p.exists():records.append(dict(**read(p),attempted=True)) + else:accounting_complete=False + seen={r['index'] for r in records};models=freeze_checkpoints(root,c,records,cut,reason) + save(root/'batch-complete.json',dict(status='FIT_QUEUE_TERMINAL' if not reason else 'GLOBAL_STOP', + global_stop=reason,cut=cut,accounting_complete=accounting_complete,records=records, + never_attempted=[dict(index=j['index'],cell=j['cell'],arm=j['arm'],pool=j['pool'], + reason='not run: budget' if cut=='NOT_RUN_BUDGET' else (reason or cut)) for j in c['jobs'] if j['index'] not in seen], + fit_cpu_seconds=sum(r['worker']['cpu_seconds'] for r in records),setup_cpu_seconds=initial_setup, + guard_cpu_seconds=sum(r.get('guard_cpu_seconds',0) for r in records),coordinator_cpu_seconds=time.process_time(), + model_manifest_sha256=sha(root/'models-terminal.json'),monitor_errors=monitor_errors, + postfit_state='READY_FOR_GIT_CHECKPOINT_FREEZE' if not reason and accounting_complete else 'FORBIDDEN_GLOBAL_STOP', + new_decodes=0,test_predictions=False,test_scoring=False,retries=0)) + return 0 if not reason and accounting_complete else 1 + + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();raise SystemExit(run(a.root)) diff --git a/tools/test_r4bc.py b/tools/test_r4bc.py new file mode 100644 index 000000000..2ada2d850 --- /dev/null +++ b/tools/test_r4bc.py @@ -0,0 +1,159 @@ +"""Synthetic acceptance for roles, comparisons, dispatch, budgets and real fit APIs.""" +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +import numpy as np +from r4bc_common import * +from r4bc_fit import assemble, run as fit +from r4bc_guard import supervise +from r4bc_postfit import component_table, git_gate +from run_r4bc import eligible_cells, tracks, cost_check + + +def fixture(base): + rng=np.random.default_rng(44);parts=[] + for k,role in enumerate(('learning','learning','validation','test')): + case=f'case-{k}';p=base/case;p.mkdir(parents=True);v=p/'v5';v.mkdir() + n=80;raw=np.arange(n,dtype=np.int64)*2+10;ids=np.arange(2,n,2,dtype=np.int64) + counts=np.arange(len(ids))%3+1;scale=.4+.1*k + xx=rng.normal(size=(n,19));seconds=(xx[:,0]+4.)*scale + np.save(v/'features.npy',xx);np.save(v/'target.npy',seconds/scale);np.save(v/'raw_ids.npy',raw);np.save(v/'seconds.npy',seconds) + old=np.column_stack([xx+1.,np.full(n,scale)]) + np.savez(p/'r2.npz',features=old) + np.savez(p/'queries.npz',eligible_s2=np.ones(len(ids),bool),anchor_ids=ids,raw_node_ids=raw[ids],multiplicity=counts,near_wall=np.zeros(len(ids),bool)) + label=p/'label.npz';np.savez(label,seconds=seconds[ids],raw_ids=raw[ids],counts=counts) + parts.append(dict(case=case,component_id='group-'+str(k//2),nodes=n, + assignments=[dict(fold=0,role=role,learning_pools=['25','50','100'] if role=='learning' else [])], + preparation=dict(preparation_root=str(p),t_set=scale,eligible_unique=len(ids), + output_sha256={f.name:sha(f) for f in p.glob('*.npz') if f.name!='label.npz'}), + v5_cache=dict(output=str(v),nodes=n,t_scale_seconds=scale,output_sha256={f.name:sha(f) for f in v.glob('*.npy')}), + label=dict(path=str(label),sha256=sha(label)))) + jobs=make_jobs() + c=dict(parts=parts,jobs=jobs,code_sha256={},source_sha256={},first_cell=2, + limits=dict(fit_cpu_seconds=122400),arm_order=list(ARMS)) + save(base/'contract.json',c);return c + + +class ProtocolTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.root=Path(os.environ.get('R4BC_TEST_ROOT',tempfile.mkdtemp(prefix='r4bc-tests-'))) + cls.root.mkdir(parents=True,exist_ok=True);cls.c=fixture(cls.root/'fixture') + + def test_01_jobs_count_and_order(self): + jobs=make_jobs();self.assertEqual(len(jobs),1005) + self.assertEqual(sum(j['kind']=='HPO' for j in jobs),900) + self.assertEqual([j['arm'] for j in jobs[:67] if j['kind']=='FINAL'],list(ARMS)) + self.assertEqual([jobs[i]['pool'] for i in (0,335,670)],[100,50,25]) + + def test_02_pool_barrier_waits_for_active_final(self): + c=dict(jobs=make_jobs(),first_cell=2);t=tracks(c);cursor={i:0 for i in t} + for cell in (2,5,8,11,14):cursor[cell]=len(t[cell]) + self.assertEqual(eligible_cells(c,cursor,checkpoint_passed=True,active_cells={14}),[14]) + self.assertEqual(eligible_cells(c,cursor,checkpoint_passed=True),[1,4,7,10,13]) + + def test_03_weight_scale_and_multiplicity(self): + counts=[np.array([1,3]),np.array([2,2]),np.array([1,1])];g=['a','a','b'] + w=hierarchy_weights(counts,g);np.testing.assert_allclose(w,[.0625,.1875,.125,.125,.25,.25]) + np.testing.assert_allclose(hierarchy_weights(counts,g,xgb=True),6*w) + + def test_04_test_role_denied_before_any_target_load(self): + job=dict(fold=0,pool=100,kind='FINAL',arm='H0p');row=self.c['parts'][-1] + with patch('r4bc_common.np.load',side_effect=AssertionError('must not open labels')): + with self.assertRaises(InputViolation):targets(row,job,'learning',full=False,access=[]) + with self.assertRaises(InputViolation):targets(row,job,'test',full=False,access=[]) + + def test_05_final_cannot_read_validation(self): + with self.assertRaises(InputViolation):targets(self.c['parts'][2],dict(fold=0,pool=100,kind='FINAL',arm='H1'),'validation',full=False,access=[]) + + def test_06_hash_violation_global_type(self): + with self.assertRaises(InputViolation):checked(self.root/'fixture/contract.json','0'*64) + + def test_07_selection_complete_and_tie(self): + trials=[dict(config_index=i,status='PASS',score=1.) for i in range(12)] + trials[0]['status']='FAILED';self.assertEqual(selection(trials)['config_index'],1) + with self.assertRaises(InputViolation):selection(trials[:-1]) + self.assertEqual(selection([dict(config_index=i,status='FAILED',score=None) for i in range(12)])['status'],'NA_ALL_HPO_FAILED') + + def test_08_budget_reservation(self): + self.assertTrue(can_reserve(100,3,7300));self.assertFalse(can_reserve(101,3,7300)) + self.assertFalse(can_reserve(float('nan'),0,7300)) + + def assembled(self,arm): + output=self.root/('arrays-'+arm);output.mkdir(exist_ok=True) + job=dict(fold=0,pool=100,arm=arm,kind='FINAL');access=[] + x,y,w,rows=assemble(self.c,job,output,access) + self.assertEqual({a['role'] for a in access},{'learning'}) + return x,y,w + + def test_09_drop_only_twentieth_column(self): + a,y,w=self.assembled('H0p');b,yb,wb=self.assembled('H1') + np.testing.assert_array_equal(a[:,:19],b);np.testing.assert_array_equal(y,yb);np.testing.assert_array_equal(w,wb) + self.assertEqual((a.shape[1],b.shape[1]),(20,19)) + + def test_10_query_weight_change_keeps_rows(self): + a,y,w=self.assembled('H2');b,z,u=self.assembled('H3') + np.testing.assert_array_equal(a,b);np.testing.assert_array_equal(y,z) + self.assertAlmostEqual(w.sum(),1.);np.testing.assert_array_equal(u,np.ones(len(u))) + + def test_11_full_node_and_precision_interface(self): + h,y,w=self.assembled('H4');a,z,u=self.assembled('A') + self.assertEqual(len(y),160);np.testing.assert_array_equal(a,h.astype(np.float32));np.testing.assert_array_equal(z,y.astype(np.float32)) + self.assertEqual(a.dtype,np.float32);np.testing.assert_array_equal(w,u) + q,_,qw=self.assembled('Q');self.assertAlmostEqual(qw.sum(),len(q)) + + def test_12_complete_components_not_partial_parts(self): + roster=[dict(case='a',component_id='g'),dict(case='b',component_id='g'),dict(case='c',component_id='h')] + rows=[dict(case=x,arm=a,relative_l2=dict(value=1.)) for x in ('a','b','c') for a in ('A','B') if (x,a)!=('b','B')] + table=component_table(rows,roster,('A','B'),'relative_l2') + self.assertEqual(table['component_ids'],['h']);self.assertEqual(table['parts'],1) + + def test_13_bootstrap_absolute_direction(self): + r=paired_difference({'a':3.,'b':4.},{'a':1.,'b':2.},replicates=50) + self.assertEqual((r['value'],r['low'],r['high']),(2.,2.,2.)) + + def test_14_prediction_gate_requires_real_git_objects(self): + p=self.root/'gate';p.mkdir(exist_ok=True) + save(p/'fake.json',dict(commit='',checkout='')) + with self.assertRaises(InputViolation):git_gate(p,'fake.json',[]) + + def test_15_guard_wall_failure_and_no_retry(self): + d=self.root/'guard-wall' + limits=dict(cpu_seconds=5,wall_seconds=.15,rss_bytes=256*2**20,disk_bytes=2**30) + r=supervise([sys.executable,'-c','import time;time.sleep(2)'],d,limits,poll=.02) + self.assertEqual(r['status'],'FAILED');self.assertIn('wall_limit',r['stop_reason']) + with self.assertRaises(FileExistsError):supervise([sys.executable,'-c','pass'],d,limits) + + def test_16_guard_failed_worker_still_checks_peak(self): + d=self.root/'guard-memory';limits=dict(cpu_seconds=5,wall_seconds=5,rss_bytes=8*2**20,disk_bytes=2**30) + r=supervise([sys.executable,'-c','a=bytearray(32*1024*1024);raise SystemExit(3)'],d,limits,poll=.2) + self.assertEqual(r['status'],'FAILED');self.assertGreater(r['peak_tree_rss_bytes'],limits['rss_bytes']) + self.assertIn('rss_limit',r['stop_reason']) + + def test_17_actual_hist_hpo_then_learning_only_final(self): + root=self.root/'fixture';job=self.c['jobs'][0] + (job_dir(root,0)).mkdir(parents=True,exist_ok=True);fit(root,0) + result=read(job_dir(root,0)/'output/result.json');self.assertTrue(np.isfinite(result['validation_score'])) + access=read(job_dir(root,0)/'output/access.json');self.assertEqual({x['role'] for x in access},{'learning','validation'}) + final=next(j for j in self.c['jobs'] if j['arm']=='H0p' and j['kind']=='FINAL' and j['cell']==2) + receipt=self.root/'synthetic-receipt.json';save(receipt,{'synthetic':True}) + trials=[dict(config_index=i,status='PASS',score=float(i),receipt_path=str(receipt),receipt_sha256=sha(receipt)) for i in range(12)] + path=selection_path(root,final);path.parent.mkdir(exist_ok=True);save(path,selection(trials)) + job_dir(root,final['index']).mkdir(parents=True,exist_ok=True);fit(root,final['index']) + self.assertEqual({x['role'] for x in read(job_dir(root,final['index'])/'output/access.json')},{'learning'}) + with self.assertRaises(FileExistsError):fit(root,final['index']) + + def test_18_actual_xgb_fixed_query_variant(self): + root=self.root/'fixture';job=next(j for j in self.c['jobs'] if j['cell']==2 and j['arm']=='Q') + job_dir(root,job['index']).mkdir(parents=True,exist_ok=True);fit(root,job['index']) + r=read(job_dir(root,job['index'])/'output/result.json') + self.assertEqual(r['params']['n_estimators'],100);self.assertEqual(r['params']['max_depth'],8) + self.assertEqual({x['role'] for x in read(job_dir(root,job['index'])/'output/access.json')},{'learning'}) + + +if __name__=='__main__':unittest.main(verbosity=2)