Run batched greedy decoding with per-row EOS tracking
Why it matters Batched serving and evaluation loops need per-row stop tracking, or finished answers grow junk tokens.
In a batch, rows finish at different times. Once a row emits EOS it must output only padding while the others keep going, and decoding stops when every row is done.
Write batched_greedy(table, last_tokens, eos_id, pad_id, max_new). The toy model is a logit table of shape (V, V): row t holds next-token logits after token t. last_tokens is the list of current last tokens, one per row. Each step: next = argmax of table[current] per row; rows that already finished emit pad_id instead; a row whose emitted token is eos_id becomes finished (the EOS itself is kept). Stop after max_new steps or once all rows are finished. Return an int array (B, steps_run).
def batched_greedy(table, last_tokens, eos_id, pad_id, max_new)Example
with table = 5 * np.eye(4)[[1, 2, 3, 0]] (0 to 1, 1 to 2, 2 to 3, 3 to 0), last_tokens [2, 0], eos 3, pad 0 and max_new 5, the result is [[3, 0, 0], [1, 2, 3]].
Understand the idea
When you generate for many prompts at once, each answer ends at its own time, like students leaving an exam hall as they finish. The hall closes only when the last one leaves.
Example: a toy model where token 0 leads to 1, 1 to 2, 2 to 3, and 3 is EOS. Row 0 starts at 2, so its first token is 3 (EOS) and it is finished. Row 1 starts at 0 and produces 1, 2, then 3. While row 1 continues, row 0 outputs padding: [3, pad, pad] and [1, 2, 3]. After step 3 both are done, so the loop stops.
Rule: next = argmax(logits) per row; next = pad where finished; finished |= (next == eos); stop when all finished or after max_new steps.
Real engines go further and remove finished sequences from the batch to free their KV cache slots, but the output still follows these rules.
Shapes and data flow
table (V, V); cur (B,) -> logits (B, V) -> next (B,); output (B, steps_run)