415. Greedy decode until end of sequence
Why it matters Greedy decoding is the default for structured outputs and evals at temperature 0.
Greedy decoding picks the arg-max token each step and stops at EOS.
Write greedy_decode(step_fn, prompt, eos_id, max_new). step_fn(tokens) returns a 1D array of logits for the next token. Append argmax tokens until eos_id is produced (include it) or max_new tokens are added. Return only the new tokens.
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def greedy_decode(step_fn, prompt, eos_id, max_new)Example 1
if step_fn always prefers token 5 and eos_id is 5, greedy_decode returns [5].
Example 2
Input: step_fn = lambda t: np.eye(6)[5], prompt = [1, 2], eos_id = 5, max_new = 10
Output: [5]
Example 3
Input: step_fn = lambda t: np.eye(10)[(t[-1] + 1) % 10], prompt = [3], eos_id = 7, max_new = 10
Output: [4, 5, 6, 7]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
A simple loop; check for EOS after appending.
Hint 2
Append the new token to the context each step.
Hint 3
Stop after emitting EOS.
Common mistakes
- Not feeding generated tokens back in.
- Dropping the EOS token from the output.
Understand the idea
Greedy decoding is the simplest way to generate text: at each step ask the model for next-token logits, take the single most likely token, add it to the context, and repeat. You stop when the model produces the end-of-sequence token or you hit a maximum number of new tokens.
prompt [1], and a step function whose best next token is always the last token plus 1, eos_id 4, max_new 10. Step 1 sees [1] and picks 2. Step 2 sees [1, 2] and picks 3. Step 3 sees [1, 2, 3] and picks 4, which is EOS, so it is included and decoding stops. The result is [2, 3, 4]. With max_new 2 it would stop at [2, 3].
tokens = copy of prompt; loop at most max_new times: logits = step_fn(tokens), t = argmax(logits), append t to both tokens and the output, break if t == eos_id; return only the new tokens
The context must grow every step, or the model keeps seeing the same prompt. Used in: deterministic LLM generation for evals, tests and structured outputs at temperature 0.
Topics
Companies2
- Cohere a candidate reported this question Cohere Machine Learning Engineer Interview Questions | Screna AI
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.