Skip to content
E
Educatum

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.

Curated by Educatum AI teamLast updated:
Loss Functions
Direct Answer

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 (O(1)O(1) target memory) rather than materializing a dense one-hot target vector of size VV (O(V)O(V) memory). Crucially, standard softmax cross-entropy still requires O(V)O(V) computation per token to evaluate the partition function ∑k=1Vexp⁡(zk)\sum_{k=1}^V \exp(z_k), unless approximated via sampled softmax, hierarchical softmax, or noise-contrastive estimation:

LCE(z,y)=−log⁡py=−zy+log⁡∑k=1Vexp⁡(zk)\mathcal{L}_{\text{CE}}(z, y) = -\log p_y = -z_y + \log \sum_{k=1}^V \exp(z_k)

The decisive advantage of cross-entropy over dense mean squared error (MSE) on predicted probabilities p=softmax(z)p = \text{softmax}(z) lies in probabilistic calibration and gradient geometry:

  1. Non-vanishing gradients: For cross-entropy with softmax, the gradient with respect to logits is ∂LCE∂zk=pk−yk\frac{\partial \mathcal{L}_{\text{CE}}}{\partial z_k} = p_k - y_k. Even when the model assigns near-zero probability (py≈0p_y \approx 0) to the true token, the gradient ∂LCE∂zy=py−1≈−1\frac{\partial \mathcal{L}_{\text{CE}}}{\partial z_y} = p_y - 1 \approx -1 remains strong.
  2. MSE gradient vanishing & dilution: For dense MSE LMSE=1V∑k=1V(pk−yk)2\mathcal{L}_{\text{MSE}} = \frac{1}{V}\sum_{k=1}^V (p_k - y_k)^2, differentiating through softmax multiplies by the Jacobian factor pj(1−pj)p_j(1 - p_j) and scales by 1/V1/V, causing severe vanishing gradients when py→0p_y \to 0 and diluting the learning signal across V−1V - 1 negative vocabulary items.
  3. Proper scoring & perplexity alignment: Cross-entropy directly minimizes KL divergence DKL(y ∥ p)D_{\text{KL}}(y \,\|\, p) (maximum likelihood), matching language model perplexity PPL=exp⁡(LCE)\text{PPL} = \exp(\mathcal{L}_{\text{CE}}).

Key Terms

  • Sparse-Target Cross-Entropy: Cross-entropy computed from integer class IDs rather than dense one-hot arrays; avoids storing an O(V)O(V) target tensor per token while still normalizing logits over the vocabulary.
  • Dense Loss (e.g., MSE): A loss that averages squared residuals across all VV output dimensions against a dense target vector (e.g., one-hot or soft teacher logits/probabilities).
  • Softmax Gradient (∂LCE∂z\frac{\partial \mathcal{L}_{\text{CE}}}{\partial z}): Equals p−yp - y, avoiding the saturating p(1−p)p(1 - p) Jacobian factor that hampers MSE on categorical distributions.
  • One-Hot Encoding: A sparse categorical identity represented as a VV-dimensional binary vector with 11 at the true token index and 00 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 V=50,000V = 50{,}000 tokens where the true token is "cat" at index 200200:

  • Memory: Storing integer targets [200] for a batch of 4,0964{,}096 tokens uses a few kilobytes (int64), whereas a dense float32 one-hot target tensor of shape (4096, 50000) would consume ~819 MB.
  • Compute: Computing exact softmax probabilities still touches all 50,00050{,}000 logits per token in both cases, though cross-entropy avoids summing (pk−0)2(p_k - 0)^2 backward derivatives through the softmax Jacobian.
  • Training behavior: If the model initially assigns p200=10−4p_{200} = 10^{-4}, cross-entropy produces a crisp logit gradient of 10−4−1≈−1.010^{-4} - 1 \approx -1.0, rapidly pushing z200z_{200} up, whereas MSE’s gradient through softmax shrinks by roughly p200(1−p200)/V≈2×10−9p_{200}(1 - p_{200})/V \approx 2 \times 10^{-9}, 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")
  • Negative Log-Likelihood & Perplexity: Cross-entropy over next-token predictions is token-level NLL, and exp⁡(LCE)\exp(\mathcal{L}_{\text{CE}}) defines perplexity.
  • Label Smoothing & Knowledge Distillation: Cases where targets are dense probability vectors q∈ΔV−1q \in \Delta^{V-1}, using soft-target cross-entropy −∑kqklog⁡pk-\sum_k q_k \log p_k rather than MSE.
  • Large-Vocabulary Approximations: Sampled Softmax, Hierarchical Softmax, and Noise-Contrastive Estimation (NCE) reduce the O(V)O(V) normalization bottleneck during training when VV 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.