Skip to content
Module 3 ยท Training and Generation
Chapter 15 of 17
Run it in your browser

Chapter 15: Greedy and Sampling

The map with New Text highlighted Figure 15.1: We are ready to generate new text with the trained model.

So far we've trained and loaded our model. Now we'd like to actually use it to generate some text. However, our model outputs a list of 65 scores (also known as logits), one for each possible character. We need to devise a strategy to choose a winner. In this chapter you will:

  • Generate text by always choosing the highest-scoring character (greedy decoding).
  • Generate text by choosing characters randomly based on their probabilities (sampling).
  • Compare the trade-offs between deterministic and creative text generation.

Words to Know

  • Greedy Decoding: always picking the single highest-probability token.
  • Sampling: choosing the next token randomly, giving higher-probability tokens a better chance to be selected.

Theory

Greedy Decoding

One method we can use is simply selecting the most likely token each time. This is known as greedy decoding.

Although we may want to select the "best" answer every time, the problem with this is we will frequently get into a loop. Suppose our model knows a phrase. It will select the next most likely token for that phrase. Now that token is included in the context so it will select the next token in that phrase. And so on it will repeat that phrase infinitely.

Since we are always choosing the most likely token greedy decoding is a deterministic method. Given the same prompt, we will receive the same output.

Sampling

We can avoid getting stuck in loops with something called sampling. Rather than automatically choosing the highest-scoring character, we convert the raw scores (also called logits) to percentages (probabilities) and pick a winner at random.

Argmax taking the tallest bar, and sampling from the distribution Figure 15.2: Greedy decoding always takes the tallest bar, and sampling draws randomly from the distribution.

When there's a 60% chance of the letter e occurring it will occur 60% of the time. When x has a 1% chance it will be selected less often. But there's still a chance it can happen. Which is good as it breaks the loop and makes your text more interesting. Downside being you won't get the same text each time it runs because it will select a different draw. All code snippets in this book use a seed (torch.manual_seed(42)) to lock the draw so when you run it you'll receive the same text.

Generation takes New Text back to the Tokens step on our "where we are" map. We generate one character and append it to our prompt then loop back.

In Business

With our house-style assistant, greedy or sampling depends on the job. You want greedy decoding if the assistant is reading out an answer to a factual question from your company manual. It should be predictable (even though greedy can still be wrong). You want sampling if it is writing a creative marketing email in your company voice. It should be varied, creative, and try new things.

Code

We implement both strategies in the same generation loop. The core difference is how next_id is chosen.

src/ch14_generate_greedy.py (excerpt)
def generate_greedy(model, prompt, encode, decode, cfg, max_new_tokens=200):
    # Always picks the token with the highest predicted score
    ids = torch.tensor([encode(prompt)], dtype=torch.long)
    for _ in range(max_new_tokens):
        ctx     = ids[:, -cfg.block_size:]
        logits  = model(ctx)
        next_id = logits[:, -1, :].argmax(dim=-1, keepdim=True)
        ids     = torch.cat([ids, next_id], dim=1)
    return decode(ids[0].tolist())

def generate_sample(model, prompt, encode, decode, cfg, max_new_tokens=200):
    # Picks the next token randomly based on the model's probabilities
    ids = torch.tensor([encode(prompt)], dtype=torch.long)
    for _ in range(max_new_tokens):
        ctx    = ids[:, -cfg.block_size:]
        logits = model(ctx)
        probs  = F.softmax(logits[:, -1, :], dim=-1)
        next_id = torch.multinomial(probs, num_samples=1)
        ids = torch.cat([ids, next_id], dim=1)
    return decode(ids[0].tolist())

Line 7 picks the character with the single highest score for greedy decoding. Lines 17 and 18 turn the scores into probabilities and draw a winner randomly for sampling.

Code flow: model(ctx) gives logits, argmax or multinomial picks next_id, which is appended to context Figure 15.3: The generation loop predicts one character at a time and appends it to the context.

You may have noticed we are using ids[:, -cfg.block_size:], which will grab only the last block_size tokens of our current text (the context) before we pass it to the model. We need to keep this as our model was trained to only understand a max of our block size which is 128. So we want to give our model no more than that. Notice that we use logits[:, -1, :] since we only care about what score the next letter will be at the last position.

As you can see there are two ways to go about this using ROMEO:\n as our prompt.

