Implement the frozen F3 protocol, nested LOWO, posterior label banks, ablations, diagnostics, checkpoint validation and full-volume inference. Record the negative G-C result: improvement at 1/4 wells, coverage80 52.38% and coverage90 60.91%, with unchanged thresholds and historical P2 results. Add native Windows logging, the RTX 3060 environment lock, detached runs, and an audited dashboard-lock recovery that preserves frozen scientific code. Update report.html, the plan and agent guidance with completed P3 status. Archive thesis sources under code_thesis with identical Git blobs and record the original-output audit without committing large data or model artifacts. Validation: 129 tests passed, 13 skipped; CUDA end-to-end smoke passed; completion audit verified 1,320 checkpoint/prediction pairs, 28 registration bundles and all 649 interior volume inlines. Scripts 04 and 09 were not rerun. Co-authored-by: Codex <codex@openai.com>
121 lines
4.7 KiB
Python
121 lines
4.7 KiB
Python
"""Train CNN–GRU v2 with the original loss on the dataset from 01_build_wells.py (B2).
|
||
|
||
python scripts/03_train.py --config configs/b2_smoke.yaml [--epochs N] [--seed S]
|
||
|
||
Differences from `code_thesis/train_open_patch_v2.py`: correct well locations, selectable TDR, validation well
|
||
separate from the train wells, no label clipping, no lag estimated from seismic–PHIE correlation,
|
||
metrics computed on the true scale. Outputs: outputs/runs/<config name>_s<seed>/.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import time
|
||
from pathlib import Path
|
||
|
||
import numpy as np
|
||
import torch
|
||
import yaml
|
||
|
||
from ml_porosity.eval.metrics import point_metrics
|
||
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
|
||
from ml_porosity.models.cnn_gru import CNNGRU
|
||
from ml_porosity.paths import outputs_dir
|
||
|
||
|
||
def zscore_rows(X: np.ndarray) -> np.ndarray:
|
||
mu = X.mean(axis=-1, keepdims=True)
|
||
sd = X.std(axis=-1, keepdims=True) + 1e-8
|
||
return (X - mu) / sd
|
||
|
||
|
||
def load_split(D, wells: list[str], tdr: str, label: str):
|
||
X = np.stack([zscore_rows(D[f"{w}/seismic_patch"].astype(np.float64)) for w in wells])
|
||
Y = np.stack([D[f"{w}/{tdr}/{label}"] for w in wells])
|
||
if not np.all(np.isfinite(Y)):
|
||
raise ValueError(f"label {tdr}/{label} contains NaN in the window at {wells}; choose a different window")
|
||
return X, Y
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--config", required=True)
|
||
ap.add_argument("--epochs", type=int)
|
||
ap.add_argument("--seed", type=int)
|
||
args = ap.parse_args()
|
||
cfg = yaml.safe_load(open(args.config))
|
||
if args.epochs is not None:
|
||
cfg["epochs"] = args.epochs
|
||
if args.seed is not None:
|
||
cfg["seed"] = args.seed
|
||
|
||
test, val, train = cfg["test_well"], cfg["val_well"], cfg["train_wells"]
|
||
if test in train or val in train or test == val:
|
||
raise ValueError("train, validation and test wells must be disjoint")
|
||
|
||
torch.manual_seed(cfg["seed"])
|
||
np.random.seed(cfg["seed"])
|
||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||
|
||
D = np.load(outputs_dir() / cfg["dataset"])
|
||
Xtr, Ytr = load_split(D, train, cfg["tdr"], cfg["label"])
|
||
Xva, Yva = load_split(D, [val], cfg["tdr"], cfg["label"])
|
||
Xte, Yte = load_split(D, [test], cfg["tdr"], cfg["label"])
|
||
mu, sd = float(Ytr.mean()), float(Ytr.std() + 1e-8) # train statistics only
|
||
|
||
def T(a):
|
||
return torch.tensor(a, dtype=torch.float32, device=device)
|
||
|
||
xtr, ytr = T(Xtr), T((Ytr - mu) / sd)[:, None]
|
||
xva, yva = T(Xva), T((Yva - mu) / sd)[:, None]
|
||
|
||
model = CNNGRU(in_ch=Xtr.shape[1], d=cfg["d_channels"], pdrop=cfg["p_dropout"]).to(device)
|
||
loss_fn = LegacyV2Loss()
|
||
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
|
||
sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode="min", factor=0.5, patience=50)
|
||
|
||
run_dir = outputs_dir() / "runs" / f"{Path(args.config).stem}_s{cfg['seed']}"
|
||
run_dir.mkdir(parents=True, exist_ok=True)
|
||
best, best_ep, t_start = float("inf"), 0, time.time()
|
||
for ep in range(1, cfg["epochs"] + 1):
|
||
model.train()
|
||
opt.zero_grad()
|
||
pred = model(xtr)
|
||
if ep <= 50: # small noise in the first epochs, as in the thesis
|
||
pred = pred + 0.01 * torch.randn_like(pred)
|
||
loss = loss_fn(pred, ytr)
|
||
loss.backward()
|
||
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
|
||
opt.step()
|
||
|
||
model.eval()
|
||
with torch.no_grad():
|
||
vloss = float(loss_fn(model(xva), yva))
|
||
sched.step(vloss)
|
||
if vloss < best:
|
||
best, best_ep = vloss, ep
|
||
torch.save(model.state_dict(), run_dir / "best.pt")
|
||
if ep == 1 or ep % 50 == 0:
|
||
print(f"ep {ep:4d} train {loss.item():.4f} val {vloss:.4f} best {best:.4f} @ {best_ep}")
|
||
|
||
model.load_state_dict(torch.load(run_dir / "best.pt", map_location=device))
|
||
model.eval()
|
||
with torch.no_grad():
|
||
yp = model(T(Xte)).cpu().numpy()[0, 0] * sd + mu
|
||
yt = Yte[0]
|
||
m = point_metrics(yt, yp)
|
||
m_const = point_metrics(yt, np.full_like(yt, mu)) # prediction = train mean
|
||
|
||
result = {"config": cfg, "device": device, "best_epoch": best_ep, "best_val_loss": best,
|
||
"train_seconds": round(time.time() - t_start, 1),
|
||
"test": m, "test_constant_train_mean": m_const}
|
||
(run_dir / "metrics.json").write_text(json.dumps(result, indent=1, ensure_ascii=False))
|
||
np.savez_compressed(run_dir / "pred_test.npz", times_ms=D[f"{test}/times_ms"], y_true=yt, y_pred=yp)
|
||
print(f"[test {test}] RMSE {m['rmse']:.4f} PCC {m['pcc']:.3f} R² {m['r2']:.2f} "
|
||
f"(constant: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|