Rank finished beams with a length penalty

Why it matters Translation and summarisation decoders use this exact penalty.

Beam search favours short outputs because every token adds a negative log-prob. A length penalty fixes that.

Write rank_beams(beams, alpha). beams is a list of (tokens, sum_logprob). Score = sum_logprob / ((5 + len) / 6) ** alpha. Return the beams' indices sorted by score, best first (ties by index).

Signaturedef rank_beams(beams, alpha)

Example

rank_beams([([1], -1.0), ([1, 2, 3, 4], -2.0)], 1.0) gives scores -1 and -1.333, so [0, 1].

Understand the idea

Each token adds a negative log probability, so a beam's total score keeps falling as it gets longer. Without correction, beam search prefers short, often cut-off outputs. A length penalty divides the score by a factor that grows with length, so long beams are not unfairly punished. alpha controls how strong the correction is. Worked example: beam 0 has 1 token and sum log prob -1.0; beam 1 has 7 tokens and -1.8. With alpha 1: beam 0 factor (5 + 1) / 6 = 1, score -1.0; beam 1 factor (5 + 7) / 6 = 2, score -0.9. So the order is [1, 0]. With alpha 0 the factor is 1 for both, raw scores -1.0 and -1.8 win, and the order is [0, 1]. Rule: score = sum_logprob / ((5 + len(tokens)) / 6) ** alpha; sort indices by score descending, breaking ties by smaller index (a stable sort on the negated score does this). Multiplying instead of dividing makes long beams even worse. Used in: beam search for machine translation and summarisation, such as the length_penalty option in generation libraries.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplerank_beams([([1], -1.0), ([1, 2, 3, 4], -2.0)], 1.0)
  • Sample 2: long winsrank_beams([([1], -1.0), (list(range(20)), -3.0)], 1.0)
  • Test 3: alpha 0rank_beams([([1], -1.0), (list(range(20)), -3.0)], 0.0)