Welcome to this module on softmax and cross-entropy in large language models. These two operations sit at the output of every autoregressive model, and understanding them precisely is essential for understanding how modern systems like GPT are trained and sampled.
Softmax maps raw logits to a categorical distribution over the vocabulary, while cross-entropy measures the negative log likelihood of the true next token under that distribution. Together they define the training objective: minimize the sum over positions of the negative log probability of each token given all previous tokens.
We then examine their role in the transformer output layer, where the residual stream is projected by an unembedding matrix into logits of dimension equal to the vocabulary size, often fifty thousand or more tokens in models like GPT and BERT.
We will state the learning objectives and course structure, moving from the mathematical foundations through numerical stability concerns to practical implementation in PyTorch.
Finally, we connect these functions to training and inference: cross-entropy drives gradient-based optimization during pretraining, while softmax temperature and sampling strategies govern decoding at deployment time.
By the end, you should see softmax and cross-entropy not as boilerplate but as the probabilistic core of language modeling. Next we derive the gradient of the softmax cross-entropy loss and implement it from scratch.
Equations, code and original cards
Course Introduction and Motivation
• Softmax and Cross-Entropy: The Output Layer of Every LLM
• Logits to Categorical Distributions
• Negative Log-Likelihood as the Training Objective
• Unembedding Projection in Transformer Output Layers
• Autoregressive Factorization of Sequence Probability
• Vocabularies of 50K+ Tokens: Computational Cost
• Learning Objectives and Course Structure
• From Derivations to Numerically Stable Implementations
• Hands-On Code in Python/PyTorch
• Cross-Entropy in Training; Softmax in Decoding
• Gradient-Based Loss Optimization
• Temperature and Sampling at Deployment
Moment 02 / 11
Mathematical Definition of Softmax
We begin with the mathematical definition of softmax, the standard map from logits to a categorical distribution in classification and attention.
The formula: sigma of z sub i equals the exponential of z sub i, divided by the sum over j of the exponential of z sub j. It normalizes arbitrary real-valued logits into probabilities.
Because each exponential is positive and the denominator normalizes them, every output lies strictly between zero and one and the outputs sum to one, a valid categorical distribution.
Note the numerical stability trick: subtract the maximum logit before exponentiating. Softmax is shift-invariant, so the distribution is unchanged, but exp of large positive values can no longer overflow.
The stabilized form subtracts max of z inside each exponential; the largest exponent becomes zero, bounding every term by one while leaving the normalized output identical.
In practice we compute softmax in vectorized form over a batch of logit vectors, applying exponentiation and row-wise normalization as tensor operations in PyTorch.
This vectorization maps onto GPU kernels, fusing the reduction and normalization so batched softmax costs essentially one pass over the logits during training.
To summarize: the softmax formula, its guarantee of a valid probability distribution, the max-subtraction trick for numerical stability, and the vectorized form used in modern frameworks.
• Vectorized row-wise softmax over batched logit tensors in PyTorch
• Fused GPU kernels make batched classification and attention efficient
Moment 03 / 11
Softmax Distribution Playground
The softmax maps raw logits to a categorical distribution: exponentiate each score, then normalize by the partition function. Begin with the logit sliders on the left.
Raising one logit increases its probability monotonically, but softmax is shift-invariant, so only differences between logits matter, never their absolute values.
Temperature divides every logit before exponentiation. Low temperature sharpens the distribution toward the argmax; high temperature raises entropy, flattening toward uniform.
Sweep both the logits and the temperature, and track the entropy of the output. This is precisely the distribution that cross-entropy loss scores during training.
Equations, code and original cards
Moment 04 / 11
Cross-Entropy Loss: Definition and Intuition
Cross-entropy loss is the standard objective for training classifiers. It quantifies the divergence between the predicted distribution over classes and the empirical one-hot target.
Formally, for a single example the loss is the negative log of the softmax probability assigned to the true class: the negative log likelihood of the correct label under the model. Confident correct predictions incur near-zero loss; confident errors are penalized without bound.
Operating directly in probability space, the loss is a proper scoring rule: it is minimized exactly when the predicted distribution matches the true conditional distribution.
Minimizing cross-entropy is equivalent to maximum likelihood estimation under a categorical model, so gradient descent on this objective drives the logits of correct classes upward.
These properties, plus its well-behaved gradients through the softmax, make it the default objective for classification and, via teacher forcing, for autoregressive language modeling.
In short, cross-entropy ties probabilistic prediction to likelihood maximization, giving a principled, differentiable measure of error that scales from small classifiers to trillion-token language models.
Equations, code and original cards
Cross-Entropy Loss: Definition and Intuition
L = -\log p_{correct}
Negative log likelihood of the true class under the softmax
Equivalent to maximum likelihood; a proper scoring rule
Default objective for classification and autoregressive language modeling
Moment 05 / 11
Derivation of Gradient for Backpropagation
We now derive the gradient of the cross-entropy loss with respect to the logits, the quantity backpropagation actually needs. This derivation underlies essentially every classification model you will train.
Apply the chain rule through softmax into cross-entropy. The derivative of the loss with respect to logit z-j decomposes into a sum over classes of the softmax Jacobian times the derivative of the negative log likelihood.
The softmax Jacobian, p-i times the Kronecker delta minus p-j, cancels against the one over p-i term from the log. The sum telescopes, leaving exactly p-i minus y-i: predicted probability minus the one-hot target. This cancellation is why we fuse softmax with cross-entropy rather than backpropagating through them separately.
In matrix form, the gradient for a batch is simply the softmax output matrix minus the one-hot label matrix, one subtraction per example. Frameworks like PyTorch exploit this in fused kernels for speed and numerical stability.
Beyond elegance, this form explains the learning dynamics: gradient magnitude is bounded by one, vanishing only when predictions match targets, which is precisely the behavior we want for stable optimization.
To summarize: chain rule through the softmax Jacobian, cancellation yielding p minus y, and a matrix formulation that makes batched implementation trivial.
Equations, code and original cards
Gradient of Softmax Cross-Entropy
• Chain rule: softmax Jacobian × d(−log p)/dp
• Cancellation yields ∂L/∂z_i = p_i − y_i
• Fused kernel: numerical stability, fast convergence
• Batched form: P − Y, one subtraction per example
\frac{\partial L}{\partial z_i} = p_i - y_i
Moment 06 / 11
Implementation Details: Python and PyTorch
Let's dive into the implementation details of softmax and cross-entropy loss in PyTorch. This section clarifies how these components compose efficiently and numerically safely in practice.
Here we see PyTorch's nn.CrossEntropyLoss. Crucially, it expects raw logits, not probabilities, because it applies log-softmax internally. This design choice ensures numerical stability during training.
To clarify, logits are the raw, unnormalized scores output by your model's final linear layer, whereas probabilities are obtained by applying softmax to logits. Passing probabilities directly to CrossEntropyLoss double-applies softmax and yields incorrect gradients.
Let's examine this Python snippet demonstrating the forward and backward pass. Notice the raw logits pass directly to the loss function without an explicit softmax, and a single backward call computes gradients through the entire computation graph.
A crucial tip here is to always work with logits directly rather than probabilities. The log-sum-exp trick inside the fused kernel avoids floating-point overflow and underflow that a naive softmax-then-log would suffer.
In summary, by leveraging PyTorch's fused log-softmax and cross-entropy kernel and working with logits, we ensure both correctness and optimal performance in training neural networks.
Tip: For numerical stability, work with logits and avoid explicit softmax in loss.
Moment 07 / 11
Advanced Techniques: Temperature and Label Smoothing
Today we examine two techniques that materially improve both training dynamics and generation quality: temperature scaling of the softmax, and label smoothing as a regularizer on cross-entropy.
Begin with temperature scaling. The temperature parameter T rescales the logits before normalization, directly controlling the sharpness of the resulting categorical distribution.
Recall that softmax exponentiates each logit z-i and normalizes. Temperature divides the logits by T first: probabilities become softmax of z over T, interpolating between an argmax and the uniform distribution.
For T below one, logits are amplified and the distribution sharpens toward argmax. For T above one, it flattens toward uniform. As T approaches zero, you recover hard argmax sampling.
Label smoothing, introduced by Szegedy and colleagues in the Inception work, regularizes the classifier by softening the one-hot target vectors.
Formally, the hard target y-k becomes q-k: one minus epsilon on the true class, plus epsilon over K spread across all classes. The model can no longer drive the correct logit to infinity.
The gradient with respect to the correct logit is now bounded, because the target never reaches one. This caps logit magnitudes, smooths the loss surface, and improves calibration and generalization.
Cross-entropy against smoothed labels decomposes into the standard loss plus a term proportional to the KL divergence pulling the predictive distribution toward uniform.
Now the implementation. This PyTorch snippet shows both mechanisms: dividing logits by temperature, and constructing smoothed targets for the cross-entropy loss.
Note the smoothed loss mixes one minus epsilon times the hard target with epsilon over the number of classes, then takes the negative log likelihood under the model.
To summarize: temperature rescales logits and controls sampling sharpness and calibration; label smoothing bounds the gradients and prevents overconfident logits. Together they yield better calibrated, better generalizing classifiers, and both appear in essentially every modern large-scale training recipe.
Equations, code and original cards
Advanced Techniques: Temperature and Label Smoothing
• Temperature scaling of softmax logits
• Label smoothing as cross-entropy regularization
• Gradient bounds, calibration, and loss-surface effects
Let's examine the research frontier from 2024 to 2026, where loss function design is actively reshaping how large language models are trained and aligned.
The state of the art still rests on cross-entropy over softmax logits, but recent work targets its failure modes: overconfidence, misalignment, and vocabulary-scale compute.
First, scaling laws from Kaplan et al. and the Chinchilla analysis of Hoffmann et al. show the loss landscape itself is predictable, with optimal model size near twenty tokens per parameter.
Second, efficiency work attacks the softmax bottleneck: adaptive and sparse softmax variants reduce the cost of normalizing over vocabularies exceeding one hundred thousand tokens.
Third, alignment research replaces pure likelihood with preference objectives, notably direct preference optimization from Rafailov et al., which fits a reward model implicitly through a KL-regularized loss.
Here is the workhorse itself: PyTorch's cross-entropy, which fuses log-softmax and negative log likelihood directly on raw logits for numerical stability.
Open problems include continuous relaxations of discrete token prediction and principled alternatives to teacher forcing, both fertile ground for new research.
In summary, the loss function is no longer a fixed choice; it is a design axis that co-evolves with scale, efficiency constraints, and alignment demands.
Equations, code and original cards
Recent Research Trends (2024-2026)
Beyond vanilla cross-entropy: scaling, efficiency, and alignment
• Scaling laws: predictable loss curves (Kaplan 2020; Chinchilla N ≈ 20D)
We turn now to frontier variations on softmax cross-entropy and the open problems in language-model training, where the objective itself remains an active design variable rather than a settled constant.
Start with alternatives to vanilla cross-entropy. Focal loss reweights easy examples downward to combat class imbalance, while label smoothing regularizes the target distribution to curb overconfident logits.
Contrastive objectives such as InfoNCE pull representations of positive pairs together and push negatives apart, imposing geometric structure that a one-hot target simply cannot encode.
Temperature adapts the softmax itself: dividing logits by a scalar flattens or sharpens the predictive distribution, the knob behind knowledge distillation and behind controlling gradient scale during training.
The harder agenda is calibration and interpretability: a model can minimize cross-entropy yet remain systematically overconfident, so modern work audits predicted probabilities against empirical accuracy.
These threads, objective design, contrastive structure, temperature, and calibration, define an active research frontier that couples theory to ablation, and they will recur throughout the course.
Equations, code and original cards
Beyond Cross-Entropy: Variants and Open Problems
Frontier directions:
• Focal loss and label smoothing beyond one-hot targets
• InfoNCE and margin objectives for representation geometry
• Softmax temperature: distillation and gradient-scale control
• Calibration and interpretability: confidence versus accuracy
Open problems: overconfidence at low cross-entropy, objective misalignment, and evaluation of calibrated uncertainty
Moment 10 / 11
Quiz: Conceptual and Computational Understanding
Time to probe how well the softmax and cross-entropy machinery has settled. Work through each question independently, and watch for the ones targeting gradient behavior and logit scaling, since that is where intuition usually breaks.
Once you finish, we will walk through the answers together and correct any misconceptions about the loss surface before moving on.
Equations, code and original cards
Moment 11 / 11
Summary and Key Takeaways
Let's close by distilling what matters about softmax, cross-entropy, and large-scale language modeling.
Softmax turns logits into a normalized categorical distribution, while cross-entropy is the negative log likelihood assigned to the true token.
With temperature tau, each probability is exponentiated logit divided by tau, then normalized by the partition function.
For a one-hot target, that loss reduces to minus the log predicted probability, and its logit gradient is prediction minus target.
That clean Jacobian structure makes backpropagation cheap, but scale demands careful normalization, clipping, and stable optimizer state.
In practice, use the log-sum-exp trick, fused kernels, mixed precision, and avoid materializing full vocabularies unnecessarily.
Open problems include calibration, long-context extrapolation, efficient attention, and alignment methods beyond simple supervised fine-tuning.
Master these mechanisms and you can read scaling papers, diagnose instabilities, and build the next generation of sequence models.
Equations, code and original cards
Summary and Key Takeaways
• Softmax with temperature; cross-entropy as token-level negative log likelihood
• Logit gradient: prediction minus one-hot; stable backpropagation at scale
\text{Cross-Entropy Loss: }\quad L = -\sum_i y_i \log(\hat{y}_i)
MAKE IT YOURS
Explain the change.
References, scope & corrections
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.