eduzrh's picture
sync code
773c429 verified
Raw History Blame Contribute Delete
4.45 kB
"""Masked data loss + optional physics residuals (Clausius-Duhem inspired)."""
from __future__ import annotations
import torch
import torch.nn.functional as F
from .data import TARGET_KEYS
IDX = {k: i for i, k in enumerate(TARGET_KEYS)}
PHASE_KEYS = ["xi_BCC", "xi_FCC", "xi_HCP", "xi_other"]
RHO_KEYS = ["rho_total", "rho_perfect", "rho_shockley", "rho_stairrod",
"rho_hirth", "rho_other_disl", "rho_112_111"]
TWIN_KEY = "twin"
def masked_mse(pred, Y, M):
"""MSE over observed entries only (missing label != zero label)."""
w = M
num = ((pred - Y) ** 2 * w).sum()
den = w.sum().clamp_min(1.0)
return num / den
def masked_mse_balanced(pred, Y, M, weights=None):
"""Mean over *variables* of the per-variable masked MSE.
Each physical output head contributes equally regardless of how many
samples carry that label -- otherwise rare heads (e.g. twin density,
6 samples) are swamped by rho_total (16 samples).
"""
F_ = pred.shape[-1]
losses = []
for j in range(F_):
m = M[..., j]
n = m.sum()
if n > 0:
losses.append((((pred[..., j] - Y[..., j]) ** 2 * m).sum() / n))
if not losses:
return torch.zeros((), device=pred.device)
stack = torch.stack(losses)
if weights is not None:
w = weights.to(pred.device).float()
idx = [j for j in range(F_) if M[..., j].sum() > 0]
w = w[idx]
return (stack * w).sum() / w.sum().clamp_min(1e-6)
return stack.mean()
def masked_l1(pred, Y, M):
return ((pred - Y).abs() * M).sum() / M.sum().clamp_min(1.0)
def physics_losses(pred, Y, M, strain, cfg):
"""Physics residuals evaluated on the *prediction* trajectory.
* monotonicity of defect densities (dislocation / twin) outside thermal
softening: rho_{t+1} >= rho_t ;
* initial-state consistency: the first frame must reproduce the measured
initial phase fractions / defect densities when they are observed;
* stress smoothness: penalise the second difference of the stress curve
(a weak regularity prior that suppresses non-physical oscillation).
"""
B, T, _ = pred.shape
dev = pred.device
total = torch.zeros((), device=dev)
logs = {}
d_eps = (strain[:, 1:] - strain[:, :-1]).clamp_min(1e-8)
# --- monotonic defect accumulation -----------------------------------
mono = torch.zeros((), device=dev)
n_mono = 0
for k in RHO_KEYS + [TWIN_KEY]:
j = IDX[k]
v = pred[..., j]
dv = (v[:, 1:] - v[:, :-1]) / d_eps
# only penalise decreases that are not preceded by an observed drop
obs = M[:, 1:, j]
pen = F.relu(-dv) * (0.5 + 0.5 * obs)
mono = mono + pen.mean()
n_mono += 1
mono = mono / max(n_mono, 1)
logs["mono"] = float(mono.detach())
total = total + cfg.w_mono * mono
# --- initial state consistency ---------------------------------------
init = torch.zeros((), device=dev)
n_init = 0
for k in PHASE_KEYS + RHO_KEYS:
j = IDX[k]
m0 = M[:, 0, j]
if m0.sum() > 0:
err = ((pred[:, 0, j] - Y[:, 0, j]) ** 2 * m0).sum() / m0.sum().clamp_min(1.0)
init = init + err
n_init += 1
init = init / max(n_init, 1)
logs["init"] = float(init.detach())
total = total + cfg.w_init * init
# --- stress smoothness ------------------------------------------------
s = pred[..., IDX["sigma"]]
if T > 2:
d2 = s[:, 2:] - 2 * s[:, 1:-1] + s[:, :-2]
smooth = (d2 ** 2).mean()
else:
smooth = torch.zeros((), device=dev)
logs["smooth"] = float(smooth.detach())
total = total + cfg.w_smooth * smooth
logs["total"] = float(total.detach())
return total, logs
def peak_loss(pred, Y, M, k: int = 0):
"""Curve-level term: match the per-sample peak of the stress curve.
Point-wise MSE shrinks towards the conditional mean, which systematically
under-estimates the yield peak (see report §6.1). This term only looks at
argmax_t sigma, i.e. one number per trajectory, so it carries little
over-fitting risk on 33 curves.
"""
import torch
m = M[..., k] > 0
if not bool(m.any()):
return pred.new_zeros(())
p = pred[..., k].masked_fill(~m, -1e9)
y = Y[..., k].masked_fill(~m, -1e9)
has = m.any(-1)
return torch.nn.functional.mse_loss(p.max(-1).values[has], y.max(-1).values[has])