PIXELBANKv9.1.0
Menu

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:

  1. Start with an empty sequence
  2. At each step, expand each beam by all vocab tokens
  3. Keep the top beam_width candidates (by total log-probability)
  4. 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:

Input:
3 2 3 2
-0.5 -1.0 -2.0
-0.8 -0.3 -3.0
-1.0 -0.5 -0.1
Output:
0 1
-0.8000
Reasoning:
  • We start with an empty sequence and expand it by all vocab tokens (0, 1, 2) with their corresponding log-probabilities: −0.5-0.5, −1.0-1.0, −2.0-2.0.
  • We keep the top 2 candidates (by total log-probability): tokens 0 and 1 with scores −0.5-0.5 and −1.0-1.0.
  • 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 −0.5+(−0.8)=−1.3-0.5 + (-0.8) = -1.3, −0.5+(−0.3)=−0.8-0.5 + (-0.3) = -0.8, −0.5+(−3.0)=−3.5-0.5 + (-3.0) = -3.5.
  • We keep the top 2 candidates: beams [0, 1] with a total log-probability of −0.8-0.8 and select this as the best sequence since further expansion will not improve the score due to the −0.8-0.8 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
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Beam Search Decoder - Hard | PixelBank