KatInterview

Greedy vs. Beam Search over a Next-Token Probability Table

Machine LearningModel answer
MediumModel answerMachine Learningbeam-searchgreedy-decodingsequence-models

Last updated

Decode a sequence from a bigram-style probability table using greedy search and beam search, and justify choices on ties, dead-ends, cycles, and length normalization.

You have a toy language model stored as a nested dictionary D. For every token t, D[t] maps each possible following token u to its conditional probability p(u | t). Generation begins at the special token '<START>' and a sequence is complete once the token '.' is emitted.

Part 1: Greedy decoding

Write a function that begins at '<START>' and repeatedly appends the most probable successor of the current token. It stops when '.' has been appended or when the current token has no usable successor. Return the generated tokens, including the final '.' if one was produced.

  • Provide both a recursive and an iterative implementation.
  • State the time and space complexity of each.

Part 2: Beam search

Write a function that performs beam search with width k, expanding level by level:

  1. Hold at most k partial sequences, ranked by cumulative log-probability.
  2. At each step, extend every live sequence with its k most probable successors.
  3. Pool the candidates and keep the best k.
  4. Continue until every sequence in the beam ends in '.'.

Return the single best sequence, and optionally the full top-k list.

In your write-up, explain how your design handles:

  • ties between equal scores or probabilities,
  • tokens that do not appear as keys in D,
  • cycles and dead-ends,
  • length normalization of scores,
  • termination criteria.

Part 3: Discussion and demo

Compare greedy and beam search in terms of output quality, cost, and typical applications. Run both implementations on a small example dictionary you construct, ideally one where greedy returns a worse sequence than beam search.

Hints

Hint 1

Work in log space: add log-probabilities instead of multiplying probabilities, which avoids underflow on long sequences. Skip any successor with probability 0.

Hint 2

Beam search with k = 1 collapses to greedy decoding. Use that as a sanity check for your implementation.

Hint 3

Decide up front how to handle finished hypotheses: carry them forward unchanged so they keep competing with live ones, and mark dead-ends as finished-but-incomplete.

Hint 4

Raw cumulative log-probability favors short outputs. Divide by length raised to a power alpha, and use a maximum-length cap so cycles cannot loop forever.