Sub topic 7
Generating Text: Greedy Search, Beam Search and Length Controls
This chapter assumes you know Python, PyTorch tensors, and the basic Transformer encoder-decoder structure. You should also know that the decoder generates one token at a time, using the source representation and the tokens it has already produced.
A model does not output one finished sentence directly. At each step, it produces a probability distribution over the vocabulary. A decoding strategy chooses the next token from that distribution. The choice affects fluency, accuracy, length, and repetition.
Autoregressive generation
Suppose the decoder has generated:
The council approvedIt assigns probabilities to possible next tokens:
| Candidate token | Probability |
|---|---|
| `a` | 0.42 |
| `the` | 0.18 |
| `40` | 0.12 |
| `yesterday` | 0.03 |
The decoder then selects a token and repeats the process. Generation stops when the model emits its end-of-sequence token or reaches a configured limit.
During generation, the decoder uses causal self-attention. This prevents it from looking at future output tokens. It also uses cross-attention to read relevant representations from the encoded source text.
Greedy search
Greedy search selects the highest-probability token at every step. In Transformers, it is commonly enabled with num_beams=1 and do_sample=False.
from transformers import pipeline
summarizer = pipeline(
"summarization",
model="facebook/bart-large-cnn",
)
article = (
"The city council voted to expand the bike lane network by 40 kilometres "
"over the next three years. Supporters said the plan would reduce traffic "
"and emissions."
)
result = summarizer(
article,
max_new_tokens=40,
min_new_tokens=10,
num_beams=1,
do_sample=False,
no_repeat_ngram_size=3,
)
print(result[0]["summary_text"])Greedy search is fast because it keeps only one partial sequence. However, the locally best token can lead to a poor sentence later. A token that looks likely now may block a better complete sequence.
Beam search
Beam search keeps several candidate sequences, called beams. At each step, it expands every beam with likely next tokens and retains the best candidates according to their cumulative score.
For example, with num_beams=4, the decoder explores up to four partial sequences at each step. This gives it a chance to recover from an early choice that was not globally best.
result = summarizer(
article,
max_new_tokens=40,
min_new_tokens=10,
num_beams=4,
do_sample=False,
no_repeat_ngram_size=3,
length_penalty=1.0,
)
print(result[0]["summary_text"])Beam search usually costs more memory and computation than greedy search. More beams do not guarantee better output. They can produce generic, overly short, or repetitive text, especially when the model's training objective does not match the task perfectly.
The length_penalty changes how sequence length affects beam scores. Values above 1.0 favour longer sequences, while values below 1.0 favour shorter ones. The exact effect depends on the model and library version, so validate settings on your own data.
Length and repetition controls
Generation limits serve different purposes:
max_new_tokenslimits the number of tokens produced. It does not count the input tokens.min_new_tokensprevents the decoder from stopping too early.max_lengthlimits the combined input and output length in many APIs.max_new_tokensis usually clearer.no_repeat_ngram_size=3blocks repeated three-token phrases.early_stopping=Truecan stop beam search when completed candidates are sufficient.length_penaltyadjusts the preference for longer or shorter candidates.
Use a minimum length carefully. If the source is short, forcing extra tokens can make the model add unsupported details. Repetition controls can also remove legitimate repeated phrases, such as names or formal headings.
For deterministic evaluation, use do_sample=False and record the decoding settings. Sampling options such as temperature, top_k, and top_p are useful when varied or creative outputs are acceptable, but they make repeated runs less predictable.
Exercise
Why can beam search produce a worse summary than greedy search even though it examines more candidate sequences?
Show answer
Beam search optimises the model's sequence score, not factual accuracy or human usefulness. Its scoring may favour short, generic, or repetitive text, and extra beams do not correct a model's weaknesses.