How an LLM Chooses the Next Token


On this page

So far in this series, we’ve followed what happens to a prompt after we send it to a language model. In From Text to Tokens and Embeddings, we saw how a tokenizer turns input text into token IDs. The model then uses each ID to look up a learned vector, which gives that token its starting representation. Then, in How LLMs Use Context, we saw how self-attention lets the model update each token’s vector with context from earlier tokens in the input.

By the end of that process, the model has built a representation of the prompt. Today we’ll look at how it goes from that representation to the first token of an answer.

Let’s return to the delivery example from What Is an LLM?. Here’s the prompt we give the model:

Summarize this delivery update in one sentence to notify the customer:

“Order 482 was scheduled for 18:00. The driver reports a van breakdown. The revised arrival time is 18:25.”

The reply could start with The, Order, or A. We’ll follow how the model scores those possibilities and how the generation code chooses among them.

1. Logits: next-token scores

A model forward pass produces logits. Greedy decoding or sampling selects a token, which is appended to the context for the next forward pass if generation continues.

The model’s input is a sequence of token IDs representing the formatted prompt. It looks up an embedding for each token and passes the resulting vectors through its transformer blocks. By the final layer, each position has a representation built from the context available to it. The representation at the last input position can use the whole supplied prefix.

The model uses a learned output layer to turn that final representation into one score per possible next token ID. These scores are called logits. For this example, we ran Qwen2.5-0.5B-Instruct on the delivery prompt. The model produced 151,936 scores for the first token of the reply. The table shows the five highest from that run, with their probabilities rounded for display.

Token piece Logit Probability
The 17.2381 29.84%
Order 16.1772 10.33%
A 16.0916 9.48%
Please 15.7642 6.84%
Delivery 15.6690 6.21%

The probabilities use all 151,936 scores. The displayed candidates account for about 63% of the probability, with the rest spread across the remaining candidates. Each row refers to a single token piece, which can be a word, part of a word, or whitespace.

The has the highest score, yet its probability is only about 30%. Given these same scores, when would we always choose The, and when might we choose something else?

2. From scores to a choice

Greedy decoding

If our rule is to take the highest-scoring token, we already have everything we need. That rule is greedy decoding. With the scores above, it picks The. In code, that is an argmax over the logits.

Using the model and tokenized prompt from the notebook, we run one forward pass, take the scores at the last input position, and look up the token with the highest score.

with torch.inference_mode():
    output = model(**inputs)

next_token_logits = output.logits[0, -1]
next_token_id = int(torch.argmax(next_token_logits))
print(tokenizer.decode([next_token_id]))

Output from the delivery example:

The

In output.logits[0, -1], 0 selects our only input sequence and -1 selects its last token position. That leaves one score per candidate token. argmax returns the index of the highest score, which is the token ID we pass to the tokenizer to get the text. Greedy decoding can make that choice directly from the logits.

Sampling

Another way to choose the next token is sampling. We draw one token at random, with higher-scoring tokens more likely to be chosen. To make that draw, we first need to turn the scores into probabilities. Softmax exponentiates each score to make a positive weight, then divides each weight by the sum of all the weights. The resulting probabilities sum to one. Exponentiation and division by the same positive number preserve the order, so the token with the highest logit also has the highest probability.

Let’s use the same token pieces in an illustrative vocabulary with only four candidates. Imagine softmax has given us this distribution:

Token piece Probability
The 40%
Order 30%
A 20%
Please 10%

The is the most likely individual outcome at 40%, while the other three tokens together have a 60% chance. In the notebook, The came up about 40.1% of the time across 10,000 draws from this same distribution.

3. How sampling settings change the odds

Suppose we still want to sample, but we want some control over what we draw. We can adjust how strongly the distribution favors the leaders, or we can restrict which candidates enter the draw. Let’s change one setting at a time.

Temperature

Temperature adjusts the strength of the preference. We divide each logit by a positive temperature before applying softmax. At temperature 1 the scores stay as they are. At 0.5 the gaps between scores double, so exponentiation gives the leaders more weight. At 2 the gaps halve, making the distribution flatter. The ranking stays the same in each case. In our four-token example, the probability of The moves from 40% to 53.3% at temperature 0.5 and to 32.5% at temperature 2.

Top-k

Top-k gives us a fixed number of candidates. With top_k=2, we keep The and Order. They originally held 70% of the probability, so we divide each retained probability by 0.70 to make the new distribution sum to one. This is renormalization. We now draw The about 57.1% of the time and Order about 42.9% of the time. The other candidates have zero chance.

Top-p

Top-p, also called nucleus sampling, gives us a probability threshold. With top_p=0.8, we add candidates in descending order until their combined probability reaches at least 80%. The and Order bring us to 70%. Adding A takes us to 90%, so A stays in the draw. After renormalization, the chances are about 44.4%, 33.3%, and 22.2%. The number of candidates can change from one prediction to the next as the distribution changes. Original nucleus sampling paper

Top-k keeps The and Order, two tokens totaling 70%. Top-p at 80% also keeps A, which takes the running total to 90%.

Comparing the settings on the delivery prompt

Now return to the delivery prompt. At temperature 1, Qwen’s top five candidates held about 63% of the original probability. Setting top_k=5 keeps exactly those five. Setting top_p=0.8 on the same distribution keeps eleven. Lowering the temperature to 0.5 without filtering raises the chance of The from about 30% to about 72%. It is still a draw, and another token can still be selected.

4. From one token to a full response

So far, we’ve looked at how to choose one token from a set of scores. To write the rest of the notification, we add that token to the text the model has seen and run another forward pass. The model produces a fresh set of scores for the next token, using the original prompt and the response generated so far.

Four steps show the generated text grow from The to The delivery was scheduled, with the newest token highlighted in each row.

Let’s follow the first four steps of the greedy run. The original delivery prompt is part of the context in every row. The first column shows only the text we’ve generated so far, and the last column shows the probability of the selected token at that step.

Generated text so far Next token selected Probability of that token
None yet The 29.8%
The delivery 24.3%
The delivery was 33.7%
The delivery was scheduled 24.9%

Look at the last row. After The delivery was, greedy decoding picks scheduled at 24.9%. But delayed is close behind at 23.7%. If sampling picked delayed instead, the model would make its next prediction with The delivery was delayed in its context. The run in the table continues from The delivery was scheduled.

This loop is called autoregressive generation. Each selected token becomes part of the context for the next prediction. Generation continues one token at a time until the model emits an end token or the runtime reaches a configured length limit.

Even with the same prompt and model, a different decoding strategy can choose a different next token. That single choice can change the rest of the response.

Imagine asking the same model to finish the sentence “I opened the door and saw…” If you keep the prompt fixed, what would greedy decoding choose each time? What might change if you sample instead? Follow either choice one step further: once the selected token becomes part of the context, the model has a new sequence to continue.


The companion notebook contains the four-token calculations and the saved Qwen runs. The original walkthrough’s setup covers the local environment. For more on the model stages, see What Is an LLM? and How LLMs Use Context.