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.