在 SQuAD 问答中,如何计算 start/end logits 损失并处理无答案样本?
解读
SQuAD 2.0 相比 1.1 引入了“不可回答”样本,要求模型在给出答案跨度的同时,还能输出“无答案”概率。面试官问“如何计算 start/end logits 损失并处理无答案样本”,核心想确认三件事:
- 你能否把分类任务拆成 start、end 两个多分类,并用交叉熵算损失;
- 你能否把“无答案”当成一个特殊类别(即 cls_index 或 0 位)与可回答位一起训练;
- 你能否在 PyTorch 里用 mask 与 ignore_index 干净地跳过 padding,并保证“无答案”标签与 logits 对齐。
回答时只要围绕“交叉熵 + 可回答掩码 + 无答案标签”展开,就能体现对任务本质与框架细节的掌握。
知识点
- SQuAD 2.0 标签格式:可回答样本给出 (start_position, end_position);不可回答样本 start=end=cls_index(通常为 0)。
- 模型输出:start_logits、end_logits,形状均为 [batch, seq_len],seq_len 含 [CLS] 与 [SEP]。
- 损失函数:两个独立的 CrossEntropyLoss,reduction='mean',对 padding 位用 attention_mask 置 -inf 或直接传 ignore_index=-100。
- 无答案处理:把 cls_index 当成合法标签,模型必须学会把最大概率压到 cls 位;推理时用“无答案”得分 vs 最佳跨度得分做阈值判断。
- PyTorch 实现要点:
- 用
logits.masked_fill((1 - attention_mask).bool(), -1e4)屏蔽 pad; - 对 start、end 分别
loss_fct(logits, label)再求平均; - 若需支持“软标签”或“起止互换”增强,可用 KL 散度,但工业界仍以硬标签交叉熵为主。
- 用
答案
import torch
import torch.nn as nn
class SquadLoss(nn.Module):
def __init__(self, ignore_index=-100):
super().__init__()
self.ce = nn.CrossEntropyLoss(ignore_index=ignore_index)
def forward(self, start_logits, end_logits,
start_positions, end_positions, attention_mask):
"""
start_logits/end_logits: [B, L]
start_positions/end_positions: [B] 不可回答样本为 cls_index
attention_mask: [B, L] 1 表示有效 token
"""
# 1. 屏蔽 pad 位,避免 pad 对梯度有贡献
start_logits = start_logits.masked_fill(~attention_mask.bool(), -1e4)
end_logits = end_logits.masked_fill(~attention_mask.bool(), -1e4)
# 2. 分别计算 start、end 的交叉熵
start_loss = self.ce(start_logits, start_positions)
end_loss = self.ce(end_logits, end_positions)
# 3. 平均后返回
return (start_loss + end_loss) / 2
训练时,对于不可回答样本,直接把 start_positions 和 end_positions 都设为 0(即 [CLS] 位),模型在损失驱动下会学会把最大概率压到 0 位;推理阶段取
no_answer_score = start_logits[:, 0] + end_logits[:, 0]
与最佳可回答跨度得分比较,若 no_answer_score > best_span_score + threshold,则返回“无答案”。这样既统一了损失计算,又兼顾了工业界常用的阈值策略。
拓展思考
- 如果业务数据里“无答案”比例极高,可以给 cls 位加 class weight 或采用 focal loss,缓解类别不平衡。
- 对于长文档分段后存在多个 span 的场景,可把“无答案”做成一个额外二分类头,与起止指针联合训练,损失改为
λ * cls_bce + (1-λ) * (start_ce + end_ce),调 λ 控制召回-精度平衡。 - 在 PyTorch 1.10+ 里可用
torch.compile把 masked_fill + CrossEntropy 融合,训练速度提升 5~8%;部署时通过 TorchScript 导出,同样保留 mask 逻辑,防止 ONNX 误折叠 softmax。