Beam Search Decoding
Key idea: keep the b highest-scoring partial sequences (sum of log-probs); expand each with every token, keep the top b; finished beams (EOS) are set aside. Greedy decoding is beam size 1 — and can miss the best sequence.
import numpy as np
def beam_search(step_logprobs, beam=3, max_len=5, eos=0):
"""step_logprobs(prefix) -> log-prob vector over the vocabulary for the next token."""
beams, done = [((), 0.0)], []
for _ in range(max_len):
cand = []
for seq, score in beams:
lp = step_logprobs(seq)
for tok in np.argsort(lp)[-beam:]:
cand.append((seq + (int(tok),), score + float(lp[tok])))
cand.sort(key=lambda c: c[1], reverse=True)
beams = []
for seq, score in cand[:beam]:
(done if seq[-1] == eos else beams).append((seq, score))
if not beams:
break
return max(done + beams, key=lambda c: c[1])
# toy model: first token 1 looks best (0.6) but leads to a weak continuation; token 2 (0.4) leads to a sure EOS
P = {(): [0.0, 0.6, 0.4], (1,): [0.3, 0.4, 0.3], (2,): [1.0, 0.0, 0.0]}
def model(seq):
p = np.array(P.get(seq, [1.0, 0.0, 0.0])) + 1e-12
return np.log(p)
greedy = beam_search(model, beam=1, max_len=2)
best = beam_search(model, beam=3, max_len=2)
assert greedy[0] == (1, 1) and best[0] == (2, 0) # beam finds the higher-probability sequence
print("ok greedy", greedy[0], round(np.exp(greedy[1]), 3), "beam", best[0], round(np.exp(best[1]), 3))