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.
The loss is -(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)
Demonstrate complete comprehension of autoregressive label shifting and ignore_index=-100 loss normalization.
Authoritative Source Resources & Provenance
Hugging Face LLM Course: Fine-tuning LLMs
Relevant Section / Range: Chapter 11.3: Dataset Preparation; Implementation with TRL
Verified Version & Date: 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.
Compared Candidate Sources & Selection Analysis (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
Relevant Section / Range: CrossEntropyLoss parameters ignore_index (default -100) and reduction
Verified Version & Date: 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.
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.
Training language models to follow instructions with human feedback
Relevant Section / Range: Section 3.5 Models (supervised fine-tuning, SFT)
Verified Version & Date: 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.
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.