Fast Inference: KV Cache, Batching and Speculative Decoding
Training a language model is one large, regular computation. Serving one is many small, irregular ones: thousands of users, prompts of every length, answers that end whenever the model emits its end token, and a new token per user every few milliseconds. The cost of an LLM product is decided here, and most of the tricks of modern serving engines follow from one fact: generating a token reads every weight of the model from memory, and does very little arithmetic with it.
This lesson works that fact out with numbers and then builds the main techniques from scratch: the KV cache and grouped-query attention, static versus continuous batching, speculative decoding (with an exact check that it does not change the output distribution), and the tiled online softmax behind FlashAttention. The cache itself was built in Inside a Decoder-Only LM and its memory formula in The KV Cache; here they are inputs to a performance model.
Prefill and decode
A request has two phases:
- Prefill: the whole prompt (say 2,000 tokens) goes through the model in one forward pass, in parallel, and fills the KV cache. Each weight is read once and used for 2,000 tokens.
- Decode: one new token per forward pass, each attending to the cache. Each weight is read once and used for one token per sequence in the batch.
The ratio of arithmetic to memory traffic is the arithmetic intensity , in FLOPs per byte. A matrix-vector product with an fp16 weight matrix of entries does FLOPs (a multiply and an add per weight) and reads bytes, so ; with a batch of sequences the same weights serve vectors and . A processor with peak throughput (FLOP/s) and memory bandwidth (bytes/s) is memory-bound while , the "ridge point" of the roofline model. The time of one decode step is then
With KV caching, the decode FLOPs per token are about for parameters plus the attention over the context. The KV cache holds, for every layer and every token, a key and a value vector for each KV head: numbers per token. Grouped-query attention (GQA) lets several query heads share one KV head: with 32 query heads and 8 KV heads, the cache is 4 times smaller and attention reads 4 times fewer bytes, at a small quality cost that training absorbs (multi-head attention).
The example puts in round numbers: a hypothetical accelerator with TB/s and TFLOP/s, and a 7-billion-parameter model shaped like common open 7B models (32 layers, width 4096, 32 heads of size 128), with the full 32 KV heads (MHA) or 8 (GQA), at a context of 2,048 tokens.
# A hypothetical accelerator with round numbers (not a real product):
BW = 2.0e12 # memory bandwidth, bytes/s
PEAK = 400e12 # fp16 matrix throughput, FLOP/s
print(f"ridge point: {PEAK / BW:.0f} FLOP per byte")
# A 7e9-parameter decoder: 32 layers, width 4096, 32 query heads of size 128
N, layers, d, heads, hd = 7e9, 32, 4096, 32, 128
w_bytes = 2 * N # fp16 weights
def kv_bytes_per_token(kv_heads, bytes_per=2):
return 2 * layers * kv_heads * hd * bytes_per # K and V, every layer
def decode_step(batch, context, kv_heads):
bytes_moved = w_bytes + batch * context * kv_bytes_per_token(kv_heads)
flops = batch * (2 * N + 4 * layers * d * context) # matmuls + attention over the context
t = max(bytes_moved / BW, flops / PEAK)
return t, flops / bytes_moved, "memory" if bytes_moved / BW > flops / PEAK else "compute"
for kv_heads, label in [(32, "MHA, 32 KV heads"), (8, "GQA, 8 KV heads")]:
print(f"\n{label}: KV cache {kv_bytes_per_token(kv_heads) / 2**10:.0f} KiB per token")
print(f"{'batch':>5} {'step ms':>8} {'tokens/s':>9} {'per user':>9} {'FLOP/B':>7} bound KV GB")
for b in (1, 8, 32, 128):
t, ai, bound = decode_step(b, 2048, kv_heads)
kv_gb = b * 2048 * kv_bytes_per_token(kv_heads) / 1e9
print(f"{b:>5} {t * 1e3:>8.2f} {b / t:>9.0f} {1 / t:>9.1f} {ai:>7.1f} {bound:<6} {kv_gb:5.1f}")
prompt = 2000
t_prefill = max(w_bytes / BW, prompt * 2 * N / PEAK)
print(f"\nprefill of {prompt} tokens: {t_prefill * 1e3:.0f} ms, {prompt * 2 * N / w_bytes:.0f} FLOP per byte (compute-bound)")ridge point: 200 FLOP per byte
MHA, 32 KV heads: KV cache 512 KiB per token
batch step ms tokens/s per user FLOP/B bound KV GB
1 7.54 133 132.7 1.0 memory 1.1
8 11.29 708 88.5 5.3 memory 8.6
32 24.18 1323 41.4 10.0 memory 34.4
128 75.72 1690 13.2 12.7 memory 137.4
GQA, 8 KV heads: KV cache 128 KiB per token
batch step ms tokens/s per user FLOP/B bound KV GB
1 7.13 140 140.2 1.1 memory 0.3
8 8.07 991 123.9 7.5 memory 2.1
32 11.29 2833 88.5 21.4 memory 8.6
128 24.18 5294 41.4 39.9 memory 34.4
prefill of 2000 tokens: 70 ms, 2000 FLOP per byte (compute-bound)
What the table says:
- Batch 1 is memory-bound by a factor of 200. One step moves 14 GB of weights at 2 TB/s: about 7 ms, so 133 to 140 tokens per second, whatever the FLOPs. Halving the bytes per weight (int8, quantization) nearly doubles this number; a faster chip with the same bandwidth does not.
- Batching is almost free until the cache dominates. With GQA, batch 32 takes 11.3 ms per step instead of 7.1 and produces 2,833 tokens/s instead of 140: 20 times the throughput for each user getting 88.5 instead of 140 tokens/s. That trade between throughput (the operator's cost) and per-user speed (the user's experience) is the central dial of serving.
- The KV cache is the real limit. With MHA, batch 128 at 2,048 tokens needs 137 GB of cache, more than most single GPUs have; even batch 32 needs 34 GB. GQA cuts it to 34 GB at batch 128, and the per-token cost from 512 to 128 KiB. Even then every row is still memory-bound: the intensity reaches 40 FLOP/byte at most, far below the ridge point of 200, because reading the cache grows with the batch just like the work does.
- Prefill is compute-bound: 2,000 tokens share each weight, so it takes 70 ms of pure arithmetic, while generating 2,000 tokens one by one would take about 14 s at batch 1. This is why time to first token and tokens per second are separate metrics (Streaming).
Batching: static versus continuous
The obvious server collects a batch of requests, runs it until every sequence has finished, then takes the next batch. Answers differ in length by an order of magnitude, so most slots sit idle waiting for the longest answer, and new requests wait in the queue for the whole batch. Continuous batching (also "in-flight" or iteration-level batching, introduced by the Orca system in 2022) schedules per step: when a sequence finishes, its slot is given to the next waiting request at the next step.
The simulator below runs 200 requests arriving at random (one every 4 steps on average) with log-normal answer lengths (mean 27 tokens, maximum 233) through 8 slots, one token per running sequence per step, and measures throughput and the latency from arrival to the last token, in steps.
import numpy as np
rng = np.random.default_rng(0)
n_req, slots = 200, 8
arrival = np.cumsum(rng.exponential(4.0, n_req)).astype(int) # one request every 4 steps on average
length = np.clip(rng.lognormal(3.0, 0.8, n_req).astype(int), 2, 400) # output tokens per request
def simulate(continuous):
queue, running, done = [], {}, {} # running: request -> tokens still to generate
nxt, step, busy = 0, 0, 0
while len(done) < n_req:
while nxt < n_req and arrival[nxt] <= step:
queue.append(nxt); nxt += 1
if continuous or not running: # static: only start a batch when the last one is finished
while queue and len(running) < slots:
r = queue.pop(0); running[r] = length[r]
step += 1 # one decode step: one token for every running request
busy += len(running)
for r in list(running):
running[r] -= 1
if running[r] == 0:
del running[r]; done[r] = step
lat = np.array([done[r] - arrival[r] for r in range(n_req)])
return step, busy / (step * slots), lat
print(f"{n_req} requests, mean output {length.mean():.0f} tokens (max {length.max()}), {slots} slots")
for name, cont in [("static batching", False), ("continuous batching", True)]:
steps, util, lat = simulate(cont)
print(f"{name:<20} steps {steps:>5} tokens/step {length.sum() / steps:.2f} slot use {util:.0%} "
f"latency mean {lat.mean():.0f} p95 {np.percentile(lat, 95):.0f} steps")200 requests, mean output 27 tokens (max 233), 8 slots
static batching steps 2080 tokens/step 2.55 slot use 32% latency mean 714 p95 1048 steps
continuous batching steps 1008 tokens/step 5.27 slot use 66% latency mean 29 p95 71 steps
At this load, static batching keeps only 32% of the slots busy, produces 2.55 tokens per step and cannot keep up: the queue grows, and the mean latency is 714 steps (p95 1,048). Continuous batching serves the same requests at 5.27 tokens per step with a mean latency of 29 steps and a p95 of 71. Nothing in the model changed; only the scheduler did. Real engines also mix prefill into decode steps ("chunked prefill"), so that a long new prompt does not stall everyone's next token.
Paged attention (vLLM, 2023) solves the memory side of the same problem. Reserving a contiguous cache of the maximum length for each sequence wastes most of it, because few answers reach that length. Instead, the cache is split into fixed-size blocks (for example 16 tokens), allocated on demand and addressed through a per-sequence block table, like virtual memory pages. Waste drops to the last, partly filled block, so more sequences fit, and sequences with the same prompt prefix can share its blocks (prefix caching).
Speculative decoding
Decode is memory-bound, so a forward pass that checks tokens costs about the same as one that generates one. Speculative decoding (Leviathan et al. and Chen et al., 2023) exploits that: a small draft model with distribution proposes tokens cheaply, the large target model with distribution scores all of them in one pass, and a rejection rule keeps a prefix of them. For each proposed token :
and stop at the first rejection. The output is distributed exactly as : the probability of emitting is from acceptance, plus the rejection mass times , where is the acceptance rate. Since , the second term is , and the sum is . With independent acceptances, a pass yields on average tokens. The example checks the identity exactly and by 200,000 samples.
import numpy as np
vocab = ["the", "bike", "dock", "app", "card", "<eos>"]
p = np.array([0.30, 0.25, 0.20, 0.10, 0.10, 0.05]) # target model (large, slow)
q = np.array([0.40, 0.10, 0.25, 0.15, 0.05, 0.05]) # draft model (small, fast)
# exact output distribution of one speculative step:
# draft x ~ q, accept with prob min(1, p/q); on rejection sample from norm(max(p - q, 0))
accept = np.minimum(p, q) # P(draft proposes x and it is accepted)
alpha = accept.sum() # acceptance rate
residual = np.maximum(p - q, 0) / np.maximum(p - q, 0).sum()
out = accept + (1 - alpha) * residual
print("target p ", p.tolist())
print("speculative out", np.round(out, 12).tolist())
print(f"exact match: {np.allclose(out, p, atol=0, rtol=1e-12)}, acceptance rate alpha = {alpha:.2f}")
# the same by sampling, 200,000 steps
rng = np.random.default_rng(0)
n = 200_000
x = rng.choice(6, n, p=q)
ok = rng.random(n) < np.minimum(1, p[x] / q[x])
x[~ok] = rng.choice(6, (~ok).sum(), p=residual)
print("sampled freq ", np.round(np.bincount(x, minlength=6) / n, 3).tolist(), f"accepted {ok.mean():.3f}")
# with gamma draft tokens per step and independent acceptance alpha:
for gamma in (1, 2, 4, 8):
exp_tokens = (1 - alpha ** (gamma + 1)) / (1 - alpha)
print(f"gamma {gamma}: expected tokens per target pass {exp_tokens:.2f}")target p [0.3, 0.25, 0.2, 0.1, 0.1, 0.05]
speculative out [0.3, 0.25, 0.2, 0.1, 0.1, 0.05]
exact match: True, acceptance rate alpha = 0.80
sampled freq [0.3, 0.252, 0.199, 0.1, 0.099, 0.05] accepted 0.799
gamma 1: expected tokens per target pass 1.80
gamma 2: expected tokens per target pass 2.44
gamma 4: expected tokens per target pass 3.36
gamma 8: expected tokens per target pass 4.33
The distributions agree to 12 decimals; the sampled frequencies agree to the third decimal, and the sampled acceptance rate is 0.799 against . With drafts, each target pass yields 3.36 tokens on average. The speed-up is less than that, because the draft passes cost time too and the target pass over 5 tokens is a little slower than over 1; reported speed-ups of 2 to 3 times are typical when the draft agrees often (code, templated text) and smaller for creative text. Variants drop the separate draft model: extra prediction heads on the target (Medusa), or the target's own early layers.
FlashAttention: attention without the matrix
Naive attention materialises the scores , a matrix per head, writes it to memory, reads it back for the softmax and again for the product with . For long sequences that traffic, not the FLOPs, dominates. FlashAttention (Dao et al., 2022) computes the same output by visiting and in blocks that fit in fast on-chip memory, keeping per query a running maximum , a running sum and an unnormalised output . When a block raises the maximum, the earlier sums are rescaled:
This online softmax is exact, not an approximation, as the example confirms.
import numpy as np
rng = np.random.default_rng(0)
T, d, block = 1024, 64, 128
Q, K, V = (rng.normal(0, 1, (T, d)) for _ in range(3))
def naive(Q, K, V):
S = Q @ K.T / np.sqrt(d) # T x T scores in memory
P = np.exp(S - S.max(axis=1, keepdims=True))
return (P / P.sum(axis=1, keepdims=True)) @ V
def tiled(Q, K, V, block):
"""Online softmax: visit K, V in blocks, keep a running max m, sum l and output acc per query."""
m = np.full((len(Q), 1), -np.inf)
l = np.zeros((len(Q), 1))
acc = np.zeros((len(Q), V.shape[1]))
for j in range(0, len(K), block):
S = Q @ K[j:j + block].T / np.sqrt(d) # only T x block scores at a time
m_new = np.maximum(m, S.max(axis=1, keepdims=True))
correction = np.exp(m - m_new) # rescale what was accumulated with the old max
P = np.exp(S - m_new)
l = l * correction + P.sum(axis=1, keepdims=True)
acc = acc * correction + P @ V[j:j + block]
m = m_new
return acc / l
O1, O2 = naive(Q, K, V), tiled(Q, K, V, block)
print("max |naive - tiled| below 1e-12:", bool(np.abs(O1 - O2).max() < 1e-12))
print(f"score memory: naive {T * T * 4 / 2**20:.1f} MiB per head, tiled {T * block * 4 / 2**20:.2f} MiB (fp32)")max |naive - tiled| below 1e-12: True
score memory: naive 4.0 MiB per head, tiled 0.50 MiB (fp32)
The tiled result equals the naive one to within , while it never holds more than scores: 0.5 MiB instead of 4 MiB per head at , and the saving grows linearly with . On a GPU the gain is speed, from fewer trips to main memory; the FLOPs are the same. In PyTorch, torch.nn.functional.scaled_dot_product_attention picks such a fused kernel automatically when the hardware supports it.
Pitfalls
- Optimising FLOPs for decode. Decode is bound by bytes: weights plus KV cache. Count bytes first.
- Measuring throughput only. Batching raises tokens per second for the server and lowers it for each user; report both, and latency percentiles.
- Forgetting the cache in memory planning. Weights fit, then 32 long conversations do not. Budget the cache per token times context times batch.
- Static batching for chat traffic. Variable answer lengths waste most slots; use an engine with continuous batching.
- Speculative decoding with a poor draft. If the acceptance rate is low, the draft passes are wasted work; measure on your traffic.
- Changing the sampling rule by accident. Speculative decoding is exact only with the rejection step above; "accept if the target's argmax agrees" is a different (greedy) method.
Practice
- Using the example's numbers, how many tokens per second at batch 1 would the 7B model reach in int4 (weights only, 3.6 GB)? Why is the real gain smaller?
- For a model with 80 layers, 8 KV heads of size 128 and fp16 cache, how large is the KV cache per token, and for one 32,000-token conversation?
- In the batching simulator, set
slots = 32. Which of the two schedulers benefits more, and why? - In the speculative example, what is if the draft equals the target? What if the two put their mass on disjoint tokens?
- Why can the online softmax rescale and by the same factor ?
Answers
- About tokens/s, roughly 4 times the fp16 rate. In reality the dequantization kernels do not reach full bandwidth, the KV cache and activations are not quantized, and the step has fixed overheads (kernel launches, sampling, scheduling).
- bytes, 320 KiB per token; for 32,000 tokens about bytes, 10.5 GB for one conversation.
- Static batching benefits far more. With 32 slots it can finally keep up (4.94 tokens per step) and its mean latency falls from 714 to 130 steps (p95 271), but its slots still idle until each batch's longest answer, and new requests still wait for a whole batch. Continuous batching was already keeping up with 8 slots: its mean latency only moves from 29 to 27 steps (p95 71), and its slot use drops to 16% because there is not enough traffic to fill 32 slots.
- If , : every draft is accepted. With disjoint supports everywhere, : every draft is rejected and each pass yields one token sampled from , so the output is still exactly , just with no speed-up.
- Both are sums of terms computed with the old maximum. Changing the reference from to multiplies every such term by , and the factor cancels in .
Test yourself
Why is decoding at batch 1 memory-bound?
- The KV cache is computed in fp32
- Each weight is read from memory once per step and used for only one token, about 1 FLOP per byte
- Attention is quadratic in the context
- Sampling is slow
In the example, what does GQA with 8 KV heads instead of 32 change at batch 128 and 2,048 tokens of context?
- Nothing, the weights dominate
- The KV cache drops from 137.4 GB to 34.4 GB and throughput rises from 1,690 to 5,294 tokens/s
- The step becomes compute-bound
- The model gets 4 times fewer parameters
What does continuous batching change compared with static batching?
- It uses a smaller model for short requests
- A finished sequence's slot is given to a waiting request at the next step instead of after the whole batch
- It batches only requests with equal lengths
- It skips the prefill
With acceptance rate and draft tokens, how many tokens does one target pass yield on average?
- 0.8
- 3.2
- 3.36
- 5
Is FlashAttention an approximation of attention?
- Yes, it drops small scores
- Yes, it uses low-rank keys
- No, the online softmax gives the same result; it saves memory traffic
- No, but it needs more FLOPs than naive attention