Pidoku

Chunked Prefill and the Token Budget

Module 17 Lesson 17.b 50 min Difficulty 3/5

Prerequisites 12.k, 17.a


Before you start: words you need#

WordPlain meaning
PrefillReading the prompt: many tokens in one pass, limited by the GPU’s arithmetic (12.c).
DecodeGenerating output: one token per request per step, limited by memory bandwidth (12.c).
Chunked prefillSplitting a long prompt over several steps so generating requests keep moving (12.k).
Token budget--max-num-batched-tokens: the most tokens one step may process.
TTFTTime to first token: how long a user waits before the answer starts.
ITLInter-token latency: the gap between two streamed tokens.
Step timeHow long one forward pass takes. Every request in the batch waits for the whole step.

1. What is it?#

--max-num-batched-tokens is the most consequential tuning flag in vLLM, and it is one number doing two opposite jobs. A request reading its prompt wants it large, so the prompt is read in few steps and the first token arrives sooner. A request already generating wants it small, because it gets one token per step, and a step that also reads 8,000 prompt tokens for somebody else takes far longer.

Chunked prefill is the mechanism that lets both kinds of request share a step (the general idea is 12.k). The budget is the dial that decides who pays. This lesson shows how vLLM implements chunking, what the budget defaults to on your hardware, what changes it, and how to pick a value from the latency you can accept.

Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it matter?#

Without chunking, a 32,000-token prompt must go into the model in one piece, and a forward pass cannot be interrupted. Every user currently streaming an answer would freeze for the whole prefill, often more than half a second. With chunking, the prompt is spread over several steps and every streaming user gets a token in each one.

The project’s own documentation gives the second reason: chunked prefill “helps achieve better GPU utilization by locating compute-bound (prefill) and memory-bound (decode) requests to the same batch.” Decode leaves the GPU’s arithmetic units mostly idle; a prefill chunk in the same step puts them to work.


3. Simple analogy#

A bus that leaves every few minutes. Regular passengers (decoders) each need one seat. A school group of 300 (a long prompt) arrives. Without chunking, the bus waits until all 300 can board at once, and everyone else is late. With chunking, the regulars board first and the group fills the remaining seats over several trips.

The size of the bus is the token budget. A huge bus carries the group in fewer trips, but each trip takes longer to load, and the regulars arrive late every time.


4. Tiny example: one 30,000-token prompt among 32 decoders#

budget 8,192
step N:   32 decoders × 1 token = 32       + 8,160 tokens of the long prompt
step N+1: 32 decoders            = 32       + next 8,160 tokens
...       4 steps to read the prompt

every decoder's inter-token gap during those 4 steps = the step time with 8,192 tokens in it

With a budget of 2,048, the prompt takes 15 steps, but each step is about four times shorter, so the decoders hardly notice.


5. Technical explanation#

Where chunking happens in the code#

Nowhere in particular, which is the elegant part. From 17.a:

Python
num_new_tokens = request.num_tokens - num_computed_tokens
...
num_new_tokens = min(num_new_tokens, request_token_budget)

A prompt larger than the remaining budget is clipped to the budget; num_computed_tokens advances by that amount; next step the request is in running with a smaller gap. Because running requests are served in admission order and each decoder needs one token, the decoders' small shares are always covered and the prefill gets what is left.

The only place enable_chunked_prefill is consulted is to forbid clipping:

Python
if (
    not self.scheduler_config.enable_chunked_prefill
    and num_new_tokens > request_token_budget
    and not self.is_mm_encoder_only
):
    # If chunked_prefill is disabled,
    # we can stop the scheduling here.
    break

With chunking off, a prompt that does not fit in the remaining budget waits for a step where it fits whole. So the budget must be at least max_model_len, or long prompts could never run. If you leave the budget unset, vLLM raises it to max_model_len for you; if you set it lower by hand, startup fails with a message telling you to raise it.

Chunked prefill is on by default for generative models. It is switched off automatically (ModelConfig.is_chunked_prefill_supported) for:

  • encoder-decoder models (Whisper-style),
  • pooling (embedding) models with bidirectional, encoder-only attention,
  • pooling models with causal attention that pool over the whole sequence (MEAN or CLS pooling, or STEP token pooling), because they need every token’s output in one pass.

Turning it off by hand on a generative model now logs a warning that the model “does not officially support disabling chunked prefill”.

What the budget defaults to#

You rarely see the hard-coded 2,048 in SchedulerConfig. vllm serve picks a value from the GPU’s memory, in EngineArgs.get_batch_defaults (vllm/engine/arg_utils.py):

Devicemax_num_batched_tokens (vllm serve)(offline LLM class)max_num_seqs
GPU with ≥ 160 GiB (B200, B300)16,38416,3841,024
GPU with ≥ 70 GiB, not an A100 (H100, H200)8,19216,3841,024
Any other GPU (A100, L40S, L4, RTX…)2,0488,192256
CPU2,048 × world size4,096 × world size128 × world size (server), 256 × (offline)
Data parallel with batched MoE256256as above

The A100 exception has a comment: “Setting large max_num_batched_tokens for A100 reduces throughput”. An 80 GiB A100 is therefore treated like a small GPU. TPUs have their own, smaller values.

Three adjustments follow, in order (only for values you did not set):

  1. --performance-mode throughput doubles both numbers.
  2. The token budget is capped at max_num_seqs × max_model_len.
  3. max_num_seqs is capped at the token budget: there is no point allowing more sequences than tokens.

The value in force is printed at startup: Chunked prefill is enabled with max_num_batched_tokens=8192.

note

The offline LLM class gets larger budgets than the server because a batch job has nobody watching tokens arrive. If you benchmark with LLM and deploy with vllm serve, you are measuring a different configuration.

The trade-off, with numbers#

Let a step with only decoders take d ms, and let prefill cost p ms per 1,000 tokens. A step that carries c prefill tokens takes roughly:

step time ≈ d + p × c / 1000

Say d = 12 ms and p = 20 ms (an 8B-class model on a large GPU; measure your own). For a 32,000-token prompt arriving while others are generating:

BudgetChunksLongest step during the prefillTTFT for the long promptITL for everyone else
2,0481612 + 41 = 53 ms0.83 s53 ms
8,192412 + 164 = 176 ms0.69 s176 ms
16,384212 + 328 = 340 ms0.66 s340 ms
32,768112 + 640 = 652 ms0.65 s652 ms, a visible freeze

The long prompt’s TTFT barely changes: the total prefill work is the same, and only the fixed d per chunk is saved. But every other request’s inter-token latency grows in step with the budget. Raising the budget buys a little TTFT and throughput at the price of smooth streaming.

That is why the project’s tuning guide says:

  • “Smaller values (e.g., 2048) achieve better ITL because there are fewer prefills slowing down decodes.”
  • “Higher values achieve better time to first token (TTFT) as you can process more prefill tokens in a batch.”
  • “For optimal throughput, we recommend setting max_num_batched_tokens > 8192 especially for smaller models on large GPUs.”

Choosing a value#

Work backwards from the inter-token latency you can tolerate:

tolerable step time   T    e.g. 80 ms for a chat product
decode step time      d    measure with only decoders running
prefill cost          p    ms per 1,000 tokens, measure with one long prompt

budget ≈ (T − d) / p × 1000
       = (80 − 12) / 20 × 1000  ≈ 3,400 tokens

For a batch or agent workload with no human reading the stream, take the largest value that does not reduce throughput. For a mixed workload, the per-request cap below is usually the better tool.

--long-prefill-token-threshold: a cap per request#

The budget is shared by all prefilling requests in a step. One 100,000-token prompt can take the entire budget step after step, and ten 500-token prompts that arrived just after it wait behind it. A per-request cap fixes that:

Python
if 0 < long_prefill_token_threshold < num_new_tokens:
    num_new_tokens = long_prefill_token_threshold

With --long-prefill-token-threshold 2048 and a budget of 8,192, no single request takes more than 2,048 tokens of a step, so a long prompt and three short ones all progress together. The default is 0, meaning no cap.

Two refinements in the v0.32.0 source:

