Files
ML-Porosity/scripts/03_train.py
lamlvh cee2ff0859 P2 diagnosis on dev, P3 dev experiments, lock protocol_p3
- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:33 +00:00

121 lines
4.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 `test 2/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()