Skip to main content
LearnMLAcademy
Intermediate10 min read

How LLMs Generate Text: Next-Token Prediction & Decoding

Control LLM text generation using temperature, top-k, top-p, and beam search, with token walkthroughs, prompt design tasks, and retrieval exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

The model has choices — how does it pick one?

Suppose the current text is “The weather is …”. The model may consider “sunny”, “cold”, “changing”, and thousands of other tokens. The neural network first produces a raw score for every vocabulary token.

Those raw scores are called logits. A softmax operation converts them into a probability distribution that is easier to interpret and sample from.

One illustrative generation step

One illustrative generation step
CandidateRaw model scoreAfter softmax (illustrative)
sunny2.066.5%
cold1.024.5%
changing0.09.0%

Treat the table as one instant in generation. A decoding rule selects from these candidates; after a token is appended, the model computes a new distribution for the longer context.

A paragraph emerges one selected token at a time

Current context

The model …

Model logits

one score per candidate

Probabilities

normalized distribution

Decoding rule

choose or sample

Selected token

append and repeat ↺

The modelThe model learnsThe model learns patterns
Every selected token is appended to the context before the next prediction step.

Greedy decoding — always take the largest probability

If the distribution is 66.5%, 24.5%, and 9.0%, greedy decoding selects sunny. It is simple and repeatable for a fixed model/input, but repeatedly taking only the top choice can make text rigid and does not make the answer factually verified.

Temperature — make the distribution sharper or flatter

Temperature changes the relative spread of candidate probabilities before sampling. Lower positive temperatures make high-scoring tokens dominate more strongly. Higher temperatures flatten the distribution so lower-ranked candidates become more viable.

Same toy logits [2, 1, 0], two temperatures

Same toy logits [2, 1, 0], two temperatures
SettingApproximate probabilitiesInterpretation
T = 1[0.665, 0.245, 0.090]Original softmax spread
T = 2[0.506, 0.307, 0.186]Flatter; lower-ranked candidates gain probability
softmax(logits / T), for T > 0
Temperature changes the scale of the logits before softmax. Do not teach T = 0 as literal division by zero; deterministic choice is handled as a separate decoding setting.

Top-k and top-p — narrow the candidate pool

Two common filters

Two common filters
MethodQuestion it asksExample
Top-kKeep how many of the highest-probability candidates?k = 3 keeps exactly the top 3 candidates before sampling
Top-p (nucleus)Keep enough high-probability candidates to reach what cumulative mass?p = 0.90 keeps as many top candidates as needed to reach at least 90%

Top-k uses a fixed candidate count. Top-p uses a probability-mass threshold, so the number of retained tokens can change from one generation step to the next.

Which decoding style fits the job?

Start from the task, not from a fashionable setting

Start from the task, not from a fashionable setting
TaskReasonable starting directionWhat still matters
Structured extractionDeterministic or tightly constrained decodingValidate schema and meaning
Normal assistant responseModerate, controlled samplingEvidence and safety still matter
Creative ideationMore sampling diversity may be usefulHigher diversity can also increase inconsistency

Why the next lesson matters

We know how the model turns its internal scores into text. How should we write the request we give it so the task is clear and testable?

Prompt Engineering →

Summary / Key Takeaways

  • An LLM first produces raw vocabulary scores called logits.
  • Softmax converts logits into a probability distribution over candidate next tokens.
  • Greedy decoding always chooses the highest-probability candidate.
  • Temperature changes how concentrated or spread out the distribution is; literal division by T = 0 is invalid.
  • Top-k keeps a fixed number of candidates, while top-p keeps enough candidates to reach a cumulative probability mass.
  • Decoding settings should match the task, and structured outputs still require validation.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "How LLMs Generate Text: Next-Token Prediction & Decoding"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What are logits in an LLM generation step?
Question 2 of 5numerical/formula
At T=1, the lesson's logits [2,1,0] become approximately [0.665, 0.245, 0.090]. At T=2 they become [0.506, 0.307, 0.186]. What changed?
Question 3 of 5interpretation
How does top-p differ from top-k?
Question 4 of 5debugging/diagnostic
A tutorial tells learners to compute `softmax(logits / 0)` for deterministic generation. What is the problem?
Question 5 of 5application/scenario
A structured extraction task needs stable, repeatable output. Which is the better starting point?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What are logits in an LLM generation step?▼

Correct Answer: Unnormalized scores for candidate vocabulary tokens

The model outputs logits, which are converted into probabilities before token selection.

2At T=1, the lesson's logits [2,1,0] become approximately [0.665, 0.245, 0.090]. At T=2 they become [0.506, 0.307, 0.186]. What changed?▼

Correct Answer: The higher temperature flattened the distribution

Higher temperature reduces relative logit differences before softmax, making lower-ranked candidates more viable.

3How does top-p differ from top-k?▼

Correct Answer: Top-k keeps a fixed number of candidates; top-p keeps enough high-probability candidates to reach a cumulative probability mass

k is a candidate count, while p is a cumulative probability threshold.

4A tutorial tells learners to compute `softmax(logits / 0)` for deterministic generation. What is the problem?▼

Correct Answer: Literal division by zero is invalid; deterministic generation should be handled as a separate decoding setting

Implementations generally represent deterministic selection separately; `T=0` should not be taught as literal arithmetic.

5A structured extraction task needs stable, repeatable output. Which is the better starting point?▼

Correct Answer: Deterministic or tightly constrained decoding plus validation

Schema-sensitive extraction benefits from stable decoding and application-side validation rather than creativity-oriented sampling.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next