Python
# `long_prefill_token_threshold` exists to stop a long prefill from
# starving other requests of the token budget. When it is the only
# request there is nobody to starve, so let it use the whole budget.
long_prefill_token_threshold = (
    self.scheduler_config.long_prefill_token_threshold
    if num_eligible_reqs > 1
    else 0
)
if long_prefill_token_threshold > 0 and self.adaptive_long_prefill_threshold:
    long_prefill_token_threshold = max(
        long_prefill_token_threshold, input_budget // num_eligible_reqs
    )

A lone request is never throttled. And --long-prefill-token-threshold-adaptive (off by default) raises the cap to a fair share of the budget when few requests are present: with a budget of 8,192 and two requests, each may take 4,096 whatever lower threshold you configured, so the budget is not left unused.

FlagDefaultWhat it does
--max-num-seqsBy GPU, aboveMost requests in running. Also sizes per-request buffers in the model runner and the largest CUDA graph, so it costs memory and startup time.
--max-num-active-seqsunsetAdmission limit below max_num_seqs: smaller decode batches without shrinking buffers or graphs.
--max-num-scheduled-tokens= budgetTokens the scheduler issues; smaller than the budget when speculative decoding adds tokens to the batch.
--scheduler-reserve-full-islonAdmit a request only if its whole prompt fits in free KV blocks (17.a).
--watermark0.0Fraction of KV blocks kept free when admitting (17.c).
--disable-chunked-mm-inputoffNever split one image’s placeholder tokens across two steps.
--prefill-schedule-interval1Under data parallelism, admit new prefills only every Nth step, aligned across ranks, so their step times match.
--max-num-queued-reqs, --max-num-queued-tokensunsetReject new requests with HTTP 503 when the queue or the prefill backlog is too large (20.c).
--performance-modebalancedthroughput doubles the two batch limits; interactivity captures a CUDA graph for every batch size from 1 to 32 to cut padding at low concurrency.

6. Under the hood#

What “prioritises decode” does and does not mean#

vLLM’s docs say chunked prefill “prioritizes decode requests”. In the code, the scheduler serves running in admission order, and a request in its prompt and a request generating are both in running; neither is preferred because of its phase. What protects decoders is arithmetic: each needs one token, so even hundreds of them use a small share of the budget. A prefilling request admitted earlier than a decoder is still scheduled before it, but normally enough budget remains for the decoder’s single token.

The one case where a decoder is skipped is when the requests ahead of it use up the budget. With a budget of 2,048 and 3,000 running decoders that could happen, which is one reason max_num_seqs is capped at the budget.

A simulator#

The table above, computed, plus the fairness problem that long_prefill_token_threshold solves: one huge prompt and several small ones arriving together.

Go
package main

import "fmt"

const (
	decodeMs  = 12.0 // a step with only decoders
	prefillMs = 20.0 // per 1,000 prefill tokens
)

type req struct {
	name     string
	prompt   int
	computed int
	ttft     float64
}

// simulate runs prefill for all requests and returns each one's time to first
// token and the slowest step (which is everyone else's worst inter-token latency).
func simulate(budget, perRequestCap int, prompts []int) ([]float64, float64) {
	reqs := make([]*req, len(prompts))
	for i, p := range prompts {
		reqs[i] = &req{name: fmt.Sprint(i), prompt: p}
	}
	clock, worst := 0.0, 0.0
	for remaining := len(reqs); remaining > 0; {
		left, used := budget, 0
		var done []*req
		for _, r := range reqs {
			if r.computed == r.prompt || left == 0 {
				continue
			}
			n := min(r.prompt-r.computed, left)
			if perRequestCap > 0 && remaining > 1 {
				n = min(n, perRequestCap)
			}
			r.computed += n
			left -= n
			used += n
			if r.computed == r.prompt {
				done = append(done, r)
			}
		}
		step := decodeMs + prefillMs*float64(used)/1000
		clock += step
		worst = max(worst, step)
		for _, r := range done {
			r.ttft = clock
			remaining--
		}
	}
	out := make([]float64, len(reqs))
	for i, r := range reqs {
		out[i] = r.ttft
	}
	return out, worst
}

func main() {
	fmt.Println("One 32,000-token prompt, by budget:")
	for _, b := range []int{2048, 8192, 16384, 32768} {
		ttft, worst := simulate(b, 0, []int{32000})
		fmt.Printf("  budget %6d  TTFT %5.2f s   worst step %4.0f ms\n", b, ttft[0]/1000, worst)
	}

	fmt.Println("\nOne 60,000-token prompt followed by four 500-token prompts, budget 8192:")
	prompts := []int{60000, 500, 500, 500, 500}
	for _, cap := range []int{0, 2048} {
		ttft, worst := simulate(8192, cap, prompts)
		fmt.Printf("  long_prefill_token_threshold=%-5d long TTFT %5.2f s   short TTFT %5.2f s   worst step %4.0f ms\n",
			cap, ttft[0]/1000, ttft[1]/1000, worst)
	}
}

Output:

One 32,000-token prompt, by budget:
  budget   2048  TTFT  0.83 s   worst step   53 ms
  budget   8192  TTFT  0.69 s   worst step  176 ms
  budget  16384  TTFT  0.66 s   worst step  340 ms
  budget  32768  TTFT  0.65 s   worst step  652 ms

One 60,000-token prompt followed by four 500-token prompts, budget 8192:
  long_prefill_token_threshold=0     long TTFT  1.34 s   short TTFT  1.34 s   worst step  176 ms
  long_prefill_token_threshold=2048  long TTFT  1.35 s   short TTFT  0.09 s   worst step  176 ms

How to read it: in the second experiment the short prompts wait 1.34 s without the cap and 0.09 s with it, while the long prompt loses 10 ms. The cap is close to free and is the first thing to set on a server that mixes long documents with short chats.


7. Performance implications#

  • The budget sets the worst inter-token latency. Every request in a batch waits for the whole step, and step time grows roughly linearly with prefill tokens in it.
  • TTFT gains from a larger budget are small for a single long prompt; they come from fewer fixed per-step costs, not less work.
  • Throughput rises with the budget up to a point, because larger steps use the GPU’s arithmetic better. Past that point steps just get longer.
  • A larger budget also costs KV memory, because vLLM profiles peak activation memory with one batch of exactly max_num_batched_tokens tokens (17.h).

8. Production implications#

  • Read the startup log for the budget actually in force; it depends on the GPU and on --performance-mode.
  • Chat products: a budget of 2,048 to 4,096 plus --long-prefill-token-threshold keeps streams smooth.
  • Batch and agent back-ends: raise the budget (16,384 or more on large GPUs) and measure throughput with vllm bench serve (19.d).
  • Very long prompts at scale: if prefill keeps hurting decode no matter the budget, split the two onto different servers: prefill/decode disaggregation (14.j, 19.b).

9. Common mistakes#

  1. Benchmarking with the LLM class and deploying with vllm serve. They have different default budgets.
  2. Raising the budget to “make TTFT better” and getting worse streaming for everyone else.
  3. Disabling chunked prefill without raising the budget to at least max_model_len.
  4. Assuming an A100 80 GB gets the H100 default. It gets 2,048.
  5. Setting a long-prefill cap and expecting it to throttle a lone request. It is not applied when only one request is present.

10. Hands-on exercise#

  1. In the program, set prefillMs to 60 (a much larger model). Which budget keeps the worst step under 100 ms?
  2. Run the second experiment with a cap of 512 and of 4,096. Plot (by hand) long-prompt TTFT against short-prompt TTFT. Where is the knee?
  3. On a real server, send one very long prompt while a second client streams a long answer. Measure the second client’s inter-token gaps with the client from 16.b. Repeat with --max-num-batched-tokens 1024.

11. Interview questions#

  1. Why does raising the budget improve a long prompt’s TTFT only slightly?
  2. What is the default token budget for vllm serve on an A100, and why is it not the same as on an H100?
  3. A server has one request in it. Does --long-prefill-token-threshold limit that request?
  4. Where in vLLM’s code does chunked prefill happen?
  5. Derive a token budget from a target inter-token latency.

12. Further reading#

Checked on 12 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in