Beam Search
Summary
Beam search is a decoding method that keeps several of the most probable sequences (beams) at each step, which improves quality compared with greedy search.
How it works
Unlike greedy decoding, which chooses one best token, beam search carries B hypotheses (the beam width). At each step every possible continuation is generated for each hypothesis, and the B best by total probability are selected.
Parameters
- num_beams (B) — the number of beams. The more there are, the better the quality, but the higher the computational cost.
- length_penalty — a penalty for length. Positive values encourage long sequences, negative ones short sequences.
- early_stopping — stopping when all the beams have reached EOS.
Comparison with other methods
| Method | Quality | Speed | Use |
|---|---|---|---|
| Greedy | Low | High | Fast answers |
| Beam search | High | Medium | Machine translation, summarization |
| Sampling | Medium | Medium | Creative tasks |
Example
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
model = AutoModelForSeq2SeqLM.from_pretrained("t5-small")
tokenizer = AutoTokenizer.from_pretrained("t5-small")
inputs = tokenizer("translate English to German: The house is wonderful.", return_tensors="pt")
outputs = model.generate(**inputs, num_beams=5, length_penalty=0.6)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
Limitations
- High computational cost.
- A tendency to repeat (this can be countered with no_repeat_ngram_size).
- Not suitable for creative tasks where variety is needed.
Diagram
graph TD
A[Start] --> B[Hypothesis 1]
A --> C[Hypothesis 2]
B --> D[Continuations]
C --> E[Continuations]
D --> F[Pick top B]
E --> F
F --> G[Next step]