Greedy vs. Beam Search over a Next-Token Probability Table
Machine LearningModel answerLast updated
Decode a sequence from a bigram-style probability table using greedy search and beam search, and justify choices on ties, dead-ends, cycles, and length normalization.
You have a toy language model stored as a nested dictionary D. For every token t, D[t] maps each possible following token u to its conditional probability p(u | t). Generation begins at the special token '<START>' and a sequence is complete once the token '.' is emitted.
Part 1: Greedy decoding
Write a function that begins at '<START>' and repeatedly appends the most probable successor of the current token. It stops when '.' has been appended or when the current token has no usable successor. Return the generated tokens, including the final '.' if one was produced.
- Provide both a recursive and an iterative implementation.
- State the time and space complexity of each.
Part 2: Beam search
Write a function that performs beam search with width k, expanding level by level:
- Hold at most
kpartial sequences, ranked by cumulative log-probability. - At each step, extend every live sequence with its
kmost probable successors. - Pool the candidates and keep the best
k. - Continue until every sequence in the beam ends in
'.'.
Return the single best sequence, and optionally the full top-k list.
In your write-up, explain how your design handles:
- ties between equal scores or probabilities,
- tokens that do not appear as keys in
D, - cycles and dead-ends,
- length normalization of scores,
- termination criteria.
Part 3: Discussion and demo
Compare greedy and beam search in terms of output quality, cost, and typical applications. Run both implementations on a small example dictionary you construct, ideally one where greedy returns a worse sequence than beam search.
Hints
Hint 1
Work in log space: add log-probabilities instead of multiplying probabilities, which avoids underflow on long sequences. Skip any successor with probability 0.
Hint 2
Beam search with k = 1 collapses to greedy decoding. Use that as a sanity check for your implementation.
Hint 3
Decide up front how to handle finished hypotheses: carry them forward unchanged so they keep competing with live ones, and mark dead-ends as finished-but-incomplete.
Hint 4
Raw cumulative log-probability favors short outputs. Divide by length raised to a power alpha, and use a maximum-length cap so cycles cannot loop forever.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Decoding looks for a high-probability path <START> → t1 → t2 → … → '.'. Under the table, a path's probability is the product of its transition probabilities. Multiplying many numbers below 1 underflows, so we sum log p instead. Ordering by sum of logs is identical to ordering by product.
- Greedy takes the argmax successor at each step and never reconsiders.
- Beam search keeps the
kbest partial paths per step. Withk = 1it is exactly greedy. Exact search over all paths is exponential in length, so beam search is a bounded-width heuristic approximation.
Part 1: Greedy
Iterative version:
def greedy_iter(D, max_len=100):
out, tok = [], "<START>"
while len(out) < max_len:
nxt = best_next(D, tok)
if nxt is None:
break
out.append(nxt)
if nxt == ".":
break
tok = nxt
return out
Recursive version, using an accumulator to avoid quadratic list concatenation:
def greedy_rec(D, max_len=100):
def go(tok, acc):
if len(acc) >= max_len:
return acc
nxt = best_next(D, tok)
if nxt is None:
return acc
acc.append(nxt)
return acc if nxt == "." else go(nxt, acc)
return go("<START>", [])
Shared helper:
def ranked_next(D, tok):
cand = [(u, p) for u, p in (D.get(tok) or {}).items() if p > 0]
return sorted(cand, key=lambda x: (-x[1], x[0])) # ties: alphabetical
def best_next(D, tok):
r = ranked_next(D, tok)
return r[0][0] if r else None
Complexity. With output length L and maximum branching factor b, each step scans b successors (the sort in the helper costs b log b, but a plain max gives O(b)). Time is O(L·b). The iterative version uses O(L) space for the output. The recursive version adds O(L) stack depth, and Python's recursion limit makes the iterative one safer for long outputs.
Part 2: Beam search
Each hypothesis is (tokens, logp, done). Per step:
- If all hypotheses are done, stop.
- Finished hypotheses are copied forward unchanged, so they continue to compete for slots.
- A live hypothesis with no usable successors is marked done but incomplete.
- Otherwise expand with the top-
ksuccessors, addinglog p, and setdonewhen the token is'.'. - Keep the best
kby ranking score usingheapq.nsmalleston(-score, tokens).
import heapq, math
def beam_search(D, k=3, max_len=50, alpha=0.0):
if k < 1:
raise ValueError("k must be >= 1")
norm = lambda toks, lp: lp / (max(len(toks), 1) ** alpha)
rank = lambda b: (-norm(b[0], b[1]), b[0])
beams = [((), 0.0, False)]
for _ in range(max_len):
if all(d for _, _, d in beams):
break
cands = []
for toks, lp, done in beams:
if done:
cands.append((toks, lp, True)); continue
last = toks[-1] if toks else "<START>"
nxt = ranked_next(D, last)[:k]
if not nxt:
cands.append((toks, lp, True)); continue
for u, p in nxt:
cands.append((toks + (u,), lp + math.log(p), u == "."))
beams = heapq.nsmallest(k, cands, key=rank)
final = sorted(beams, key=lambda b: (not (b[0] and b[0][-1] == "."),) + rank(b))
return [(list(t), lp) for t, lp, _ in final if t]
The first element is the best sequence, and the whole list is the top-k.
Design decisions
- Ties. Sort successors by
(-p, token)and sequences by(-score, tokens). This makes output deterministic. - Missing tokens and dead-ends. A token absent from
D, or whose successors all havep = 0, ends that hypothesis. It is returned without'.'. In the final ranking, sequences that did end with'.'are preferred over incomplete ones. - Cycles. A loop like
a → b → awith probability 1 never lowers the score, so it could run forever.max_lenguarantees termination, and truncated sequences are returned as they are. - Zero probabilities. Skipped, since
log 0 = -∞. - Length normalization. Every token adds a negative term, so raw scores favor short outputs. Rank by
logp / len^alpha.alpha = 0is raw log-probability, and values around 0.6 to 1.0 are typical. Apply it consistently both when pruning each step and when ranking the final list. - Termination. Stop when all beams are done or
max_lensteps have run. Without normalization you may also stop early once the best finished score is at least the best live score, because scores only decrease as sequences grow. This shortcut is invalid with normalization.
Correctness
Greedy is correct by construction: each step picks argmax p(u | t) and the loop always ends via '.', a dead-end, or max_len. For beam search, after each step the beam holds the k best hypotheses reachable by expanding the previous beam. This is not the global top-k, so beam search is a heuristic. Restricting each parent to its top-k successors loses nothing, since no parent can contribute more than k of the k survivors.
Complexity
| Time | Space | |
|---|---|---|
| Greedy (iterative) | O(L·b) | O(L) |
| Greedy (recursive) | O(L·b) | O(L) plus O(L) stack |
| Beam search | O(L·k·(b log b + L)) | O(k·L) |
The extra L term is tuple copying. Back-pointers remove it.
Part 3: Comparison and demo
Example where greedy fails:
D = {
"<START>": {"a": 0.6, "b": 0.4},
"a": {"x": 0.5, "y": 0.5},
"x": {".": 0.4, "z": 0.6},
"y": {".": 0.4, "z": 0.6},
"b": {".": 0.95, "q": 0.05},
}
Greedy takes a (0.6), then x (alphabetical tie), then z, and z has no successors, so it dead-ends without '.'. A width-2 beam keeps b alive and finds b . with probability 0.4 × 0.95 = 0.38, a complete sequence that beats the incomplete greedy path. The lesson is that an early locally best choice can lead to a poor path.
When to use which. Greedy is fastest, uses minimal memory, and is fine for low-latency or highly peaked distributions. Beam search costs roughly k times more and typically gives higher-likelihood outputs, which suits translation, summarization, and speech recognition. Larger beams can produce generic or overly short text, which is why length normalization matters. Open-ended generation usually uses sampling instead.
Common mistakes
- Multiplying probabilities instead of summing logs.
- Dropping finished hypotheses, so shorter complete ones disappear.
- Forgetting a
max_lencap and looping on cycles. - Comparing raw scores across different lengths without normalization.
- Treating beam search as exact.