62 / 90

第 62 天:損失遮罩與訓練目標標籤構建

基於 ignore_index = -100 構建目標標籤,使因果交叉熵損失僅對助手應答計算梯度與反向傳播。

模型與訓練 480 分鐘有效研習(8 小時)
01 120 分鐘

自迴歸下文標記位移與因果交叉熵損失原理

智能體輔助探究

前置要求

完成第 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)進行了精確平均。

獨立掌握標準

透徹掌握自迴歸標記位移機制及 ignore_index=-100 損失歸約數學特性。

權威來源資源與權利證明

linking Apache-2.0

Hugging Face LLM Course: Fine-tuning LLMs

作者 / 機構: Hugging Face course contributors | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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. | 原始出處連結 ↗

對應章節 / 時間戳: 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。

自主實作與記錄

編寫函數 mask_prompt_labels(input_ids, assistant_header_ids),定位助手標記頭並將在此之前的所有標記嚴格賦值為 -100。

獨立掌握標準

構建 100% 準確將非助手響應標記置為 -100 的訓練標籤構造算法。

權威來源資源與權利證明

linking BSD-3-Clause

PyTorch Documentation: torch.nn.CrossEntropyLoss

作者 / 機構: PyTorch Core Development Team | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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. 理解相較於靜態定長填充,按 mini-batch 內最長序列進行動態填充可大幅節約計算顯存與 FLOPs。
2. 在 DataLoader 的整理函數(collate_fn)中,input_ids 填充 pad_token_id,labels 填充 -100。
3. 校驗位移與填充對齊:證明尾部填充標記在交叉熵損失計算中貢獻為零梯度。
4. 開展反向傳播驗證實驗:構建輕量 LM 頭部執行 forward 和 backward(),斷言被遮罩位置的梯度張量為純零。

自主實作與記錄

構造一個包含 2 條不同長度樣本的批次,執行前向傳播與反向傳播,斷言 labels 為 -100 位置的嵌入層梯度完全為零。

獨立掌握標準

在理論與代碼實驗兩個層面嚴密證實損失遮罩杜絕了提示詞與填充標記的梯度回傳。

權威來源資源與權利證明

linking Apache 2.0

TRL: DataCollatorForCompletionOnlyLM and SFTTrainer Documentation

作者 / 機構: Hugging Face TRL Maintainers | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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 數據整理器

獨立實戰考核(無 AI 輔助)

前置要求

第 62 天活動 1 至 3 的全部技能。

學習目標

獨立設計並全面測試生產級 SFTDataCollator,支持多輪對話、應答專屬損失遮罩、動態填充與零梯度洩漏驗證。

操作指引

1. 編寫 SFTDataCollator(response_ids, pad_token_id) 類。
2. 接入分詞後的變長多輪對話批次樣本。
3. 精準定位各樣本中的 response_ids,僅將助手應答輪次保留為目標標籤,將其餘部分與後續填充統統置為 -100。
4. 按批次最大長度右側填充,確保張量對齊。
5. 編寫單元測試斷言有效目標標記數精確等於助手應答標記總和。

自主實作與記錄

對包含 3 條不同輪次對話的測試批次運行整理器,斷言標籤遮罩完全無誤並執行微型模型推理驗證損失。

獨立掌握標準

獨立交付通過完整單元測試、具備應答專屬遮罩與動態填充能力的工業級微調整理器。

權威來源資源與權利證明

linking Apache 2.0

Stanford Alpaca: train.py Supervised Fine-Tuning Script

作者 / 機構: Stanford CRFM Team | 原始出處連結 ↗

對應章節 / 時間戳: 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 | 原始出處連結 ↗

對應章節 / 時間戳: 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.