KatInterview

Decoding Text from Next-Token Probabilities: Greedy vs Beam

Machine LearningModel answer
MediumModel answerMachine Learningbeam-searchdecodinglanguage-models

Last updated

Build a greedy decoder and a width-k beam search over a next-token model, return each sentence with its probability, and explain why long outputs score low and how to correct it.

A language model produces text one token at a time. You can query it through a function next_probs(prefix). It takes a tuple of the tokens emitted so far and returns a dictionary mapping each candidate next token to its probability. The probabilities from a single call sum to 1.

The vocabulary contains a special end-of-sentence token eos. Decoding ends when eos is produced or when max_len tokens have been generated, whichever happens first. The probability of a full sentence is the product of the conditional probabilities of its tokens, each conditioned on everything before it.

Part 1: Greedy decoding

Write greedy_decode(next_probs, eos, max_len). At every step it appends the single most probable next token. It returns (tokens, probability). Give the time complexity in terms of the sentence length and the vocabulary size.

Part 2: Beam search

Write beam_search(next_probs, eos, max_len, k). At every step it keeps the k best partial sentences rather than one. It returns the best sentence and its probability. Explain:

  • what each beam entry stores,
  • what happens to a path that has already emitted eos,
  • when the search stops,
  • the time, memory and model-call cost.

Part 3: Why long sentences score low (discussion, no code)

The sentence probability you return tends to be small for long sentences. Explain why, how this changes which sentence beam search prefers, and what you would change in the scoring or the search. Cover the difference between numerical underflow and selection bias, and how a correction can be tuned and can overcorrect.

Points to settle up front

State your assumptions about:

  • whether the distribution depends on the full prefix,
  • whether eos is included in the returned tokens and in the probability,
  • how ties are broken,
  • whether you report raw probability or log-probability,
  • what is returned when max_len is reached without eos.

Hints

Hint 1

Work in log space: add log-probabilities instead of multiplying probabilities, and convert with exp only when reporting. Pick a deterministic tie-break, such as the smaller token in sorted order.

Hint 2

For beam search, keep a list of (log_prob, tokens) entries. Move paths that end in eos to a finished list and expand only the live ones. Then pool all children of all live paths and keep the best k.

Hint 3

For the length discussion, think about every extra token multiplying the score by a number at most 1. Compare that with dividing the log-score by length (raised to a power alpha), and consider when finished and live hypotheses become comparable.