P0 + P1: ml_porosity package, audited F3 data, LOWO baselines, protocol v2

P0
- ml_porosity/: survey geometry, LAS/TDR/SEG-Y readers (4 ms delay fix,
  invalid time scalar, header LUT for incomplete cubes), anti-aliased
  log-to-time resampling, CNN-GRU v2 with the thesis loss, 41+ unit tests.
- Full F3 Demo 2023 under data/ (text well/fault files tracked, bulk data
  ignored); the filtered copy and its cleanup notes are removed.
- SHA-256 manifests for F3, Volve, NLOG and the thesis outputs.

P1
- configs/protocol.yaml v2, locked by SHA-256 at 2026-10-26T04:28:09Z,
  before the first LOWO run (04:30:50Z); 05_lowo.py refuses to run on a
  hash mismatch. This commit postdates the runs.
- Wavelet/synthetic tie QC, residual misregistration, LOWO 5 seeds for
  B0a, B0b, B1, B2, B3a, B3b (scripts 04-06); gate G-A: no pivot.
- Volve D3: horizons, well picks, checkshots and the ST10010 cube read
  from data/Volve (scripts/07).
- D-1 label check against measured NLOG density (scripts/08): PHIE_DT
  stays the primary label.
- docs/plan.md, Volve and NLOG inventories, report.html.

Full-text reference PDFs in refs/ stay local (ignored).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 08:41:11 +00:00
parent d11b7b1bb5
commit a76e61398a
163 changed files with 120177 additions and 2742 deletions

View File

@@ -0,0 +1,78 @@
"""Huấn luyện CNN–GRU cho B2 (loss gốc) và B3 (Gaussian NLL), chọn epoch theo vòng inner."""
from __future__ import annotations
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
from ml_porosity.models.cnn_gru import CNNGRU
class CNNGRUHetero(nn.Module):
"""Backbone CNN–GRU v2 với head 2 kênh: μ và σ = softplus(·) + σ_min."""
def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05, sigma_min: float = 1e-3):
super().__init__()
self.net = CNNGRU(in_ch, d, pdrop)
self.net.head = nn.Conv1d(2 * d, 2, kernel_size=1)
self.net.head_skip = nn.Conv1d(in_ch, 2, kernel_size=1)
self.net.bias = nn.Parameter(torch.zeros(2))
self.sigma_min = sigma_min
def forward(self, x):
h = self.net.cnn(x)
h2, _ = self.net.gru(h.transpose(1, 2))
out = self.net.head(h2.transpose(1, 2)) + self.net.head_skip(x) + self.net.bias.view(1, 2, 1)
return out[:, :1], F.softplus(out[:, 1:]) + self.sigma_min
def gaussian_nll(mu, sigma, y):
return torch.mean(torch.log(sigma) + 0.5 * ((y - mu) / sigma) ** 2)
def train_cnn(Xtr, Ytr, cfg: dict, kind: str, seed: int, epochs: int, device: str,
Xva=None, Yva=None, eval_every: int = 25):
"""kind: "legacy" (B2) hoặc "nll" (B3). Y ở thang đã chuẩn hoá. Trả về (model, [(epoch, val_mse)])."""
torch.manual_seed(seed)
np.random.seed(seed)
T = lambda a: torch.tensor(a, dtype=torch.float32, device=device)
x, y = T(Xtr), T(Ytr)[:, None]
in_ch = Xtr.shape[1]
if kind == "legacy":
model = CNNGRU(in_ch, cfg["d_channels"], cfg["p_dropout"]).to(device)
loss_fn = LegacyV2Loss()
else:
model = CNNGRUHetero(in_ch, cfg["d_channels"], cfg["p_dropout"]).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
curve = []
xv = T(Xva) if Xva is not None else None
for ep in range(1, epochs + 1):
model.train()
opt.zero_grad()
if kind == "legacy":
pred = model(x)
if ep <= 50:
pred = pred + 0.01 * torch.randn_like(pred)
loss = loss_fn(pred, y)
else:
mu, sig = model(x)
loss = gaussian_nll(mu, sig, y)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
opt.step()
if xv is not None and ep % eval_every == 0:
mu_v = predict(model, Xva, device)[0]
curve.append((ep, float(np.mean((mu_v - Yva) ** 2))))
return model, curve
@torch.no_grad()
def predict(model, X, device):
model.eval()
out = model(torch.tensor(X, dtype=torch.float32, device=device))
if isinstance(out, tuple):
return out[0][:, 0].cpu().numpy(), out[1][:, 0].cpu().numpy()
return out[:, 0].cpu().numpy(), None