Files
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

302 lines
15 KiB
Python
Raw Permalink 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.
"""The SMC warp posterior of smc.py on GPU (torch, float64).
Same algorithm and same random stream: all random numbers are still drawn from the numpy Generator in exactly the
order of smc.py (γ and resampling stay on the CPU); synthetics, likelihood, particle π_γ, the Gaussian reference and
the whole elliptical slice shrinkage loop run batched on the device, with no host synchronisation inside each
shrinkage step (ess_moves). With the same seed, results match the CPU version up to rounding error, unless an
accept/reject decision falls exactly within that error — the chain then diverges but keeps the same distribution.
Synthetic: piecewise-linear warp inversion by batched searchsorted, AI interpolation, reflectivity, then the 'same'
convolution and interpolation to t_out are merged into one fixed (n_r, L) matrix per wavelet (conv_interp_matrix).
"""
from __future__ import annotations
import copy
import numpy as np
import torch
from ml_porosity.registration import smc
from ml_porosity.registration.sampler import ess
from ml_porosity.registration.smc import TiePosterior, next_gamma, systematic_resample
F64 = torch.float64
def interp_weights(x: np.ndarray, xp: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""(j, w) with np.interp(x, xp, f) = (1 − w)·f[j] + w·f[j + 1]; clamped at both ends as in np.interp."""
j = np.clip(np.searchsorted(xp, x, side="right") - 1, 0, len(xp) - 2)
return j, np.clip((x - xp[j]) / (xp[j + 1] - xp[j]), 0.0, 1.0)
def conv_interp_matrix(w_fine: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray) -> np.ndarray:
"""M (n_r, L) with tie_likelihood.forward_fine(ai, t_fine, t_out, w_fine) = r(ai) @ M: scipy's 'same'
convolution (the segment starting at (n_w − 1) // 2 of the full convolution), then interpolation from the
midpoints to t_out."""
n_r, n_w = len(t_fine) - 1, len(w_fine)
j, w = interp_weights(t_out, 0.5 * (t_fine[1:] + t_fine[:-1]))
i = np.arange(n_r)[:, None]
def col(jj):
k = jj[None, :] + (n_w - 1) // 2 - i
return np.where((k >= 0) & (k < n_w), w_fine[np.clip(k, 0, n_w - 1)], 0.0)
return (1.0 - w) * col(j) + w * col(j + 1)
def interp_t(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
"""Batched np.interp: x (P, n); xp (P, m) (each row increasing) or (m,); fp (m,)."""
j = (torch.searchsorted(xp, x, right=True) - 1).clamp_(0, xp.shape[-1] - 2)
x0, x1 = (xp[j], xp[j + 1]) if xp.dim() == 1 else (xp.gather(1, j), xp.gather(1, j + 1))
w = ((x - x0) / (x1 - x0)).clamp_(0.0, 1.0)
return fp[j] + w * (fp[j + 1] - fp[j])
def profile_loglik_t(syn: torch.Tensor, seis: torch.Tensor) -> torch.Tensor:
"""tie_likelihood.profile_loglik on tensors."""
a = torch.clamp(syn @ seis / torch.clamp((syn**2).sum(1), min=1e-30), min=0.0)
return -0.5 * len(seis) * torch.log(((seis - a[:, None] * syn) ** 2).sum(1))
class TiePosteriorTorch:
"""TiePosterior with synthetics, likelihood and π_γ computed in batches on `device`. The numpy methods (u, z,
synth, loglik, parts, reference, with_wavelet, n_eval, seis) keep the TiePosterior interface so that
smc.gamma_acf, smc.smc_fit_phase and scripts/14 can be shared; the *_t versions take/return device tensors."""
def __init__(self, T: TiePosterior, device):
self.cpu, self.device = T, torch.device(device)
if self.device.type == "cuda":
torch.cuda.set_device(self.device) # implicit-device operations also go to the right GPU
f = self.tensor
self.mu, self.Lc, self.Pk, self.A, self.off, self.d_k = map(f, (T.mu, T.Lc, T.P, T.A, T.off, T.d_k))
self.tau_g, self.QT, self.tau_fine, self.ai_log = map(f, (T.tau_g, T.QT, T.tau_fine, T.ai_log))
self.seis_t = f(T.seis)
self._set_wavelet()
self._cnt = torch.zeros((), dtype=torch.int64, device=self.device)
def tensor(self, x) -> torch.Tensor:
return torch.as_tensor(np.asarray(x, dtype=float), dtype=F64, device=self.device)
def _set_wavelet(self) -> None:
self.t_crop = self.tensor(self.cpu.t_crop)
self.M = self.tensor(conv_interp_matrix(self.cpu.w_fine, self.cpu.t_crop, self.cpu.t_out))
def with_wavelet(self, w_fine: np.ndarray) -> "TiePosteriorTorch":
T = copy.copy(self)
T.cpu = self.cpu.with_wavelet(w_fine)
T._set_wavelet()
T._cnt = torch.zeros_like(self._cnt)
return T
@property
def seis(self) -> np.ndarray:
return self.cpu.seis
@property
def w_fine(self) -> np.ndarray:
return self.cpu.w_fine
@property
def n_eval(self) -> int:
"""Number of synthetics computed (as in TiePosterior: parts counts only valid particles)."""
return int(self._cnt)
@n_eval.setter
def n_eval(self, v: int) -> None:
self._cnt.fill_(int(v))
def u_t(self, Z: torch.Tensor) -> torch.Tensor:
return self.mu + Z @ self.Lc.T
def _synth_tg(self, tg: torch.Tensor) -> torch.Tensor:
"""(P, L) from t at the warp-grid nodes (P, n_g)."""
tau = interp_t(self.t_crop.expand(len(tg), -1).contiguous(), tg.contiguous(), self.tau_g)
ai = interp_t(tau, self.tau_fine, self.ai_log)
return ((ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])) @ self.M
def synth_t(self, U: torch.Tensor) -> torch.Tensor:
self._cnt += len(U)
return self._synth_tg(self.tau_g + U[:, :1] + torch.expm1(U[:, 1:]) @ self.QT)
def parts_t(self, Z: torch.Tensor, mask: torch.Tensor | None = None) -> tuple[torch.Tensor, torch.Tensor]:
"""TiePosterior.parts on tensors, without host synchronisation. Synthetics are computed for all rows and
violating particles are then masked (cheaper than filtering on the GPU); `mask` (bool, optional) marks the rows
actually needed — only these are counted in n_eval."""
U = self.u_t(Z)
g = U[:, 1:]
eg = torch.expm1(g)
exact = U[:, :1] + eg @ self.Pk.T
lin = U @ self.A.T + self.off
la = -0.5 * (((self.d_k - exact) ** 2).sum(1) - ((self.d_k - lin) ** 2).sum(1)) / self.cpu.s2a
tg = self.tau_g + U[:, :1] + eg @ self.QT
ok = g.abs().amax(1) <= self.cpu.g_max
if self.cpu.cover is not None:
ok &= (tg[:, 0] <= self.cpu.cover[0]) & (tg[:, -1] >= self.cpu.cover[1])
self._cnt += (ok if mask is None else ok & mask).sum()
ls = profile_loglik_t(self._synth_tg(tg), self.seis_t)
return torch.where(ok, -0.5 * (Z**2).sum(1) + la, -np.inf), torch.where(ok, ls, -np.inf)
def reference_t(self, m: torch.Tensor, gamma: float, infl: float = 2.0, eps: float = 0.05):
"""TiePosterior.reference on the device. Returns tensors (m, L)."""
eye = torch.eye(len(m), dtype=F64, device=self.device)
syn = self.synth_t(self.u_t(torch.cat([m[None], m + eps * eye])))
s0, J = syn[0], (syn[1:] - syn[0]).T / eps
a = max(float(s0 @ self.seis_t) / max(float(s0 @ s0), 1e-30), 0.0)
s2 = float(((self.seis_t - a * s0) ** 2).sum()) / len(self.seis_t)
return m, torch.linalg.cholesky(eye + (gamma / infl) * a**2 * (J.T @ J) / s2)
def u(self, Z: np.ndarray) -> np.ndarray:
return self.cpu.u(Z)
def z(self, U: np.ndarray) -> np.ndarray:
return self.cpu.z(U)
def t_grid(self, U: np.ndarray) -> np.ndarray:
return self.cpu.t_grid(U)
def synth(self, U: np.ndarray) -> np.ndarray:
return self.synth_t(self.tensor(np.atleast_2d(U))).cpu().numpy()
def loglik(self, U: np.ndarray) -> np.ndarray:
return profile_loglik_t(self.synth_t(self.tensor(np.atleast_2d(U))), self.seis_t).cpu().numpy()
def parts(self, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
b, ls = self.parts_t(self.tensor(np.atleast_2d(Z)))
return b.cpu().numpy(), ls.cpu().numpy()
def reference(self, m: np.ndarray, gamma: float, infl: float = 2.0, eps: float = 0.05):
return tuple(x.cpu().numpy() for x in self.reference_t(self.tensor(m), gamma, infl, eps))
_LAST_GRAPH: dict = {}
def cuda_graph(fn, device: torch.device):
"""Capture fn() — no arguments, no host synchronisation, only in-place writes into pre-allocated tensors — as a
CUDA graph; returns the replay function. fn is run once beforehand for warm-up (cuBLAS workspace, ...), so that
run must be free of side effects.
All graphs on a device share one stream and the memory pool of the graph captured before them: the pool of a
discarded graph is returned to the device only on empty_cache, so recapturing every SMC stage with a fresh pool
would hold unbounded memory. The previous graph is kept until the new one has been captured (the shared pool must
still have a user, on the host side too) and is never replayed again — sharing a pool is safe only when at most
one graph is still replayed at any time; ess_moves drops its graph when done. capture_begin is called directly
instead of torch.cuda.graph, which empties the memory cache on every capture."""
side, prev = _LAST_GRAPH.get(device) or (torch.cuda.Stream(device), None)
side.wait_stream(torch.cuda.current_stream(device))
graph = torch.cuda.CUDAGraph()
with torch.cuda.stream(side):
fn()
graph.capture_begin(pool=None if prev is None else prev.pool(), capture_error_mode="thread_local")
try:
fn()
finally:
graph.capture_end()
torch.cuda.current_stream(device).wait_stream(side)
_LAST_GRAPH[device] = side, graph
return graph.replay
def ess_moves(T: TiePosteriorTorch, Z, base, ll, gamma: float, ref, n_moves: int, rng, max_iter: int = 60,
check_every: int = 4):
"""smc.ess_moves with Z, base, ll, ref as device tensors, without host synchronisation in the shrinkage loop.
Each shrinkage step evaluates all P particles and masks those already accepted (on the GPU one call costs almost
the same regardless of P), writing in place into fixed state, so on CUDA the whole step is captured as one graph.
Random numbers are still drawn on the CPU in exactly the order of the numpy version: ξ, u, initial angle, then
the shrinkages — uniform(lo, hi) = lo + (hi − lo)·U with U the next number in the stream, so a pool of U(0, 1) is
drawn in advance, the particles rejected at each step take numbers in index order, and the Generator is then
reset and advanced by exactly the number used. The host reads the device only every `check_every` steps to check
whether any particle remains unaccepted."""
m, L = ref
dev = Z.device
logq = lambda X: -0.5 * (((X - m) @ L) ** 2).sum(1)
comb = lambda b, l: torch.where(torch.isfinite(b), b + gamma * l, -np.inf)
Z, base, ll = Z.clone(), base.clone(), ll.clone()
Lq = comb(base, ll) - logq(Z)
P, d = Z.shape
nu = torch.zeros_like(Z)
log_y, th, lo, hi = (torch.zeros_like(ll) for _ in range(4))
pool = torch.zeros(P * max_iter, dtype=F64, device=dev)
act = torch.zeros(P, dtype=torch.bool, device=dev)
used = torch.zeros((), dtype=torch.int64, device=dev)
def step(): # act all False: no change
zp = m + (Z - m) * torch.cos(th)[:, None] + (nu - m) * torch.sin(th)[:, None]
b, l = T.parts_t(zp, act)
lq = comb(b, l) - logq(zp)
up = lq > log_y
acc, rej = act & up, act & ~up
Z.copy_(torch.where(acc[:, None], zp, Z))
for x, y in ((base, b), (ll, l), (Lq, lq)):
x.copy_(torch.where(acc, y, x))
neg = th < 0
lo.copy_(torch.where(rej & neg, th, lo))
hi.copy_(torch.where(rej & ~neg, th, hi))
u = pool[(used + rej.cumsum(0) - 1).clamp_(0, len(pool) - 1)]
th.copy_(torch.where(rej, lo + (hi - lo) * u, th))
used.add_(rej.sum())
act.copy_(rej)
cuda = dev.type == "cuda"
run = cuda_graph(step, dev) if cuda else step
shrink = 0
for _ in range(n_moves):
head = [rng.standard_normal(P * d), np.log(rng.uniform(size=P)), rng.uniform(0.0, 2 * np.pi, P)]
state = rng.bit_generator.state
buf = torch.from_numpy(np.concatenate(head + [rng.random(P * max_iter)]))
buf = (buf.pin_memory() if cuda else buf).to(dev, non_blocking=True)
xi, log_u, th0, pool0 = torch.split(buf, [P * d, P, P, P * max_iter])
nu.copy_(m + torch.linalg.solve_triangular(L.T, xi.view(P, d).T, upper=True).T)
log_y.copy_(Lq + log_u)
for x, y in ((th, th0), (lo, th0 - 2 * np.pi), (hi, th0), (pool, pool0)):
x.copy_(y)
act.fill_(True)
used.zero_()
for it in range(1, max_iter + 1):
run()
if it % check_every == 0 or it == max_iter:
n_act, n_used = torch.stack([act.sum(), used]).tolist()
if n_act == 0:
break
rng.bit_generator.state = state
rng.random(n_used)
shrink += n_used
return Z, base, ll, shrink / (P * n_moves)
def smc_tie_posterior(T: TiePosteriorTorch, Z0: np.ndarray, checkpoints, rng, min_frac: float = 0.5,
n_moves: int = 8, infl: float = 2.0, max_stages: int = 500) -> dict:
"""smc.smc_tie_posterior on the device; numpy in/out as in the CPU version."""
Z = T.tensor(np.atleast_2d(Z0))
base, ll = T.parts_t(Z)
if not bool(torch.isfinite(base).all()):
raise ValueError("initial samples violate the constraints")
g, logZ = 0.0, 0.0
out = {"Z": {}, "ll": {}, "logZ": {}, "stages": []}
for gk in sorted(set(float(x) for x in checkpoints)):
while g < gk:
ll_np = ll.cpu().numpy()
g_new = next_gamma(ll_np, g, gk, min_frac)
logw = (g_new - g) * ll_np
logZ += float(np.logaddexp.reduce(logw)) - np.log(len(logw))
idx = systematic_resample(logw, rng)
idx_t = torch.from_numpy(idx).to(Z.device)
Z, base, ll = Z[idx_t], base[idx_t], ll[idx_t]
Zb = Z.clone()
Z, base, ll, sh = ess_moves(T, Z, base, ll, g_new, T.reference_t(Z.mean(0), g_new, infl), n_moves, rng)
out["stages"].append({"gamma": g_new, "ess": ess(logw), "n_unique": int(np.unique(idx).size),
"shrink": sh, "jump_z": float(torch.sqrt(torch.mean((Z - Zb) ** 2)))})
g = g_new
if len(out["stages"]) >= max_stages:
raise RuntimeError(f"exceeded {max_stages} tempering stages (γ = {g:.4g})")
out["Z"][gk], out["ll"][gk], out["logZ"][gk] = Z.cpu().numpy(), ll.cpu().numpy(), logZ
return out
def smc_fit_phase(Ts: list[TiePosteriorTorch], Z0s: list[np.ndarray], B: np.ndarray, phase0: float, seed: list[int],
**kw) -> tuple[float, dict]:
"""smc.smc_fit_phase with the SMC run on the device."""
return smc.smc_fit_phase(Ts, Z0s, B, phase0, seed, run=smc_tie_posterior, **kw)