Let’s look at text generation strategies (also called decoding strategies) for generating more original text. First, we’ll briefly review the generatetextsimple function we used earlier in generateandprint_sample. Then we’ll introduce two techniques, temperature scaling and top-k sampling, to improve that function.
Next, we plug a GPTModel instance (model) into the generatetextsimple function, which uses the LLM to generate one token at a time:
tokenizer = tiktoken.get_encoding("gpt2")
token_ids = generate_text_simple(
model=model,
idx=text_to_token_ids("Every effort moves you", tokenizer),
max_new_tokens=25,
context_size=GPT_CONFIG_124M["context_length"]
)
print("Output text:\n", token_ids_to_text(token_ids, tokenizer))
## output
Output text:
Every effort moves you know," was one of the axioms he laid down across the Sevres and silver of an exquisitely appointed lun
As explained earlier, the generated token is the one with the highest probability score among all tokens in the vocabulary at each generation step. That means even if we run generatetextsimple multiple times with the same starting context (Every effort moves you), the LLM will always produce the same output.
Temperature scaling
Now let’s look at temperature scaling, a technique that adds a probabilistic selection process to the next-token generation task. In the earlier generatetextsimple function, we always used torch.argmax (also called greedy decoding) to sample the token with the highest probability as the next token. To generate more diverse text, we can replace argmax with a function that samples from a probability distribution (here, the probability scores the LLM produces for each vocabulary entry at each token-generation step).
To illustrate probability sampling with a concrete example, let’s briefly walk through next-word generation using a very small vocabulary:
vocab = {
"closer": 0,
"every": 1,
"effort": 2,
"forward": 3,
"inches": 4,
"moves": 5,
"pizza": 6,
"toward": 7,
"you": 8,
}
inverse_vocab = {v: k for k, v in vocab.items()}
# Suppose input is "every effort moves you", and the LLM
# returns the following logits for the next token:
next_token_logits = torch.tensor(
[4.51, 0.89, -1.90, 6.75, 1.63, -1.62, -1.89, 6.28, 1.79]
)
probas = torch.softmax(next_token_logits, dim=0)
next_token_id = torch.argmax(probas).item()
# The next generated token is then as follows:
print(inverse_vocab[next_token_id])
## output
forward
Next, suppose the LLM is given the starting context “every effort moves you” and produces the following logits for the next token. Inside generatetextsimple, we convert the logits to probabilities with the softmax function and obtain the token ID for the generated token with the argmax function; then we can map it back to text through the inverse vocabulary.
Because the largest logit value—and therefore the largest softmax probability score—is in the fourth position (index position 3, since Python uses zero-based indexing), the generated word is “forward.”
To implement a probabilistic sampling process, we can now replace argmax with the multinomial function in PyTorch:
torch.manual_seed(123)
next_token_id = torch.multinomial(probas, num_samples=1).item()
print(inverse_vocab[next_token_id])
##output
forward
The printed output is still “forward,” just as before. What happened?
The multinomial function samples the next token according to its probability score. In other words, “forward” is still the most likely token and will be selected by multinomial most of the time—but not every time. To illustrate this, let’s implement a function that repeats this sampling 1,000 times:
This means that if we replace argmax with the multinomial function in the generateandprint_sample function, the LLM will sometimes generate phrases such as “every effort moves you toward,” “every effort moves you inches,” and “every effort moves you closer” instead of “every effort moves you forward.”
We can further control the distribution and the selection process with a concept called temperature scaling. Temperature scaling is just a fancy way of saying that we divide the logits by a number greater than 0.
def softmax_with_temperature(logits, temperature):
scaled_logits = logits / temperature
return torch.softmax(scaled_logits, dim=0)
A temperature greater than 1 leads to a more uniform distribution of token probabilities, while a temperature less than 1 leads to a more confident (steeper or more peaked) distribution. Let’s illustrate this by plotting the original probabilities against probabilities scaled with different temperature values:

Figure 5.14 Temperature of 1 represents the unscaled probability score for each token in the vocabulary.
At a temperature of 1, the logits are divided by 1 before being passed to the softmax function to calculate probability scores. In other words, using a temperature of 1 is the same as applying no temperature scaling at all. In this case, the token selection probabilities equal the original softmax probability scores obtained through PyTorch’s multinomial sampling function.
As we can see in Figure 5.14, applying a very low temperature, such as 0.1, produces a sharper distribution, so the multinomial function behaves almost like the argmax function and selects the most likely token (here, “forward”) nearly 100% of the time. Likewise, a temperature of 5 produces a more uniform distribution, so other tokens are selected more often. This can add more variety to the generated text, but it is also more likely to produce nonsensical text.
Top-k sampling
We have now implemented a probabilistic sampling method and combined it with temperature scaling to increase output diversity. We found that higher temperature values lead to a more uniform distribution of next-token probabilities, which produces richer output because it reduces the chance that the model repeatedly selects the most likely token.
This approach allows the generation process to explore less likely but potentially more interesting and creative paths. However, one drawback is that it can sometimes produce grammatically incorrect or completely nonsensical output, such as “every effort moves you pizza.”
Top-k sampling, combined with probabilistic sampling and temperature scaling, can improve text generation results. In top-k sampling, we can restrict the tokens being sampled to the top-k most likely tokens and exclude all other tokens from the selection process by masking their probability scores, as shown in Figure 5.15.

Figure 5.15 With top-k sampling and k = 3, we focus on the three tokens associated with the highest logits and mask all other tokens with negative infinity (-inf) before applying the softmax function. This produces a probability distribution in which non-top-k tokens have a probability of 0.
The top-k method replaces all unselected logits with negative infinity (-inf), so when softmax is computed, the probability scores for non-top-k tokens become 0 and the remaining probabilities sum to 1.
Then we apply PyTorch’s where function to set the logit values of tokens below the lowest logit among our top three choices to negative infinity (-inf):
Finally, we apply the softmax function to turn these into next-token probabilities:
topk_probas = torch.softmax(new_logits, dim=0)
print(topk_probas)
## output
tensor([0.0615, 0.0000, 0.0000, 0.5775, 0.0000, 0.0000, 0.0000, 0.3610, 0.0000])
We can now apply temperature scaling and the multinomial function for probabilistic sampling, choosing the next token from these three nonzero probability scores. Next, we’ll implement this by modifying the text generation function.
Modifying the text generation function
Now let’s combine temperature sampling and top-k sampling to modify the generatetextsimple function we used earlier to generate text with an LLM, creating a new generation function.
Now let’s see how this new generation function works:
As we can see, the generated text is very different from the text we generated earlier with the generate_simple function (“Every effort moves you know,” was one of the axioms he laid...!). This is a memorized passage from the training set.