"""Resumable P3 stages. Worker processes never write report.html or select checkpoints.""" from __future__ import annotations import copy import itertools import json import os import subprocess import sys import time from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait from multiprocessing import get_context from pathlib import Path import numpy as np from ml_porosity.f3.data import F3Data from ml_porosity.f3.progress import update, write_json from ml_porosity.f3.protocol import digest, fingerprint, freeze, training_sets from ml_porosity.paths import REPO_ROOT, outputs_dir def set_name(names) -> str: return '__'.join(sorted(names)) def reg_path(root: Path, names, sigma_a: float = 7, no_anchors: bool = False) -> Path: return root / 'registration' / f'{set_name(names)}_sa{sigma_a:g}{"_noanchors" if no_anchors else ""}.npz' def job_path(root: Path, names, method: str, label: str, seed: int, sigma_a: float = 7) -> Path: return root / 'train' / f'{set_name(names)}__{method}__{label}__s{seed}__sa{sigma_a:g}.npz' def load_bundle(path: Path) -> dict: with np.load(path) as z: return {k: z[k] for k in z.files} def reusable(path: Path, key: str) -> bool: meta = path.with_suffix('.json') if not path.exists() or not meta.exists(): return False stored = json.loads(meta.read_text(encoding='utf-8')) if stored.get('fingerprint') != key: raise RuntimeError(f'Resume fingerprint mismatch: {path}. Use a new output directory.') expected = stored.get('artifact_sha256') if expected is None or digest(path) != expected: raise RuntimeError(f'Missing or mismatched completed-artifact checksum: {path}') if path.parent.name == 'train': checkpoint = path.with_suffix('.pt') if not checkpoint.exists() or digest(checkpoint) != stored.get('checkpoint_sha256'): raise RuntimeError(f'Missing or mismatched model checkpoint: {checkpoint}') with np.load(path) as z: if not z.files: raise RuntimeError(f'Empty completed artifact: {path}') for k in z.files: a = z[k] if np.issubdtype(a.dtype, np.number): valid = (not np.isnan(a).any() and not np.isposinf(a).any() and np.isfinite(a).any(axis=-1).all()) if k.endswith('/logpi') else np.isfinite(a).all() if not valid: raise RuntimeError(f'Corrupt/non-finite artifact: {path}/{k}') return True def registration_worker(job: dict) -> dict: import torch from ml_porosity.f3.registration import register_set torch.set_num_threads(job['p']['runtime']['cpu_threads_per_worker']) data = F3Data(job['p'], training_wells=tuple(job['names'])) path = reg_path(Path(job['root']), job['names'], job['sa'], job['no_anchors']) if reusable(path, job['key']): return {'cached': True, 'path': str(path)} bundle, meta = register_set(data, tuple(job['names']), job['p'], job['device'], job['sa'], job['no_anchors']) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix('.tmp.npz') np.savez_compressed(tmp, **bundle) tmp.replace(path) write_json(path.with_suffix('.json'), meta | {'fingerprint': job['key'], 'artifact_sha256': digest(path)}) return {'cached': False, 'path': str(path), **meta} def training_worker(job: dict) -> dict: from ml_porosity.f3.training import method_spec, train_trajectory root, p = Path(job['root']), job['p'] path = job_path(root, job['names'], job['method'], job['label'], job['seed'], job['sa']) if reusable(path, job['key']): return {'cached': True, 'path': str(path)} data = F3Data(p, training_wells=tuple(job['names'])) bundle = load_bundle(reg_path(root, job['names'], job['sa'], job['method'] == 'M2-no-anchors')) if tuple(bundle['wells']) != tuple(sorted(job['names'])): raise RuntimeError('Training cache contains different wells') all_names = list(p['data']['wells']) Xall = np.stack([data.X(w) for w in all_names]) if job['method'] == 'M2-LFM': m, s = bundle[f'{job["label"]}/norm'] lfm = (bundle[f'{job["label"]}/lfm'] - m) / s Xall = np.concatenate([Xall, np.broadcast_to(lfm, (len(Xall), 1, len(lfm)))], axis=1) X = Xall[[all_names.index(w) for w in job['names']]] spec = method_spec(bundle, job['label'], job['method'], p) path.parent.mkdir(parents=True, exist_ok=True) ckpt = path.with_suffix('.pt') pred, meta = train_trajectory(X, Xall, spec, job['method'], p['training'] | {'fixed_sigma': p['methods']['fixed_sigma']}, job['seed'], p['training']['budgets'], job['device'], ckpt) mean, sd = bundle[f'{job["label"]}/norm'] for k in pred: pred[k] = pred[k] * sd + (mean if k.endswith('/mu') else 0) pred['wells'] = np.asarray(all_names) pred['norm'] = bundle[f'{job["label"]}/norm'] tmp = path.with_suffix('.tmp.npz') np.savez_compressed(tmp, **pred) tmp.replace(path) write_json(path.with_suffix('.json'), meta | {'fingerprint': job['key'], 'artifact_sha256': digest(path), 'checkpoint_sha256': digest(ckpt), 'training_wells': job['names'], 'label': job['label'], 'method': job['method'], 'seed': job['seed'], 'sigma_a_ms': job['sa']}) return {'cached': False, 'path': str(path), **meta} def run_jobs(jobs: list[dict], fn, workers: int, stage: str) -> list[dict]: started = time.perf_counter() results = [] smoke = bool(jobs and Path(jobs[0]['root']).name == 'smoke') task = 'p3-review' if smoke else 'p3-vol' if stage.startswith('volume-') else 'p3-lowo' update(status=f'{"Smoke test — " if smoke else ""}Đang chạy {stage}', message='Mỗi job chỉ nhận đúng tập giếng train; smoke không phải kết quả chính.', completed=0, total=len(jobs), eta_seconds=None, error=None, tasks={task: 'doing'}) with ProcessPoolExecutor(max_workers=workers, mp_context=get_context('spawn')) as pool: futures = {pool.submit(fn, job): job for job in jobs} pending = set(futures) while pending: done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED) if not done: update(elapsed_seconds=time.perf_counter()-started, message=f'{stage}: {len(results)}/{len(jobs)} job; scheduler đang chờ {min(workers, len(pending))} worker. Chưa có job mới hoàn tất.') continue for fut in done: try: result = fut.result() except Exception as exc: for future in pending: future.cancel() update(status='Job failed; pending jobs cancelled', error=str(exc), message='Completed artifacts are preserved. Running workers finish before the scheduler exits.') raise results.append(result) fresh = sum(not r.get('cached') for r in results) elapsed = time.perf_counter() - started remain = len(jobs) - len(results) eta = elapsed/fresh*remain if fresh else None update(completed=len(results), total=len(jobs), eta_seconds=eta, elapsed_seconds=elapsed, message=f'{stage}: xong {len(results)}/{len(jobs)} job; cache {len(results)-fresh}. Các job được kiểm tra fingerprint khi chạy lại.') print(f'{stage} {len(results)}/{len(jobs)} {result["path"]}', flush=True) return results def registration_jobs(p: dict, stamp: dict, root: Path, device: str, deployment: bool = False) -> list[dict]: jobs = [] sets = training_sets(p['data']['wells'], 3 if deployment else 2) for names in sets: arms = [(p['registration']['sigma_a_ms'], False)] if not deployment: arms += [(s, False) for s in p['registration']['sigma_a_sensitivity_ms']] if 'M2-no-anchors' in p['methods']['ablations']: arms += [(p['registration']['sigma_a_ms'], True)] for sa, no in arms: settings = dict(names=list(names), sa=sa, no_anchors=no) jobs.append(dict(p=p, root=str(root), device=device, **settings, key=fingerprint(stamp, stage='registration', **settings))) return jobs def training_jobs(p: dict, stamp: dict, root: Path, device: str) -> list[dict]: jobs = [] for names in training_sets(p['data']['wells']): arms = [(p['registration']['sigma_a_ms'], lab, m) for lab in p['data']['labels'] for m in p['methods']['main']] arms += [(p['registration']['sigma_a_ms'], lab, m) for lab in p['methods']['ablation_labels'] for m in p['methods']['ablations']] arms += [(sa, lab, m) for sa in p['registration']['sigma_a_sensitivity_ms'] for lab in p['registration']['sensitivity_labels'] for m in p['registration']['sensitivity_methods']] for (sa, label, method), seed in itertools.product(arms, p['split']['seeds']): settings = dict(names=list(names), method=method, label=label, seed=seed, sa=sa) jobs.append(dict(p=p, root=str(root), device=device, **settings, key=fingerprint(stamp, stage='train', **settings))) return jobs def prepare() -> None: update(status='Chuẩn bị dữ liệu', message='Dựng patch đúng vị trí giếng và nhãn chống alias; chưa huấn luyện.', tasks={'p3-env': 'doing'}) subprocess.run([sys.executable, str(REPO_ROOT / 'scripts/01_build_wells.py')], cwd=REPO_ROOT, check=True) import torch if not torch.cuda.is_available(): raise RuntimeError('CUDA is unavailable; CPU execution must be requested explicitly for tests.') update(status='Dữ liệu và CUDA sẵn sàng', message=f'{torch.cuda.get_device_name(0)}; đã dựng f3_wells.npz.', tasks={'p3-env': 'done'}) def benchmark_worker(job: dict) -> dict: from ml_porosity.f3.training import train_trajectory rng = np.random.default_rng(job['seed']) X = rng.normal(size=(2, 9, 126)) Y = rng.normal(size=(2, 64, 126)) if job['method'] == 'M2-S256': Y = rng.normal(size=(2, 256, 126)) if job['method'] == 'B3b': Y = Y[:, :1] if job['method'] in ('B4c', 'B4d'): spec = dict(kind='softdtw' if job['method'] == 'B4c' else 'dilate', Y=Y[:, 0], gamma=0.1, band=8) if job['method'] == 'B4d': spec['alpha'] = 0.5 else: spec = dict(kind='bank', Y=Y, logpi=np.full(Y.shape[:2], -np.log(Y.shape[1])), lam=0.37) train_trajectory(X, X, spec, job['method'], job['p']['training'], job['seed'], [10], job['device']) measurement_start = time.time() _, meta = train_trajectory(X, X, spec, job['method'], job['p']['training'], job['seed'], [job['steps']], job['device']) return meta | {'method': job['method'], 'measurement_start': measurement_start, 'measurement_end': time.time()} def benchmark(p: dict, device: str, steps: int, worker_counts: list[int]) -> dict: import torch update(status='Đo tốc độ RTX 3060', message='Dùng dữ liệu giả cùng kích thước; không xem nhãn test F3.', tasks={'p3-bench': 'doing'}) previous_file = outputs_dir()/'p3/benchmark.json' previous = json.loads(previous_file.read_text(encoding='utf-8')) if previous_file.exists() else {} same = previous.get('torch') == torch.__version__ and previous.get('device') == device trials = [t for t in previous.get('trials', []) if same and t.get('jobs') and all(j['steps'] == steps for j in t['jobs']) and t['workers'] not in worker_counts] for workers in worker_counts: start = time.perf_counter() jobs = [dict(p=p, device=device, steps=steps, method=m, seed=i) for i, m in enumerate(['B3b', 'M2-Sa', 'B4c', 'B4d', 'B2', 'M2-S256', 'M2-TCN'] * 2)] try: with ProcessPoolExecutor(max_workers=workers, mp_context=get_context('spawn')) as pool: result = list(pool.map(benchmark_worker, jobs)) elapsed = time.perf_counter()-start steady = max(j['measurement_end'] for j in result)-min(j['measurement_start'] for j in result) trials.append({'workers': workers, 'wall_seconds': elapsed, 'steady_wall_seconds': steady, 'steps_total': len(jobs)*steps, 'throughput_steps_per_second': len(jobs)*steps/steady, 'jobs': result}) except Exception as exc: trials.append({'workers': workers, 'error': str(exc)}) valid = [v for v in trials if 'error' not in v] if not valid: raise RuntimeError(f'All benchmark configurations failed: {trials}') best = max(valid, key=lambda v: v['throughput_steps_per_second']) planned = training_jobs(p, {}, Path('.'), device) n_jobs = len(planned) timing = {method: float(np.mean([j['seconds_per_step'] for j in best['jobs'] if j['method'] == method])) for method in {j['method'] for j in best['jobs']}} def category(method): if method.endswith('-TCN'): return 'M2-TCN' if method in timing: return method if method.startswith('B3'): return 'B3b' return 'M2-Sa' # Individual timings include contention. Calibrate their sum to measured wall time. scheduling_factor = min(1.0, best['steady_wall_seconds']/sum(j['wall_seconds'] for j in best['jobs'])) nominal = sum(timing[category(j['method'])]*max(p['training']['budgets']) for j in planned)*scheduling_factor out = {'device': device, 'gpu': torch.cuda.get_device_name(0) if device.startswith('cuda') else 'CPU', 'torch': torch.__version__, 'python': sys.version, 'trials': trials, 'recommended_workers': best['workers'], 'training_jobs': n_jobs, 'max_steps_per_job': max(p['training']['budgets']), 'training_seconds': nominal, 'training_range_seconds': [nominal*0.8, nominal*1.6], 'posterior_seconds': None, 'volume_seconds': None, 'note': 'Measured synthetic-input training benchmark. Registration and full-volume ETA require their own pilot; not included in training_seconds.'} from ml_porosity.f3.volume import volume_benchmark out['volume'] = volume_benchmark(p, device) out['volume_seconds'] = out['volume']['inference_seconds'] write_json(outputs_dir()/'p3/benchmark.json', out) update(status='Đã đo tốc độ huấn luyện', message=f'{n_jobs} trajectory; ước lượng train {nominal/3600:.1f} giờ, chưa gồm posterior và volume.', benchmark=out, eta_seconds=None, tasks={'p3-bench': 'doing'}) return out def benchmark_registration(p: dict, device: str) -> dict: """One training-only registration pilot, isolated from the scientific output tree.""" from ml_porosity.f3.protocol import CONFIG, source_hash root = outputs_dir()/'p3/benchmark_registration' names = training_sets(p['data']['wells'])[0] stamp = {'protocol_sha256': digest(CONFIG, True), 'code_sha256': source_hash(), 'benchmark_only': True} jobs = registration_jobs(p, stamp, root, device) pilots = [jobs[0]] no_anchor_jobs = [job for job in jobs if tuple(job['names']) == names and job['no_anchors']] if no_anchor_jobs: pilots.append(no_anchor_jobs[0]) update(status='Đo thời gian registration', message=f'Pilot chỉ dùng hai giếng train {names}; không huấn luyện hoặc xem nhãn test P3.') timings = [] for job in pilots: result = registration_worker(job) if result.get('cached'): result = json.loads(reg_path(root, names, job['sa'], job['no_anchors']).with_suffix('.json').read_text(encoding='utf-8')) timings.append({'no_anchors': job['no_anchors'], 'seconds': result['wall_seconds']}) seconds = timings[0]['seconds'] # Four 3-well deployment sets cost roughly six 2-well sets; sharing one GPU limits parallel speedup. pair_equivalents = len(registration_jobs(p, stamp, root, device)) + 6 no_anchor_count = sum(job['no_anchors'] for job in jobs) anchor_equivalents = len(jobs)-no_anchor_count+6 workload = seconds*anchor_equivalents+timings[-1]['seconds']*no_anchor_count out = {'training_wells': names, 'seconds_per_two_well_set': seconds, 'pair_equivalents': pair_equivalents, 'pilots': timings, 'range_seconds': [workload/2, workload*2], 'note': 'One real-data training pair measured with and without anchors. Range is an extrapolation, not a confidence interval; other sigma arms and shared-GPU scheduling can differ.'} write_json(outputs_dir()/'p3/registration_benchmark.json', out) benchfile = outputs_dir()/'p3/benchmark.json' values = {'registration_benchmark': out} if benchfile.exists(): bench = json.loads(benchfile.read_text(encoding='utf-8')) train_range = bench['training_range_seconds'] vol_range = bench['volume']['range_seconds_with_io'] # Extra deployment training and scoring are allowed 15% of the measured training budget. values['full_runtime_range_seconds'] = [train_range[i]*1.15+out['range_seconds'][i]+vol_range[i] for i in (0, 1)] update(status='Đã đo và ước lượng P3', message='Đã có benchmark train, registration và volume. Chưa chạy lưới P3 chính.', **values, tasks={'p3-bench': 'done'}) return out def run(stage: str, p: dict, device: str, workers: int, smoke: bool = False) -> None: stamp = freeze(check=True) root = outputs_dir()/'p3' if smoke: p = copy.deepcopy(p) p['split']['seeds'] = [0] p['data']['labels'] = [p['data']['primary_label']] p['methods']['main'] = ['B3b', 'B3d-Sa', 'M2-Sa'] p['methods']['ablations'] = [] p['registration'].update(particles=16, S=8, hyper_starts=1, smc_moves=1, phase_half_width=0, phase_max_extra=0, sigma_a_sensitivity_ms=[]) p['training']['budgets'] = [2, 4] root = root/'smoke' stamp = stamp | {'smoke': p} if stage == 'register': run_jobs(registration_jobs(p, stamp, root, device), registration_worker, workers, stage) elif stage == 'train': run_jobs(training_jobs(p, stamp, root, device), training_worker, workers, stage) elif stage in ('diagnostics', 'summarize'): from ml_porosity.f3.evaluation import diagnostics, summarize (diagnostics if stage == 'diagnostics' else summarize)(p, root) else: raise ValueError(stage)