自迴歸下文標記位移與因果交叉熵損失原理
智能體輔助探究
前置要求
完成第 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.