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.

Signaturedef greedy_decode(step_fn, prompt, eos_id, max_new)

Example

if step_fn always prefers token 5 and eos_id is 5, greedy_decode returns [5].

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. Worked example: 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]. Rule: 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplegreedy_decode(lambda t: np.eye(6)[5], [1, 2], 5, 10)
  • Sample 2: countergreedy_decode(lambda t: np.eye(10)[(t[-1] + 1) % 10], [3], 7, 10)
  • Test 3: max newgreedy_decode(lambda t: np.eye(4)[len(t) % 3], [0], 3, 5)