Requests don’t arrive collectively or end collectively. If a server fixes one batch and waits for each member to complete, shorter requests depart empty slots whereas longer requests proceed. The GPU might have room for brand new work, however the static batch can not admit it.
Steady batching adjustments the membership of the lively batch between mannequin iterations. A scheduler can admit a brand new immediate, advance current decodes, and take away completed requests at every step. The selection of which work to schedule impacts time to first token, time between output tokens, throughput, and KV cache strain.
On this publish, you’ll find out about:
- How steady batching adjustments the lively request set between iterations
- How token budgets and cache capability constrain a scheduler
- How prefill coverage and equity have an effect on queue and streaming latency
Let’s get began.
Steady Batching and Scheduling: An Introduction.
Picture by Ambitious Studio* | Rick Barrett. Some rights reserved.
Overview
This publish is split into three elements; they’re:
- From Static to Steady Batching
- An Iteration-Degree Scheduler
- Token Budgets and Prefill Coverage
From Static to Steady Batching
Static batching teams requests earlier than execution and retains the group collectively till all end. It’s easy for offline jobs with related lengths. Dynamic batching waits briefly to type a batch from arriving requests, however a standard dynamic batch should still keep fastened as soon as it begins. Steady batching, additionally referred to as in-flight batching, adjustments lively membership at iteration boundaries.
For instance, three requests might arrive at completely different occasions:
| Iterations | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Request A | Prefill | Decode | Decode | Accomplished | – |
| Request B | – | Prefill | Decode | Decode | Decode |
| Request C | – | – | – | Prefill | Decode |
After A finishes, C can use the freed slot even whereas B continues. The scheduler can not normally change a working GPU kernel midway via an iteration. The helpful scheduling boundary is the subsequent mannequin step.
An iteration can comprise one new token for every decoding sequence and a piece of immediate tokens for a number of prefilling sequences. These jobs have completely different shapes: prefill processes many positions in parallel, whereas decode usually processes one place per lively sequence. Mixing them can enhance occupancy, however a protracted prefill might delay the subsequent token for an current stream.
An Iteration-Degree Scheduler
The next standard-library simulation schedules token work. It doesn’t execute a mannequin. Run the block to see which requests make progress every iteration.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
from dataclasses import dataclass
@dataclass class Request: identify: str arrival: int prompt_tokens: int output_tokens: int prefill_left: int = 0 decode_left: int = 0 first_token_at: int | None = None
def __post_init__(self): self.prefill_left = self.prompt_tokens self.decode_left = self.output_tokens
@property def reserved_tokens(self): return self.prompt_tokens + self.output_tokens
requests = [ Request(“A”, arrival=0, prompt_tokens=8, output_tokens=3), Request(“B”, arrival=1, prompt_tokens=3, output_tokens=5), Request(“C”, arrival=2, prompt_tokens=6, output_tokens=2), ] max_num_seqs = 2 max_num_batched_tokens = 6 kv_token_capacity = 20
ready = [] lively = [] accomplished = [] next_arrival = 0 iteration = 0
whereas len(accomplished) < len(requests): whereas next_arrival < len(requests) and requests[next_arrival].arrival <= iteration: ready.append(requests[next_arrival]) next_arrival += 1
# Reserve full immediate plus most output size earlier than admission. whereas ready and len(lively) < max_num_seqs: candidate = ready[0] reserved = sum(req.reserved_tokens for req in lively) if reserved + candidate.reserved_tokens > kv_token_capacity: break lively.append(ready.pop(0))
finances = max_num_batched_tokens actions = []
# Give every prepared decode one token earlier than scheduling new prefill work. for req in lively: if finances and req.prefill_left == 0 and req.decode_left: req.decode_left -= 1 finances -= 1 if req.first_token_at is None: req.first_token_at = iteration actions.append(f“{req.identify}:decode 1”)
# Use the remaining token finances for prefill chunks. for req in lively: if finances and req.prefill_left: chunk = min(req.prefill_left, finances) req.prefill_left -= chunk finances -= chunk if req.prefill_left == 0: # The final immediate place provides the primary output logits. req.decode_left -= 1 req.first_token_at = iteration actions.append(f“{req.identify}:prefill {chunk} + first token”) else: actions.append(f“{req.identify}:prefill {chunk}”)
completed = [ req for req in active if req.prefill_left == 0 and req.decode_left == 0 ] for req in completed: lively.take away(req) accomplished.append(req)
print(f“step {iteration:02d}: {‘, ‘.be part of(actions) or ‘idle’}”) if not actions and next_arrival == len(requests) and not lively: elevate RuntimeError(“requests can not match the cache finances”) iteration += 1
for req in accomplished: print(req.identify, “first output step:”, req.first_token_at) |
The scheduler reserves the complete most sequence size at admission. That’s conservative: actual engines might allocate cache blocks as wanted, then preempt or reject requests if reminiscence runs quick. The simulation makes use of a hard and fast token finances and a sequence-count restrict. Neither restrict alone is adequate: two very lengthy prefills can exceed a token finances even when solely two sequences are lively.
The ultimate prefill place produces logits for the primary output token. Later output tokens use decode steps. The first_token_at worth is a model-iteration quantity, not a wall-clock TTFT. An iteration containing six prefill tokens can take a unique period of time from one containing two decode tokens. It is best to measure execution time for the precise shapes and add queueing, switch, and streaming overhead to foretell latency.
This scheduler is deliberately easy. It makes use of FIFO admission, reserves every request’s full immediate and most output size, offers decode work precedence over prefill, and by no means preempts an lively request. A manufacturing scheduler can substitute every of those selections, however each different introduces a unique trade-off.
FIFO admission is predictable, however a big request on the entrance of the queue can block smaller requests behind it. Precedence scheduling can cut back latency for pressing work, nevertheless it wants getting older or deadlines so lower-priority requests don’t starve. Full cache reservation prevents overcommit, nevertheless it leaves reminiscence idle when requests cease early. Allocating cache house on demand improves common utilization, however it might require preemption, recomputation, rejection, or failure when many requests develop without delay. The coverage should additionally outline how cancellation and capability exhaustion launch or reassign sources.
A scheduler might also account for the precise token work of packed or paged batches as an alternative of assuming that each lively request has the padded size of the biggest request. Sequence size, consideration sample, adapter selection, and sampling work can all have an effect on the price of an iteration. The perfect coverage due to this fact relies on whether or not the service prioritizes queue time, streaming latency, throughput, equity, or reminiscence utilization.
Token Budgets and Prefill Coverage
Every mannequin iteration should fulfill a token finances, an active-sequence restrict, and the accessible KV cache capability. Helpful limits rely upon the mannequin, accessible GPU reminiscence, anticipated immediate lengths, and latency targets.
The instance schedules prepared decodes first. This protects the inter-token latency of current streams, however steady arrivals of decode work might depart little room for lengthy prefills. Prefill-first scheduling might cut back queue time for brand new requests however create seen gaps in current streams. Chunked prefill lets the scheduler break up a protracted immediate and blend it with decode work, as Lengthy-Context Inference confirmed. Truthful scheduling wants a rule for a way lengthy any request might wait.
The corresponding controls are arguments to LLM():
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from vllm import LLM, SamplingParams
llm = LLM( mannequin=“fb/opt-125m”, max_model_len=512, max_num_seqs=4, max_num_batched_tokens=128, enable_chunked_prefill=True, )
outputs = llm.generate( [“A KV cache stores”, “Continuous batching schedules”], SamplingParams(temperature=0.0, min_tokens=8, max_tokens=16), use_tqdm=False, ) for output in outputs: print(repr(output.outputs[0].textual content)) |
The setting max_model_len=512 limits the mixed immediate and generated sequence size for every request. It’s a per-sequence context restrict, not an iteration finances.
The setting max_num_seqs=4 limits what number of sequences vLLM can schedule in a single mannequin iteration. Elevating it permits extra concurrent requests, however these requests compete for KV cache capability and the token finances.
The setting max_num_batched_tokens=128 limits the full variety of token positions processed in a single iteration. A decode sequence normally contributes one new place, whereas a prefill might contribute many immediate positions. The scheduler should match their mixed work inside this finances.
The setting enable_chunked_prefill=True permits a immediate bigger than the remaining iteration finances to be break up throughout a number of iterations. This lets vLLM combine a part of a protracted prefill with decode work as an alternative of constructing the lengthy immediate occupy one outsized iteration. The setting adjustments scheduling granularity; it doesn’t change the mannequin’s context restrict or cut back the full prefill computation.
These limits work collectively. An iteration should fulfill each the sequence-count restrict and the token finances, whereas each admitted request should match the model-length and KV cache constraints. Bigger values might enhance throughput by exposing extra work to the GPU, however they’ll additionally improve cache strain or delay current decode streams. Examine configurations utilizing the identical request combine and measure queue time, TTFT, time per later output token, throughput, and KV cache use.
Additional Studying
Abstract
Steady batching admits and removes requests between mannequin iterations. Token budgets, active-sequence limits, cache capability, and prefill coverage decide which work can run subsequent. A scheduler that improves complete throughput can nonetheless hurt queue time or streaming latency, so evaluate insurance policies below the identical visitors and report each service-level and useful resource metrics.