Terminal
$ python src/ch14_generate_greedy.py
--- GREEDY (always picks highest-score token) ---
ROMEO:
I will the come the some the stand the son,
And the so shall the see the shall the see the stand
...
--- SAMPLING (picks randomly from distribution) ---
ROMEO:
My must greather, but what it? whom, he ere.

EBRUTUS:
Morcy there bagainVain, I will ever may
To epated as great that the appral tankswain
...
--- Observations ---
Greedy tends to be more repetitive.
Sampling is more varied but can make unexpected choices.
Terminal
$ python diagrams/charts/ch15_probabilities.py
Saved ch15-probabilities.png and ch15-probabilities.pdf

Bars comparing greedy and sampling on the same probabilities Figure 15.4: Greedy always picks the tallest bar. Sampling can pick any bar, in proportion to its height.

What just happened:

  • The greedy approach quickly got stuck in a repetitive loop ("the shall the shall...").
  • The sampling approach produced varied, non-repetitive text, but it included some strange spellings ("greather", "bagainVain") because it occasionally picked low-probability characters.

Shape Check

Table 15.1 lists the shapes used during the character prediction step.

Table 15.1: Tensors used during the text generation loop.

Tensor Shape What it means
logits[:, -1, :] [1, 65] 65 vocabulary scores for the final character in the sequence.
next_id [1, 1] 1 chosen character ID.

Try It

Try It

Different starting prompts create different context for the model. The script below shows how sampling handles new prompts.

src/examples/ch15_different_prompts.py (excerpt)
1
2
3
4
5
6
7
8
9
# ...
encode_fn = lambda s: encode(s, char_to_id)
decode_fn = lambda ids: decode(ids, id_to_char)

print(f"--- Prompt: 'KING:\\n' ---")
print(generate_sample(model, "KING:\n", encode_fn, decode_fn, cfg, 50))

print(f"\n--- Prompt: 'JULIET:\\n' ---")
print(generate_sample(model, "JULIET:\n", encode_fn, decode_fn, cfg, 50))

Lines 6 and 9 generate new text starting from two different prompts.

Terminal
$ python src/examples/ch15_different_prompts.py
--- Prompt: 'KING:\n' ---
KING:
My mine gore to kink on Villence,
For my love grin

--- Prompt: 'JULIET:\n' ---
JULIET:
What reason this bagainVain, I will evers,
As do p

Key Takeaways

  • Greedy decoding always chooses the highest-scoring token, which leads to predictable but repetitive text.
  • Sampling chooses the next token randomly based on the probability distribution, and the text comes out varied and natural.
  • The generation loop works by predicting one character, appending it to the context, and repeating the process.
  • We crop the input context to the model's maximum block_size before each prediction.

Check Your Understanding

  1. Why does greedy decoding often get stuck repeating the same phrase?
  2. What PyTorch function do we use to randomly pick a token based on its probabilities?
  3. Why do we slice the logits tensor with [:, -1, :] in the generation loop?

Assignment

Assignment 15: Which half changes

About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.

  1. Run it. Run src/ch14_generate_greedy.py as it is. Copy the text under the GREEDY heading and the text under the SAMPLING heading.
  2. Change one number. In the demo part of the file, find torch.manual_seed(42). The seed fixes the random draws, so every run of the script picks the same characters. Change 42 to any whole number you like and run the script again.
  3. Compare. Which of the two texts changed? Which one is the same, character for character? In the greedy text, which words keep coming back?
  4. Explain it. In two or three sentences a manager could follow, say which rule you would choose for a task that must give the same answer every time, and what you give up by choosing it.

Hand in: both pairs of texts, your answers to step 3, and your sentences.

Further Reading

Why always picking the likeliest word goes wrong. Always taking the highest-scoring next token, which Chapter 15 calls greedy decoding, produces flat and repetitive text, and this paper shows that this happens because human writing is not made of the most predictable word at every turn. Their alternative keeps the smallest set of tokens whose probabilities add up to a chosen share and samples from that. How you choose the next token matters as much as how well the model was trained.

Holtzman, A., Buys, J., Du, L., Forbes, M., & Choi, Y. (2019). The curious case of neural text degeneration (arXiv:1904.09751). arXiv. https://doi.org/10.48550/arXiv.1904.09751

Next up: Chapter 16: Temperature and Top-k