自回归下文标记位移与因果交叉熵损失原理
智能体辅助探究
前置要求
完成第 61 天并掌握多分类交叉熵损失的数学原理。
学习目标
深入理解因果语言模型对数几率(logits)与标签(labels)的位移对齐机制,掌握 PyTorch 中 CrossEntropyLoss(ignore_index=-100) 的归约计算法则。
操作指引
学习来源:在本活动现有的阅读与练习时段内,参考 Hugging Face LLM Course: Fine-tuning LLMs 的 Chapter 11.3: Dataset Preparation; Implementation with TRL,用自己的话解释一处与本地任务的联系。保留现有练习与验收检查;若外部资料无法访问,使用课程自写的解释。1. 追踪自回归标记预测对齐:输入序列 x_0, x_1, ..., x_{T-1} 中,位置 t 输出的 logits 负责预测目标 x_{t+1}。
2. 推导张量切片对齐规则:shift_logits = logits[..., :-1, :].contiguous(),shift_labels = labels[..., 1:].contiguous()。
3. 分析带 ignore_index=-100 的交叉熵归约:标签为 -100 的标记不仅在分子(负对数似然)中被忽略,且完全不计入分母的平均有效标记数。
4. 在小维度合成张量上手工推导负对数似然,验证与 PyTorch 算子输出的数值绝对一致。
自主演练与记录
给定形状为 (1, 4, 3) 的预测对数几率与标签 [-100, 1, 2, -100],调用 CrossEntropyLoss(ignore_index=-100) 计算损失,并通过手工公式证明仅对未掩码标记(位置 1 和 2)进行了精确平均。
损失理论值恰为 -(log_softmax(logits[0, 1])[1] + log_softmax(logits[0, 2])[2]) / 2。
import torch
import torch.nn as nn
import torch.nn.functional as F
logits = torch.randn(1, 4, 3, requires_grad=True)
labels = torch.tensor([[ -100, 1, 2, -100 ]])
criterion = nn.CrossEntropyLoss(ignore_index=-100)
loss = criterion(logits.view(-1, 3), labels.view(-1))
lsm = F.log_softmax(logits[0], dim=-1)
expected = -(lsm[1, 1] + lsm[2, 2]) / 2.0
assert torch.allclose(loss, expected)
透彻掌握自回归标记位移机制及 ignore_index=-100 损失归约数学特性。
权威源资源与权利证明
Hugging Face LLM Course: Fine-tuning LLMs
对应章节 / 时间戳: Chapter 11.3: Dataset Preparation; Implementation with TRL
验证版本与日期: Public edition checked 2026-11-01; moving pages may change
Sequenced templates, supervised fine-tuning and evaluation teaching with exercises/quizzes. LoRA method and memory claims are checked against the original paper, PEFT and the local parameter ledger, not accepted wholesale from Chapter 11.4.
Python, PyTorch, language-model training and the preceding chat-format lessons.
Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.
对比候选资源与选型分析 (2)
Retained for initialization and the low-rank method, not a beginner teaching sequence.
Retained for actual API and implementation defaults; reference documentation is not a complete teaching course.
PyTorch Documentation: torch.nn.CrossEntropyLoss
对应章节 / 时间戳: CrossEntropyLoss parameters ignore_index (default -100) and reduction
验证版本与日期: PyTorch 2.x Documentation (Verified: 2026-10-30)
Primary specification for ignore_index=-100 behavior, weight averaging over unmasked tokens, and loss reduction arithmetic.
Softmax probabilities, negative log likelihood, multi-class classification.
Mathematical formulation of masked cross-entropy and equivalent tensor implementations are provided in lesson code.
对比候选资源与选型分析 (2)
Keras cross-entropy loss with sample_weight masking; PyTorch ignore_index is the standard in transformer fine-tuning.
Functional cross-entropy with manual boolean masking; PyTorch ignore_index=-100 is our target implementation.
Training language models to follow instructions with human feedback
对应章节 / 时间戳: Section 3.5 Models (supervised fine-tuning, SFT)
验证版本与日期: arXiv:2203.02155v1 (Verified: 2026-10-30)
Foundational InstructGPT paper defining the SFT objective: maximizing log-likelihood of demonstrator completions conditioned on prompts.
Supervised fine-tuning, conditional autoregressive generation.
The conditional likelihood objective and prompt-conditioning derivations are completely formulated in the review.
对比候选资源与选型分析 (2)
Earlier RLHF formulation on summarization; InstructGPT standardizes the prompt-response SFT training phase.
Focuses on massive multi-task scaling; InstructGPT details the exact prompt-conditioned loss setup.