Continuous Batching Scheduler for Autoregressive Decoding
Medium · Coding & Algorithms · Machine Learning Engineer · Onsite
Problem Statement
Implement a continuous-batching scheduler that decodes multiple variable-length token sequences concurrently through a batched next-token prediction callable.
Request Specification
Each incoming job is represented by Request:
Request(
request_id: int,
prompt_tokens: List[int],
max_tokens: int,
stop_token: Optional[int] = None,
stop_sequence: Optional[List[int]] = None,
)
request_id: unique integer key identifying the request in the returned output map.prompt_tokens: initial integer token IDs passed into the model on the first step; prompt tokens are never included in the returned generated output.max_tokens: maximum number of newly generated tokens permitted (max_tokens >= 0; negative values raiseValueError).stop_token/stop_sequence: optional stopping rule; supplying both raisesValueError, and passing an emptystop_sequence([]) raisesValueError.- Mutating caller lists after constructing
Requestmust not affect the stored request fields.
Scheduler Behavior
Implement:
run_dynamic_batching(
requests: List[Request],
model_next: Callable[[List[List[int]]], List[int]],
batch_size: int,
on_finish: Optional[Callable[[int, List[int]], None]] = None,
) -> Dict[int, List[int]]
- Validation: Raise
ValueErrorifbatch_size < 1or if anyrequest_idappears more than once inrequests. - Slot admission (FIFO): Maintain at most
batch_sizeactive sequences at a time, filling open slots fromrequestsin arrival order. A request withmax_tokens == 0finishes immediately with[](invokingon_finish(request_id, [])if supplied) without occupying a batch slot or invokingmodel_next. - Batched step execution: While at least one slot holds an active sequence, gather the full token list (
prompt_tokens + generated_so_far) for every occupied slot (1 <= len(prefixes) <= batch_size, with no dummy padding) and callmodel_next(prefixes). Ifmodel_nextreturns a list whose length differs fromlen(prefixes), raiseValueError. - Token routing and completion: Append each returned token to the exact slot from which its prefix originated, even when earlier slots are empty. A sequence completes as soon as either condition holds:
- Stop match: Its generated tokens (excluding
prompt_tokens) end with[stop_token]orstop_sequence. Remove those trailing stop token(s) from its final output. - Token cap: Its generated token count reaches
max_tokens(if a stop rule also matched on that final token, still strip the stop token(s)).
- Stop match: Its generated tokens (excluding
- Refilling and callbacks: Whenever a sequence finishes, store its final generated token list under
results[request_id], invokeon_finish(request_id, final_tokens)once if provided, vacate its slot, and immediately admit waiting requests into any free slots before the nextmodel_nextcall. Guard internal buffers so in-place list mutations insidemodel_nextoron_finishcannot corrupt decoding state or returned results.
Examples
Example 1
Input:
batch_size = 2
requests = [
Request(101, prompt_tokens=[101], max_tokens=1),
Request(102, prompt_tokens=[102], max_tokens=3),
Request(103, prompt_tokens=[103], max_tokens=1),
]
# Scripted model emissions per request:
# 101 -> [50]
# 102 -> [61, 62, 63]
# 103 -> [70]
Output:
{101: [50], 102: [61, 62, 63], 103: [70]}
Explanation: Step 1 decodes [101, 102] ([[101], [102]] -> [50, 61]); request 101 reaches max_tokens = 1 and vacates slot 0, which immediately admits waiting request 103. Step 2 decodes [103, 102] ([[103], [102, 61]] -> [70, 62]); request 103 finishes and slot 0 stays empty because the queue is exhausted. Step 3 sends a partial batch of size 1 ([[102, 61, 62]] -> [63]), routing row 0 back to slot 1 and completing request 102 in 3 total model calls.
Example 2
Input:
batch_size = 2
requests = [
Request(10, prompt_tokens=[10, 4], max_tokens=5, stop_sequence=[4, 5]),
Request(20, prompt_tokens=[20], max_tokens=4, stop_token=99),
]
# Scripted model emissions per request:
# 10 -> [5, 8, 4, 5, 9]
# 20 -> [31, 99, 32, 33]
Output:
{10: [5, 8], 20: [31]}
Explanation: On step 1, request 10 emits 5; although prompt_tokens + generated ends with [4, 5], 4 came from the prompt, so generation continues. On step 2, request 20 emits 99, matching stop_token = 99 and finishing with [31] (99 stripped). Steps 3 and 4 advance request 10 alone, emitting 4 then 5; now the generated suffix [5, 8, 4, 5] ends with [4, 5], so it stops and strips [4, 5] to return [5, 8].
Constraints
batch_size >= 1(batch_size < 1raisesValueError).0 <= len(requests) <= 10^4, with allrequest_idvalues distinct (duplicates raiseValueError).max_tokens >= 0(max_tokens < 0raisesValueError).- At most one of
stop_tokenandstop_sequenceis non-None, and ifstop_sequenceis provided,len(stop_sequence) >= 1. - Every call to
model_next(prefixes)receives1 <= len(prefixes) <= min(batch_size, unfinished_active_requests)and must returnlen(prefixes)integers (mismatched lengths raiseValueError).
Step-by-step walkthrough
Understand the problem and lock down edge-case rules
Language models generate text by autoregressive decoding: at each step, the model takes a sequence of token IDs (
[prompt..., generated_so_far...]) and predicts the single next token ID, repeating until a stopping rule fires. We are givenmodel_next(batch_prefixes) -> next_tokens, which advances up tobatch_size(B) sequences at once.Before writing code, clarify and lock down the exact boundary rules:
max_tokenscounts only generated tokens, never prompt tokens. A request withmax_tokens = 0finishes immediately with[]without ever occupying a slot or callingmodel_next.- Stopping checks apply only to generated tokens. If
prompt_tokens = [10, 4]andstop_sequence = [4, 5], generating5on the first step ([10, 4, 5]) does not match because4came from the prompt. - Unify
stop_tokenandstop_sequence: A singlestop_token = 99behaves identically tostop_sequence = [99]. - Strip the stop tokens from the final output: If generation ends because of a stop rule (including on the exact
max_tokens-th token), remove the trailing stop token(s) from the returned list. - Admit waiting requests in FIFO (First-In, First-Out) arrival order.
from typing import Callable, Dict, List, Optional class Request: """One generation request.""" def __init__(self, request_id: int, prompt_tokens: List[int], max_tokens: int, stop_token: Optional[int] = None, stop_sequence: Optional[List[int]] = None): if stop_token is not None and stop_sequence is not None: raise ValueError("give a stop_token or a stop_sequence, not both") if stop_sequence is not None and len(stop_sequence) == 0: raise ValueError("stop_sequence must not be empty") if max_tokens < 0: raise ValueError("max_tokens must be >= 0") self.request_id = request_id # Copy input lists so external caller mutations cannot alter stored request specs. self.prompt_tokens = list(prompt_tokens) self.max_tokens = max_tokens self.stop_token = stop_token self.stop_sequence = None if stop_sequence is None else list(stop_sequence)Why dynamic batching beats static batching
During GPU token decoding at moderate batch sizes, each step spends most of its time loading model weights from GPU memory, so calling
model_nextonBsequences takes roughly the same wall-clock time as calling it on1sequence. Minimizing totalmodel_nextcalls therefore directly speeds up serving.Compare
B = 2on four requestsr0, r1, r2, r3that generate4, 1, 1, 2tokens (8tokens total):Sequential (1 at a time): 4 + 1 + 1 + 2 = 8 model calls Static batches of B=2: Batch 1 [r0(4), r1(1)] -> 4 calls (slot 1 sits idle for 3 steps!) Batch 2 [r2(1), r3(2)] -> 2 calls (slot 0 sits idle for 1 step!) Total = 6 model calls Dynamic batching (refill): Step 1: [r0, r1] -> r1 finishes! Refill slot 1 with r2 Step 2: [r0, r2] -> r2 finishes! Refill slot 1 with r3 Step 3: [r0, r3] Step 4: [r0, r3] -> both finish together! Total = 4 model calls (every single slot-step does useful work)Data structures: queue, fixed slots, and per-sequence state
We organize the engine around four explicit data structures:
waiting(deque[Request]): FIFO queue of pending requests not yet assigned a slot.slots(List[Optional[_Sequence]]of lengthB): Fixed slot table whereslots[slot_id]holds the active_Sequencein that slot, orNonewhen the slot is free. Keeping a request in the sameslot_iduntil completion mirrors real LLM engines, where each slot owns a dedicated region of GPU key-value cache memory.active_slot_ids(List[int]rebuilt each step): Maps compact batch rowrow -> slot_idfor non-empty slots. Whenever an earlier slot becomesNonewith an empty queue,rowandslot_iddiverge:
slots (B = 3): slot 0: None slot 1: req_7 slot 2: req_8 active_slot_ids: [1, 2] prefixes sent: row 0 -> req_7's tokens row 1 -> req_8's tokens next_tokens[row]: row 0 routes back to slots[active_slot_ids[0]] == slots[1] (NOT slots[0]!)results(Dict[int, List[int]]): Stores{request_id: generated_tokens}as each request finishes.
class _Sequence: """Mutable decoding state for one active request occupying a batch slot.""" def __init__(self, request: Request): self.request = request # tokens: full sequence [prompt..., generated...] fed to model_next at each step. self.tokens = list(request.prompt_tokens) self.prompt_len = len(request.prompt_tokens) # Normalize single stop_token into a 1-element list so stop checks have one code path. if request.stop_token is not None: self.stop = [request.stop_token] elif request.stop_sequence is not None: self.stop = request.stop_sequence else: self.stop = [] def num_generated(self) -> int: """Count how many tokens have been generated after the initial prompt.""" return len(self.tokens) - self.prompt_lenDetecting stop sequences without prompt bleed or reset bugs
After appending one newly predicted token to
seq.tokens, we check whether the generated output now ends withseq.stop. Two subtle bugs catch candidates here:- Prompt bleed: If
prompt_tokens = [10, 4]andseq.stop = [4, 5], generating5makesseq.tokens = [10, 4, 5]. Checkingseq.tokens[-2:] == [4, 5]alone would falsely match! Requiringseq.num_generated() >= len(seq.stop)guarantees every matched token was generated. - Overlapping partial matches: Suppose
seq.stop = [1, 2]and the model generates1, 1, 2:
Generated tokens: 1 1 2 Buggy match counter: 1 --> mismatch, reset 0 --> mismatch, stays 0 (MISSES stop!) Full suffix slice [-2:]: - [1, 1] != [1, 2] [1, 2] == [1, 2] (STOPS cleanly!)Comparing the trailing slice
seq.tokens[-stop_len:] == seq.stoptakesO(stop_len)per step and avoids reset bugs completely:def _hit_stop(seq: _Sequence) -> bool: """Return True if the generated suffix (excluding prompt tokens) ends with seq.stop.""" stop_len = len(seq.stop) # Require num_generated() >= stop_len so prompt tokens never contribute to a stop match. if stop_len == 0 or seq.num_generated() < stop_len: return False # Compare the full trailing slice to handle overlapping prefixes like [1, 1, 2] vs [1, 2]. return seq.tokens[-stop_len:] == seq.stop def _output(seq: _Sequence, stopped: bool) -> List[int]: """Extract generated tokens, stripping the trailing stop sequence if stopped is True.""" generated = seq.tokens[seq.prompt_len:] if stopped: stop_len = len(seq.stop) generated = generated[:len(generated) - stop_len] return generated- Prompt bleed: If
Admitting waiting requests into free slots
Whenever slots are initially empty or become
Noneafter a step,_refillwalksslot_idfrom0toB - 1and pops requests fromwaiting. If it pops a request withmax_tokens == 0, it records[]immediately and keeps popping insidewhile waiting:so that slot still gets filled by the next real request (and trailingmax_tokens == 0requests are drained right away).Notice the defensive copy in
_record: passinglist(tokens)toon_finishensures a caller callback that mutates its list argument cannot corruptresults[request_id].from collections import deque def _record(results: Dict[int, List[int]], on_finish: Optional[Callable[[int, List[int]], None]], request_id: int, tokens: List[int]) -> None: """Save final output for request_id and invoke optional callback with a defensive copy.""" results[request_id] = tokens if on_finish is not None: # Pass a shallow copy so callback mutations cannot corrupt results[request_id]. on_finish(request_id, list(tokens)) def _refill(slots: List[Optional[_Sequence]], waiting: deque, results: Dict[int, List[int]], on_finish: Optional[Callable[[int, List[int]], None]]) -> None: """Fill every None slot in `slots` from `waiting` in FIFO arrival order.""" for slot_id in range(len(slots)): if slots[slot_id] is not None: continue while waiting: request = waiting.popleft() if request.max_tokens == 0: # Zero-token requests complete immediately without taking a slot or model call. _record(results, on_finish, request.request_id, []) continue slots[slot_id] = _Sequence(request) breakAfter
_refillreturns, one key loop invariant always holds: either allBslots are occupied, orwaitingis completely empty.The decoding loop, compact row mapping, and termination
Each step of
run_dynamic_batchingruns five clean phases:- Collect
active_slot_ids: Scanslotsfor non-Noneindices. Ifactive_slot_idsis empty,break— by our_refillinvariant,waitingis guaranteed empty too! When1 <= len(active_slot_ids) < Bnear the end, we naturally send a smaller batch without dummy padding. - Copy prefixes (
list(seq.tokens)): Becausemodel_nextis an untrusted black box, handing it our internalseq.tokenslist directly would let a mutating model breaknum_generated() == max_tokensand cause an infinite loop. - Call
model_next(prefixes)and verifylen(next_tokens) == len(active_slot_ids). - Route tokens back via
enumerate(active_slot_ids): Appendnext_tokens[row]toslots[slot_id], checkstoppedormax_tokens(givingstoppedpriority so a stop sequence completed on the final allowed token is still stripped), record the output, and freeslots[slot_id] = None. - Call
_refillso newly freed slots are immediately reused on the very next step.
Why termination is guaranteed: Every iteration appends 1 token to at least 1 active sequence, and each sequence has a finite integer cap
max_tokens >= 1, so every admitted sequence must vacate its slot withinmax_tokenssteps.- Collect
Walk through Example 1 with slot refill and a partial batch
Trace
batch_size = 2on Example 1's three requests: -101: prompt[101],max_tokens = 1, model emits50-102: prompt[102],max_tokens = 3, model emits61, 62, 63-103: prompt[103],max_tokens = 1, model emits70Phase slots waiting active_slot_ids prefixes sent next_tokens ------------- ---------------------- ------- --------------- ------------------------ ----------- Initial refill [101: [101], 102:[102]] [103] - - - Step 1 call [101, 102] [103] [0, 1] [[101], [102]] [50, 61] Step 1 update 101 hits max=1 -> results[101]=[50], slots[0]=None; _refill puts 103 into slots[0]! Step 2 call [103, 102] [] [0, 1] [[103], [102, 61]] [70, 62] Step 2 update 103 hits max=1 -> results[103]=[70], slots[0]=None; _refill sees empty queue Step 3 call [None, 102] [] [1] [[102, 61, 62]] [63] Step 3 update row 0 maps to slot 1! 102 hits max=3 -> results[102]=[61, 62, 63], slots=[None, None] Step 4 check [None, None] [] [] -> break!Look closely at Step 3:
slots[0]isNoneandslots[1]holds102, soactive_slot_ids = [1]has length1 < B.next_tokens[0](63) routes cleanly throughactive_slot_ids[0] -> slot 1, returning{101: [50], 102: [61, 62, 63], 103: [70]}.Complete solution
from typing import Callable, Dict, List, Optional from collections import deque class Request: """One generation request. request_id: unique id; the result dictionary is keyed by it. prompt_tokens: the prefix the model starts from (never part of the output). max_tokens: maximum number of generated tokens (the prompt is not counted). stop_token / stop_sequence: at most one of them. Generation ends as soon as the generated tokens (not the prompt) end with it. The stop token(s) are removed from the returned output. """ def __init__(self, request_id: int, prompt_tokens: List[int], max_tokens: int, stop_token: Optional[int] = None, stop_sequence: Optional[List[int]] = None): if stop_token is not None and stop_sequence is not None: raise ValueError("give a stop_token or a stop_sequence, not both") if stop_sequence is not None and len(stop_sequence) == 0: raise ValueError("stop_sequence must not be empty") if max_tokens < 0: raise ValueError("max_tokens must be >= 0") self.request_id = request_id # Copy input lists so external caller mutations cannot alter stored request specs. self.prompt_tokens = list(prompt_tokens) self.max_tokens = max_tokens self.stop_token = stop_token self.stop_sequence = None if stop_sequence is None else list(stop_sequence) class _Sequence: """Mutable decoding state for one active request occupying a batch slot.""" def __init__(self, request: Request): self.request = request # tokens: full sequence [prompt..., generated...] fed to model_next at each step. self.tokens = list(request.prompt_tokens) self.prompt_len = len(request.prompt_tokens) # Normalize single stop_token into a 1-element list so stop checks have one code path. if request.stop_token is not None: self.stop = [request.stop_token] elif request.stop_sequence is not None: self.stop = request.stop_sequence else: self.stop = [] def num_generated(self) -> int: """Count how many tokens have been generated after the initial prompt.""" return len(self.tokens) - self.prompt_len def _hit_stop(seq: _Sequence) -> bool: """Return True if the generated suffix (excluding prompt tokens) ends with seq.stop.""" stop_len = len(seq.stop) # Require num_generated() >= stop_len so prompt tokens never contribute to a stop match. if stop_len == 0 or seq.num_generated() < stop_len: return False # Compare the full trailing slice to handle overlapping prefixes like [1, 1, 2] vs [1, 2]. return seq.tokens[-stop_len:] == seq.stop def _output(seq: _Sequence, stopped: bool) -> List[int]: """Extract generated tokens, stripping the trailing stop sequence if stopped is True.""" generated = seq.tokens[seq.prompt_len:] if stopped: stop_len = len(seq.stop) generated = generated[:len(generated) - stop_len] return generated def _record(results: Dict[int, List[int]], on_finish: Optional[Callable[[int, List[int]], None]], request_id: int, tokens: List[int]) -> None: """Save final output for request_id and invoke optional callback with a defensive copy.""" results[request_id] = tokens if on_finish is not None: # Pass a shallow copy so callback mutations cannot corrupt results[request_id]. on_finish(request_id, list(tokens)) def _refill(slots: List[Optional[_Sequence]], waiting: deque, results: Dict[int, List[int]], on_finish: Optional[Callable[[int, List[int]], None]]) -> None: """Fill every None slot in `slots` from `waiting` in FIFO arrival order.""" for slot_id in range(len(slots)): if slots[slot_id] is not None: continue while waiting: request = waiting.popleft() if request.max_tokens == 0: # Zero-token requests complete immediately without taking a slot or model call. _record(results, on_finish, request.request_id, []) continue slots[slot_id] = _Sequence(request) break def run_dynamic_batching(requests: List[Request], model_next: Callable[[List[List[int]]], List[int]], batch_size: int, on_finish: Optional[Callable[[int, List[int]], None]] = None) -> Dict[int, List[int]]: """Decode every request with at most `batch_size` sequences per model call.""" # Phase 1: validate batch capacity and ensure all request_ids are unique. if batch_size < 1: raise ValueError("batch_size must be >= 1") seen_ids = set() for request in requests: if request.request_id in seen_ids: raise ValueError(f"duplicate request_id {request.request_id}") seen_ids.add(request.request_id) # waiting: FIFO queue of pending Request objects, e.g. deque([req_2, req_3]). waiting = deque(requests) # slots: fixed-size table [seq_or_None, ...] of length batch_size mapping slot_id -> _Sequence. slots: List[Optional[_Sequence]] = [None] * batch_size # results: final map {request_id: [generated_token, ...]}. results: Dict[int, List[int]] = {} # Phase 2: admit initial batch before entering the step loop. _refill(slots, waiting, results, on_finish) # Phase 3: advance active sequences one token per step until all slots and queue are empty. while True: # active_slot_ids: maps compact batch row i -> slot_id (crucial when earlier slots are None). active_slot_ids = [] for slot_id in range(batch_size): if slots[slot_id] is not None: active_slot_ids.append(slot_id) # Because _refill ran right before this check, no active slots implies waiting is empty too. if not active_slot_ids: break # Copy each prefix list so a black-box model_next cannot mutate our internal _Sequence state. prefixes = [] for slot_id in active_slot_ids: seq = slots[slot_id] assert seq is not None prefixes.append(list(seq.tokens)) next_tokens = model_next(prefixes) if len(next_tokens) != len(active_slot_ids): raise ValueError( f"model returned {len(next_tokens)} tokens for {len(active_slot_ids)} sequences" ) # Phase 4: route each predicted token via active_slot_ids[row], check stop/limit, free finished slots. for row, slot_id in enumerate(active_slot_ids): seq = slots[slot_id] assert seq is not None seq.tokens.append(next_tokens[row]) stopped = _hit_stop(seq) reached_limit = seq.num_generated() == seq.request.max_tokens if stopped or reached_limit: final_tokens = _output(seq, stopped) _record(results, on_finish, seq.request.request_id, final_tokens) slots[slot_id] = None # Phase 5: immediately refill any freed slots from the waiting queue before the next step. _refill(slots, waiting, results, on_finish) return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of dynamic batching (also called continuous or iteration-level batching) like a four-stool ramen counter with a line of hungry customers outside, where the chef ladles one spoonful into every occupied bowl simultaneously each round. Under static batching, if three customers finish a small bowl in 1 round while the fourth orders an extra-large 6-round bowl, the three empty stools sit roped off for 5 rounds until the slow eater leaves before the next group can sit down. Under dynamic batching, the moment any customer finishes and leaves a stool, the host immediately seats the next waiting person from the FIFO (First-In, First-Out) queue onto that freed stool before the next round starts, while a small stool-number clipboard (active_slot_ids) ensures each spoonful lands in the right customer's bowl even when stools at the end of the shift sit empty.
Decoding requests one by one leaves B - 1 of the model's batch capacity unused on every call, while static batching stalls an entire batch behind its single longest generation. On the implementation side, the classic bug is indexing next_tokens[slot_id] directly instead of mapping batch_row -> slot_id: as soon as slot 0 finishes and the waiting queue is empty, model_next receives only the remaining active rows, so row 0 actually belongs to slot 1 rather than slot 0.
Walk through Example 1 with B = 2 and three requests (101, 102, 103) needing 1, 3, and 1 tokens:
1. Initial fill & Step 1: Seats [101, 102] into [slot 0, slot 1]. model_next generates 1 token for each (50 and 61); 101 hits its 1-token limit and finishes, freeing slot 0, which _refill immediately assigns to waiting 103.
2. Step 2: Runs at full batch size 2 on [103, 102], emitting 70 and 62. Request 103 finishes ([70]), freeing slot 0 with an empty waiting queue.
3. Step 3: active_slot_ids = [1] sends a partial 1-row batch for 102, routing next_tokens[0] = 63 back to slot 1 and completing all 5 generated tokens in 3 model calls instead of 4 under static batching or 5 sequentially.
Complexity
Let N be the number of requests, B the batch capacity, P the sum of all prompt lengths, T the total number of tokens emitted by model_next across all steps (including any matched stop tokens), k the maximum stop-sequence length, L the maximum single sequence length (prompt + generated), and S the number of model_next calls.
- Number of model calls (
S): Because_refillfills every available slot whenever requests wait, every call emits between1andBtokens (ceil(T / B) <= S <= T, withS = 0whenT = 0), andSis bounded below by the longest individual generation. - Engine bookkeeping time (excluding
model_nextitself):O(N + P + S * B + T * k + S * B * L)— queueingNrequests and copying prompts/outputs takesO(N + P + T); scanning allBslots to buildactive_slot_idsacrossSsteps takesO(S * B); checking the trailingk-token suffix after each emitted token takesO(T * k); and copying active token prefixes formodel_nexttakes at mostO(S * B * L)(the exact input sizemodel_nextmust read on each call anyway). - Space:
O(N + B + P + T)—waitingholds at mostNrequest references,slotsandactive_slot_idsholdO(B)entries, and active sequence buffers plusresultsstoreO(P + T)integers in total.
Edge cases
- Empty
requestslist (N = 0):_refillleaves all slotsNone, the loop exits on the firstif not active_slot_ids: break, andmodel_nextis called0times. max_tokens == 0requests: Completed immediately inside_refillwith[](andon_finish(request_id, [])) without ever occupying a slot or triggering a model call, even when severalmax_tokens == 0requests sit back to back at the end of the queue.- Partially filled batches with gaps (
len(active_slot_ids) < B): IfB = 3andslots = [None, seq_1, seq_2],active_slot_ids = [1, 2]sends 2 prefixes (never padding with fake rows) and mapsnext_tokens[0] -> slots[1]andnext_tokens[1] -> slots[2]. - Prompt ending with a prefix of
stop_sequence: Prompt[10, 4]withstop_sequence = [4, 5]and first generated token5hasnum_generated() = 1 < 2, so_hit_stoprightly returnsFalse. - Overlapping partial stop matches: Generated tokens
1, 1, 2withstop_sequence = [1, 2]matches cleanly on step 3 viaseq.tokens[-2:] == [1, 2], returning[1]. - Stop match on the exact
max_tokens-th token: Checkingstoppedfirst strips the matched stop tokens ([15, 99]withmax_tokens = 2andstop_token = 99returns[15]). - Untrusted black-box
model_nextoron_finish: Defensive list copies (list(seq.tokens)andlist(tokens)) prevent external mutations from corrupting sequence lengths, termination, orresults.
Common mistakes
- Routing outputs with
next_tokens[slot_id]instead ofactive_slot_ids[row]: Fails withIndexErroror silently routes tokens into the wrong user's response as soon as an earlier slot becomesNonewhile higher-numbered slots are still running. - Tracking stop sequences with a naive counter that resets to
0on mismatch: Fails on overlapping patterns like stop[1, 2]inside1, 1, 2because the second1resets the counter instead of staying at matched length1. - Checking
seq.tokens[-k:] == seq.stopwithoutseq.num_generated() >= k: Falsely triggers a stop when the prompt itself ends with part (or all) of the stop sequence. - Waiting for all
Bslots to empty before refilling: Degrades dynamic batching back into static batching, stranding idle slots behind long generations. - Stopping the
whileloop as soon aswaitingbecomes empty: Prematurely cuts off active sequences that are still mid-generation insideslots. - Mutating the active sequence list while iterating over it: Deleting finished items from a list mid-loop shifts indices and skips inspecting the neighboring sequence.
- Passing internal
seq.tokenslists directly tomodel_next: Allows a black-box model that appends in place to pushnum_generated()pastmax_tokens, breaking an==termination check.
Alternative approaches
- Compact active list instead of fixed slots: Store
active: List[_Sequence]of length<= B, filter out finished sequences into a new list each step, and append fromwaitingwhilelen(active) < B. That avoidsNonegaps in pure Python, though fixedslotsis preferred in ML systems interviews because real inference servers bind eachslot_idto persistent GPU KV-cache memory. - Stateful
BatchDecoderclass with astep()method: Exposingadd_request(req)andstep()lets an async web server interleave network I/O, token-by-token SSE/WebSocket streaming, and newly arriving requests between decoding iterations.
Follow-up questions
- How does continuous batching interact with GPU KV-cache memory in a production Transformer serving engine? In a real Transformer, recomputing the entire prefix on every step is too slow, so each slot owns a KV cache (stored Key and Value attention tensors for all previous tokens in that sequence). A newly admitted request first runs a compute-heavy prefill pass over all its
prompt_tokensto populate its KV cache before joining 1-token decode steps; modern engines like vLLM use PagedAttention (splitting KV cache memory into fixed-size pages like OS virtual memory) so freed cache blocks can be recycled immediately without memory fragmentation, gating_refillon bothBand available GPU cache blocks. - What subtleties arise if callers specify stop criteria as UTF-8 text strings rather than token ID lists? Tokenization is not unique across boundaries — for example,
"\n\n"might be emitted as two separate"\n"tokens or fused into one"\n\n "token — so matching fixed token IDs can miss valid text matches! Instead, incrementally decode tokens into text and check the string suffix, holding back any trailing characters that form a partial prefix of the stop string before streaming text to the client. - If a stop sequence can contain hundreds of tokens, how can you avoid slicing and comparing the trailing window after every generated token? Precompute the KMP (Knuth-Morris-Pratt) prefix-function failure table (an array recording the longest proper prefix of
stopthat is also a suffix at each position) once when theRequestis created, and store a single integermatched_lenper_Sequence. Each newly generated token updatesmatched_lenin amortizedO(1)time by falling back along the failure table on mismatches instead of reslicingktokens every step.
Follow-up questions
- How does continuous batching interact with GPU KV-cache memory in a production Transformer serving engine?
- What subtleties arise if callers specify stop criteria as UTF-8 text strings rather than token ID lists?
- If a stop sequence can contain hundreds of tokens, how can you avoid slicing and comparing the trailing window after every generated token?
Similar questions
- Calculate Courier Earnings Across Overlapping Order Events
- Aggregate User Session Duration per Audio Space
- O(1) Dynamic Set with Uniform Random Draws
- Processes vs. Threads
- Constant-Time LFU Cache
- Stream Iterator with Checkpoint Recovery
More xAI interview questions
- In-Memory Key-Value Store with Nested Transactions Medium
- Hardest Engineering Problem and Team Motivation Hard
- Calculate Courier Earnings Across Overlapping Order Events Medium Pro
- Constant-Time LFU Cache Medium Pro
- Continuous Slot-Refilling Decode Loop for Batched Token Generation Medium Pro
- Walking Through Dataset Curation and Measuring Its Downstream Model Impact Medium Pro
- Top Three Accomplishments, Five-Minute Project Pitch, and Technical Deep Dive Medium Pro
- Quantity-Bounded LRU Cache Medium Pro
- Comparing OS Processes and Threads Medium Pro
- Single-Pass Web Corpus Cleaning Pipeline Medium Pro