62 / 90

第62日: 損失マスクと学習ターゲットラベルの構築

ignore_index = -100によるプロンプト損失マスクを実装し、交差エントロピー損失をアシスタント応答のみに限定する。

モデルと学習 480 分(8時間)
01 120 分

自己回帰ネクストトークンシフトと因果的交差エントロピー損失

エージェント支援による探究

前提条件

第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)のみが平均されていることを数式で検証せよ。

独立習得基準

自己回帰ラベルシフトと ignore_index=-100 による損失正規化の数学的挙動を完全に説明・検証できること。

公式ソースリソースと権利証跡

linking Apache-2.0

Hugging Face LLM Course: Fine-tuning LLMs

著者・提供機関: Hugging Face course contributors | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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)
LoRA original paper ↗ compared_alternative [arXiv.org perpetual non-exclusive license / Open Access]

Retained for initialization and the low-rank method, not a beginner teaching sequence.

Hugging Face PEFT ↗ compared_alternative [Apache-2.0]

Retained for actual API and implementation defaults; reference documentation is not a complete teaching course.

linking BSD-3-Clause

PyTorch Documentation: torch.nn.CrossEntropyLoss

著者・提供機関: PyTorch Core Development Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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.

linking Open Access

Training language models to follow instructions with human feedback

著者・提供機関: Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, et al. | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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.

02 120 分

ターゲットラベルの構築と ignore_index = -100 によるプロンプト損失マスク

独立演習

前提条件

第62日アクティビティ1およびChatML対話トークン列の構造。

学習目標

プロンプトやシステム指示を -100 でマスクしたラベルテンソルを構築し、学習勾配がアシスタント応答のみに作用するよう制御する。

手順

1. 全トークンで損失を計算する事前学習と、P(response | prompt) を最大化する指示微調(SFT)の違いを対比する。
2. プロンプトトークンで損失を計算する危険性を理解する: モデルが質問の丸暗記にパラメータを浪費し、回答ではなくユーザー発言を復唱する退行を引き起こす。
3. ラベルテンソルの構築手順: input_ids を複製し、アシスタント応答開始ヘッダ(例: '<|im_start|>assistant\n')を検出し、それ以前の位置にすべて -100 を代入する。
4. マルチターン対話への拡張: アシスタントの全ターンを検出し、ユーザーおよびシステムの発話位置をすべて -100 にマスクする。

演習と予測記録

アシスタントヘッダの位置を特定し、それ以前のすべてのトークン位置を -100 に設定する関数 mask_prompt_labels(input_ids, assistant_header_ids) を作成せよ。

独立習得基準

アシスタント応答以外のすべてのトークンを 100% 確実に -100 でマスクするラベル生成ロジックを実装できること。

公式ソースリソースと権利証跡

linking BSD-3-Clause

PyTorch Documentation: torch.nn.CrossEntropyLoss

著者・提供機関: PyTorch Core Development Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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.

linking Apache 2.0

Stanford Alpaca: train.py Supervised Fine-Tuning Script

著者・提供機関: Stanford CRFM Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: train.py: PROMPT_DICT, IGNORE_INDEX = -100, preprocess() masks the source tokens, DataCollatorForSupervisedDataset pads labels with IGNORE_INDEX

検証バージョンと日付: Stanford Alpaca train.py (Verified: 2026-10-30)

選定理由:

Standard open-source implementation showing labels = copy.deepcopy(input_ids) and targets[:prompt_len] = -100 masking.

ソース前提知識:

PyTorch Dataset, DataLoader, token masking with -100.

安全フォールバック(オフライン回復性):

The entire masking tensor construction and prompt boundary finding logic is self-contained in our exercises.

比較対象候補リソースと選定評価 (2)
Hugging Face transformers run_clm.py ↗ compared_alternative [Apache 2.0]

Computes loss on all tokens (pre-training style); Alpaca train.py demonstrates target-only instruction masking.

DeepSpeed-Chat training pipeline ↗ compared_alternative [Apache 2.0]

Complex distributed training pipeline; Alpaca train.py gives the minimal, readable reference implementation.

03 120 分

動的バッチパディング、照合マスクと勾配検証

エージェント支援による実践

前提条件

第62日アクティビティ1・2およびPyTorch DataLoader collate_fn。

学習目標

動的バッチパディングとターゲットマスクを実装し、逆伝播時にプロンプトトークンの埋め込み勾配が完全にゼロであることを実証する。

手順

1. 固定長パディングと比較して、ミニバッチ内の最長系列に合わせた動的パディングが計算効率上有利である理由を理解する。
2. DataLoader の collate_fn において、input_ids には pad_token_id を、labels には -100 を埋め込む。
3. シフトとパディングのアライメント: 系列末尾のパディングトークンが交差エントロピー勾配に一切寄与しないことを確認する。
4. 勾配検証実験: 小規模なLMヘッドを通して順伝播および backward() を実行し、マスクされた位置の勾配テンソルが厳密にゼロであることを確認する。

演習と予測記録

