Compare and contrast the impact of using sparse (e.g., cross-entropy) and dense (e.g., mean squared error) loss functions in training language models.
Sparse cross-entropy takes integer token indices (O(1) target memory) instead of dense O(V) one-hot vectors, though computing softmax normalization over vocabulary V still costs O(V) per token unless approximated. Compared with MSE over softmax probabilities, cross-entropy avoids vanishing gradients from the softmax Jacobian p(1 - p) and gradient dilution across V - 1 negative classes. Because cross-entropy directly minimizes negative log-likelihood and aligns with perplexity, it trains language models faster and produces sharper probability distributions.
Study Card: Sparse vs. Dense Loss Functions in Language Modeling
Direct Answer
In language modeling, sparse cross-entropy (such as PyTorch nn.CrossEntropyLoss or TensorFlow SparseCategoricalCrossentropy) represents each target token as a single integer index ( target memory) rather than materializing a dense one-hot target vector of size ( memory). Crucially, standard softmax cross-entropy still requires computation per token to evaluate the partition function , unless approximated via sampled softmax, hierarchical softmax, or noise-contrastive estimation:
The decisive advantage of cross-entropy over dense mean squared error (MSE) on predicted probabilities lies in probabilistic calibration and gradient geometry:
- Non-vanishing gradients: For cross-entropy with softmax, the gradient with respect to logits is . Even when the model assigns near-zero probability () to the true token, the gradient remains strong.
- MSE gradient vanishing & dilution: For dense MSE , differentiating through softmax multiplies by the Jacobian factor and scales by , causing severe vanishing gradients when and diluting the learning signal across negative vocabulary items.
- Proper scoring & perplexity alignment: Cross-entropy directly minimizes KL divergence (maximum likelihood), matching language model perplexity .
Key Terms
- Sparse-Target Cross-Entropy: Cross-entropy computed from integer class IDs rather than dense one-hot arrays; avoids storing an target tensor per token while still normalizing logits over the vocabulary.
- Dense Loss (e.g., MSE): A loss that averages squared residuals across all output dimensions against a dense target vector (e.g., one-hot or soft teacher logits/probabilities).
- Softmax Gradient (): Equals , avoiding the saturating Jacobian factor that hampers MSE on categorical distributions.
- One-Hot Encoding: A sparse categorical identity represented as a -dimensional binary vector with at the true token index and elsewhere.
- Dense Soft Targets: Non-sparse target vectors (such as label smoothing or knowledge distillation teacher distributions) where multiple classes carry non-zero target mass.
Example
Consider next-token prediction over a vocabulary of tokens where the true token is "cat" at index :
- Memory: Storing integer targets
[200]for a batch of tokens uses a few kilobytes (int64), whereas a densefloat32one-hot target tensor of shape(4096, 50000)would consume ~819 MB. - Compute: Computing exact softmax probabilities still touches all logits per token in both cases, though cross-entropy avoids summing backward derivatives through the softmax Jacobian.
- Training behavior: If the model initially assigns , cross-entropy produces a crisp logit gradient of , rapidly pushing up, whereas MSE’s gradient through softmax shrinks by roughly , stalling learning.
Code Implementation
import torch
import torch.nn as nn
import torch.nn.functional as F
vocab_size = 1000
target_class = torch.tensor([2])
target_one_hot = F.one_hot(target_class, num_classes=vocab_size).float()
# Confidently wrong logits: true token (index 2) gets a very low logit (-8.0), wrong token (index 0) gets +8.0
logits_ce = torch.zeros(1, vocab_size)
logits_ce[0, 0] = 8.0
logits_ce[0, 2] = -8.0
logits_ce.requires_grad_(True)
logits_mse = logits_ce.detach().clone().requires_grad_(True)
# 1. Sparse-target Cross-Entropy Loss (operates directly on logits and class index)
loss_ce = nn.CrossEntropyLoss()(logits_ce, target_class)
loss_ce.backward()
# 2. Dense MSE Loss on softmax probabilities (must normalize logits to probabilities first)
probs_mse = F.softmax(logits_mse, dim=-1)
loss_mse = nn.MSELoss()(probs_mse, target_one_hot)
loss_mse.backward()
print(f"Cross-Entropy Loss: {loss_ce.item():.4f}")
print(f"MSE Loss (on probs): {loss_mse.item():.6f}")
print(f"CE grad norm on logits: {logits_ce.grad.norm().item():.6f}")
print(f"MSE grad norm on logits: {logits_mse.grad.norm().item():.10f} # Vanishes when confidently wrong")
Related Concepts
- Negative Log-Likelihood & Perplexity: Cross-entropy over next-token predictions is token-level NLL, and defines perplexity.
- Label Smoothing & Knowledge Distillation: Cases where targets are dense probability vectors , using soft-target cross-entropy rather than MSE.
- Large-Vocabulary Approximations: Sampled Softmax, Hierarchical Softmax, and Noise-Contrastive Estimation (NCE) reduce the normalization bottleneck during training when is very large.
- Flash/Fused Cross-Entropy: Memory-efficient Triton/CUDA kernels compute log-sum-exp and gradients in tiles without materializing large intermediate
(B*T, V)float32 probability matrices in HBM.