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>
This commit is contained in:
2026-10-27 06:03:33 +00:00
parent a76e61398a
commit cee2ff0859
84 changed files with 8793 additions and 460 deletions

View File

@@ -1,10 +1,10 @@
"""Huấn luyện CNN–GRU v2 với loss gốc trên bộ dữ liệu từ 01_build_wells.py (B2).
"""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]
So với `test 2/train_open_patch_v2.py`: vị trí giếng đúng, TDR chọn được, giếng validation
tách khỏi giếng train, không clip nhãn, không ước lượng lag bằng tương quan seismic–PHIE,
metric tính ở thang thật. Đầu ra: outputs/runs/<tên config>_s<seed>/.
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
@@ -34,7 +34,7 @@ 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"nhãn {tdr}/{label} có NaN trong cửa sổ ở {wells}; cần chọn cửa sổ khác")
raise ValueError(f"label {tdr}/{label} contains NaN in the window at {wells}; choose a different window")
return X, Y
@@ -52,7 +52,7 @@ def main() -> None:
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("giếng train, validation và test phải tách rời")
raise ValueError("train, validation and test wells must be disjoint")
torch.manual_seed(cfg["seed"])
np.random.seed(cfg["seed"])
@@ -62,7 +62,7 @@ def main() -> None:
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) # chỉ dùng thống kê train
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)
@@ -82,7 +82,7 @@ def main() -> None:
model.train()
opt.zero_grad()
pred = model(xtr)
if ep <= 50: # nhiễu nhỏ những epoch đầu như luận văn
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()
@@ -105,7 +105,7 @@ def main() -> None:
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)) # dự đoán bằng trung bình train
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),
@@ -113,7 +113,7 @@ def main() -> None:
(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"(hằng số: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}")
f"(constant: RMSE {m_const['rmse']:.4f}, R² {m_const['r2']:.2f}) -> {run_dir}")
if __name__ == "__main__":