How does the final output layer turn the last hidden states into next-token probabilities?

Last updated 22 November 2026

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.

  1. Final norm: apply a final LayerNorm/RMSNorm to the residual stream, which is needed in pre-norm models.

  2. Unembedding:

    • Compute logits = h · W_U (shape (B, T, V)).

    • Each logit is a dot product between h and that token's output vector, i.e. a similarity score.

    • If weights are tied, W_U = Eᵀ.

  3. 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_softmax is 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·V FLOPs 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.

  • https://medium.com/@thakur.rana/prompt-tuning-adapting-llms-without-updating-their-weights-7f63e4b3c9f4
  • https://medium.com/@pacosun/how-does-the-model-turn-its-final-state-into-words-e1f06dba1417
  • https://github.com/veronikayurchuk/paligemma-from-scratch
All Transformers interview questions