"""Independent PyTorch 2.10 CPU observations for classification, regression, metric, CTC and custom losses."""
import json
import platform
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
def focal_loss(logits: torch.Tensor, targets: torch.Tensor, gamma: float = 2.0, alpha: float = 0.25) -> torch.Tensor:
ce = F.cross_entropy(logits, targets, reduction="none")
pt = torch.exp(-ce)
return (alpha * (1.0 - pt) ** gamma * ce).mean()
class MultiClassDiceLoss(nn.Module):
"""Multi-class Dice loss taking raw logits (N,C,H,W) and integer masks (N,H,W)."""
def __init__(self, smooth: float = 1.0):
super().__init__()
self.smooth = smooth
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
probs = torch.softmax(logits, dim=1)
num_classes = logits.size(1)
one_hot = F.one_hot(targets, num_classes=num_classes).permute(0, 3, 1, 2).float()
dims = (0, 2, 3)
inter = (probs * one_hot).sum(dim=dims)
denom = probs.sum(dim=dims) + one_hot.sum(dim=dims)
dice = (2.0 * inter + self.smooth) / (denom + self.smooth)
return 1.0 - dice.mean()
class CombinedSegLoss(nn.Module):
def __init__(self, ce_weight: float = 0.4, dice_weight: float = 0.6):
super().__init__()
self.ce_weight = ce_weight
self.dice_weight = dice_weight
self.ce = nn.CrossEntropyLoss()
self.dice = MultiClassDiceLoss()
def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
return self.ce_weight * self.ce(logits, targets) + self.dice_weight * self.dice(logits, targets)
def run_cases():
torch.manual_seed(2026)
cases = []
# 1. Classification losses: CrossEntropyLoss, NLLLoss equivalence, label_smoothing, soft targets, double-softmax trap
logits = torch.tensor([[2.0, 0.5, 0.3], [0.1, 3.0, 0.2], [0.2, 0.1, 4.0]])
targets = torch.tensor([0, 1, 2])
ce = nn.CrossEntropyLoss()(logits, targets)
nll = nn.NLLLoss()(torch.log_softmax(logits, dim=1), targets)
ce_vs_nll_diff = float((ce - nll).abs().item())
# Double softmax inflates loss artificially
ce_double_sm = nn.CrossEntropyLoss()(torch.softmax(logits, dim=1), targets)
ce_smooth = nn.CrossEntropyLoss(label_smoothing=0.1)(logits, targets)
soft_t = torch.tensor([[0.9, 0.05, 0.05], [0.05, 0.9, 0.05]])
ce_soft = nn.CrossEntropyLoss()(logits[:2], soft_t)
c1_ok = ce_vs_nll_diff < 1e-6 and float(ce_double_sm.item()) > float(ce.item()) * 2.0 and float(ce_smooth.item()) > float(ce.item()) and float(ce_soft.item()) > 0.0
cases.append(dict(
name="classification_ce_and_nll",
inputs=dict(batch=3, classes=3, label_smoothing=0.1),
prerequisites="PyTorch 2.10 CPU",
action="验证 CrossEntropyLoss 与 LogSoftmax+NLLLoss 精确等价、重复 Softmax 会扭曲损失,以及标签平滑和软标签输入。",
expected=dict(ce_eq_nll=True, double_softmax_inflates=True, smooth_gt_hard=True, soft_targets_ok=True),
actual=dict(ce_eq_nll=ce_vs_nll_diff < 1e-6, double_softmax_inflates=float(ce_double_sm.item()) > float(ce.item()) * 2.0, smooth_gt_hard=float(ce_smooth.item()) > float(ce.item()), soft_targets_ok=float(ce_soft.item()) > 0.0),
measurements=dict(ce=round(float(ce.item()), 4), ce_double_softmax=round(float(ce_double_sm.item()), 4), ce_smooth=round(float(ce_smooth.item()), 4)),
passed=c1_ok,
))
# 2. BCELoss vs BCEWithLogitsLoss, pos_weight, and int-target TypeError/RuntimeError check
raw_b = torch.tensor([2.0, -1.0, 0.5, -3.0])
y_b = torch.tensor([1.0, 0.0, 1.0, 0.0])
bce_prob = nn.BCELoss()(torch.sigmoid(raw_b), y_b)
bce_logits = nn.BCEWithLogitsLoss()(raw_b, y_b)
bce_diff = float((bce_prob - bce_logits).abs().item())
bce_pw = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([10.0]))(raw_b, y_b)
int_target_failed = False
try:
nn.BCEWithLogitsLoss()(raw_b, torch.tensor([1, 0, 1, 0]))
except RuntimeError:
int_target_failed = True
c2_ok = bce_diff < 1e-6 and float(bce_pw.item()) > float(bce_logits.item()) and int_target_failed
cases.append(dict(
name="binary_bce_and_logits",
inputs=dict(raw=[2.0, -1.0, 0.5, -3.0], pos_weight=10.0),
prerequisites="对比 BCELoss(sigmoid(x)) 与 BCEWithLogitsLoss(x)",
action="验证两者数值等价、pos_weight 提升正例惩罚权重,以及整型标签传入 BCEWithLogitsLoss 抛出 RuntimeError。",
expected=dict(bce_matches_logits=True, pos_weight_increases_loss=True, int_target_rejected=True),
actual=dict(bce_matches_logits=bce_diff < 1e-6, pos_weight_increases_loss=float(bce_pw.item()) > float(bce_logits.item()), int_target_rejected=int_target_failed),
measurements=dict(bce=round(float(bce_logits.item()), 4), bce_pos_weight10=round(float(bce_pw.item()), 4)),
passed=c2_ok,
))
# 3. Regression losses: MSE, L1, SmoothL1, HuberLoss outlier sensitivity
errs = torch.tensor([0.0, 1.0, 5.0, 10.0])
zeros = torch.zeros(4)
mse_v = [round(v, 2) for v in nn.MSELoss(reduction="none")(errs, zeros).tolist()]
l1_v = [round(v, 2) for v in nn.L1Loss(reduction="none")(errs, zeros).tolist()]
sl1_v = [round(v, 2) for v in nn.SmoothL1Loss(reduction="none")(errs, zeros).tolist()]
huber_v = [round(v, 2) for v in nn.HuberLoss(delta=1.5, reduction="none")(errs, zeros).tolist()]
c3_ok = mse_v == [0.0, 1.0, 25.0, 100.0] and l1_v == [0.0, 1.0, 5.0, 10.0] and sl1_v == [0.0, 0.5, 4.5, 9.5] and huber_v[3] < mse_v[3]
cases.append(dict(
name="regression_mse_l1_huber",
inputs=dict(errors=[0.0, 1.0, 5.0, 10.0], huber_delta=1.5),
prerequisites="reduction='none' 观察不同误差尺度下的逐样本损失",
action="核对 MSE 平方放大离群点(100.0)、L1 线性增长(10.0)、SmoothL1(9.5)及 HuberLoss(delta=1.5)。",
expected=dict(mse=[0.0, 1.0, 25.0, 100.0], l1=[0.0, 1.0, 5.0, 10.0], smooth_l1=[0.0, 0.5, 4.5, 9.5], huber_lt_mse=True),
actual=dict(mse=mse_v, l1=l1_v, smooth_l1=sl1_v, huber_lt_mse=huber_v[3] < mse_v[3]),
measurements=dict(huber_delta15=huber_v),
passed=c3_ok,
))
# 4. Advanced losses: KLDivLoss (distillation), MarginRankingLoss, TripletMarginLoss, CTCLoss
t_logits = torch.randn(8, 5)
s_logits = torch.randn(8, 5)
temp = 4.0
kl_distill = nn.KLDivLoss(reduction="batchmean")(torch.log_softmax(s_logits / temp, dim=1), torch.softmax(t_logits / temp, dim=1)) * (temp ** 2)
kl_same = nn.KLDivLoss(reduction="batchmean")(torch.log_softmax(t_logits, dim=1), torch.softmax(t_logits, dim=1))
mrl = nn.MarginRankingLoss(margin=0.5)(torch.tensor([0.8, 0.3, 0.6]), torch.tensor([0.2, 0.7, 0.5]), torch.tensor([1.0, -1.0, 1.0]))
a_emb = torch.zeros(4, 16)
p_emb = torch.full((4, 16), 0.1)
n_emb = torch.full((4, 16), 2.0)
triplet_good = nn.TripletMarginLoss(margin=1.0)(a_emb, p_emb, n_emb)
triplet_bad = nn.TripletMarginLoss(margin=1.0)(a_emb, n_emb, p_emb)
ctc_lp = torch.log_softmax(torch.randn(30, 2, 10), dim=2)
ctc_t = torch.randint(1, 10, (12,))
ctc_loss = nn.CTCLoss(blank=0)(ctc_lp, ctc_t, torch.tensor([30, 30]), torch.tensor([6, 6]))
c4_ok = float(kl_same.item()) < 1e-6 and float(kl_distill.item()) > 0.0 and abs(float(mrl.item()) - (0.5 / 3.0)) < 1e-4 and float(triplet_good.item()) == 0.0 and float(triplet_bad.item()) > 1.0 and float(ctc_loss.item()) > 0.0
cases.append(dict(
name="advanced_kl_ranking_triplet_ctc",
inputs=dict(temp=4.0, margin_rank=0.5, triplet_margin=1.0, ctc_T=30),
prerequisites="KLDivLoss(batchmean)、MarginRankingLoss、TripletMarginLoss 与 CTCLoss",
action="验证同分布 KL 散度为 0、蒸馏 KL>0、排序损失、正负三元组距离对比及 CTC 对齐损失。",
expected=dict(kl_self_zero=True, kl_distill_pos=True, triplet_good_zero=True, triplet_bad_gt_1=True, ctc_pos=True),
actual=dict(kl_self_zero=float(kl_same.item()) < 1e-6, kl_distill_pos=float(kl_distill.item()) > 0.0, triplet_good_zero=float(triplet_good.item()) == 0.0, triplet_bad_gt_1=float(triplet_bad.item()) > 1.0, ctc_pos=float(ctc_loss.item()) > 0.0),
measurements=dict(kl_distill=round(float(kl_distill.item()), 4), margin_ranking=round(float(mrl.item()), 4), ctc_loss=round(float(ctc_loss.item()), 4)),
passed=c4_ok,
))
# 5. reduction='mean'/'sum'/'none', class weights, and ignore_index=255
pr = torch.tensor([1.0, 2.0, 3.0, 4.0])
tr = torch.tensor([1.5, 2.5, 2.0, 5.0])
r_mean = round(float(nn.MSELoss(reduction="mean")(pr, tr).item()), 4)
r_sum = round(float(nn.MSELoss(reduction="sum")(pr, tr).item()), 4)
r_none = nn.MSELoss(reduction="none")(pr, tr).tolist()
weighted = round(float((nn.MSELoss(reduction="none")(pr, tr) * torch.tensor([1.0, 1.0, 2.0, 2.0])).mean().item()), 4)
seg_pred = torch.randn(2, 4, 8, 8)
seg_tgt = torch.randint(0, 4, (2, 8, 8))
seg_tgt[:, 0, :] = 255
ign_loss = nn.CrossEntropyLoss(ignore_index=255)(seg_pred, seg_tgt)
cls_w = torch.tensor([0.1, 1.0, 2.0])
w_ce = nn.CrossEntropyLoss(weight=cls_w)(logits, targets)
c5_ok = bool(r_mean == 0.625 and r_sum == 2.5 and r_none == [0.25, 0.25, 1.0, 1.0] and weighted == 1.125 and torch.isfinite(ign_loss).item() and torch.isfinite(w_ce).item())
cases.append(dict(
name="reduction_weights_and_ignore_index",
inputs=dict(ignore_index=255, sample_weights=[1.0, 1.0, 2.0, 2.0]),
prerequisites="核对 mean/sum/none 汇总方式、逆频类别权重与分割边界忽略索引",
action="验证 mean=0.625、sum=2.5、加权=1.125,以及含 255 标签像素图正常计算有限损失。",
expected=dict(mean=0.625, sum=2.5, weighted=1.125, ignore255_finite=True),
actual=dict(mean=r_mean, sum=r_sum, weighted=weighted, ignore255_finite=bool(torch.isfinite(ign_loss).item())),
passed=c5_ok,
))
# 6. Custom Focal Loss & fixed CombinedSegLoss (CE + MultiClassDiceLoss) with backward pass
seg_logits = torch.randn(2, 4, 8, 8, requires_grad=True)
seg_mask = torch.randint(0, 4, (2, 8, 8))
comb = CombinedSegLoss(ce_weight=0.4, dice_weight=0.6)
comb_val = comb(seg_logits, seg_mask)
comb_val.backward()
grad_finite = bool(torch.isfinite(seg_logits.grad).all().item()) and float(seg_logits.grad.norm().item()) > 0.0
# Focal loss down-weights easy high-confidence samples relative to cross-entropy
fl_val = focal_loss(logits, targets, gamma=2.0, alpha=0.25)
c6_ok = grad_finite and float(comb_val.item()) > 0.0 and float(fl_val.item()) < float(ce.item())
cases.append(dict(
name="custom_focal_and_combined_dice",
inputs=dict(seg_shape=[2, 4, 8, 8], ce_weight=0.4, dice_weight=0.6),
prerequisites="修正多分类 Dice 需将整型掩码 (N,H,W) 转为 one-hot 并使用 softmax 概率",
action="验证 Focal Loss 压低易分样本损失,以及修正后的 CombinedSegLoss 正常反传非零有限梯度。",
expected=dict(focal_lt_ce=True, combined_grad_finite=True),
actual=dict(focal_lt_ce=float(fl_val.item()) < float(ce.item()), combined_grad_finite=grad_finite),
measurements=dict(focal_loss=round(float(fl_val.item()), 5), combined_loss=round(float(comb_val.item()), 4)),
passed=c6_ok,
))
print(json.dumps(dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-loss-function-lab/explore-loss-functions.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-loss-functions.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a427.zip