自己回帰ネクストトークンシフトと因果的交差エントロピー損失
エージェント支援による探究
前提条件
第61日の修了および多クラス交差エントロピーの数学的基礎。
学習目標
因果的言語モデルがロジットとラベルをシフトさせる仕組みを理解し、PyTorchのtorch.nn.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 のロジットは x_{t+1} を予測する。
2. シフトインデックスを導出する: shift_logits = logits[..., :-1, :].contiguous()、shift_labels = labels[..., 1:].contiguous()。
3. ignore_index=-100 を伴う交差エントロピーの縮小計算を検証する: shift_labels == -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.