Quick 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 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

  1. 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.
  2. 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.
  3. 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.

Beam Search over a Fixed Log-Probability Table

mediumMicrosoftSoftware Engineer

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.

Examples

Example 1
Input
([[-0.5, -1.0, -2.0], [-0.3, -1.5, -0.8], [-1.0, -0.2, -0.9]], 2)
Output
[[0, 0, 1], [0, 2, 1]]
Notes
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].
Example 2
Input
([[-1.0, -0.5], [-0.5, -1.0]], 2)
Output
[[1, 0], [0, 0]]
Notes
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.

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

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def beam_search(log_probs: list[list[float]], beam_width: int) -> list[list[int]]:
Sample call
beam_search([[-0.5, -1.0, -2.0], [-0.3, -1.5, -0.8], [-1.0, -0.2, -0.9]], 2)
Language
Case 1
Input
([[-0.5, -1.0, -2.0], [-0.3, -1.5, -0.8], [-1.0, -0.2, -0.9]], 2)
Expected
[[0, 0, 1], [0, 2, 1]]
Case 2
Input
([[-1.0, -0.5], [-0.5, -1.0]], 2)
Expected
[[1, 0], [0, 0]]

Browse More Questions

Show the approach

Approach

Keep the current beams as (token list, score) pairs, starting from one empty list with score 0.0. For each row of log_probs, build every extension of every beam: append each token ID and add that row's value to the parent's score, so each sum is formed in step order. That gives at most beam_width * vocab_size <= 400 candidates per step. Sort them by score from highest to lowest, ordering equal scores by token list in ascending lexicographic order, and keep the first beam_width. After the last row the kept beams are already in the required output order, so return their token lists.

Invariant: after each step the beam holds the beam_width highest-ranked extensions of the previous beam under the stated ranking. All candidates at a step have the same length and are distinct, so the ranking is a strict total order and the answer is unique. The full candidate pool has to be re-sorted at every step: a child of a lower-ranked parent can outrank a child of a higher-ranked parent, and equal scores are ordered by the whole token list, which can disagree with parent rank or insertion order (Example 2 shows both).

Edge cases: beam_width <= vocab_size means step 0 already yields at least beam_width candidates, so exactly beam_width sequences come back. With vocab_size 1 the only answer is the all-zero sequence. With beam_width 1 the search takes the best token at each step and the smallest token ID on a tie. Scores use only additions in one fixed order, so the same double values, and the same ties, appear in every language.

Time complexity:
O(L^2 * B * V * log(B * V)), with L = seq_len, V = vocab_size, B = beam_width (each token-list copy or comparison costs O(L))
Space complexity:
O(L * B * V)