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 raise ValueError).
  • stop_token / stop_sequence: optional stopping rule; supplying both raises ValueError, and passing an empty stop_sequence ([]) raises ValueError.
  • Mutating caller lists after constructing Request must 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 ValueError if batch_size < 1 or if any request_id appears more than once in requests.
  • Slot admission (FIFO): Maintain at most batch_size active sequences at a time, filling open slots from requests in arrival order. A request with max_tokens == 0 finishes immediately with [] (invoking on_finish(request_id, []) if supplied) without occupying a batch slot or invoking model_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 call model_next(prefixes). If model_next returns a list whose length differs from len(prefixes), raise ValueError.
  • 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:
    1. Stop match: Its generated tokens (excluding prompt_tokens) end with [stop_token] or stop_sequence. Remove those trailing stop token(s) from its final output.
    2. 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)).
  • Refilling and callbacks: Whenever a sequence finishes, store its final generated token list under results[request_id], invoke on_finish(request_id, final_tokens) once if provided, vacate its slot, and immediately admit waiting requests into any free slots before the next model_next call. Guard internal buffers so in-place list mutations inside model_next or on_finish cannot 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 < 1 raises ValueError).
  • 0 <= len(requests) <= 10^4, with all request_id values distinct (duplicates raise ValueError).
  • max_tokens >= 0 (max_tokens < 0 raises ValueError).
  • At most one of stop_token and stop_sequence is non-None, and if stop_sequence is provided, len(stop_sequence) >= 1.
  • Every call to model_next(prefixes) receives 1 <= len(prefixes) <= min(batch_size, unfinished_active_requests) and must return len(prefixes) integers (mismatched lengths raise ValueError).

Step-by-step walkthrough

  1. 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 given model_next(batch_prefixes) -> next_tokens, which advances up to batch_size (B) sequences at once.

    Before writing code, clarify and lock down the exact boundary rules:

    • max_tokens counts only generated tokens, never prompt tokens. A request with max_tokens = 0 finishes immediately with [] without ever occupying a slot or calling model_next.
    • Stopping checks apply only to generated tokens. If prompt_tokens = [10, 4] and stop_sequence = [4, 5], generating 5 on the first step ([10, 4, 5]) does not match because 4 came from the prompt.
    • Unify stop_token and stop_sequence: A single stop_token = 99 behaves identically to stop_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)
    
  2. 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_next on B sequences takes roughly the same wall-clock time as calling it on 1 sequence. Minimizing total model_next calls therefore directly speeds up serving.

    Compare B = 2 on four requests r0, r1, r2, r3 that generate 4, 1, 1, 2 tokens (8 tokens 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)
    
  3. 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 length B): Fixed slot table where slots[slot_id] holds the active _Sequence in that slot, or None when the slot is free. Keeping a request in the same slot_id until 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 row row -> slot_id for non-empty slots. Whenever an earlier slot becomes None with an empty queue, row and slot_id diverge:
    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_len
    
  4. Detecting 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 with seq.stop. Two subtle bugs catch candidates here:

    1. Prompt bleed: If prompt_tokens = [10, 4] and seq.stop = [4, 5], generating 5 makes seq.tokens = [10, 4, 5]. Checking seq.tokens[-2:] == [4, 5] alone would falsely match! Requiring seq.num_generated() >= len(seq.stop) guarantees every matched token was generated.
    2. Overlapping partial matches: Suppose seq.stop = [1, 2] and the model generates 1, 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.stop takes O(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
    
  5. Admitting waiting requests into free slots

    Whenever slots are initially empty or become None after a step, _refill walks slot_id from 0 to B - 1 and pops requests from waiting. If it pops a request with max_tokens == 0, it records [] immediately and keeps popping inside while waiting: so that slot still gets filled by the next real request (and trailing max_tokens == 0 requests are drained right away).

    Notice the defensive copy in _record: passing list(tokens) to on_finish ensures a caller callback that mutates its list argument cannot corrupt results[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)
                break
    

    After _refill returns, one key loop invariant always holds: either all B slots are occupied, or waiting is completely empty.

  6. The decoding loop, compact row mapping, and termination

    Each step of run_dynamic_batching runs five clean phases:

    1. Collect active_slot_ids: Scan slots for non-None indices. If active_slot_ids is empty, break — by our _refill invariant, waiting is guaranteed empty too! When 1 <= len(active_slot_ids) < B near the end, we naturally send a smaller batch without dummy padding.
    2. Copy prefixes (list(seq.tokens)): Because model_next is an untrusted black box, handing it our internal seq.tokens list directly would let a mutating model break num_generated() == max_tokens and cause an infinite loop.
    3. Call model_next(prefixes) and verify len(next_tokens) == len(active_slot_ids).
    4. Route tokens back via enumerate(active_slot_ids): Append next_tokens[row] to slots[slot_id], check stopped or max_tokens (giving stopped priority so a stop sequence completed on the final allowed token is still stripped), record the output, and free slots[slot_id] = None.
    5. Call _refill so 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 within max_tokens steps.

  7. Walk through Example 1 with slot refill and a partial batch

    Trace batch_size = 2 on Example 1's three requests: - 101: prompt [101], max_tokens = 1, model emits 50 - 102: prompt [102], max_tokens = 3, model emits 61, 62, 63 - 103: prompt [103], max_tokens = 1, model emits 70

    Phase          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] is None and slots[1] holds 102, so active_slot_ids = [1] has length 1 < B. next_tokens[0] (63) routes cleanly through active_slot_ids[0] -> slot 1, returning {101: [50], 102: [61, 62, 63], 103: [70]}.

  8. 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 _refill fills every available slot whenever requests wait, every call emits between 1 and B tokens (ceil(T / B) <= S <= T, with S = 0 when T = 0), and S is bounded below by the longest individual generation.
  • Engine bookkeeping time (excluding model_next itself): O(N + P + S * B + T * k + S * B * L) — queueing N requests and copying prompts/outputs takes O(N + P + T); scanning all B slots to build active_slot_ids across S steps takes O(S * B); checking the trailing k-token suffix after each emitted token takes O(T * k); and copying active token prefixes for model_next takes at most O(S * B * L) (the exact input size model_next must read on each call anyway).
  • Space: O(N + B + P + T) — waiting holds at most N request references, slots and active_slot_ids hold O(B) entries, and active sequence buffers plus results store O(P + T) integers in total.

