"""Descriptive F3 volume from a frozen 20-member deployment ensemble, streamed by inline.""" from __future__ import annotations import json import time from pathlib import Path import numpy as np from ml_porosity.f3.progress import update, write_json from ml_porosity.f3.protocol import digest, fingerprint, freeze, training_sets from ml_porosity.f3.runner import job_path, load_bundle, registration_jobs, registration_worker, reusable, run_jobs, training_worker from ml_porosity.paths import outputs_dir def deployment_budget(values, candidates) -> int: median = float(np.median(values)) return min(candidates, key=lambda x: (abs(x-median), x)) def fit_deployment(p: dict, device: str, workers: int) -> dict: import pandas as pd root, stamp = outputs_dir()/'p3', freeze(check=True) selection = pd.read_csv(root/'summary/selection.csv') cfg = p['volume'] method, label = cfg['method'], cfg['label'] run_jobs(registration_jobs(p, stamp, root, device, deployment=True), registration_worker, workers, 'volume-register') jobs, members = [], [] for names in training_sets(p['data']['wells'], 3): for seed in p['split']['seeds']: scores = selection[(selection.method == method) & (selection.label == label) & (selection.seed == seed) & (selection.sigma_a_ms == p['registration']['sigma_a_ms'])] if len(scores) != 4: raise RuntimeError('Need all four outer selections before deployment fitting') budget = deployment_budget(scores.budget.to_numpy(), p['training']['budgets']) import copy q = copy.deepcopy(p) q['training']['budgets'] = [budget] settings = dict(names=list(names), method=method, label=label, seed=seed, sa=p['registration']['sigma_a_ms']) jobs.append(dict(p=q, root=str(root), device=device, **settings, key=fingerprint(stamp, stage='deployment-train', budget=budget, **settings))) path = job_path(root, names, method, label, seed, p['registration']['sigma_a_ms']) members.append({'checkpoint': str(path.with_suffix('.pt').relative_to(root)), 'prediction': str(path.relative_to(root)), 'budget': budget, 'training_wells': names, 'seed': seed}) run_jobs(jobs, training_worker, workers, 'volume-fit') meta = {'members': members, 'method': method, 'label': label, 'protocol_sha256': stamp['protocol_sha256'], 'note': '20-member ensemble for descriptive volume only; LOWO scores use separate 15-member blind ensembles.'} write_json(root/'deployment.json', meta) return meta def load_models(p: dict, device: str): import torch from ml_porosity.f3.training import make_model root = outputs_dir()/'p3' stamp = freeze(check=True) meta = json.loads((root/'deployment.json').read_text(encoding='utf-8')) if len(meta['members']) != 4*len(p['split']['seeds']) or meta['protocol_sha256'] != stamp['protocol_sha256']: raise RuntimeError('Incomplete or mismatched deployment ensemble') models = [] for item in meta['members']: key = fingerprint(stamp, stage='deployment-train', budget=item['budget'], names=list(item['training_wells']), method=meta['method'], label=meta['label'], seed=item['seed'], sa=p['registration']['sigma_a_ms']) if not reusable(root/item['prediction'], key): raise RuntimeError('Deployment prediction/checkpoint pair is incomplete') saved = torch.load(root/item['checkpoint'], map_location='cpu', weights_only=True) model = make_model(saved['method'], saved['channels'], saved['config']) model.load_state_dict(saved['states'][item['budget']]) model.to(device).eval() norm = load_bundle(root/item['prediction'])['norm'] models.append((model, float(norm[0]), float(norm[1]))) return models def predict_batch(models, patches: np.ndarray, device: str) -> tuple[np.ndarray, np.ndarray]: import torch x = torch.as_tensor(patches, dtype=torch.float32, device=device) running_mean, m2, sum_aleatoric = None, None, None with torch.inference_mode(): for n, (model, mean, sd) in enumerate(models, 1): mu, sigma = model(x) mu, sigma = mu[:, 0]*sd+mean, sigma[:, 0]*sd if running_mean is None: running_mean, m2, sum_aleatoric = mu.clone(), torch.zeros_like(mu), sigma**2 else: delta = mu-running_mean running_mean = running_mean+delta/n m2 = m2+delta*(mu-running_mean) sum_aleatoric = sum_aleatoric+sigma**2 std = torch.sqrt(torch.clamp((sum_aleatoric+m2)/len(models), min=0)) return running_mean.cpu().numpy(), std.cpu().numpy() def volume_benchmark(p: dict, device: str, batches: int = 4) -> dict: """Architecture-only pilot; no production checkpoint or F3 labels are required.""" import torch from ml_porosity.f3.training import make_model n = 4*len(p['split']['seeds']) models = [(make_model(p['volume']['method'], 9, p['training']).to(device).eval(), 0.25, 0.03) for _ in range(n)] rng = np.random.default_rng(73) x = rng.normal(size=(p['volume']['batch_size'], 9, 126)).astype(np.float32) predict_batch(models, x, device) if device.startswith('cuda'): torch.cuda.synchronize() start = time.perf_counter() for _ in range(batches): predict_batch(models, x, device) if device.startswith('cuda'): torch.cuda.synchronize() elapsed = time.perf_counter()-start from ml_porosity.data.seismic_io import SeismicCube with SeismicCube() as cube: traces = (len(cube.ilines)-2)*(len(cube.xlines)-2) estimate = traces/(batches*len(x)/elapsed) del models if device.startswith('cuda'): torch.cuda.empty_cache() return {'members': n, 'batch_size': len(x), 'measured_batches': batches, 'seconds': elapsed, 'traces_per_second': batches*len(x)/elapsed, 'full_interior_traces': traces, 'inference_seconds': estimate, 'range_seconds_with_io': [estimate*1.1, estimate*1.8], 'note': 'Measured with 20 random-weight models of the deployment architecture; range adds SEG-Y reading, normalization and disk writing. Not a production prediction.'} def predict_volume(p: dict, device: str, sections: bool = False, limit_inlines: int | None = None) -> dict: from ml_porosity.data.seismic_io import SeismicCube from ml_porosity.f3.data import F3Data stamp = freeze(check=True) from ml_porosity.paths import f3_segy if digest(f3_segy()) != stamp['segy_sha256']: raise RuntimeError('F3 cube changed after protocol locking; refusing volume prediction') root = outputs_dir()/'p3' models = load_models(p, device) data = F3Data(p) dest = root/('volume_sections' if sections else 'volume_pilot' if limit_inlines else 'volume') dest.mkdir(parents=True, exist_ok=True) state_file = dest/'state.json' key = fingerprint(stamp, stage='volume', deployment=json.loads((root/'deployment.json').read_text(encoding='utf-8')), sections=sections, limit_inlines=limit_inlines) state = json.loads(state_file.read_text(encoding='utf-8')) if state_file.exists() else {'fingerprint': key, 'completed_ilines': []} if state['fingerprint'] != key: raise RuntimeError('Volume resume fingerprint mismatch') if state['completed_ilines'] and any(not (dest/n).exists() for n in ('mean.npy', 'sigma.npy')): raise RuntimeError('Volume state lists completed rows but an output file is missing; refusing to skip missing predictions') start = time.perf_counter() with SeismicCube() as cube: time_mask = cube.window(*p['data']['window_ms']) times = cube.times_ms[time_mask] if not np.array_equal(times, data.t_main): raise ValueError('Cube and training time axes differ') shape = (len(cube.ilines), len(cube.xlines), len(times)) outputs = [] for name in ('mean.npy', 'sigma.npy'): path = dest/name new = not path.exists() arr = np.lib.format.open_memmap(path, mode='w+' if new else 'r+', dtype='float32', shape=shape) if new: arr[:] = np.nan arr.flush() elif arr.shape != shape: raise ValueError('Existing volume shape differs') outputs.append(arr) selected_i = {int(data.ext(w, 'il')) for w in data.wells} selected_j = {int(np.flatnonzero(cube.xlines == int(data.ext(w, 'xl')))[0]) for w in data.wells} line_cache = {} def line(i): if i not in line_cache: il = int(cube.ilines[i]) a = np.asarray(cube._f.iline[il], dtype=np.float32)[:, time_mask] line_cache[i] = a return line_cache[i] total = len(cube.ilines)-2 if limit_inlines: total = min(total, limit_inlines) completed_now = 0 for i in range(1, total+1): if i in state['completed_ilines']: continue il = int(cube.ilines[i]) columns = np.arange(1, len(cube.xlines)-1) if sections and il not in selected_i: columns = np.array(sorted(j for j in selected_j if 0 < j < len(cube.xlines)-1)) block = np.stack([line(i-1), line(i), line(i+1)]) view = np.lib.stride_tricks.sliding_window_view(block, 3, axis=1).transpose(1, 0, 3, 2) for j0 in range(0, len(columns), p['volume']['batch_size']): cols = columns[j0:j0+p['volume']['batch_size']] x = np.ascontiguousarray(view[cols-1].reshape(len(cols), 9, len(times)), dtype=np.float64) x = (x-x.mean(axis=2, keepdims=True))/(x.std(axis=2, keepdims=True)+1e-8) mu, sigma = predict_batch(models, x, device) outputs[0][i, cols] = mu outputs[1][i, cols] = sigma for arr in outputs: arr.flush() state['completed_ilines'].append(i) write_json(state_file, state) completed_now += 1 elapsed = time.perf_counter()-start update(status='Đang suy luận volume', message=f'Đã ghi inline {il}; phần biên không có đủ patch được giữ NaN.', completed=len(state['completed_ilines']), total=total, eta_seconds=elapsed/completed_now*(total-len(state['completed_ilines'])), tasks={'p3-vol': 'doing'}) for old in list(line_cache): if old < i: del line_cache[old] meta = {'shape': shape, 'ilines': cube.ilines.tolist(), 'xlines': cube.xlines.tolist(), 'times_ms': times.tolist(), 'members': len(models), 'units': 'porosity fraction', 'sections_only': sections, 'pilot': bool(limit_inlines), 'wall_seconds': time.perf_counter()-start, 'edge_policy': p['volume']['edge'], 'interpretation': p['volume']['interpretation'], 'fingerprint': key} write_json(dest/'metadata.json', meta) plot_sections(outputs[0], outputs[1], data, cube.ilines, cube.xlines, times, dest) update(status='Volume đã hoàn tất' if not limit_inlines else 'Pilot volume đã hoàn tất', message='Đầu ra sonic-derived porosity và σ; không dùng volume để chấm G-C.', completed=None, total=None, eta_seconds=None, tasks={'p3-vol': 'todo' if limit_inlines else 'done'}) return meta def plot_sections(mean, sigma, data, ilines, xlines, times, dest): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt limits = [(float(np.nanmin(mean))*100, float(np.nanmax(mean))*100), (0., float(np.nanmax(sigma))*100)] for w in data.wells: i = int(np.flatnonzero(ilines == int(data.ext(w, 'il')))[0]) j = int(np.flatnonzero(xlines == int(data.ext(w, 'xl')))[0]) for name, a, b, axis in (('inline', mean[i], sigma[i], xlines), ('crossline', mean[:, j], sigma[:, j], ilines)): if not np.isfinite(a).any(): continue fig, axs = plt.subplots(1, 2, figsize=(12, 5), sharey=True, layout='constrained') for ax, values, title, clim, cmap_name in zip(axs, (a, b), ('Mean (p.u.)', 'Predictive sigma (p.u.)'), limits, ('viridis', 'magma')): cmap = matplotlib.colormaps[cmap_name].with_extremes(bad='#bdbdbd') dt = float(times[1]-times[0]) img = ax.imshow(100*values.T, origin='upper', aspect='auto', interpolation='nearest', cmap=cmap, vmin=clim[0], vmax=clim[1], extent=[axis[0]-.5, axis[-1]+.5, times[-1]+dt/2, times[0]-dt/2]) ax.set(title=title, xlabel=name) fig.colorbar(img, ax=ax) axs[0].set_ylabel('TWT (ms)') fig.suptitle(f'{w} — descriptive sonic-derived porosity; gray = unavailable') fig.savefig(dest/f'{w}_{name}.png', dpi=140) plt.close(fig)