Beam search: keep more than one story alive

A toy sentence grows token by token. Widen the beam and watch weaker branches survive one more step; narrow it to one and watch a plausible path die. This is how many LLMs finish a reply.

y26w47

Last week the k-NN classifier let geometry vote with no hidden weights. The week before, softmax sampling rolled weighted dice for a single next token. Production LLMs often sit in the middle at decode time: they still score next tokens, but they keep several partial sentences alive instead of one greedy chain. That compromise is beam search, a staple of inference before chat interfaces made sampling fashionable again.

Each step, the model hypothetically forks every active path, adds candidate tokens with log-probability scores, then prunes to the top B branches. Widen B and a sleepy branch (“the cat sat on the mat”) can outlast a flashy early leader (“the cat ran away”). Shrink B to 1 and you are back to plain greedy decoding, fast but brittle.

How to play:

  1. Leave beam width at 2, press Expand one step twice, and watch two prefixes diverge after The cat.
  2. Switch to 1, reset, run again: the sitting-on-the-mat story may vanish after one step.
  3. Set 3 or 5, reset, hit Run to period, and read the ranked log scores on the survivors.
  4. Open Pruned this step and see which forks lost the score race.

Try this:

  1. Beam 1 through to the period: note which ending wins (often the short “ran away” chain).
  2. Same clicks with beam 5: a longer “sat on the mat” path should still appear in the list.
  3. After a full run, compare log scores: the winner is not always the shortest sentence.

Why this matters

Beam search is ancient in speech recognition and machine translation, and it still shows up when engineers want reproducible, slightly safer completions. Modern chat models often default to sampling (temperature, top-p) for personality, but the idea is the same fork-and-prune dance with extra randomness. Pair this toy with the transformer story and the GPT-3 scale jump, then peek at attention and softmax temperature to see where the scores come from.

Missed the earlier editions? Train a perceptron, watch a Markov chain babble, lose to unbeatable tic-tac-toe, teach a filter to see edges, watch an agent learn from reward, see how a model reads text in tokens, watch one roll downhill to learn, let a machine find groups on its own, see a line learn to bend, watch words decide who to listen to, explore vs exploit on slot machines, chat with ELIZA, scribble Hopfield memory, count words for spam, paint walls for A*, spin softmax temperature, or let neighbors vote.

Beam width

Active beams

    Beam search keeps the top B partial sentences after each decode step instead of betting on a single greedy chain. Real LLMs use the same trick to reduce silly dead ends while staying faster than exploring every path.