Decoding: Greedy, Sampling and Beam Search
🎲 What is decoding? A language model only gives a probability distribution over the next token. Decoding is the rule that turns those distributions into text: always take the most likely token (greedy), draw one at random after reshaping the distribution (temperature, top-k, top-p), or keep several candidate continuations and extend the best ones (beam search).
Mercor's machine learning engineer onsite followed a train-a-small-LLM project with Transformer fundamentals that included greedy, beam, top-k and top-p decoding (the question).
The Prompt
Each method is a few lines, so the interviewer grades exact semantics (what top-p keeps at the boundary, what temperature 0 means), batching, and a beam search that handles end-of-sequence correctly.
"You have a function that returns next-token logits for a batch of sequences. Implement greedy decoding, sampling with temperature, top-k and top-p, and beam search."
Clarifying Questions
You: What is the model interface? I'll assume step(seqs) takes (B, T) token ids and returns (B, V)
logits for the next token.
Interviewer: Yes. Treat it as a black box.
You: Is there an end-of-sequence token, and what happens to a sequence after it ends?
Interviewer: Yes, eos. A finished sequence keeps emitting eos as padding until all are done.
You: For top-p, do I keep the smallest set of tokens whose probabilities sum to at least p, including the one
that crosses p?
Interviewer: Yes. And temperature 0 should mean greedy.
You: For beam search, one prompt at a time is fine? And do you want length normalization?
Interviewer: One prompt. Add a length penalty exponent, default off.
What You'll Build
greedy(step, prompt, n, eos) -> (B, T + n'): argmax at every step.filter_logits(logits, temperature, top_k, top_p) -> (B, V): disallowed tokens set to-inf.sample(logits, temperature, top_k, top_p, generator) -> (B,): one token per row.beam_search(step, prompt, beam, n, eos, alpha) -> (score, seq): the best finished sequence.