Sub topic 7
Generating text: greedy search, beam search and length controls
This chapter assumes you know what an encoder-decoder Transformer is, what cross-attention does, and how to call model.generate in Hugging Face Transformers. It covers how the decoder turns probabilities into text, and which settings you should change for summarisation and translation.
From probabilities to text
During training with teacher forcing, the decoder sees the correct previous tokens. At inference time it does not have them, so it generates one token at a time. This is called autoregressive decoding. At each step the decoder produces a probability distribution over the vocabulary. A decoding strategy decides which token to pick, appends it to the output, and feeds it back in. Generation stops when the model emits the end-of-sequence token or reaches a length limit.
The strategy matters because the best sequence is not the same as the best token at each step. The number of possible sequences grows exponentially with length, so the model cannot score all of them. Every strategy is a way to search that space cheaply.
The encoder runs once. Only the decoder loop repeats, and it reuses cached keys and values from earlier steps so that each new step is cheap.
Greedy search
Greedy search picks the highest-probability token at every step. It is fast and fully deterministic.
Its weakness is that an early choice cannot be undone. A token that looks best now may force a poor continuation later. In practice greedy output is often acceptable for short, well-constrained outputs, but it tends to be blander and more repetitive than beam search on translation and summarisation.
In generate, greedy search is the default when num_beams=1 and do_sample=False.
Beam search
Beam search keeps the num_beams best partial sequences (the beam) at each step. For each one it considers every possible next token, scores the extended sequences, and keeps the best num_beams overall. Scores are the sum of log-probabilities of the tokens so far.
A small example shows why this helps. Suppose a model must pick between two paths:
| Path | Token 1 prob. | Token 2 prob. | Joint prob. |
|---|---|---|---|
| A | 0.55 | 0.20 | 0.110 |
| B | 0.45 | 0.90 | 0.405 |
Greedy picks A at step one because 0.55 beats 0.45, and ends with a joint probability of 0.110. Beam search with two beams keeps both prefixes, sees that B wins after step two, and returns B.
Beam search is not guaranteed to find the single best sequence. It is a wider greedy search. Cost grows roughly linearly with num_beams in compute and memory, so a beam of 4 costs about four times as much as greedy per step.
Length normalisation
Because scores are sums of log-probabilities, every extra token lowers the score. Without correction, beam search favours short outputs. The length_penalty parameter divides the sequence score by length ** length_penalty.
length_penalty=1.0is the default and normalises by length.- Values above 1.0 favour longer outputs.
- Values below 1.0 favour shorter outputs.
length_penaltyonly affects beam search. It has no effect with greedy search.
The early_stopping flag controls when beam search stops. With True, it stops as soon as num_beams finished candidates exist. With False, it applies a heuristic and may keep searching. With "never", it searches until no better candidate can exist. Summarisation checkpoints such as facebook/bart-large-cnn ship with a generation config that sets these values, so check model.generation_config before overriding them.
Length controls
Length settings are the most important controls for summarisation, where output length is part of the task.
| Parameter | Meaning | Common mistake |
|---|---|---|
| `max_new_tokens` | Maximum number of generated tokens | Confusing it with `max_length` |
| `max_length` | Maximum total length of the output sequence (for an encoder-decoder, this is the decoder sequence) | Using it together with `max_new_tokens`, which then takes precedence |
| `min_length` / `min_new_tokens` | Block the end token until this length is reached | Setting it above what the source supports, which forces padding with invented content |
| `length_penalty` | Beam score normalisation | Expecting it to enforce a length |
These limits count tokens, not words or characters. A subword tokeniser splits rare words into several pieces, so 60 tokens is often about 40 to 45 English words. Languages such as German produce more tokens per word.
Note that max_length and min_length are measured in tokens of the target sequence. Setting max_length too low truncates the output mid-sentence. The model does not know it is about to be cut off, so it does not compress its content to fit.
Repetition controls
Encoder-decoder models, especially with greedy search, can loop. A phrase repeats until the length limit is hit. Three settings help.
no_repeat_ngram_size=3forbids any 3-token sequence from appearing twice. It is a hard rule. Use it carefully, because legitimate repetition, such as a person's name appearing twice in a summary, is blocked as well. A small value like 2 is almost always too strict for names and titles. Values of 3 or 4 are typical for summaries.repetition_penaltydivides the score of tokens that already appeared. A value around 1.1 to 1.3 is mild. Large values push the model toward odd synonyms.encoder_no_repeat_ngram_sizeprevents the output from copying n-grams from the input. It suits paraphrasing, but it is the wrong choice for extractive-style summaries and for translation of names.
Sampling and why it is usually not used here
You can set do_sample=True with temperature, top_k or top_p to draw tokens at random. That produces varied text, which suits open-ended generation. For summarisation and translation, the source largely fixes the correct content, so you normally want the most likely output, and beam search or greedy search is the standard choice. Sampling raises the chance of hallucinated details. If you do need several different candidates, for example to rerank them, use num_return_sequences with beam search or with sampling.
A comparison you can run
This script translates the same sentence with greedy search and with beam search, then prints each result and its sequence score. It uses the MarianMT model from earlier chapters.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "Helsinki-NLP/opus-mt-en-de"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
sentence = "The committee decided to postpone the decision until next month."
batch = tokenizer([sentence], return_tensors="pt")
settings = {
"greedy": dict(num_beams=1, do_sample=False),
"beam4": dict(num_beams=4, do_sample=False, length_penalty=1.0),
}
for label, kwargs in settings.items():
out = model.generate(
**batch,
max_new_tokens=64,
return_dict_in_generate=True,
output_scores=True,
**kwargs,
)
text = tokenizer.batch_decode(out.sequences, skip_special_tokens=True)[0]
score = out.sequences_scores[0].item() if "beam" in label else float("nan")
print(f"{label:6s} | {text} | score={score:.3f}")Two details are worth noting. First, sequences_scores exists only for beam search, so the script prints nan for greedy. Second, the beam score is length-normalised, so it is comparable across candidates of different lengths but not across different length_penalty values.
For short, simple sentences the two outputs are often identical. The gap appears on longer sentences with word-order choices, such as German verb placement.
Choosing settings for each task
| Task | Typical starting point | Reason |
|---|---|---|
| Translation | `num_beams=4` or `5`, `max_new_tokens` about 1.5 times the source token count | Beam search improves fluency, and translations are close to source length |
| News summarisation | `num_beams=4`, `min_length` and `max_length` set to the target range, `no_repeat_ngram_size=3`, `length_penalty=2.0` | Summaries must be much shorter than the source and should not loop |
| Very short outputs (headlines) | `num_beams=4`, small `max_new_tokens` such as 24 | Tight budget, so truncation risk matters |
| Latency-sensitive service | `num_beams=1` | Greedy is several times cheaper |
Treat these as starting points and tune on a held-out set of your own data, measured with the metrics from a later chapter.
Common errors
- Output cut mid-sentence.
max_new_tokensis too small for the content. Raise it, or lowermin_lengthexpectations and rely on a tighter prompt or fine-tuning. - Output is a copy of the first sentences. The model has learned extractive behaviour. Raise
length_penaltycarefully and check the checkpoint, sincebart-large-cnnis known for lead-sentence copying. - Repeated phrases. Add
no_repeat_ngram_size=3before reaching for a largerrepetition_penalty. - Beam search is slower than expected and memory errors appear. Memory scales with batch size times
num_beams. Reduce one of them. - Setting
length_penaltywithnum_beams=1. It has no effect, andgeneratemay warn. - Dropping special tokens by accident. Always pass
skip_special_tokens=Truetobatch_decodefor clean text, and remember that padding tokens appear in batched output.
Applying the controls to summarisation
This script summarises one article under two configurations so you can see how length controls change the result.
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
article = (
"The city council voted on Tuesday to expand the bike lane network by 40 kilometres "
"over the next three years. Supporters said the plan would reduce traffic and emissions, "
"while some shop owners worried about losing parking spaces near their stores. "
"The first new lanes are expected to open next spring."
)
short = summarizer(
article, max_length=30, min_length=10, num_beams=4,
no_repeat_ngram_size=3, do_sample=False,
)
longer = summarizer(
article, max_length=80, min_length=40, num_beams=4,
length_penalty=2.0, no_repeat_ngram_size=3, do_sample=False,
)
print("SHORT :", short[0]["summary_text"])
print("LONGER:", longer[0]["summary_text"])With a min_length of 40 tokens and an article of about 65 tokens, the longer setting forces the model to say more than the source supports comfortably, and it often repeats a sentence nearly verbatim. This shows why min_length should follow what the source can support, not an arbitrary target.
Exercise
A beam search with num_beams=4 produces one-word translations for long sentences. Name the cause and two settings you would change.
Show answer
Beam scores are sums of log-probabilities, so longer sequences score lower and beam search prefers short ones. Raise length_penalty above 1.0 to favour longer outputs, and set min_new_tokens (or min_length) so the end token is blocked until a sensible length. Also check that max_new_tokens is not too small.
Exercise
You apply no_repeat_ngram_size=2 to a news summariser and notice that a person's full name appears only once, with later mentions replaced by awkward words. Why does this happen, and what should you do?
Show answer
With a value of 2, any pair of consecutive tokens may appear only once in the output, so a name made of two or more tokens cannot be repeated. Raise the value to 3 or 4, or use a mild repetition_penalty instead, and check the result on examples that mention names several times.
Exercise
Greedy search gives a joint probability of 0.110 for a path, but another path has 0.405. Which setting lets the decoder find the second path, and does it guarantee finding the best possible sequence?
Show answer
Set num_beams greater than 1 (for example 2 or more) so that both prefixes are kept after the first step. It does not guarantee the best possible sequence, because beam search still prunes the space to num_beams candidates at each step.