Serving models: KV cache, batching and vLLM

Prefill versus decode, continuous batching, PagedAttention, speculative decoding, and how to size and benchmark an inference server.

Expert about 7 h

The picture

  1. 01

    Request

    prompt tokens

  2. 02

    Prefill

    compute-bound

  3. 03

    Decode

    memory-bound

  4. 04

    Continuous batching

    fill the GPU

  5. 05

    Stream

    tokens out

Two phases with different bottlenecks

  • Prefill: process the whole prompt at once. Highly parallel, compute-bound. Determines time to first token (TTFT).
  • Decode: generate one token at a time. Each step reads all the weights (and the KV cache) from GPU memory to produce a single token, so it is memory-bandwidth-bound. Determines time per output token (TPOT).

A useful rule for a single sequence: tokens per second is at most memory bandwidth divided by the bytes read per token.

def max_decode_tps(bandwidth_gb_s: float, params_b: float, bytes_per_param: float = 2.0):
    return bandwidth_gb_s / (params_b * bytes_per_param)

print(max_decode_tps(2000, 7))      # a 7B model in 16-bit on a 2 TB/s GPU: about 140 tokens/s per sequence

Because the weights are read once per step regardless of how many sequences are in the batch, batching many sequences together makes decode almost free per extra sequence, until compute or the KV cache runs out. Throughput comes from batching; latency comes from not queueing too long.

Continuous batching and PagedAttention

Naive batching waits for the longest sequence in a batch. Continuous (in-flight) batching adds new requests and removes finished ones at every step, keeping the GPU busy. The KV cache grows with each sequence and, if allocated contiguously, wastes memory through fragmentation. PagedAttention stores it in fixed-size blocks like virtual memory pages, allowing far more concurrent sequences and prefix sharing between requests with a common prompt.

Serving with vLLM

pip install vllm
vllm serve Qwen/Qwen2.5-7B-Instruct \
  --max-model-len 8192 \
  --gpu-memory-utilization 0.90 \
  --enable-prefix-caching

It exposes an OpenAI-compatible API, so your existing client code works:

from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")
r = client.chat.completions.create(model="Qwen/Qwen2.5-7B-Instruct",
                                   messages=[{"role": "user", "content": "Explain PagedAttention briefly."}], max_tokens=200)
print(r.choices[0].message.content)

For offline bulk jobs, use the Python API, which batches for you:

from vllm import LLM, SamplingParams
llm = LLM(model="Qwen/Qwen2.5-7B-Instruct", max_model_len=8192)
outs = llm.generate(prompts, SamplingParams(temperature=0, max_tokens=256))
texts = [o.outputs[0].text for o in outs]

Flag names evolve, so read the docs for your installed version.

Sizing a GPU

def capacity(gpu_gb, weights_gb, layers, kv_heads, head_dim, ctx_len, bytes_per=2, util=0.9):
    free = gpu_gb * util - weights_gb
    per_seq_gb = 2 * layers * kv_heads * head_dim * ctx_len * bytes_per / 1e9
    return int(free / per_seq_gb), per_seq_gb

print(capacity(80, 15, 32, 8, 128, 4096))        # 7B, GQA with 8 KV heads, 4k context on an 80 GB GPU

This ignores activation memory and fragmentation, so treat it as an upper bound and measure. Quantising weights frees memory for more KV cache; quantising the KV cache itself frees more at some quality risk.

Speculative decoding

A small draft model proposes several tokens; the large model verifies them in one forward pass and accepts the prefix that matches what it would have produced. Output quality is unchanged, and latency drops when the draft model is often right. It helps most at low batch sizes, where decode is most bandwidth-bound.

Benchmark properly

import asyncio, time, statistics as st
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="unused")

async def one(prompt):
    t0, first, n = time.perf_counter(), None, 0
    stream = await client.chat.completions.create(model=MODEL, messages=[{"role": "user", "content": prompt}], max_tokens=200, stream=True)
    async for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            first = first or time.perf_counter() - t0
            n += 1
    return first, (time.perf_counter() - t0), n

async def load(prompts, concurrency):
    sem = asyncio.Semaphore(concurrency)
    async def guarded(p):
        async with sem:
            return await one(p)
    t0 = time.perf_counter()
    res = await asyncio.gather(*(guarded(p) for p in prompts))
    wall = time.perf_counter() - t0
    ttft = sorted(r[0] for r in res)
    print(f"c={concurrency} p50 TTFT {st.median(ttft):.2f}s p95 {ttft[int(.95*len(ttft))-1]:.2f}s  throughput {sum(r[2] for r in res)/wall:.0f} tok/s")

for c in (1, 8, 32, 64):
    asyncio.run(load(PROMPTS, c))

Sweep concurrency and plot throughput against p95 latency: the knee of that curve is your operating point. Use realistic prompt and output length distributions, because a benchmark with short prompts will flatter you.

Which engine

vLLM and SGLang give excellent open-source throughput; TGI integrates with the Hugging Face ecosystem; TensorRT-LLM squeezes more from NVIDIA hardware at the cost of build complexity. Managed APIs remove all of this: do the sums on cost per million tokens at your real utilisation before self-hosting, because idle GPUs are expensive.

Common mistakes

  • Benchmarking with batch size 1 and extrapolating.
  • Ignoring the KV cache when sizing memory.
  • Self-hosting at 10 percent utilisation.

Exercises

  1. Serve a small model with vLLM and produce a concurrency sweep chart.
  2. Compare cost per million output tokens for self-hosting at your measured throughput with a hosted API price.

You are done when you can…

  • Explain why decode is memory-bandwidth-bound and what that implies for batch size
  • Serve a model with vLLM and benchmark time-to-first-token and throughput under load
  • Estimate how many concurrent sequences a GPU can hold given weights and KV cache