62 / 90

Day 62: Loss Masking & Target Label Construction

Construct target labels with ignore_index = -100 to restrict cross-entropy loss exclusively to assistant responses.

Models and Training 480 active minutes (8 hours)
01 120 min

Autoregressive Next-Token Shifting and Causal Cross-Entropy Loss

Agent-Assisted Exploration

Prerequisites

Completion of Day 61 and familiarity with multi-class cross-entropy mathematics.

Learning Objective

Understand how causal language models shift logits and labels, and master PyTorch's torch.nn.CrossEntropyLoss(ignore_index=-100) arithmetic.

Instructions

Study source: within this activity's existing reading/practice time, use Hugging Face LLM Course: Fine-tuning LLMs, Chapter 11.3: Dataset Preparation; Implementation with TRL, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. 1. Trace next-token prediction alignment: for input sequence x_0, x_1, ..., x_{T-1}, model logits at step t predict label x_{t+1}.
2. Derive the index shift: shift_logits = logits[..., :-1, :].contiguous() and shift_labels = labels[..., 1:].contiguous().
3. Study CrossEntropyLoss reduction with ignore_index=-100: positions where shift_labels == -100 are ignored in negative log-likelihood calculation and excluded from the loss denominator.
4. Calculate loss reduction manually on small synthetic tensors to verify exact mathematical equivalence with PyTorch output.

Practice & Prediction Log

Given logits of shape (1, 4, 3) and labels [-100, 1, 2, -100], compute cross-entropy loss using torch.nn.CrossEntropyLoss(ignore_index=-100). Verify by manual formula that unmasked tokens (indices 1 and 2) are correctly averaged.

Independent Mastery Criterion

Demonstrate complete comprehension of autoregressive label shifting and ignore_index=-100 loss normalization.

Authoritative Source Resources & Provenance

linking Apache-2.0

Hugging Face LLM Course: Fine-tuning LLMs

Author: Hugging Face course contributors | Original Source Link ↗

Relevant Section / Range: Chapter 11.3: Dataset Preparation; Implementation with TRL

Verified Version & Date: Public edition checked 2026-11-01; moving pages may change

Selection Rationale:

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.

Source Prerequisites:

Python, PyTorch, language-model training and the preceding chat-format lessons.

Safe Fallback (Offline Resilience):

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

Compared Candidate Sources & Selection Analysis (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

Author: PyTorch Core Development Team | Original Source Link ↗

Relevant Section / Range: CrossEntropyLoss parameters ignore_index (default -100) and reduction

Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)

Selection Rationale:

Primary specification for ignore_index=-100 behavior, weight averaging over unmasked tokens, and loss reduction arithmetic.

Source Prerequisites:

Softmax probabilities, negative log likelihood, multi-class classification.

Safe Fallback (Offline Resilience):

Mathematical formulation of masked cross-entropy and equivalent tensor implementations are provided in lesson code.