Edge cases

  • Empty requests list (N = 0): _refill leaves all slots None, the loop exits on the first if not active_slot_ids: break, and model_next is called 0 times.
  • max_tokens == 0 requests: Completed immediately inside _refill with [] (and on_finish(request_id, [])) without ever occupying a slot or triggering a model call, even when several max_tokens == 0 requests sit back to back at the end of the queue.
  • Partially filled batches with gaps (len(active_slot_ids) < B): If B = 3 and slots = [None, seq_1, seq_2], active_slot_ids = [1, 2] sends 2 prefixes (never padding with fake rows) and maps next_tokens[0] -> slots[1] and next_tokens[1] -> slots[2].
  • Prompt ending with a prefix of stop_sequence: Prompt [10, 4] with stop_sequence = [4, 5] and first generated token 5 has num_generated() = 1 < 2, so _hit_stop rightly returns False.
  • Overlapping partial stop matches: Generated tokens 1, 1, 2 with stop_sequence = [1, 2] matches cleanly on step 3 via seq.tokens[-2:] == [1, 2], returning [1].
  • Stop match on the exact max_tokens-th token: Checking stopped first strips the matched stop tokens ([15, 99] with max_tokens = 2 and stop_token = 99 returns [15]).
  • Untrusted black-box model_next or on_finish: Defensive list copies (list(seq.tokens) and list(tokens)) prevent external mutations from corrupting sequence lengths, termination, or results.

Common mistakes

  • Routing outputs with next_tokens[slot_id] instead of active_slot_ids[row]: Fails with IndexError or silently routes tokens into the wrong user's response as soon as an earlier slot becomes None while higher-numbered slots are still running.
  • Tracking stop sequences with a naive counter that resets to 0 on mismatch: Fails on overlapping patterns like stop [1, 2] inside 1, 1, 2 because the second 1 resets the counter instead of staying at matched length 1.
  • Checking seq.tokens[-k:] == seq.stop without seq.num_generated() >= k: Falsely triggers a stop when the prompt itself ends with part (or all) of the stop sequence.
  • Waiting for all B slots to empty before refilling: Degrades dynamic batching back into static batching, stranding idle slots behind long generations.
  • Stopping the while loop as soon as waiting becomes empty: Prematurely cuts off active sequences that are still mid-generation inside slots.
  • 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.tokens lists directly to model_next: Allows a black-box model that appends in place to push num_generated() past max_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 from waiting while len(active) < B. That avoids None gaps in pure Python, though fixed slots is preferred in ML systems interviews because real inference servers bind each slot_id to persistent GPU KV-cache memory.
  • Stateful BatchDecoder class with a step() method: Exposing add_request(req) and step() 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_tokens to 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 _refill on both B and 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 stop that is also a suffix at each position) once when the Request is created, and store a single integer matched_len per _Sequence. Each newly generated token updates matched_len in amortized O(1) time by falling back along the failure table on mismatches instead of reslicing k tokens every step.

Follow-up questions

Similar questions

More xAI interview questions

All 53 xAI questions →