長さの異なる2つの系列からなるバッチを作成し、順伝播と逆伝播を実行して、-100 でマスクされた位置のトークン埋め込み勾配がゼロであることをアサートせよ。

独立習得基準

マスクされたトークンがモデルパラメータの勾配更新に一切寄与しないことを実験的に証明できること。

公式ソースリソースと権利証跡

linking Apache 2.0

TRL: DataCollatorForCompletionOnlyLM and SFTTrainer Documentation

著者・提供機関: Hugging Face TRL Maintainers | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Looking deeper into the SFT method: Label shifting and masking; Train on completion only

検証バージョンと日付: Hugging Face TRL 0.8+ Documentation (Verified: 2026-10-30)

選定理由:

Standard production library for completion-only loss masking, detailing response_template token matching and dynamic batch padding.

ソース前提知識:

PyTorch collate_fn, Hugging Face Trainer.

安全フォールバック(オフライン回復性):

Custom pure PyTorch implementation of response-template masking and dynamic padding is built step-by-step.

比較対象候補リソースと選定評価 (2)
Unsloth FastLanguageModel SFT Data Prep ↗ compared_alternative [Apache 2.0]

Optimized CUDA-kernel collators; TRL provides transparent pure-Python/PyTorch baseline.

NVIDIA NeMo Megatron Bridge SFT Collator ↗ compared_alternative [Apache 2.0]

Enterprise Megatron-based collator; TRL is standard for community PyTorch/HF pipelines.

linking BSD-3-Clause

PyTorch Documentation: torch.nn.CrossEntropyLoss

著者・提供機関: PyTorch Core Development Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: 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.

04 120 分

独立習得評価: 正確なマスク検証を備えた本番用SFTデータ照合器

独立評価(支援なし)

前提条件

第62日アクティビティ1〜3の全内容。

学習目標

マルチターン対話、応答のみの損失マスク、動的パディング、勾配漏洩ゼロ保証を備えた本番品質のSFTDataCollatorを独自に構築・検証する。

手順

1. SFTDataCollator(response_ids, pad_token_id) を実装する。
2. トークン化された可変長対話バッチを受け入れる。
3. 各サンプルにおいて response_ids の位置を特定し、それ以降のアシスタント発話のみをターゲットとして残し、その他すべてを -100 にマスクする。
4. バッチ最長に合わせて右パディングを行い、labels のパディング位置を -100 に設定する。
5. 単体テストを作成し、全プロンプトおよびパディングが -100 であり、アシスタント応答のみが有効なターゲットであることをアサートする。

演習と予測記録

長さの異なる3つの対話サンプルを含むテストバッチに対して照合器を実行し、損失マスクとテンソル形状の完全性を検証せよ。

独立習得基準

マルチターンの応答のみ損失マスクと動的パディングを兼ね備えたSFTデータ照合器を自力で完成させること。

公式ソースリソースと権利証跡

linking Apache 2.0

Stanford Alpaca: train.py Supervised Fine-Tuning Script

著者・提供機関: Stanford CRFM Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: train.py: PROMPT_DICT, IGNORE_INDEX = -100, preprocess() masks the source tokens, DataCollatorForSupervisedDataset pads labels with IGNORE_INDEX

検証バージョンと日付: Stanford Alpaca train.py (Verified: 2026-10-30)

選定理由:

Standard open-source implementation showing labels = copy.deepcopy(input_ids) and targets[:prompt_len] = -100 masking.

ソース前提知識:

PyTorch Dataset, DataLoader, token masking with -100.

安全フォールバック(オフライン回復性):

The entire masking tensor construction and prompt boundary finding logic is self-contained in our exercises.

比較対象候補リソースと選定評価 (2)
Hugging Face transformers run_clm.py ↗ compared_alternative [Apache 2.0]

Computes loss on all tokens (pre-training style); Alpaca train.py demonstrates target-only instruction masking.

DeepSpeed-Chat training pipeline ↗ compared_alternative [Apache 2.0]

Complex distributed training pipeline; Alpaca train.py gives the minimal, readable reference implementation.

linking Apache 2.0

TRL: DataCollatorForCompletionOnlyLM and SFTTrainer Documentation

著者・提供機関: Hugging Face TRL Maintainers | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Looking deeper into the SFT method: Label shifting and masking; Train on completion only

検証バージョンと日付: Hugging Face TRL 0.8+ Documentation (Verified: 2026-10-30)

選定理由:

Standard production library for completion-only loss masking, detailing response_template token matching and dynamic batch padding.

ソース前提知識:

PyTorch collate_fn, Hugging Face Trainer.

安全フォールバック(オフライン回復性):

Custom pure PyTorch implementation of response-template masking and dynamic padding is built step-by-step.

比較対象候補リソースと選定評価 (2)
Unsloth FastLanguageModel SFT Data Prep ↗ compared_alternative [Apache 2.0]

Optimized CUDA-kernel collators; TRL provides transparent pure-Python/PyTorch baseline.

NVIDIA NeMo Megatron Bridge SFT Collator ↗ compared_alternative [Apache 2.0]

Enterprise Megatron-based collator; TRL is standard for community PyTorch/HF pipelines.