cbct / pre /code /losses.py
JulianHJR's picture
Add files using upload-large-folder tool
3799002 verified
Raw
History Blame Contribute Delete
6.16 kB
"""Stage-2 loss terms (upgraded).
sdf : clamped L1 distance regression (near-surface weighted)
eikonal : ||grad||=1 regularizer (valid distance field)
occ : Dice on soft occupancy = sigmoid(-sdf/tau)
normal : 1 - cos(pred_normal, gt_normal) near the surface (tooth AND canal)
nest : containment -- canal interior must lie inside the tooth.
Now two complementary terms:
(a) soft penalty: canal-inside points that fall outside the tooth
(b) hard SDF ordering: s_canal(x) >= s_tooth(x) + margin everywhere,
which geometrically guarantees the canal surface is interior.
prior : latent code L2 regularizer
"""
import torch
import torch.nn.functional as F
def sdf_l1(pred, gt, clamp_mm=2.0, near_w=4.0):
p = torch.clamp(pred, -clamp_mm, clamp_mm)
g = torch.clamp(gt, -clamp_mm, clamp_mm)
w = 1.0 + near_w * torch.exp(-(g ** 2) / (0.5 ** 2))
return (w * (p - g).abs()).mean()
def eikonal(grad):
n = grad.norm(dim=-1)
return ((n - 1.0) ** 2).mean()
def occupancy_dice(pred_sdf, gt_sdf, tau=0.3, eps=1e-5):
p = torch.sigmoid(-pred_sdf / tau)
g = (gt_sdf < 0).float()
inter = (p * g).sum()
return 1.0 - (2 * inter + eps) / (p.sum() + g.sum() + eps)
def normal_loss(pred_grad, gt_normal, gt_sdf, band_mm=0.5):
mask = (gt_sdf.abs() < band_mm).float()
if mask.sum() < 1:
return pred_grad.sum() * 0.0
pn = F.normalize(pred_grad, dim=-1)
cos = (pn * gt_normal).sum(-1)
return ((1.0 - cos) * mask).sum() / (mask.sum() + 1e-6)
def containment(sdf_tooth, sdf_canal, margin_mm=0.2):
"""Two-part containment.
(a) soft: points predicted inside the canal (s_canal<0) but outside the tooth
(s_tooth>-margin) are penalized by how far outside they are.
(b) hard ordering: everywhere, s_canal should be >= s_tooth + margin (the canal
is strictly inside, so its signed distance is 'more positive' / less negative
only near its own surface -- enforcing ordering keeps the canal interior).
Returns (loss_soft, loss_order)."""
inside_canal = torch.sigmoid(-sdf_canal / 0.1) # soft indicator, differentiable
viol = F.relu(sdf_tooth + margin_mm)
loss_soft = (inside_canal * viol).mean()
# ordering: penalize where s_tooth > s_canal - margin (canal not interior enough)
loss_order = F.relu(sdf_tooth - sdf_canal + margin_mm).mean()
return loss_soft, loss_order
def latent_prior(z):
return (z ** 2).mean()
def centerline_loss(pred_sdf_canal, on_center, margin_mm=0.3):
"""SOFT clDice-style continuity: encourage centerline points to be inside the
predicted canal, but with a HINGE that saturates -- it does not keep pushing the
SDF arbitrarily negative (which previously inflated phantom canal volume). We clamp
the violation so a single noisy centerline point can't blow up the canal."""
w = on_center
if w.sum() < 1:
return pred_sdf_canal.sum() * 0.0
# only ask the centerline to be *just* inside (sdf < 0), clamped to a small band
viol = torch.clamp(pred_sdf_canal + margin_mm, min=0.0, max=margin_mm * 2.0)
return (w * viol).sum() / (w.sum() + 1e-6)
def smoothness_loss(pred_sdf_canal, gt_sdf_canal, clamp_mm=2.0):
"""Volume-control / anti-phantom regularizer (robust replacement for the hard
centerline constraint that previously inflated canal volume). Penalizes predicted
canal INTERIOR (sdf<0) wherever the GROUND-TRUTH canal is clearly OUTSIDE
(gt_sdf > band): i.e. the model is hallucinating canal where there is none. This
directly fights the chamfer-exploding phantom blobs without touching real canal."""
band = 0.6
pred_inside = torch.sigmoid(-pred_sdf_canal / 0.1) # ~1 where predicted canal interior
gt_outside = torch.clamp(gt_sdf_canal - band, min=0.0) # >0 where GT clearly not canal
return (pred_inside * gt_outside).mean()
def stage2_total(pred_sdf, grads, batch, z, cfg):
"""Assemble the weighted total loss + a dict of components."""
w = cfg["stage2"]["loss_weights"]
s2 = cfg["stage2"]
cw = float(s2.get("canal_weight", 2.0)) # up-weight the (small) canal
st, sc = pred_sdf[..., 0], pred_sdf[..., 1]
gt_t, gt_c = batch["sdf_tooth"], batch["sdf_canal"]
l_sdf = sdf_l1(st, gt_t, s2["sdf_clamp_mm"]) + cw * sdf_l1(sc, gt_c, s2["sdf_clamp_mm"])
l_occ = occupancy_dice(st, gt_t, s2["occ_tau_mm"]) + \
cw * occupancy_dice(sc, gt_c, s2["occ_tau_mm"])
l_soft, l_order = containment(st, sc, s2["margin_mm"])
l_nest = l_soft + float(s2.get("order_weight", 1.0)) * l_order
l_prior = latent_prior(z)
if "on_center" in batch:
l_center = centerline_loss(sc, batch["on_center"], s2["margin_mm"])
else:
l_center = torch.zeros((), device=st.device)
l_smooth = smoothness_loss(sc, gt_c, s2["sdf_clamp_mm"])
if grads is not None:
l_eik = eikonal(grads["tooth"]) + eikonal(grads["canal"])
l_nrm = normal_loss(grads["tooth"], batch["nrm_tooth"], gt_t)
if "nrm_canal" in batch:
l_nrm = l_nrm + cw * normal_loss(grads["canal"], batch["nrm_canal"], gt_c)
else:
l_eik = torch.zeros((), device=st.device)
l_nrm = torch.zeros((), device=st.device)
total = (w["sdf"] * l_sdf + w["eikonal"] * l_eik + w["occ"] * l_occ +
w["normal"] * l_nrm + w["nest"] * l_nest + w["prior"] * l_prior +
w.get("centerline", 0.0) * l_center + w.get("smoothness", 0.0) * l_smooth)
comps = dict(sdf=float(l_sdf.detach()),
eik=float(l_eik.detach() if hasattr(l_eik, 'detach') else l_eik),
occ=float(l_occ.detach()),
nrm=float(l_nrm.detach() if hasattr(l_nrm, 'detach') else l_nrm),
nest=float(l_nest.detach()),
center=float(l_center.detach() if hasattr(l_center, 'detach') else l_center),
smooth=float(l_smooth.detach() if hasattr(l_smooth, 'detach') else l_smooth),
prior=float(l_prior.detach()),
total=float(total.detach()))
return total, comps