Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 11-beam-search-decoding.jsJavaScript

Beam Search Decoding Over a Next-Token Table

Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.

Same file as in the repo · ~20s timeout

From file header (JSDoc)

Beam Search Decoding Over a Next-Token Table

Problem: Greedy decoding can miss the most likely sequence. Implement beam
search over a toy bigram language model `table` where `table[token]` is a
list of `[nextToken, probability]`. Decoding starts from "<s>" and a
hypothesis finishes when it emits "</s>". At each step expand every live
beam by all next tokens, score by total log-probability, and keep the best
`beamWidth` expansions (ties by lexicographic token sequence); expansions
ending in "</s>" move to the finished list. Stop after `maxLen` steps, when
no beams are live, or when the best finished score beats every live beam
(log-probabilities only decrease). Return `{ tokens, logProb }` for the best
finished hypothesis (or best live one if none finished), excluding "<s>"
and "</s>".

Constraints:
- 1 <= beamWidth <= 64, 1 <= maxLen <= 256, probabilities in (0, 1]

Example:
  <s> -> A 0.55 | B 0.45;  A -> C 0.4 | D 0.35 | E 0.25;  B -> F 0.9 | G 0.1
  C, D, E, F, G -> </s> 1.0
  beamWidth 1 (greedy) -> ["A", "C"]  p = 0.22
  beamWidth 2          -> ["B", "F"]  p = 0.405

Approach: Keep a list of live hypotheses; each step generates at most
beamWidth * V candidates, sorts them and keeps the top beamWidth. Working
in log space avoids underflow on long sequences. Time
O(maxLen * beamWidth * V * log(beamWidth * V)), space O(beamWidth * maxLen).
@param {Record<string, [string, number][]>} table
@param {number} beamWidth
@param {number} maxLen
@returns {{ tokens: string[], logProb: number }}
Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.