Implement beam search over a table of per-step token log-probabilities
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Implement a basic beam search for token prediction, as used in large language model inference.
You are given a 2D list `log_probs` where `log_probs[step][token_id]` is the log-probability of choosing `token_id` at that `step`. You are also given an integer `beam_width`, the number of top candidates to keep at each step.
At each step, extend every current candidate sequence by every possible token, compute the cumulative score of each extension (the sum of its log-probabilities), and keep only the best `beam_width` candidates. After all steps are processed, return the final `beam_width` sequences ordered from highest cumulative score to lowest. Each sequence is a list of token IDs.
### Function Signature
```python
def beam_search(log_probs: list[list[float]], beam_width: int) -> list[list[int]]:
```
### Rules
- The search starts from one empty sequence with score `0.0`.
- `log_probs` is a fixed table: the log-probability of a token at a step is the same no matter which tokens came before it.
- The cumulative score of a sequence is the sum of the log-probabilities of its tokens, added in step order.
- Candidates are ranked by cumulative score, highest first. When two candidates have the same score, the one whose token list is lexicographically smaller ranks higher. The same ranking is used when pruning at every step and for the order of the returned list.
- Return exactly `beam_width` sequences, each of length `seq_len`.
### Constraints
- `1 <= seq_len <= 10`, where `seq_len == len(log_probs)`
- `1 <= vocab_size <= 20`
- `1 <= beam_width <= vocab_size`
- `log_probs` has shape `[seq_len][vocab_size]`
- Every log-probability is a negative float or zero
### Examples
```text
Input: log_probs = [[-0.5, -1.0, -2.0], [-0.3, -1.5, -0.8], [-1.0, -0.2, -0.9]], beam_width = 2
Output: [[0, 0, 1], [0, 2, 1]]
```
After step 0 the beams are `[0]` (score -0.5) and `[1]` (score -1.0). At step 1, `[0, 0]` scores -0.8 while `[0, 2]` and `[1, 0]` tie at -1.3, and the tie rule keeps `[0, 2]`; at step 2 the best extensions are `[0, 0, 1]` at -1.0 and `[0, 2, 1]` at -1.5, ahead of `[0, 0, 2]` at -1.7.
```text
Input: log_probs = [[-1.0, -1.0], [-1.0, -1.0]], beam_width = 2
Output: [[0, 0], [0, 1]]
```
Every sequence scores -2.0, so the tie rule decides: `[0, 0]` and `[0, 1]` are the two lexicographically smallest token lists.
```text
Input: log_probs = [[-1.0, -0.5], [-0.5, -1.0]], beam_width = 2
Output: [[1, 0], [0, 0]]
```
`[1, 0]` scores -1.0. `[1, 1]` and `[0, 0]` both score -1.5, and `[0, 0]` takes second place because it is lexicographically smaller, even though its parent `[0]` ranked below `[1]` after step 0.
Overview: Implement beam search over a table of per-step token log-probabilities, keeping the best beam_width partial sequences at each step and returning the final candidates ranked by cumulative score. It tests candidate expansion, pruning, and applying a deterministic tie-breaking rule.
Implement a basic beam search for token prediction, as used in large language model inference.
You are given a 2D list `log_probs` where `log_probs[step][token_id]` is the log-probability of choosing token `token_id` at step `step`, and an integer `beam_width`, the number of top candidates to keep at each step. Let `seq_len = len(log_probs)` and let `vocab_size` be the length of each row.
At each step, extend every current candidate sequence by every possible token, compute the cumulative score of each extension, and keep only the best `beam_width` candidates. After all steps are processed, return the final `beam_width` sequences ordered from highest cumulative score to lowest. Each sequence is a list of token IDs.
Rules:
- The search starts from one empty sequence with score `0.0`.
- `log_probs` is a fixed table: the log-probability of a token at a step is the same no matter which tokens came before it.
- The cumulative score of a sequence is the sum of the log-probabilities of its tokens, added in step order (start at `0.0`, add the step 0 value, then the step 1 value, and so on). Scores are double-precision floating-point values (`float` in Python, `number` in JavaScript, `double` in Java and C++).
- Candidates are ranked by cumulative score, highest first. When two candidates have the same score, the one whose token list is lexicographically smaller ranks higher. The same ranking is used when pruning at every step and for the order of the returned list.
- Return exactly `beam_width` sequences, each of length `seq_len`.
Every value in the output is a token ID below 20, so no integer here comes near 2^31-1.
Example 1:
Input: log_probs = [[-0.5, -1.0, -2.0], [-0.3, -1.5, -0.8], [-1.0, -0.2, -0.9]], beam_width = 2
Output: [[0, 0, 1], [0, 2, 1]]
After step 0 the beams are [0] (score -0.5) and [1] (score -1.0). At step 1, [0, 0] scores -0.8 while [0, 2] and [1, 0] tie at -1.3 (the sums -0.5 + -0.8 and -1.0 + -0.3 are exactly equal in double arithmetic), and the tie rule keeps [0, 2]. At step 2 the best extensions are [0, 0, 1] at -1.0 and [0, 2, 1] at -1.5, ahead of [0, 0, 2] at -1.7.
Example 2:
Input: log_probs = [[-1.0, -0.5], [-0.5, -1.0]], beam_width = 2
Output: [[1, 0], [0, 0]]
[1, 0] scores -1.0. [1, 1] and [0, 0] both score -1.5, and [0, 0] takes second place because it is lexicographically smaller, even though its parent [0] ranked below [1] after step 0.
Constraints
- 1 <= seq_len <= 10, where seq_len == len(log_probs)
- 1 <= vocab_size <= 20
- 1 <= beam_width <= vocab_size
- log_probs has shape [seq_len][vocab_size]
- Every log-probability is a negative float or zero
- Every log-probability is finite and at least -100.0
Examples
Input: ([[-0.5, -1.0, -2.0], [-0.3, -1.5, -0.8], [-1.0, -0.2, -0.9]], 2)
Expected Output: [[0, 0, 1], [0, 2, 1]]
Explanation: Example 1: -0.5 + -0.8 and -1.0 + -0.3 are exactly equal doubles, so [0, 2] and [1, 0] tie after step 1 and the tie rule keeps [0, 2].
Input: ([[-1.0, -0.5], [-0.5, -1.0]], 2)
Expected Output: [[1, 0], [0, 0]]
Explanation: Example 2: [0, 0] ties [1, 1] at -1.5 and takes second place on the token list even though its parent [0] ranked second after step 0.
Hints
- Begin with a single empty sequence at score 0.0 and process log_probs one row at a time, extending each kept sequence by every token of that row.
- Compare two candidates by score first, highest first, and only then by their token lists in lexicographic order; use that one comparison both for pruning and for the final order.
- Example 2 shows that a sequence whose parent ranked lower can still finish ahead, so the order of the parents does not settle the order of their children.