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,6 +1,6 @@
"""Các loss của luận văn (`test 2/train_open_patch_v2.py`), chuyển nguyên trạng để dựng baseline B0.
"""Losses from the thesis (`test 2/train_open_patch_v2.py`), ported verbatim to build baseline B0.
Lưu ý (plan mục 1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L nên chỉ có 5 ràng buộc độc lập.
Note (plan §1.1 #7): shape_loss ≈ 2·pcc_loss − 2/L, so there are only 5 independent constraints.
"""
from __future__ import annotations
@@ -37,7 +37,7 @@ def var_match_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
def crosscorr_loss(pred: torch.Tensor, target: torch.Tensor, max_shift: int = 8) -> torch.Tensor:
"""MSE nhỏ nhất trên dải shift [-max_shift, max_shift]."""
"""Minimum MSE over the shift range [-max_shift, max_shift]."""
x = pred.squeeze(1); y = target.squeeze(1)
L = x.shape[1]
losses = []

87
ml_porosity/losses/rml.py Normal file
View File

@@ -0,0 +1,87 @@
"""Sub-window losses on the "label bank" (plan §4.4–4.5).
Each training well w has S candidate labels Y_w (S, L) and log-weights log π_w (S). For each sub-window j:
ℓ_wjs = Σ_{i ∈ j} log N(y_ws,i; μ_i, σ_i²)
RML: −(1/(λ n_j)) · log Σ_s π_ws exp(λ ℓ_wjs)
hard-min: −(1/n_j) · max_s ℓ_wjs (λ → ∞, uniform π; B4a)
S = 1 gives the mean Gaussian NLL (B3, point tie). A bank of ±K-sample shifts of a single label with
uniform π gives soft-min/hard-min over bulk shifts (B4b/B4a). The same windowing mechanism is used for all methods.
"""
from __future__ import annotations
import math
import numpy as np
import torch
LOG_2PI = math.log(2 * math.pi)
def window_starts(n_wells: int, L: int, win: int, J: int, margin: int, gen: torch.Generator, device) -> torch.Tensor:
hi = L - win - margin
return torch.randint(margin, hi + 1, (n_wells, J), generator=gen, device="cpu").to(device)
def gather_windows(x: torch.Tensor, starts: torch.Tensor, win: int) -> torch.Tensor:
"""x (B, ..., L), starts (B, J) → (B, J, ..., win)."""
idx = starts[..., None] + torch.arange(win, device=x.device) # (B, J, win)
B = x.shape[0]
mid = x.shape[1:-1]
xe = x.unsqueeze(1).expand(B, idx.shape[1], *mid, x.shape[-1])
ie = idx.view(B, idx.shape[1], *([1] * len(mid)), win).expand(B, idx.shape[1], *mid, win)
return torch.gather(xe, -1, ie)
def window_loglik(mu, sigma, Y, starts, win):
"""mu, sigma (B, L); Y (B, S, L) → ℓ (B, J, S)."""
m = gather_windows(mu, starts, win)[:, :, None, :]
s = gather_windows(sigma, starts, win)[:, :, None, :]
y = gather_windows(Y, starts, win)
return (-torch.log(s) - 0.5 * ((y - m) / s) ** 2 - 0.5 * LOG_2PI).sum(-1)
def bank_loss(mu, sigma, Y, logpi, starts, win: int, lam: float | None):
"""lam = None → hard-min (max ℓ); otherwise RML with power λ."""
ll = window_loglik(mu, sigma, Y, starts, win)
if lam is None:
return -(ll.max(-1).values / win).mean()
v = torch.logsumexp(logpi[:, None, :] + lam * ll, dim=-1)
return -(v / (lam * win)).mean()
def mse_bank_loss(mu, Y, starts, win: int):
"""Mean MSE over the labels of the bank (H1: the optimum is the label blurred by p_δ)."""
m = gather_windows(mu, starts, win)[:, :, None, :]
y = gather_windows(Y, starts, win)
return ((y - m) ** 2).mean()
def shift_bank(y: np.ndarray, max_shift: int) -> np.ndarray:
"""(2K+1, L): y shifted by k samples (label y_{i+k}), NaN outside the boundaries."""
L = len(y)
out = np.full((2 * max_shift + 1, L), np.nan)
for n, k in enumerate(range(-max_shift, max_shift + 1)):
lo, hi = max(0, -k), min(L, L - k)
out[n, lo:hi] = y[lo + k: hi + k]
return out
def effective_lambda(labels: list[np.ndarray], f_c_hz: float = 6.0, dt_ms: float = 4.0, max_lag: int = 32) -> tuple[float, float]:
"""λ = 1/τ_c with τ_c = 1 + 2 Σ_k ρ(k)², where ρ is the pooled ACF of the training labels high-pass filtered
above f_c (a proxy for the residual in the seismic band). Σ runs up to the first lag with ρ ≤ 0 (at most
max_lag). Returns (λ, τ_c)."""
from ml_porosity.eval.metrics import split_bands
acc = np.zeros(max_lag + 1)
for y in labels:
hi = split_bands(np.asarray(y, dtype=float), f_c_hz, dt_ms)[1]
hi = hi - hi.mean()
a = np.correlate(hi, hi, "full")[len(hi) - 1: len(hi) + max_lag]
acc += a
rho = acc / acc[0]
k = np.argmax(rho[1:] <= 0) + 1 if np.any(rho[1:] <= 0) else max_lag + 1
tau_c = 1.0 + 2.0 * float(np.sum(rho[1:k] ** 2))
return 1.0 / tau_c, tau_c

View File

@@ -0,0 +1,175 @@
"""Soft-DTW (Cuturi & Blondel 2017) and DILATE (Le Guen & Thome 2019) for B4c/B4d.
The cost of cell (i, j) is the Gaussian NLL of label j under prediction (μ_i, σ_i); Sakoe–Chiba band constraint
|i − j| ≤ band. The NLL can be negative, so a weighted symmetric step pattern is used (diagonal step ×2,
horizontal/vertical ×1; Sakoe & Chiba 1978): every path from (0, 0) to (n−1, m−1) has total weight n + m, so
shifting the cost by a constant does not bias the choice of path length. The result is divided by n + m. The DP
runs along anti-diagonals, vectorised over the batch, with gradients via autograd.
"""
from __future__ import annotations
import math
import torch
BIG = 1e8
def soft_dtw(D: torch.Tensor, gamma: float, band: int | None = None) -> torch.Tensor:
"""D (B, n, m) → R(n−1, m−1) (B,) with R(i, j) = softmin_γ(R(i−1, j−1) + 2D_ij, R(i−1, j) + D_ij, R(i, j−1) + D_ij),
R(−1, −1) = 0. R is stored per anti-diagonal k = i + j, indexed by i; cells outside the band = BIG."""
B, n, m = D.shape
big = torch.full((B, 1), BIG, device=D.device, dtype=D.dtype)
prev2 = prev1 = torch.full((B, n), BIG, device=D.device, dtype=D.dtype)
for k in range(n + m - 1):
i0, i1 = max(0, k - m + 1), min(k, n - 1)
i = torch.arange(i0, i1 + 1, device=D.device)
d = D[:, i, k - i]
sh2 = torch.cat([torch.zeros_like(big) if k == 0 else big, prev2[:, :-1]], 1) # sh2[:, i] = R(i−1, j−1)
sh1 = torch.cat([big, prev1[:, :-1]], 1) # sh1[:, i] = R(i−1, j)
r = torch.stack([sh2[:, i] + 2 * d, sh1[:, i] + d, prev1[:, i] + d], 0) # prev1[:, i] = R(i, j−1)
val = -gamma * torch.logsumexp(-r / gamma, 0)
if band is not None:
val = torch.where(((2 * i - k).abs() <= band)[None, :], val, torch.full_like(val, BIG))
prev2, prev1 = prev1, torch.cat([big.expand(B, i0), val, big.expand(B, n - 1 - i1)], 1)
return prev1[:, n - 1]
def nll_cost(mu: torch.Tensor, sigma: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""mu, sigma, y (B, n) → D (B, n, n), D_ij = −log N(y_j; μ_i, σ_i²)."""
return torch.log(sigma)[:, :, None] + 0.5 * ((y[:, None, :] - mu[:, :, None]) / sigma[:, :, None]) ** 2 \
+ 0.5 * math.log(2 * math.pi)
def softdtw_loss(mu, sigma, y, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
"""mu, sigma, y (B, n): batch mean of soft-DTW/(2n)."""
n = mu.shape[-1]
return (soft_dtw(nll_cost(mu, sigma, y), gamma, band) / (2 * n)).mean()
def dilate_loss(mu, sigma, y, alpha: float = 0.5, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
"""α·soft-DTW/(2n) + (1 − α)·TDI, TDI = ⟨A*, Ω⟩/(2n), A* = ∂R/∂D (step-weighted expected alignment),
Ω_ij = ((i − j)/n)² penalises temporal distortion (Le Guen & Thome 2019)."""
n = mu.shape[-1]
D = nll_cost(mu, sigma, y)
if not D.requires_grad:
D.requires_grad_(True)
v = soft_dtw(D, gamma, band)
A = torch.autograd.grad(v.sum(), D, create_graph=True)[0]
idx = torch.arange(n, device=mu.device, dtype=mu.dtype)
omega = ((idx[:, None] - idx[None, :]) / n) ** 2
tdi = (A * omega).sum((1, 2))
return ((alpha * v + (1 - alpha) * tdi) / (2 * n)).mean()
# ---------------------------------------------------------------- fast version (numba, analytic gradient)
#
# Same recursion as soft_dtw above. Backward: E(i, j) = ∂R_end/∂R(i, j) = Σ_s E(s)·q_{(i,j)}(s), where q is the
# softmax weight of the predecessor in the softmin of cell s; ∂R_end/∂D_ij = E(i, j)·Σ_p w_p q_p(i, j). DILATE
# additionally needs ∇_D TDI = H·Ω (Hessian–vector product): the directional derivative along Ω of the whole
# forward pass (Ṙ, q̇) and backward pass (Ė) (Mensch & Blondel 2018). Verified against the autograd version in
# tests/test_losses.py.
import numpy as np
from numba import njit, prange
@njit(parallel=True, cache=True)
def _sdtw_nll(mu, sg, y, gamma, band, alpha):
"""For each row b: loss_b = α·R_end + (1 − α)·TDI with D_ij = −log N(y_j; μ_i, σ_i²), Ω_ij = ((i − j)/n)²,
together with ∂loss_b/∂μ, ∂loss_b/∂σ. Only cells inside the band are visited; cells outside have R = big, so
E = 0, G = 0."""
B, n = mu.shape
big = 1e10
bw = band if band >= 0 else 2 * n
hvp = alpha < 1.0
c0 = 0.5 * np.log(2.0 * np.pi)
loss = np.empty(B)
g_mu = np.zeros((B, n))
g_s = np.zeros((B, n))
for b in prange(B):
R = np.full((n + 2, n + 2), big)
Rd = np.zeros((n + 2, n + 2))
Q = np.zeros((n + 2, n + 2, 3))
Qd = np.zeros((n + 2, n + 2, 3))
R[0, 0] = 0.0
for i in range(1, n + 1):
mi = mu[b, i - 1]
si = sg[b, i - 1]
ls = np.log(si)
for j in range(max(1, i - bw), min(n, i + bw) + 1):
r = (y[b, j - 1] - mi) / si
d = ls + 0.5 * r * r + c0
a0 = R[i - 1, j - 1] + 2.0 * d
a1 = R[i - 1, j] + d
a2 = R[i, j - 1] + d
am = min(a0, min(a1, a2))
e0 = np.exp(-(a0 - am) / gamma)
e1 = np.exp(-(a1 - am) / gamma)
e2 = np.exp(-(a2 - am) / gamma)
s = e0 + e1 + e2
R[i, j] = am - gamma * np.log(s)
q0, q1, q2 = e0 / s, e1 / s, e2 / s
Q[i, j, 0], Q[i, j, 1], Q[i, j, 2] = q0, q1, q2
if hvp:
z = ((i - j) / n) ** 2
b0 = Rd[i - 1, j - 1] + 2.0 * z
b1 = Rd[i - 1, j] + z
b2 = Rd[i, j - 1] + z
rd = q0 * b0 + q1 * b1 + q2 * b2
Rd[i, j] = rd
Qd[i, j, 0] = -q0 * (b0 - rd) / gamma
Qd[i, j, 1] = -q1 * (b1 - rd) / gamma
Qd[i, j, 2] = -q2 * (b2 - rd) / gamma
E = np.zeros((n + 2, n + 2))
Ed = np.zeros((n + 2, n + 2))
E[n, n] = 1.0
tdi = 0.0
for i in range(n, 0, -1):
mi = mu[b, i - 1]
si = sg[b, i - 1]
for j in range(min(n, i + bw), max(1, i - bw) - 1, -1):
if i < n or j < n:
E[i, j] = E[i + 1, j + 1] * Q[i + 1, j + 1, 0] + E[i + 1, j] * Q[i + 1, j, 1] + E[i, j + 1] * Q[i, j + 1, 2]
if hvp:
Ed[i, j] = (Ed[i + 1, j + 1] * Q[i + 1, j + 1, 0] + E[i + 1, j + 1] * Qd[i + 1, j + 1, 0]
+ Ed[i + 1, j] * Q[i + 1, j, 1] + E[i + 1, j] * Qd[i + 1, j, 1]
+ Ed[i, j + 1] * Q[i, j + 1, 2] + E[i, j + 1] * Qd[i, j + 1, 2])
c = 2.0 * Q[i, j, 0] + Q[i, j, 1] + Q[i, j, 2]
gd = alpha * E[i, j] * c # ∂loss/∂D_ij
if hvp:
cd = 2.0 * Qd[i, j, 0] + Qd[i, j, 1] + Qd[i, j, 2]
gd += (1.0 - alpha) * (Ed[i, j] * c + E[i, j] * cd)
tdi += E[i, j] * c * ((i - j) / n) ** 2
r = y[b, j - 1] - mi
g_mu[b, i - 1] -= gd * r / (si * si)
g_s[b, i - 1] += gd * (1.0 / si - r * r / (si * si * si))
loss[b] = alpha * R[n, n] + (1.0 - alpha) * tdi
return loss, g_mu, g_s
class _SoftDTWNLL(torch.autograd.Function):
"""Batch mean of [α·R_end + (1 − α)·TDI]/(2n) with NLL cost; computed on the CPU (float64)."""
@staticmethod
def forward(ctx, mu, sigma, y, gamma, band, alpha):
m_, s_, y_ = (t.detach().double().cpu().numpy() for t in (mu, sigma, y))
B, n = m_.shape
loss, g_mu, g_s = _sdtw_nll(m_, s_, y_, float(gamma), -1 if band is None else int(band), float(alpha))
T = lambda a: torch.as_tensor(a, dtype=mu.dtype, device=mu.device)
ctx.save_for_backward(T(g_mu / (2 * n * B)), T(g_s / (2 * n * B)))
return T(loss.mean() / (2 * n))
@staticmethod
def backward(ctx, go):
g_mu, g_s = ctx.saved_tensors
return go * g_mu, go * g_s, None, None, None, None
def softdtw_loss_fast(mu, sigma, y, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
return _SoftDTWNLL.apply(mu, sigma, y, gamma, band, 1.0)
def dilate_loss_fast(mu, sigma, y, alpha: float = 0.5, gamma: float = 0.1, band: int | None = 8) -> torch.Tensor:
return _SoftDTWNLL.apply(mu, sigma, y, gamma, band, alpha)