Compared Candidate Sources & Selection Analysis (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

Author: Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, et al. | Original Source Link ↗

Relevant Section / Range: Section 3.5 Models (supervised fine-tuning, SFT)

Verified Version & Date: arXiv:2203.02155v1 (Verified: 2026-10-30)

Selection Rationale:

Foundational InstructGPT paper defining the SFT objective: maximizing log-likelihood of demonstrator completions conditioned on prompts.

Source Prerequisites:

Supervised fine-tuning, conditional autoregressive generation.

Safe Fallback (Offline Resilience):

The conditional likelihood objective and prompt-conditioning derivations are completely formulated in the review.

Compared Candidate Sources & Selection Analysis (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 min

Target Label Construction and Prompt Loss Masking with ignore_index = -100

Independent Exploration

Prerequisites

Day 62 Activity 1 and ChatML conversation token sequences.

Learning Objective

Construct label tensors that mask prompt and system tokens with -100, ensuring training gradient capacity focuses purely on assistant completions.

Instructions

1. Contrast pre-training loss (loss on all tokens) with Supervised Fine-Tuning (SFT) conditional likelihood: P(response | prompt).
2. Understand the hazard of computing loss on user prompt tokens: the model wastes parameters memorizing user questions and generates user turns instead of answers.
3. Formulate label tensor creation: clone input_ids, locate the start of assistant response (e.g., token sequence for '<|im_start|>assistant\n'), and assign -100 to all preceding positions.
4. Handle multi-turn dialogues: locate every assistant turn boundary, keeping only assistant tokens unmasked while masking all user and system turns.

Practice & Prediction Log

Write a function mask_prompt_labels(input_ids, assistant_header_ids) that locates the assistant header token sequence (a list of token ids) and sets the labels of the header and every token before it to -100.

Independent Mastery Criterion

Construct verified target label tensors that mask 100% of non-assistant tokens with -100.

Authoritative Source Resources & Provenance

linking BSD-3-Clause

PyTorch Documentation: torch.nn.CrossEntropyLoss

Author: PyTorch Core Development Team | Original Source Link ↗

Relevant Section / Range: CrossEntropyLoss parameters ignore_index (default -100) and reduction

Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)

Selection Rationale:

Primary specification for ignore_index=-100 behavior, weight averaging over unmasked tokens, and loss reduction arithmetic.

Source Prerequisites:

Softmax probabilities, negative log likelihood, multi-class classification.

Safe Fallback (Offline Resilience):

Mathematical formulation of masked cross-entropy and equivalent tensor implementations are provided in lesson code.

Compared Candidate Sources & Selection Analysis (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

Author: Stanford CRFM Team | Original Source Link ↗

Relevant Section / Range: train.py: PROMPT_DICT, IGNORE_INDEX = -100, preprocess() masks the source tokens, DataCollatorForSupervisedDataset pads labels with IGNORE_INDEX

Verified Version & Date: Stanford Alpaca train.py (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

PyTorch Dataset, DataLoader, token masking with -100.

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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 min

Dynamic Batch Padding, Collator Masking, and Gradient Verification

Agent-Assisted Practice

Prerequisites

Day 62 Activities 1 and 2, PyTorch DataLoader collate_fn.

Learning Objective

Implement dynamic batch padding with -100 target masking, and verify via backward gradients that zero gradient updates flow into prompt token embeddings.

Instructions

1. Understand why dynamic padding to the longest sequence in a mini-batch is computationally superior to static max_length padding.
2. In DataLoader collate_fn, pad input_ids with tokenizer.pad_token_id and pad labels with -100.
3. Align shifting and padding: verify that padding at the sequence tail with -100 contributes 0 to cross-entropy gradients.
4. Perform gradient verification: pass a batch through an embedding layer and small linear LM head, call loss.backward(), and inspect grad tensor at prompt positions.

Practice & Prediction Log

Construct a synthetic batch of 2 sequences of different lengths. Run forward and backward passes. Assert that grad of token embeddings for prompt positions masked with -100 is strictly zero.

Independent Mastery Criterion

Prove mathematically and empirically through backward gradient inspection that masked tokens exert zero gradient influence.

Authoritative Source Resources & Provenance

linking Apache 2.0

TRL: DataCollatorForCompletionOnlyLM and SFTTrainer Documentation

Author: Hugging Face TRL Maintainers | Original Source Link ↗

Relevant Section / Range: Looking deeper into the SFT method: Label shifting and masking; Train on completion only

Verified Version & Date: Hugging Face TRL 0.8+ Documentation (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

PyTorch collate_fn, Hugging Face Trainer.

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: PyTorch Core Development Team | Original Source Link ↗

Relevant Section / Range: CrossEntropyLoss parameters ignore_index (default -100) and reduction

Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)

Selection Rationale:

Primary specification for ignore_index=-100 behavior, weight averaging over unmasked tokens, and loss reduction arithmetic.

Source Prerequisites:

Softmax probabilities, negative log likelihood, multi-class classification.

Safe Fallback (Offline Resilience):

Mathematical formulation of masked cross-entropy and equivalent tensor implementations are provided in lesson code.

Compared Candidate Sources & Selection Analysis (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 min

Independent Assessment: Verified SFT Data Collator with Exact Masking Verification

Independent Mastery Assessment

Prerequisites

Day 62 Activities 1-3.

Learning Objective

Build and independently test a production-grade SFTDataCollator supporting multi-turn dialogues, completion-only masking, dynamic padding, and verified zero-gradient leakage.

Instructions

1. Implement SFTDataCollator(response_ids, pad_token_id).
2. Accept a batch of tokenized conversation examples.
3. For each example, locate response_ids markers. Mask all tokens prior to response_ids with -100, and include response tokens and end-of-turn token in loss computation.
4. Apply right-padding to batch max length, setting pad positions in labels to -100.
5. Write unit tests verifying that all prompt tokens, system tokens, and padding tokens have label -100, while only assistant response tokens have valid targets.

Practice & Prediction Log

Run your SFTDataCollator on a test batch of 3 varying-length conversations. Assert 100% correct label masking and run a mock model step checking loss computation.

Independent Mastery Criterion

Deliver an independent SFT data collator with 100% test pass rate for multi-turn completion-only loss masking and batch padding.

Authoritative Source Resources & Provenance

linking Apache 2.0

Stanford Alpaca: train.py Supervised Fine-Tuning Script

Author: Stanford CRFM Team | Original Source Link ↗

Relevant Section / Range: train.py: PROMPT_DICT, IGNORE_INDEX = -100, preprocess() masks the source tokens, DataCollatorForSupervisedDataset pads labels with IGNORE_INDEX

Verified Version & Date: Stanford Alpaca train.py (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

PyTorch Dataset, DataLoader, token masking with -100.

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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

Author: Hugging Face TRL Maintainers | Original Source Link ↗

Relevant Section / Range: Looking deeper into the SFT method: Label shifting and masking; Train on completion only

Verified Version & Date: Hugging Face TRL 0.8+ Documentation (Verified: 2026-10-30)

Selection Rationale:

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

Source Prerequisites:

PyTorch collate_fn, Hugging Face Trainer.

Safe Fallback (Offline Resilience):

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

Compared Candidate Sources & Selection Analysis (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.