Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Shape | The size of each dimension of a tensor, such as (37 tokens, 4096). |
| Static shape | A size known before the program runs, so code can be specialised for it. |
| Dynamic shape | A size that changes from call to call, such as the number of tokens in this step. |
| Padding | Filling a tensor up to a bigger size with dummy values so it matches a fixed shape. |
| Bucket | One of a fixed set of sizes that real sizes are rounded up to. |
| Varlen | Packing sequences of different lengths end to end, plus a list of where each starts, instead of padding them. |
| Recompilation | Compiling a function again because a guard (11.i) found a shape it was not compiled for. |
| CUDA graph | A recorded sequence of GPU work, replayed with one launch. Fixed shapes and fixed addresses (5.f). |
1. What is it?#
Static shapes are known before the program runs. Dynamic shapes change per call. LLM serving is dynamic by nature: prompt lengths, the number of requests in a step and the length of every request’s context all change all the time. Nearly every optimisation technique, on the other hand, prefers static shapes.
Living with that tension is one of the central compromises of production inference.
Facts checked on 12 November 2026.
2. Why does it matter?#
Technique wants
───────────────────────────────────────────────────────
CUDA graphs (5.f) fixed shapes AND fixed memory addresses
AOT compilation (11.i) fixed shapes, or a declared range
Kernel autotuning known shapes to time
Memory planning known shapes to plan
Tensor cores (11.c) dimensions in friendly multiples
Real traffic gives
───────────────────────────────────────────────────────
Prompt length a handful to hundreds of thousands of tokens
Requests in a step changes every step as requests join and finish
Context per request grows by one every decode step
Output length unknown until the model stopsSomething has to give. What gives is a mix of bucketing, packing and kernels that treat the changing size as data rather than as part of the shape.
3. Simple analogy#
Shoe sizes. Feet come in every length; factories want a few fixed sizes. So shoes come in sizes 6, 7, 8 and 9, and everyone wears the nearest size up. A little waste for each person, huge efficiency for the factory.
Bucketing shapes is exactly this, and the design question is the same: how many sizes, and where to put them.
Varlen is the other answer: instead of giving everyone a box of the same size, pack all the shoes end to end in one long box and write down where each pair starts.
4. Tiny example: what padding and bucketing cost#
The program samples 1,024 prompt lengths from a long-tailed distribution (median about 245 tokens, capped at 8,192), then measures two kinds of waste: padding each prefill batch to its longest prompt, and rounding each decode step’s batch up to the next size that has a captured CUDA graph.
// shapes.go — what dynamic shapes cost: padding prompts to a common length,
// and rounding decode batches up to the nearest captured CUDA-graph size.
package main
import (
"fmt"
"math"
"math/rand"
)
func main() {
rng := rand.New(rand.NewSource(7))
// 1. Prefill: prompts with a long-tailed length distribution (median ~245 tokens).
prompts := make([]int, 1024)
for i := range prompts {
l := int(math.Exp(5.5 + 1.2*rng.NormFloat64()))
prompts[i] = min(max(l, 1), 8192)
}
fmt.Println("prefill: batches padded to their longest prompt")
for _, b := range []int{8, 32, 128} {
var real, padded int
for s := 0; s < len(prompts); s += b {
longest := 0
for _, l := range prompts[s : s+b] {
real += l
longest = max(longest, l)
}
padded += longest * b
}
fmt.Printf(" batch %3d: %5.1f%% of the computed tokens are padding (varlen: 0%%)\n",
b, 100*float64(padded-real)/float64(padded))
}
// 2. Decode: batch size changes every step; graphs exist only for some sizes.
pow2 := []int{1, 2, 4, 8, 16, 32, 64, 128, 256}
vllm := []int{1, 2, 4}
for s := 8; s <= 256; s += 8 { // vLLM's default list up to 256
vllm = append(vllm, s)
}
waste := func(sizes []int) float64 {
var real, run int
r := rand.New(rand.NewSource(1))
for step := 0; step < 100000; step++ {
b := 1 + r.Intn(200) // live sequences this step
for _, s := range sizes {
if s >= b {
real, run = real+b, run+s
break
}
}
}
return 100 * float64(run-real) / float64(run)
}
fmt.Println("\ndecode: batch rounded up to the next captured size (batches 1..200)")
fmt.Printf(" powers of two (%2d graphs): %4.1f%% padded slots\n", len(pow2), waste(pow2))
fmt.Printf(" vLLM-style (%2d graphs): %4.1f%% padded slots\n", len(vllm), waste(vllm))
}Output:
prefill: batches padded to their longest prompt
batch 8: 73.5% of the computed tokens are padding (varlen: 0%)
batch 32: 86.2% of the computed tokens are padding (varlen: 0%)
batch 128: 92.4% of the computed tokens are padding (varlen: 0%)
decode: batch rounded up to the next captured size (batches 1..200)
powers of two ( 9 graphs): 31.5% padded slots
vLLM-style (35 graphs): 3.3% padded slotsPadding prompts is ruinous: with realistic lengths, 74–92% of the tokens computed are padding, and it gets worse with bigger batches because a bigger batch is more likely to contain one very long prompt. Varlen packing removes all of it.
Bucketing decode batches is cheap if the buckets are dense. Powers of two waste almost a third of the slots; vLLM’s default sizes (1, 2, 4, then every multiple of 8 up to 256) waste about 3%, at the price of capturing 35 graphs instead of 9.
The padded decode slots also cost less than their share suggests. Their GEMM rows are nearly free, because decode GEMMs sit in the flat part of the curve (11.c); the real cost is small extra work in attention and elementwise kernels.
5. Technical explanation#
The four dynamic dimensions#
1. TOKENS IN THE STEP
Engines run a flat batch of tokens from many requests (11.g), so this one number
changes every step.
Handled by: CUDA graphs captured for a list of sizes, plus padding up to the next one.
2. PROMPT LENGTH
From a few tokens to hundreds of thousands.
Handled by: varlen kernels; chunked prefill caps how many prompt tokens join one step (12.k).
3. CONTEXT LENGTH OF EACH REQUEST
Grows every decode step.
Handled by: the paged KV cache; the length is passed to the kernel as data (12.l).
4. THE MIX OF PREFILL AND DECODE TOKENS IN A STEP
With chunked prefill both kinds share a step.
Handled by: attention kernels that take per-request metadata (query starts, lengths).Strategy 1: buckets and padding#
vLLM default CUDA-graph sizes: 1, 2, 4, 8, 16, 24, ..., 256, then every 16 up to the maximum
A step with 37 tokens runs the graph for 40; 3 slots are dummies.More buckets mean less padding but more capture time at startup and more GPU memory for the graphs. The list is configurable (18.d); tune it only after measuring your real batch-size distribution.
Strategy 2: varlen packing#
Padded: Packed (varlen):
[t t t t . . . .] tokens: [t t t t | t t | t t t t t t]
[t t . . . . . .] starts: [0, 4, 6, 12]
[t t t t t t . .]
12 real, 12 padding 12 real, 0 paddingFlashAttention’s flash_attn_varlen_func takes exactly this (cu_seqlens, the cumulative start
offsets), and every serving engine’s attention backend takes the equivalent (query_start_loc in
vLLM). The GEMMs do not care at all: a packed batch is just M rows.
Strategy 3: sizes as data, not shapes#
Paged attention: each request's context length and block list are INPUTS to the kernel.
The kernel loops until it runs out of blocks for that request.
→ any context length, no recompilation, no new CUDA graphThis is why a CUDA graph captured once can serve requests whose contexts keep growing: the graph replays the same kernels, and the kernels read the new lengths from a buffer at a fixed address. The paged design solves a compilation problem as well as a memory problem, a point often missed.
Strategy 4: symbolic shapes in the compiler#
torch.compile(model, dynamic=True) # treat sizes as symbols from the start
torch._dynamo.mark_dynamic(x, 0) # or mark one dimension of one inputThe compiler generates code that works for any value of the marked size, with guards for the assumptions it still makes. The costs: some specialisations are lost (tile sizes cannot be chosen for the exact shape), and guards are checked on every call.
PyTorch’s default is automatic dynamic shapes: compile static on the first call, and if a later call fails a guard because a size changed, recompile once with that dimension marked dynamic. Usually the right default.
vLLM goes further: it compiles once, before serving, with the token dimension symbolic, drops the shape guards that would trigger recompilation, and guarantees no request ever triggers a compile (18.d).
6. Under the hood: watch a recompilation#
TORCH_LOGS="recompiles,dynamic" python script.pyThe log says why each recompile happened:
Recompiling function forward in model.py:42
triggered by the following guard failure(s):
- 0/0: tensor 'x' size mismatch at index 0. expected 8, actual 9After recompile_limit recompilations of one function (default 8), Dynamo logs
torch._dynamo hit config.recompile_limit (8) and stops compiling it; from then on that function
runs eagerly. A silent, permanent slowdown. Search production logs for that line.
7. Performance implications#
Approach Speed vs ideal static Flexibility
Fully static, one shape 100% none
Buckets + padding (dense buckets) close to 100% for decode good
Symbolic shapes in the compiler slightly below static excellent
Varlen kernels ~100% for prefill excellent
Prompts padded to a common length a fraction (section 4) good
Eager, no compilation lowest at small batch totalThe practical recipe used by every major engine: varlen kernels for prefill, bucketed CUDA graphs for decode, paged attention for context length. That recovers nearly all of the static performance with full flexibility.
8. Production implications#
- Make sure prefill is packed. Padding is the largest and most overlooked waste in home-grown serving code (section 4).
- Size the CUDA-graph list to your traffic. Measure how many tokens your decode steps really carry, then check the capture list covers that range densely.
- Cap input length at the gateway. Unbounded prompts mean unbounded prefill time and
activation memory; the engine’s
max_model_lenis the hard limit, but reject earlier with a clear error. - Alert on recompilation and on the recompile-limit message.
- Keep startup compilation off the request path: compile and capture before the instance is marked ready; vLLM does both at startup (18.d).
9. Common mistakes#
- Padding every sequence to the maximum length. Most of the compute is then dummies.
- Too few, too sparse buckets. Powers of two waste about a third of the decode slots.
- Too many buckets. Every captured graph costs startup time and memory.
- Not capping input length. One giant prompt can stall or crash an instance.
- Recompilation storms from shapes the compiler was never told are dynamic.
- Assuming symbolic shapes are free. They cost a little speed in exchange for no recompilation.
10. Hands-on exercise#
- Run
shapes.go. Sort the prompts by length before forming batches. How much padding is left? Why do engines not simply do this? - Replace the uniform decode batch sizes with a distribution from your own server’s metrics (or a skewed one, mostly 1–16 with a long tail) and design a 12-bucket list that minimises padding.
- In PyTorch, implement attention over three sequences of lengths 5, 300 and 2,000 with padding,
and with
flash_attn_varlen_func. Compare time and check the outputs agree. - Compile a small model with the default settings, call it with ten different batch sizes and
count recompilations with
TORCH_LOGS="recompiles". Repeat withdynamic=True. - Start vLLM with a small
max_cudagraph_capture_sizeand then a large one. Compare startup time, the memory reported for CUDA graphs and decode speed at batch 100.
11. Interview questions#
- Which dimensions vary in LLM serving, and how is each one handled?
- What is bucketing, and how would you choose the buckets?
- What is varlen packing, and how much can it save over padding?
- How does paged attention avoid recompiling or recapturing as contexts grow?
- What does PyTorch’s “automatic dynamic shapes” do, and what happens at the recompile limit?
- How does vLLM guarantee that no request triggers a compilation?
- Why should input length be capped at the gateway?
12. Further reading#
Checked on 12 November 2026.