422. 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 1
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]].
Example 2
Input: table = TB, last_tokens = [2, 0], eos_id = 3, pad_id = 0, max_new = 5
Output: [[3, 0, 0], [1, 2, 3]]
Example 3
Input: table = TB, last_tokens = [0, 1, 3], eos_id = 3, pad_id = 0, max_new = 2
Output: [[1, 2], [2, 3], [0, 1]]
Constraints
tablehas shape(V, V)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Keep a bool finished array; use np.where to replace outputs of finished rows.
Hint 2
A bool array tracks finished rows.
Hint 3
np.where swaps in the pad id.
Hint 4
Check done.all() after each step.
Common mistakes
- Continuing to generate for finished rows.
- Stopping the whole batch when the first row finishes.
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.
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.
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)
Topics
Companies1
- xAI a candidate reported this question xAI Machine Learning Engineer Interview Questions | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.