Beam Search Decoder
Implement beam search decoding for text generation.
Given a vocabulary and a function that returns log-probabilities for the next token given a sequence, perform beam search:
- Start with an empty sequence
- At each step, expand each beam by all vocab tokens
- Keep the top beam_width candidates (by total log-probability)
- Stop after max_length steps or when all beams end with EOS
For simplicity, log-probabilities are provided as a matrix: logprobs[step][token_id].
Input:
- Line 1: vocab_size beam_width max_length eos_id
- Next max_length lines: log-probability rows (vocab_size floats each)
Output: The best sequence (space-separated token IDs, excluding EOS) and its score rounded to 4 decimal places.
Example
3 2 3 2 -0.5 -1.0 -2.0 -0.8 -0.3 -3.0 -1.0 -0.5 -0.1
0 1 -0.8000
- We start with an empty sequence and expand it by all vocab tokens (0, 1, 2) with their corresponding log-probabilities: , , .
- We keep the top 2 candidates (by total log-probability): tokens 0 and 1 with scores and .
- At the next step, we expand each beam by all vocab tokens and calculate their total log-probabilities, e.g., for beam [0], we have , , .
- We keep the top 2 candidates: beams [0, 1] with a total log-probability of and select this as the best sequence since further expansion will not improve the score due to the being the highest among all possible expansions.
Constraints
- 1 <= beam_width <= 10, 1 <= max_length <= 10
- 0 <= eos_id < vocab_size
- If beam hits EOS, it's a complete beam (don't extend further)
- Pick the best complete beam. If none, pick best incomplete beam