Code Lab / Challenge 15

Beam Search with Length Normalization

MediumBeam search with length normalisation

The problem, as an interviewer would set it

Implement beam search over an injected next-token function, with the language
model mocked out so decoding is deterministic and testable.

Model protocol - `step_fn(prefix) -> np.ndarray` of shape (V,), the
log-probabilities of the next token given the token list `prefix`.

Implement:

    beam_search(step_fn, start_token, beam_width, max_len, eos_id,
                length_penalty=0.0) -> list[tuple[list[int], float]]

    - a beam is the token list generated after start_token; the prefix handed
      to step_fn is [start_token] + tokens
    - carry a CUMULATIVE LOG-PROBABILITY per beam: add log-probs, never
      multiply probabilities
    - each step scores all B * V continuations at once and keeps the best B
      via np.argpartition (O(B*V), not a full O(B*V log(B*V)) sort)
    - a beam whose new token is eos_id is parked in a `completed` list and
      never expanded again; the survivors carry on, and beams still alive at
      max_len are completed as they stand
    - the reported score is the GNMT length normalization (Wu et al., 2016),
      with len the number of generated tokens:
          score = logp / ((5 + len) / 6) ** length_penalty
    - return at most beam_width (tokens, score) pairs, best score first
    - an eos_id outside the vocabulary disables early stopping
What interviewers look for

Accumulating log-probs instead of multiplying, parking finished beams, what the length penalty buys

A strong solution demonstrates:
- Why decoding lives in log space: 800 tokens at an average probability of
  0.25 each is 0.25**800 ~ 2e-482, far below float64's smallest subnormal
  (~5e-324), so the product is exactly 0.0. Sums stay representable,
  products do not.
- Beam width is one dial, greedy decode at one end (B=1) and exhaustive search
  at the other (B >= V**max_len). Everything between is a heuristic with no
  optimality guarantee, so a wider beam can still score worse on the metric
  you care about.
- Beam search is biased towards short sequences: every extra token adds a
  negative log-prob, so EOS looks attractive early. Length normalization
  divides that bias out, and alpha is a real tuning knob.
- Finished beams are results, not candidates. Parking them leaves the live set
  free for hypotheses that can still improve. This version lets the live set
  shrink as beams finish; Hugging Face transformers instead keeps the top 2B
  candidates per step so B beams stay alive, a trade of compute for recall.
Common mistakes: multiplying probabilities and underflowing to zero;
re-expanding a beam that already emitted EOS, which puts EOS mid-output;
killing the whole search when the top beam finishes; ranking raw log-probs
against normalized scores in the same list; sorting all B*V candidates when a
partition suffices; quoting a length_penalty value without saying which
formula it feeds (transformers divides by len**alpha, not the GNMT form).
Follow-ups: the GNMT coverage penalty; diverse beam search; batching all B
prefixes through one forward pass with a shared, copy-on-write KV cache;
min_len by masking EOS; why search suits closed-ended tasks (translation, ASR) while
open-ended generation samples instead, since high-likelihood text degenerates
into repetition (Holtzman et al., 2020); why chat LLM serving rarely offers
beam search (up to B times the KV cache, poor fit with continuous batching).

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge