Skip to content
King Jin

24 November 2026 · Inference engine notes · 2/4

Inference Engines 02: Batching, Chunked Prefill and Scheduling

Part 2 shares a few questions that came up while I read mini-sglang's scheduling code, and the tech behind them. If the weights sit in GPU memory the whole time, why is decode slow because of moving them? How does one GPU serving lots of people pack everyone's tokens into a single computation? What does chunked prefill actually cut up? And once requests pile up, how does the scheduler decide who gets in first?

Prefill and decode

  • Prefill = reading the question: the whole prompt is in front of you, so it's computed in one parallel pass; the notes taken while reading are the KV cache
  • Decode = writing the answer: one token at a time, each depending on the one before; every new token rereads the notes
  • The GPU works in rounds: each round packs everyone's work into one forward, and a request in decode gets 1 new token per round

Why decode is slow

  • The time goes into moving weights from GPU memory to where the compute units are
AnalogyWhat it's like
HBM (GPU memory)WarehouseTens of GB, holds the whole model; off-chip, behind a channel of limited width
On-chip SRAM (L2, shared memory, registers)WorkbenchVery fast, but a bit over 100 MB for the whole card; a 1.2 GB model doesn't fit
  • Compute units only work on the workbench, so in every forward each layer's weights stream from the warehouse across the workbench once, and again the next round
  • Rough numbers, Qwen3-0.6B on an H100 SXM:
    • About 3.35 TB/s of memory bandwidth; moving the bf16 weights (about 1.2 GB) once takes about 0.4 ms
    • Computing 1 token is about 1.2 GFLOP; at roughly 1000 TFLOPS of bf16 that's about 1 µs
    • Moving is a few hundred times slower than computing, so decode spends almost all its time waiting on memory
  • One pass over the weights costs about the same whether it multiplies 1 row or 64: five requests run separately move the weights five times; stacked together they move them once
  • Compute only catches up with memory once a round stacks a few hundred rows. At batch size 1 it's matrix × vector (GEMV); stacking turns it into matrix × matrix (GEMM), as the GEMM section of ML System 03 covers

Stacking one round into one matrix

  • Most of each layer is linear layers (QKV projection, O projection, MLP); a smaller part is attention
  • Linear layers: everyone shares the same weights, each token is computed on its own, and rows don't affect each other → stack every token in the round into one N × hidden matrix and multiply once
  • Attention: each token may only look at its own request's history → it needs boundaries and is computed per request
  • Example: A and B each decode 1 token, and C arrives with a 5-token prompt, so 7 rows are stacked together
    • cu_seqlens_q = [0, 1, 2, 7]: a prefix sum telling the kernel that row 0 is A, row 1 is B, and rows 2–6 are C
    • Page table: which slots in the KV pool hold each request's KV
    • The attention kernel (FlashAttention / FlashInfer) uses both so that A only sees A's KV
  • The K side has its own cu_seqlens_k, summed over device_len: Q holds only the rows computed this round, while K is the request's whole history so far
  • In a prefill round, the LM head uses cu_seqlens_q[1:] - 1 to find each request's last row and computes logits only for those rows
  • The example above is a mixed batch. mini-sglang never mixes within a round: in a decode round each request is 1 row and cu_seqlens_q is just [0, 1, 2, …]; a prefill round is several prompts laid end to end

In mini-sglang, all of this is prepared in _prepare_batch in scheduler/scheduler.py:

  • positions: each token's position within its own request ([cached_len, device_len)), for RoPE
  • input_tuple: each token's row and column in token_pool; _forward uses it to pull out a 1-D input_ids, requests laid end to end with no padding
  • out_loc: the same rows and columns looked up in page_table, giving the KV-pool slot where each newly computed K/V is written
  • write_tuple: where in token_pool each newly sampled token is written back
  • attn_backend.prepare_metadata (attention/fa.py): computes cu_seqlens_q and cu_seqlens_k, and slices this batch's rows out of the global page table

Chunked prefill

  • The problem: 3 people are decoding, 1 token each per round. Someone new sends a 10,000-token prompt. Read it all in one round and that round gets very long; the other 3 get nothing that round, and their users see the output freeze
  • The fix: cut the long prompt into chunks and read it over several rounds, with a cap on each round's token budget
  • Say the budget is 2048 per round and the engine can mix prefill and decode in one round:
