File size: 2,834 Bytes
bb5e4ec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | """Loss functions with explicit FP32 stability & Batch Feature-Consistency Regularizer."""
from __future__ import annotations
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
"""Multi-class Focal Loss (Lin et al., gamma=2.0) with optional class alpha weights."""
def __init__(self, gamma: float = 2.0, alpha: list[float] | None = None):
super().__init__()
self.gamma = gamma
if alpha is not None:
self.register_buffer("alpha", torch.tensor(alpha, dtype=torch.float32))
else:
self.alpha = None
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
logits_f = logits.float()
ce = F.cross_entropy(logits_f, targets, reduction="none")
pt = torch.exp(-ce)
focal = ((1.0 - pt) ** self.gamma) * ce
if self.alpha is not None:
focal = self.alpha.to(logits_f.device)[targets] * focal
return focal.mean()
def compute_batch_consistency_loss(features: torch.Tensor) -> torch.Tensor:
"""Batch Feature-Consistency Regularizer (formerly misnamed `bio_pinn` in early drafts).
Measures mean L2 feature difference across adjacent shuffled batch entries (`features.roll(1)`).
Disclosed transparently as an auxiliary batch regularizer (set `lambda_phys=0.0` in all
working Aug-12 models because larger values caused representation collapse).
"""
feat_f = features.float()
return torch.mean(torch.norm(feat_f.roll(1, dims=0) - feat_f, dim=-1))
def compute_loss_with_consistency(
logits: torch.Tensor,
features: torch.Tensor,
targets: torch.Tensor,
loss_type: str = "ce",
class_weights: torch.Tensor | None = None,
focal_fn: FocalLoss | None = None,
lambda_phys: float = 0.0,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Compute primary classification loss + `lambda_phys * consistency_loss` strictly in FP32."""
with torch.autocast(device_type=logits.device.type, enabled=False):
logits_f = logits.float()
if loss_type == "ce":
cls_loss = F.cross_entropy(logits_f, targets)
elif loss_type == "weighted_ce":
assert class_weights is not None, "weighted_ce requires class_weights tensor"
cls_loss = F.cross_entropy(logits_f, targets, weight=class_weights.float().to(logits_f.device))
elif loss_type == "focal":
assert focal_fn is not None, "focal requires FocalLoss module"
cls_loss = focal_fn(logits_f, targets)
else:
raise ValueError(f"Unsupported loss_type: {loss_type}")
phys_loss = compute_batch_consistency_loss(features)
total = cls_loss + lambda_phys * phys_loss if lambda_phys > 0.0 else cls_loss
return total, cls_loss, phys_loss
|