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

@@ -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)