RoundLong requestThe other 3
1Reads chunk 1, writes KV; the token it happens to produce is thrown away1 token each
2–4Reads the next chunks: reads old KV, writes new KV1 token each
5Finishes the last chunk; only now does its first token come out1 token each
6 onMoves to decode1 token each
  • Nothing starts writing halfway through the prompt: the earlier chunk rounds do produce a token, but it's a guess from half the prompt and gets dropped
  • The result doesn't change: when chunk 2 runs attention it reads the K/V that chunk 1 left in the KV cache, which is mathematically the same as reading everything at once
  • Chunking only changes how many rounds the work takes; the cost is that the long request's own first token comes a little later

How mini-sglang chunks

  • scheduler/prefill.py: chunk_size = min(token_budget, remain_len). token_budget is what's left of this round's budget, so when earlier requests use part of it, the last one admitted gets cut
  • The cut request is a ChunkedReq, whose can_decode is always False, so it never joins the decode set
  • Dropping that token: _prepare_batch points its sampled token at position -1 of its token_pool row, and _process_last_data hits continue for a ChunkedReq, so nothing is sent to the user
  • The next chunk picks up from the previous chunk's cached_len, which is the extend case below
  • mini-sglang never mixes within a round, and prefill goes first: the 3 people in the table above actually get no tokens in rounds 1–5 and wait until the whole long prompt is read
  • So in mini-sglang, chunking mainly caps the size of a single forward, which keeps activation memory bounded. The effect in the table only shows up in engines that mix batches, such as vLLM, or SGLang with --enable-mixed-chunk

Extend: prefill with cached_len > 0

  • Three cases are the same operation: chunk 2 onward of a chunked prefill, prefill after a prefix-cache hit, and verification in speculative decoding
  • In each, part of the notes is already in the KV cache; feed in a short run of new tokens, reading the old notes while writing new ones
  • mini-sglang calls it extend, in core.py: extend_len = device_len - cached_len
  • prepare_metadata in attention/fa.py builds cu_seqlens_q three ways:
    • Decode: 1 row per request, a plain arange
    • Prefill with no cache hit: Q and K have the same lengths, so it reuses cu_seqlens_k
    • Extend: Q is shorter than K, so it's summed separately
  • mini-sglang has no speculative decoding, so extend only comes from chunking and prefix hits

When requests pile up

  • Every round fills the GPU within three limits: the token budget, the number of seats and the KV pool, i.e. the three admission gates from part 1
  • As requests pile up, one of them fills first, and whoever can't squeeze in keeps waiting
  • What users see as load rises:
    • Time to first token keeps growing while total tokens per second keeps rising: the extra wait is spent in the queue, and a bigger batch still moves the weights only once
    • Each user's tokens come a bit slower: a bigger batch means more KV to read each round, and in mini-sglang the prefill rounds for new requests cut in and interrupt whoever is writing
    • Once memory or seats are full, total throughput stops growing, and extra requests just wait longer

Two ways to admit requests

  • mini-sglang would rather admit fewer requests than run into trouble midway; full SGLang admits more up front and sends some back when it runs short
mini-sglangFull SGLang
Queue orderStrictly first come, first servedConfigurable (--schedule-policy), e.g. lpm
Memory accountingReserves as if everyone writes their full max_tokensAssumes each request writes only part of it, so more fit at once
Running out midwayCan't happenRetract: back to the queue, KV freed, recomputed later
Within a roundAll prefill or all decode, prefill firstCan mix
Several instancesNoneA router in front, dispatching by prefix

On the mini-sglang side:

  • The reservation is only bookkeeping at admission; pages are still allocated on demand each round (allocate_paged). When everyone sets a large max_tokens but writes little, memory sits empty and new requests still can't get in
  • Available memory = free pages + old prefixes in the Radix tree that can be evicted; when pages are actually needed and free ones run short, unused old prefixes are evicted first
  • A matched prefix is locked first and the fit is checked again: once locked it no longer counts as evictable, so available memory has shrunk
  • Cancellation: the client disconnects → the API Server sends an AbortMsg → the Scheduler takes the request out of the queue or the decode set and frees its resources

On the full SGLang side:

  • lpm (longest prefix match): the request with the longest cached prefix goes first, while that prefix is still in the cache
  • If the estimate is too optimistic, memory runs out mid-decode: a few requests are retracted, what they've already written is kept, and when they come back the prompt plus that output is prefilled again; the estimate is also made more conservative
  • Mixed batches let decode keep going instead of stopping for prefill
  • Router: with several machines, requests with the same prefix go to the same one so the cache actually gets hits