Continuous-Batch Inference Loop with Slot Refilling
Data Structure DesignModel answerLast updated
Implement a dynamic batching generation loop that keeps a fixed-size batch full by refilling completed slots from a waiting queue until all requests are served.
Continuous-Batch Inference Loop with Slot Refilling
You are building the generation loop for a text inference server. A mock language model exposes one method: given a batch of token sequences (each sequence is the full list of tokens seen so far for one request), it returns the next token for every sequence in the batch.
class MockModel:
def next_tokens(self, batch: list[list[int]]) -> list[int]:
"""
batch[i] is the complete token sequence for one in-progress request.
Returns one next token per entry, preserving input order.
"""
Your task is to implement generate, which takes a list of requests and a maximum number of concurrent slots, and returns every request's generated tokens once all requests are complete.
from dataclasses import dataclass
@dataclass
class Request:
request_id: str
prompt: list[int]
max_tokens: int
def generate(
model: MockModel,
requests: list[Request],
num_slots: int,
stop_token: int,
) -> dict[str, list[int]]:
"""
Runs generation for all requests using dynamic batching.
Returns a mapping from request_id to the list of generated tokens.
"""
How it works
At any point in time, up to num_slots requests run concurrently. Each model call receives the current token sequences for every active slot and produces one new token per slot. After each step:
- A request is complete if the new token is the stop token, or if the number of tokens generated so far equals the request's
max_tokenslimit. - Every slot that held a completed request is immediately refilled from the front of the waiting queue before the next model call.
- The loop ends when every request has finished and the batch is empty.
Constraints
- A single model call processes at most
num_slotssequences. - The model is stateless: every call must supply the full token prefix built up so far (prompt + all previously generated tokens).
- Requests are admitted from the queue in the order they appear in
requests. model.next_tokensreturns exactly one token per input entry, in the same order.max_tokenscounts only the newly generated tokens, not the prompt.- The stop token should not be included in the returned output for a completed request.
- If fewer than
num_slotsrequests remain (queue empty, some slots idle), the model call covers only the occupied slots.
What your solution should handle
- Requests that finish at very different steps (uneven output lengths).
- More total requests than available slots, requiring multiple refill events.
- A request whose very first generated token is the stop token.
- A
max_tokensof 1 (single-token output). - No request lost, duplicated, or returned with extra tokens.
Hints
Hint 1
Track each active slot with a small record: which request occupies it, the tokens generated so far, and the full current sequence to send to the model. A list indexed by slot number works well.
Hint 2
After receiving the model's output, check completion for every slot before building the next batch. Refill freed slots from the queue in the same pass so the next model call sees a full batch.
Hint 3
The model call should only include occupied slots, not empty ones. Keep a separate mapping from model-call position to slot index so you can route each output token back to the right request.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is keeping a fixed-size batch as full as possible while requests finish at unpredictable steps. The solution needs three pieces of state:
- A FIFO queue of requests waiting to be admitted.
- A slot table mapping each slot index to the request currently occupying it (or empty).
- A token buffer per request to accumulate generated tokens.
A "step" is one call to model.next_tokens. At each step, you collect the active slots, call the model, apply completion checks, drain finished slots, refill from the queue, then repeat.
Key design decisions
Stateless model means full prefix every call. Since the mock model has no memory, each slot must carry the prompt plus every token generated so far. This is realistic: real inference engines use a KV cache to avoid recomputing the prefix, but the interface here is stateless, so you pay the full cost each call.
Compact the batch, don't pad. Rather than sending num_slots entries with empty placeholders, only send occupied slots. This requires a mapping from model-output position back to slot index, but it avoids undefined behavior from sending the model empty sequences.
Refill before the next call, not after. Refilling immediately after a slot clears keeps utilization high. If you deferred refilling to the start of the next iteration you'd get the same result, but clearing and refilling in one pass is cleaner.
Stop token is not returned. Strip it before storing; the caller asked for generated content, not the termination signal.
Implementation
from collections import deque
from dataclasses import dataclass, field
@dataclass
class Request:
request_id: str
prompt: list[int]
max_tokens: int
class MockModel:
def next_tokens(self, batch: list[list[int]]) -> list[int]:
raise NotImplementedError
def generate(
model: MockModel,
requests: list[Request],
num_slots: int,
stop_token: int,
) -> dict[str, list[int]]:
queue: deque[Request] = deque(requests)
# slot_request[i] = Request occupying slot i, or None
slot_request: list[Request | None] = [None] * num_slots
# slot_tokens[i] = generated tokens so far for slot i
slot_tokens: list[list[int]] = [[] for _ in range(num_slots)]
results: dict[str, list[int]] = {}
def fill_empty_slots() -> None:
for i in range(num_slots):
if slot_request[i] is None and queue:
slot_request[i] = queue.popleft()
slot_tokens[i] = []
# Prime the batch before the first step
fill_empty_slots()
while any(r is not None for r in slot_request):
# Build the batch from occupied slots only
active_indices = [i for i, r in enumerate(slot_request) if r is not None]
batch = [
slot_request[i].prompt + slot_tokens[i] # type: ignore[operator]
for i in active_indices
]
next_toks = model.next_tokens(batch)
# Process each result, check completion
for pos, slot_idx in enumerate(active_indices):
token = next_toks[pos]
req = slot_request[slot_idx]
assert req is not None
if token == stop_token:
# Finished by stop token — do not include the stop token
results[req.request_id] = list(slot_tokens[slot_idx])
slot_request[slot_idx] = None
slot_tokens[slot_idx] = []
else:
slot_tokens[slot_idx].append(token)
if len(slot_tokens[slot_idx]) >= req.max_tokens:
# Finished by length limit
results[req.request_id] = list(slot_tokens[slot_idx])
slot_request[slot_idx] = None
slot_tokens[slot_idx] = []
# Refill any freed slots before the next step
fill_empty_slots()
return results
Complexity
- Time: O(R × L × P) where R is the number of requests, L is the average output length, and P is the average prompt length. The P factor comes from re-sending the full prefix every step — a KV cache would reduce this to O(R × L).
- Space: O(num_slots × max(prompt + max_tokens)) for the active sequences, plus O(R × L) for the accumulated results.
- Model calls: roughly
sum(output_lengths) / num_slotssteps, compared to R separate calls in static batching. Dynamic refilling extracts most of the throughput benefit as long as the queue is non-empty.
Common mistakes
- Returning the stop token in the output. The problem says to exclude it; forgetting this is the most frequent error.
- Off-by-one on
max_tokens. Checking>= max_tokensafter appending is correct. Checking> max_tokensor checking before appending silently produces wrong lengths. - Losing a request. If you clear
slot_request[i]without writing toresultsfirst, that request disappears. Always write before clearing. - Sending empty slot entries to the model. If you pad to
num_slotsand the model receives an empty list[], behavior is undefined. Only send occupied slots. - Not refilling before checking termination. Refilling after checking is fine; the order within a step does not matter as long as you refill before the next model call.
Follow-up directions
A natural extension is tracking per-request latency (first-token time vs. total time), or implementing a priority queue instead of FIFO admission. On the model side, replacing the stateless interface with a KV-cache-aware one changes the prefix cost from O(L) to O(1) per step, which is the main reason real serving engines maintain session state.