Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 4 of 12
Next Token Prediction in Training
At the heart of LLM generation is predicting the next token. Understanding this process shows you exactly why LLMs produce the outputs they do.
From Logits to Probabilities
After the forward pass, the model outputs raw scores called logits — one for each token in the vocabulary. A high logit means the model thinks that token is likely; a low or negative logit means it is unlikely.
Logits are converted to probabilities using the softmax function:
- Each logit is exponentiated (e^logit)
- All values are divided by their sum
- The result is a valid probability distribution that sums to 1.0
This probability distribution tells us: 'Given everything in the context, the model predicts that the next token should be X with probability P.'
Probability Distribution Example
# Converting logits to probabilities (softmax)
import math
def softmax(logits):
"""Convert raw logit scores to probabilities."""
# Subtract max for numerical stability
max_logit = max(logits)
exp_logits = [math.exp(l - max_logit) for l in logits]
total = sum(exp_logits)
return [e / total for e in exp_logits]
# Example: logits for the 10 most likely tokens after "The capital of France is"
# (In a real LLM, there would be 50,000-100,000 logits, one per vocabulary token)
tokens = ["Paris", "Lyon", "Marseille", "France", "a", "the", "located", "famous", "beautiful", "known"]
logits = [8.5, 2.1, 1.8, 0.5, -1.2, -2.0, 0.3, 0.8, 0.6, 0.4]
probabilities = softmax(logits)
print("Prompt: 'The capital of France is'")
print()
print("Token Probability Distribution (top 10 from vocab):")
print("-" * 50)
for token, prob in sorted(zip(tokens, probabilities), key=lambda x: -x[1]):
bar = "█" * int(prob * 40)
print(f" '{token}': {prob:.4f} ({prob*100:.2f}%) {bar}")
print()
print(f"Total probability (must sum to 1.0): {sum(probabilities):.4f}")
print()
print("'Paris' has the highest probability — that is the next token most likely to be selected.")Finished this lesson?