How does the final output layer turn the last hidden states into next-token probabilities?
Last updated
The last hidden state is normalized, then projected by a d×V unembedding matrix into one logit per vocabulary token. A softmax turns those logits into a probability distribution over the next token.
Final norm: apply a final LayerNorm/RMSNorm to the residual stream, which is needed in pre-norm models.
Unembedding:
Compute
logits = h · W_U(shape(B, T, V)).Each logit is a dot product between
hand that token's output vector, i.e. a similarity score.If weights are tied,
W_U = Eᵀ.
Softmax:
p_i = exp(z_i/τ) / Σ_j exp(z_j/τ).:Temperature
τsharpens or flattens the distribution.Implementations subtract the max logit for numerical stability.
Training vs inference:
Training: logits at every position feed cross-entropy against the shifted targets.
log_softmaxis fused into the loss.Inference: only the last position's logits are needed.
Decoding then picks a token via greedy, top-k, top-p or similar sampling.
Cost: the projection is
T·d·VFLOPs and the logits tensor can be huge (vocab of 100k+), so it's often chunked. Some models add logit soft-capping (e.g. Gemma) to bound magnitudes.