MODULE 2 · LESSON 9 · 12 MIN
Inference: How a Model Generates a Response
By Siten Sanghvi · Published · Updated
Inference is what a trained model does every time you send it a request: it scores every possible next token, one rule picks a token, that token joins the text, and the cycle repeats until the model stops. Training happens before you arrive. Inference happens on every request.
That single loop explains why a reply can stream a piece at a time, why the same prompt can produce different answers, and why long answers take longer. It also has limits. A real service wraps the loop with batching (serving several requests together), caching and provider settings, and those change what you observe. This lesson describes the common autoregressive text generator (each token is produced from the tokens before it) introduced in What Is a Large Language Model?; other designs can differ.
The loop, one token at a time
BT-L04 gave the four-step version. Here is what happens inside it for each token:
- Tokenize. Your prompt becomes token IDs from the model's vocabulary (Tokens, Embeddings, and Context Windows Explained).
- Embed. Each ID becomes a vector of numbers.
- Run the transformer. Attention and feed-forward layers turn those vectors into context-aware representations. In a decoder, a position may attend only to earlier positions, never later ones (Attention Is All You Need, section 3.1).
- Project to logits. The last position's representation becomes one raw score, called a logit, for every token in the vocabulary. Vocabulary size varies by model; Llama 3 uses 128K tokens.
- Apply softmax. The logits become probabilities that add up to 1. This is the model's distribution over the next token (Attention Is All You Need, section 3.4).
- Choose. A decoding rule picks one token: the highest-probability one, or a random draw from the distribution.
- Append and repeat. The chosen token is added to the context and the cycle runs again, until the model emits an end-of-sequence token or reaches a length limit (vLLM paper, section 2.2).
In this plain loop a chosen token becomes fixed context. The model does not go back and edit it.
Serving systems split the work into two phases. All prompt tokens are known up front, so the system can process them in parallel ("prefill"); each new token afterwards needs another sequential step ("decode") (Pope et al., section 2.2). Model-side latency therefore has two parts: time to process the prompt, then time per generated token.
EXHIBIT 09 / SAMPLING
Explore the mechanismOne token. One decision.
Reshape scores, filter the tail, then choose.
Filtered next-token probabilities
After “The backup job finished,” the toy logits are 3.0, 2.2, 1.5, 0.5, −0.5. This example applies temperature, softmax, top-k and top-p in that order. A choice weight is not evidence of truth or a measurement from a model.
Inspect the example data and reasoning
| Token | Before filtering | After filtering | Seeded tally / 20 |
|---|---|---|---|
| successfully | 56.0% | 56.0% | Not drawn |
| with | 25.2% | 25.2% | Not drawn |
| in | 12.5% | 12.5% | Not drawn |
| but | 4.6% | 4.6% | Not drawn |
| at | 1.7% | 1.7% | Not drawn |
Five handpicked logits and seeded samples. Probabilities are not truth scores or a hosted-service reproducibility promise.
Read the mechanism without interacting
- Scores
- Softmax turns logits divided by temperature into a distribution.
- Filters
- Top-k limits count; top-p keeps the smallest ranked set reaching the chosen mass.
- Choice
- Renormalize the retained set and choose a token. The choice becomes next-step context.
Try top-k 2, then top-p 0.9. The model weights stay unchanged while the allowed choices change.
Try explaining it: Which settings change the selection rule rather than the model weights?
Why a reply can appear a piece at a time
In the plain loop the next token cannot be chosen until the previous one has been, so a service can forward each piece as soon as it exists. Streaming is an API option, not automatic. The Anthropic Messages API documents a stream setting that sends the response incrementally as server-sent events, and the OpenAI chat parameters describe the same idea. Streaming changes when you see text, not how many steps the model takes. Some apps also add a typing effect on top, so the display alone does not prove how the text was produced.
"One token per step" describes the plain loop, not every production system. Speculative decoding, for example, can compute several tokens in one step while keeping the same output distribution (Leviathan et al.).
Temperature, top-k and top-p: shaping the choice
These settings change how the distribution becomes one token. They do not retrain or change the model's weights.
- Temperature divides the logits before softmax (Hinton et al., section 2; Holtzman et al., section 3.3). Below 1 the distribution becomes sharper; above 1 it becomes flatter. The ranking of tokens never changes, so the top token stays on top.
- Greedy decoding always takes the highest-probability token. It is the limit as temperature approaches 0, and libraries often expose it as a separate mode (Hugging Face guide). It suits short outputs but tends to repeat itself on longer ones.
- Top-k keeps the k most probable tokens, rescales them to add up to 1 (renormalizes), and samples from them (Holtzman et al., section 3.2). A fixed k fits badly when the distribution is very flat or very peaked.
- Top-p (nucleus) keeps the smallest set of tokens whose cumulative probability reaches p, renormalizes, and samples (Holtzman et al., section 3.1). The set grows and shrinks with how peaked or flat the distribution is at each step.
Here is one step with illustrative logits 3.0, 2.2, 1.5, 0.5 and -0.5 for the next token after "The backup job finished". These are made-up numbers, not output from a real model.
| Setting | successfully | with | in | but | at |
|---|---|---|---|---|---|
| Temperature 0.5 | 79.4% | 16.0% | 4.0% | 0.5% | 0.1% |
| Temperature 1 | 56.0% | 25.2% | 12.5% | 4.6% | 1.7% |
| Temperature 2 | 38.4% | 25.8% | 18.1% | 11.0% | 6.7% |
| Temperature 1, top-k 2 | 69.0% | 31.0% | removed | removed | removed |
| Temperature 1, top-p 0.9 | 59.8% | 26.9% | 13.3% | removed | removed |
When top-p 0.9 is applied after temperature, it keeps 2, 3 or 4 tokens at temperature 0.5, 1 and 2. Providers differ in which settings they expose, and implementations may apply these steps in different orders, so check the documentation. OpenAI's SDK documentation, for example, suggests changing temperature or top-p but not both.
Why the same prompt can give different answers
When the rule is a random draw, each run can choose differently, and an early different token changes everything conditioned on it. Lowering randomness narrows the variation but does not guarantee identical output from a hosted service. OpenAI's SDK docs describe its seed option as a Beta, best-effort feature and state that determinism is not guaranteed (parameter docs); its archived cookbook page covers older models and shows the same caveat. One documented cause is that numerical results can depend on how many requests share a batch, which changes with server load (Thinking Machines). That analysis rests on specific open-model experiments, and its fix, batch-invariant kernels, ran slower. Treat repeatable output as something to test, not assume.
Why long answers take longer, and what the KV cache does
Standard generation of K tokens needs K sequential runs of the model (Leviathan et al.), so output length drives time. Each step also has to attend over the whole context so far.
To avoid recomputing that, serving systems keep the attention keys and values of earlier tokens (the attention data computed for each one) in a KV cache and compute only the new token's (vLLM paper, section 2.2). This works because earlier positions cannot depend on later ones. The cost is memory: the cache is large and grows with each request's length. In the vLLM paper's 13B-model, 40GB-GPU setup it took close to 30% of memory. In Pope et al.'s PaLM experiments, time spent loading the KV cache dominated at large batch sizes and long contexts, and loading weights at small ones. How much a longer context slows a particular service depends on the model, hardware and batching, so measure it.
Structured output, cost and vendor settings
Because the model chooses tokens one at a time from a probability distribution, a format instruction alone does not guarantee valid JSON. Constrained decoding restricts each step to tokens that keep the output valid under a grammar (Outlines paper). Provider features for this still have caveats. OpenAI's Structured Outputs guide notes that a refusal may not follow the schema and that hitting the token limit can leave output incomplete, so validate and handle both.
Anthropic's pricing page lists input and output tokens separately per million tokens, with output priced higher for every model listed; other providers vary. Do not infer a request's cost from output length alone.
Vendor settings (checked 2026-11-09). Anthropic's API version 2026-10-21 migration guide says a request that sends temperature, top_p or top_k returns a 400 error under that version, and that Claude 4.7 and later models already accept only defaults. Advice like "set temperature to 0" is therefore not universal. Check the documentation for the model and API version you use.
Try it: see the loop vary
First, check the table by hand. With logits 2.0, 1.0 and 0.1, softmax at temperature 1 gives 65.9%, 24.2% and 9.9%. Divide the logits by 0.5 and recompute; the top token should reach about 86%.
Then send the same open-ended prompt to an assistant five times and note where the replies first diverge. If your tool exposes a randomness setting, repeat at its lowest value: expect less variation, not identical text.
The takeaway
Inference is a loop: the model scores every possible next token, a decoding rule picks one, and the choice becomes part of the context for the next step. Temperature, top-k and top-p shape that choice without changing the model. Output length sets how many sequential steps a reply needs, and the KV cache trades memory for avoided recomputation. Lower randomness reduces variation but does not guarantee identical output, and provider settings change, so check the documentation for your model.
Related lessons
- The Transformer Architecture Explained shows the attention and feed-forward layers that run inside each step of this loop.
- Tokens, Embeddings, and Context Windows Explained explains the tokens the loop reads and writes, and the context limit it works within.
- Latency, Throughput, and Reliability in AI Systems covers what slows a deployed AI service and how to keep it reliable.
Up next
Model Evaluation: Benchmarks, MMLU, and Why They're Imperfect: the last lesson of Module 2 asks how anyone measures whether one model is better than another, and why those measurements are harder to trust than they look.
VISUAL FIELDNOTES / 09
Keep the big picture.
A one-page visual companion. Save it, print it, or explain it to someone else.
View the full-size sheet ↗One token. One decision.
Reshape scores, filter the tail, then choose.
One US Letter page · Vector artwork · Fits A4 when printed to fit
Read the key points as text
- Scores
- Softmax turns logits divided by temperature into a distribution.
- Filters
- Top-k limits count; top-p keeps the smallest ranked set reaching the chosen mass.
- Choice
- Renormalize the retained set and choose a token. The choice becomes next-step context.
Remember: Softmax turns logits divided by temperature into a distribution.
Try it: Try top-k 2, then top-p 0.9. The model weights stay unchanged while the allowed choices change.
Recall: Which settings change the selection rule rather than the model weights?
OPTIONAL CHECK
Check your understanding.
The optional check requires JavaScript. You can continue reading the lesson.
A chat tool shows an answer a few words at a time. Which explanation fits how the plain generation loop works?
Which order describes how one token is produced in the plain generation loop?
For a fixed prompt, temperature is lowered from 1.0 to 0.5 at one step. What happens to the next-token distribution?
At one step a model puts 96% of the probability on a single token. With top-p set to 0.9, which tokens remain candidates?
At another step the probability is spread almost evenly across dozens of reasonable tokens. Why is a fixed top-k of 5 a poor fit there?
A team runs the same prompt twice through a hosted API at its lowest-randomness setting and gets slightly different replies. Which conclusion is best supported?
What does the KV cache save during generation, and what is the trade-off?
In the plain decoding loop, why does an 800-token answer take longer than an 80-token answer?
A pipeline asks a model for JSON and the parser occasionally fails. What is the soundest improvement?
A runbook says: 'Always set temperature to 0 for repeatable output.' What is the best critique?
Quiz complete
YOUR LEARNING
Keep your place.
Your progress is saved on this device.