Decode with beam search
Greedy decoding picks the best next token each step and can miss a better full sentence. Beam search keeps the best B partial sequences at every step.
Write beam_search(log_prob_fn, start, beam, steps, eos). log_prob_fn(seq) returns a dict token -> log probability for the next token. Start from [start] with score 0.
Each step, extend every unfinished beam with every token, add log probs, and keep the top `beam` candidates by score (ties: compare sequences as lists, smaller first). A beam that ends in eos is finished: carry it forward unchanged and let it compete for a slot. Stop after `steps` steps or when all kept beams are finished. Return (best_sequence, best_score).
def beam_search(log_prob_fn, start, beam, steps, eos)Understand the idea
Greedy decoding grabs the single best next token every step and may miss a better full sentence. Beam search keeps the best B partial sequences at each step, scored by summed log probabilities. Like a chess player who keeps a few promising lines in mind instead of one. Worked example: from the start, token A has probability 0.6 and token B 0.4. After A, the best next token has 0.4; after B, the best has 0.9. Greedy picks A and ends with 0.6 x 0.4 = 0.24. Beam with B = 2 keeps both and finds B then 0.9: 0.4 x 0.9 = 0.36. In logs: ln 0.6 + ln 0.4 = -1.427 versus ln 0.4 + ln 0.9 = -1.022, and higher wins. A beam ending in eos is finished: carry it unchanged and let it compete with new candidates. Rule: each step expand unfinished beams by every token, add log probs, keep the top B (ties: smaller sequence as a list first), stop after the step limit or when all kept beams are finished. Translation and some speech models decode this way.