7 Inference and Serving 7 / 8
  1. In this chapter
  2. Your first inference service
  3. Decoding and Sampling
  4. KV Cache and Inference Performance
  5. Prefix Caching and PD Disaggregation
  6. Model Quantization
  7. LLM Inference Serving
  8. Continuous Batching and PagedAttention
  9. Speculative Decoding
All chapters →

Chapter 7 · Inference and Serving 7.7

Continuous Batching and PagedAttention: How a Server Handles Many Requests at Once

Every decode step reads all the weights, so putting several requests in one batch raises throughput almost for free. This page measures concurrency, continuous batching, paged KV caches and prefix caching with llama.cpp to show how one GPU serves many requests.

Intermediate 35 min read Updated Companion code ↓

After this page you will be able to

  • Explain why batching requests in the decode phase raises throughput almost for free, and under which conditions the "almost" stops holding.
  • Tell static batching from continuous batching and estimate how much time the latter saves on requests of different lengths.
  • Work out how large the KV cache of one request is, why reserving the maximum length wastes memory and how the paging of PagedAttention fixes it.
  • State the conditions under which prefix caching hits and restructure prompts accordingly.
  • Read the concurrency-related parameters of llama.cpp and vLLM.
On this page
  1. Why Batching Requests Raises Throughput
  2. Static and Continuous Batching
  3. Scheduling Details: How Prefill and Decode Share Each Step
  4. The KV Cache: the Ceiling of Concurrency
  5. Reserving the Maximum Length vs Paging
  6. The Same Question in llama.cpp
  7. Prefix Caching: an Identical Beginning Is Computed Once
  8. Summary and Exercises
  9. Quick quiz
  10. Further Reading
  11. FAQ

The throughput of an inference server comes from batching: every decode step reads all the weights from memory once, one read can serve all the requests in the batch, and the bigger the batch, the lower the cost per token. Continuous batching lets a new request fill in as soon as another one ends, PagedAttention cuts the KV cache into fixed-size blocks to avoid wasting memory, and prefix caching computes an identical beginning only once. Together they are the common skeleton of servers such as vLLM and llama.cpp.

Experimental setup

The numbers on this page come from one machine and one client: a MacBook Pro (Apple M2 Max, 64 GB of unified memory) running llama-server from llama.cpp (build 11146) with Qwen2.5-7B-Instruct quantized to Q4_K_M (4.68 GB) and 16 slots. The client and the measurement method are on the page LLM Inference Serving, which also explains why every experiment starts with a warm-up. Absolute numbers differ on other hardware; take away the trends and the method.

Why Batching Requests Raises Throughput

Generating a token goes through all the layers, so it reads all the weights from memory once. The cost of reading the weights does not depend on how many tokens are generated in this step: when BB requests decode at the same time, one read serves all BB of them, and the amount read per token falls to 1/B1/B. That is why batching raises throughput.

A roofline argument shows how far this benefit extends. A linear layer that processes BB tokens needs 2BN2BN floating-point operations (NN is the number of weights of the layer) and reads NN weights; stored in BF16 that is 2N2N bytes, so for every byte read there are BB operations: the arithmetic intensity equals the batch size. An H100 SXM has a memory bandwidth of 3.35 TB/s and about 989 TFLOPS of dense BF16 compute (the 1,979 TFLOPS that NVIDIA lists includes sparsity, and the dense figure is half of that); the ratio is about 295 FLOP/B. For a batch much smaller than 295, the time of a step is set by reading the weights, and adding a few sequences barely increases it.

The KV cache cannot be shared like this: every sequence has its own K and V and reads its own part at every step. The bigger the batch and the longer the contexts, the more that is read. With the numbers worked out below, the FP16 weights of Qwen2.5-7B are 14.2 GiB, every sequence of 4096 tokens reads 224 MiB of KV cache per step, and at about 65 sequences the KV reads match the weight reads. So “bigger is better” has a limit, set jointly by compute, the amount of KV cache read and the memory capacity.

Let us measure it on this M2 Max. The code below lets CC requests arrive at once (64-token prompts, 128 generated tokens each) and records the total throughput, the speed of one request, the time to first token and the slot occupancy from the server’s /metrics. It reuses the client.py of LLM Inference Serving:

async def watch(s, stop, peak):  # poll /metrics for slot occupancy
    while not stop.is_set():
        async with s.get(URL + "/metrics") as r:
            for line in (await r.text()).splitlines():
                name, _, val = line.partition(" ")
                if name.startswith("llamacpp:requests_"):
                    peak[name] = max(peak.get(name, 0), float(val))
        await asyncio.sleep(0.2)


async def sweep():
    s, toks = await start()
    step = {}  # concurrency -> seconds per decoded token
    print("  C  total tok/s  per-req tok/s  TTFT mean/max(s)  busy  queued")
    for C in (1, 2, 3, 4, 6, 8, 12, 16, 24, 32):
        runs = []
        for rep in range(2):
            stop, peak = asyncio.Event(), {}
            w = asyncio.create_task(watch(s, stop, peak))
            t0 = time.perf_counter()
            rs = await asyncio.gather(*[
                request(s, piece(toks, i, 64), 128, t0) for i in range(C)])
            stop.set()
            await w
            runs.append((
                sum(r["n"] for r in rs) / max(r["done"] for r in rs),
                st.mean(r["tpot"] for r in rs),
                st.mean(r["ttft"] for r in rs), max(r["ttft"] for r in rs),
                peak.get("llamacpp:requests_processing", 0),
                peak.get("llamacpp:requests_deferred", 0)))
        m = [st.mean(x) for x in zip(*runs)]
        step[C] = m[1]
        print(f"{C:>3} {m[0]:11.1f} {1 / m[1]:14.1f} {m[2]:9.2f} /{m[3]:6.2f} "
              f"{max(r[4] for r in runs):5.0f} {max(r[5] for r in runs):7.0f}")
    await s.close()
    return step


STEP = asyncio.run(sweep())

Output:

  C  total tok/s  per-req tok/s  TTFT mean/max(s)  busy  queued
  1        38.1           40.1      0.19 /  0.19     1       0
  2        47.0           24.8      0.31 /  0.31     2       0
  3        51.1           17.8      0.39 /  0.39     3       0
  4        65.4           17.3      0.47 /  0.47     4       0
  6        68.6           12.2      0.76 /  0.76     6       0
  8        76.2           10.2      0.94 /  0.94     8       0
 12       111.6           10.4      1.50 /  1.50    12       0
 16       139.0           10.0      1.99 /  2.00    16       0
 24       106.7            9.8      6.66 / 16.02    16       8
 32       133.8            9.7      9.84 / 17.61    16      16
Total throughput and per-request speed at different concurrency, Qwen2.5-7B Q4_K_M on an M2 Max The left panel shows total throughput against concurrency: from 1 to 16 concurrent requests it rises from 38.1 to 139.0 tokens/s; beyond the 16 slots the extra requests queue and the total falls back to between 107 and 134. The right panel shows the speed of a single request: from 40.1 tokens/s at concurrency 1 down to 10.2 at concurrency 8, then roughly flat around 10. Concurrency vs throughput: total 3.6x higher, each request at a quarter speed Total throughput (tokens/s) 0 40 80 120 160 1 2 3 4 6 8 12 16 24 32 Concurrent requests 16 slots 38.1 139.0 Speed of one request (tokens/s) 0 10 20 30 40 1 2 3 4 6 8 12 16 24 32 Concurrent requests 16 slots 40.1 10.0 Hollow points: more requests than slots, the extra ones queue
Each concurrency level was run twice and averaged; every request has a 64-token prompt and generates 128 tokens. Hollow points have more requests than the 16 slots, so the extra ones wait for earlier ones to finish and the total falls back.

Four things to read in the table:

  1. Throughput grew 3.6 times and each request only slowed to a quarter. From concurrency 1 to 16, the total throughput rises from 38.1 to 139.0 tokens/s while the speed of one request falls from 40.1 to 10.0 tokens/s. Sixteen times as many requests are served, and each is only 4 times slower.
  2. The curve is neither flat nor smooth. The step time (the reciprocal of the per-request speed) is 24.9, 40.4 and 56.2 ms at concurrency 1, 2 and 3, about 15 ms more for every extra sequence; at concurrency 4 it is 57.9 ms, hardly higher; from 8 upward it stays at 96 to 100 ms. The roofline model predicts that “a few more sequences barely add to the time”, which is not what this machine does between 1 and 8. This agrees with the kernel selection of the llama.cpp Metal backend: in ggml-metal-ops.cpp a comment says the small-batch matrix-vector kernels “should be efficient for BS [2, ~8]”, and for K-quants such as Q4_K and Q6_K they are used only for batch sizes 4 to 8 (batch sizes 2 and 3 still go through the row-by-row matrix-vector kernel, which reads the weights once more for every extra sequence), and only above 8 does it switch to the matrix-matrix kernel. The steps in the curve sit at these boundaries, but I did not profile the kernels one by one, so this is an explanation consistent with the source and not a verified conclusion. Do not take this curve as the expectation for other hardware; measure on your own hardware and engine before going live.
  3. Once the slots are full, requests queue. At concurrency 24 and 32, busy stays at 16 and queued is 8 and 16: the extra requests wait for earlier ones to finish, and the maximum time to first token jumps to 16 to 18 s. The total throughput at concurrency 24 also falls back to 106.7 tokens/s because the second wave has only 8 requests and the batch is not full; concurrency 32 is two full waves, and the throughput returns to 133.8 tokens/s.
  4. The time to first token grows with concurrency. When 16 requests arrive together, 16×64=102416 \times 64 = 1024 prompt tokens have to be prefilled first, so the mean time to first token rises from 0.19 s at concurrency 1 to 1.99 s.

Static and Continuous Batching

Batching raises a second problem: the requests of a batch have different output lengths. Static batching starts and ends a batch of requests together: a short request finishes first, its slot stays empty, and the next batch can only start after the longest request ends. Continuous batching, also called iteration-level scheduling, uses “one decode step” as the unit of scheduling: after every step it checks which requests have finished and immediately moves requests from the queue into the free slots. The idea comes from Orca (OSDI 2022); the vLLM paper summarizes this family of mechanisms as working at the iteration level, where after each iteration completed requests are removed from the batch and new ones are added.

Let us verify it on a real server. 48 requests arrive at once, each with a 128-token prompt and an output length drawn from a log-normal distribution (fixed seed, so it is the same every time):

import random


def make_lengths(n=48, seed=7):  # skewed (log-normal) output lengths
    rng = random.Random(seed)
    return [min(512, max(8, round(100 * rng.lognormvariate(0, 0.9))))
            for _ in range(n)]


lengths = make_lengths()
print(f"{len(lengths)} requests, output tokens: min {min(lengths)}, "
      f"median {st.median(lengths):.0f}, mean {st.mean(lengths):.0f}, "
      f"max {max(lengths)}, total {sum(lengths)}")
48 requests, output tokens: min 15, median 61, mean 97, max 453, total 4656

The server has 16 slots. llama-server enables continuous batching by default, and adding -nocb (--no-cont-batching) degrades it to static batching. Each mode is run twice, restarting the server every time and warming up for 40 seconds first:

import os


async def batching(label):
    s, toks = await start()
    await warm_up(s, toks, 40)
    t0 = time.perf_counter()  # all 48 requests arrive at t = 0
    rs = await asyncio.gather(*[request(s, piece(toks, i, 128), n, t0)
                                for i, n in enumerate(lengths)])
    done = sorted(r["done"] for r in rs)
    print(f"{'server':>8} {'total(s)':>8} {'tok/s':>7} {'mean(s)':>8} "
          f"{'p90(s)':>7} {'TTFT(s)':>8}")
    print(f"{label:>8} {done[-1]:8.1f} {sum(lengths) / done[-1]:7.1f} "
          f"{st.mean(done):8.1f} {done[int(0.9 * len(done))]:7.1f} "
          f"{st.mean(r['ttft'] for r in rs):8.1f}")
    await s.close()


# MODE is "default" or "-nocb", matching how the server was started
asyncio.run(batching(os.environ.get("MODE", "default")))

The four runs in one table (default is continuous batching and -nocb is static batching; mean and p90 are the mean and the 90th percentile of the completion times of the requests, and TTFT includes queueing time):

  server total(s)   tok/s  mean(s)  p90(s)  TTFT(s)
 default     51.3    90.8     27.4    44.2     15.2
   -nocb     68.6    67.9     36.3    64.2     27.5
 default     51.0    91.2     28.4    45.6     15.9
   -nocb     67.9    68.6     38.1    63.7     30.0

The two repetitions are close. Continuous batching takes 51 s in total and static batching 68 s, about a quarter less time, and the total throughput rises from 68 to 91 tokens/s; the mean completion time falls from 37 to 28 s and the 90th percentile from 64 to 45 s. Under static batching the time of every batch is set by its longest request. This workload falls into three batches of 16 requests whose longest outputs are 218, 453 and 192 tokens: after the short requests finish, their slots stay empty for the rest of the batch, the batch keeps shrinking and the GPU is less and less busy.

Why does continuous batching not save more? Start with all the work to be done: 48 requests with 4656 output tokens in total. If 16 sequences were decoding at all times (about 100 ms per step), it would take only 4656/16×0.1≈294656 / 16 \times 0.1 \approx 29 s. Add the prefill of every request: a 128-token prompt takes 0.343 s, during which all slots have to wait, so 48 requests cost 48×0.343≈16.548 \times 0.343 \approx 16.5 s, the same for both schedules. So a third of the 51 seconds is prefill and the remaining 35 s or so is decode. What it has above the ideal 29 s is mostly the “drain” phase after the queue has emptied: in the simulation below the last request starts generating only at second 38, and during the following 14.6 s the batch only gets smaller, with the one 453-token request alone on the server for the last few seconds.

Write the phenomenon in 30 lines of code: at each step look up the step time for the current batch size in the table measured in the previous section, and when a new request enters, pause the whole batch for the duration of one prefill. STEP comes from the sweep cell of the previous section and PROMPT_SECONDS from the anatomy cell of LLM Inference Serving:

def step(b):  # seconds per decode step with b active sequences
    ks = sorted(STEP)
    if b <= ks[0]:
        return STEP[ks[0]]
    for lo, hi in zip(ks, ks[1:]):
        if b <= hi:
            return STEP[lo] + (STEP[hi] - STEP[lo]) * (b - lo) / (hi - lo)
    return STEP[ks[-1]]


def simulate(lengths, slots, continuous, stall):
    todo, run, t, done = list(lengths), [], 0.0, []
    while todo or run:
        if continuous or not run:  # static batching only refills when empty
            while todo and len(run) < slots:
                run.append(todo.pop(0))
                t += stall  # a new prompt stalls everyone for its prefill
        t += step(len(run))
        run = [n - 1 for n in run]
        done += [t] * sum(n == 0 for n in run)
        run = [n for n in run if n > 0]
    return done


print("batch    " + " ".join(f"{b:5d}" for b in STEP))
print("step(ms) " + " ".join(f"{1000 * v:5.1f}" for v in STEP.values()))

lengths = make_lengths()
stall = PROMPT_SECONDS[128]  # seconds one 128-token prompt blocks the batch
print(f"prefill of a 128-token prompt: {stall:.3f} s")
print("mode         makespan  tok/s  mean_done  p90_done")
for name, cont in (("continuous", True), ("static", False)):
    d = simulate(lengths, 16, cont, stall)
    print(f"{name:<12} {d[-1]:7.1f} {sum(lengths) / d[-1]:7.1f} "
          f"{st.mean(d):9.1f} {d[int(0.9 * len(d))]:8.1f}")
batch        1     2     3     4     6     8    12    16    24    32
step(ms)  24.9  40.4  56.2  57.9  82.2  98.4  96.5 100.3 101.6 103.5
prefill of a 128-token prompt: 0.343 s
mode         makespan  tok/s  mean_done  p90_done
continuous      52.5    88.6      29.9     47.0
static          68.6    67.9      37.7     64.0

The simulated total times differ from the measured ones by only a few percent: continuous batching 52.5 s against 51.0 to 51.3 s measured, static batching 68.6 s against 67.9 to 68.6 s. No parameter of the model is fitted; its inputs are just two measured tables, the time per step and the prefill time. This shows that on this machine, the effect of the scheduling policy on the total time can be explained by two things: “the batch size decides the step time” and “when a slot is refilled”. Taking the model apart: the prefill is 16.5 s for both schedules, the decode part is about 36 s for continuous batching and about 52 s for static batching, and against the ideal of 29 s the former reaches 81% and the latter only 56%.

The widget below uses the same simulator. Its default settings (16 slots, the 48 requests of this page, a 128-token prompt, the measured curve) are the experiment above, and you should see 52.5 s against 68.6 s. Drag the controls and see:

  • Set the output lengths to “All equal”: the total time of the two schedules is the same (46.6 s in both cases), because the requests of a batch finish together and no slot stays idle under static batching. Set it to “Long tail”: continuous batching takes 27% less time, the most of the length distributions.
  • Switch the step time to “Ideal: independent of batch size”: the benefit of batching is at its largest, the throughput of continuous batching rises from 89 to 164 tokens/s and that of static batching from 68 to 123 tokens/s, and the former still takes 25% less time. Switch it to “Extreme: proportional to batch size”: every extra sequence adds its own share of time, batching brings no throughput benefit, and both schedules take the same total time.
  • Set the prompt length to 1024: prefill takes most of the time (105 s for the 48 requests out of a total of 141 s), and the two schedules differ by only 10%. For very long prompts the bottleneck is prefill, not the scheduling of decode.
  • Lower the slots to 2: the two schedules differ by only 7%, since the batch is small and static batching wastes few slots.
Is the gap larger or smaller in an online service

This experiment is a burst of 48 requests at once, with a “drain” at the end: the last long requests have the server to themselves and the batch is small. In an online service requests keep arriving and the batch is full most of the time, and the benefit of continuous batching shows up as follows: a new request does not have to wait until the current batch ends but can enter at the next step. Under static batching a new request waits for the whole batch to end, so the time to first token differs by one “batch length”.

Scheduling Details: How Prefill and Decode Share Each Step

A new request has to be prefilled first. Prefill processes the whole prompt at once, is limited by compute, and takes roughly time proportional to the prompt length (1024 tokens took about 2.2 s on the previous page). If all requests that are decoding have to wait for it, their token gaps show one long pause; the simulation above expresses this as “the whole batch pauses”.

Chunked prefill cuts a long prompt into chunks, processes one chunk per step and lets the requests that are decoding ride along. The SARATHI paper calls this “decode-maximal batching”: one prefill chunk saturates the compute, the decode requests piggyback on it, and the cost of the piggybacked decodes is up to an order of magnitude lower than a decode-only batch. vLLM V1 enables chunked prefill by default where possible; when scheduling, it first admits all pending decode requests and then fills the rest of the max_num_batched_tokens budget with prefill chunks. The trade-off in the vLLM documentation: a smaller value gives steadier token gaps for decode, a larger value gives a faster first token, and for throughput a value above 8192 is recommended for smaller models. In the llama.cpp server the corresponding parameters are -b (logical batch size, default 2048) and -ub (physical batch size, default 512).

The KV Cache: the Ceiling of Concurrency

How much memory one request takes and how many requests fit at the same time are both decided by the KV cache. The KV cache per token is 2×2 \times layers ×\times KV heads ×\times head dimension ×\times bytes per number. The code below works it out from the config.json of Qwen2.5-7B and estimates how many requests fit on an 80 GiB card (assuming 90% of the memory is usable and 4 GiB is left for activations; both numbers are assumptions):

import glob
import json
import math
import os

cfg = json.load(open(glob.glob(os.path.expanduser(
    "~/.cache/huggingface/hub/models--Qwen--Qwen2.5-7B/snapshots/*/"
    "config.json"))[0]))
d, ff, v = cfg["hidden_size"], cfg["intermediate_size"], cfg["vocab_size"]
L, kv = cfg["num_hidden_layers"], cfg["num_key_value_heads"]
hd = d // cfg["num_attention_heads"]

per_token = 2 * L * kv * hd * 2  # K and V, 2 bytes each (FP16)
attn = 2 * d * d + 2 * d * kv * hd + d + 2 * kv * hd  # q,k,v,o (+ q,k,v bias)
params = 2 * v * d + L * (attn + 3 * d * ff + 2 * d) + d
GiB = 2 ** 30
print(f"layers {L}, KV heads {kv}, head dim {hd}")
print(f"KV cache per token: {per_token:,} bytes")
print(f"  4096-token slot: {4096 * per_token / 2**20:.0f} MiB, "
      f"65536-token pool: {65536 * per_token / GiB:.2f} GiB")
print(f"parameters: {params / 1e9:.3f} B -> FP16 weights "
      f"{2 * params / GiB:.1f} GiB")
print(f"KV reads per step equal weight reads at "
      f"{2 * params / (4096 * per_token):.0f} sequences of 4096 tokens")

# a 80 GiB GPU, 90% usable, 4 GiB reserved for activations (assumption)
pool = 0.9 * 80 * GiB - 2 * params - 4 * GiB
tokens = pool / per_token
print(f"KV pool: {pool / GiB:.1f} GiB = {tokens / 1e6:.2f} M tokens")
fixed = int(tokens // 8192)  # every request reserves max_model_len = 8192
paged = int(tokens // (math.ceil(1000 / 16) * 16))  # 1000-token average
print(f"sequences, reserve 8192 tokens each: {fixed}")
print(f"sequences, 16-token blocks, 1000 tokens avg: {paged}")

Output:

layers 28, KV heads 4, head dim 128
KV cache per token: 57,344 bytes
  4096-token slot: 224 MiB, 65536-token pool: 3.50 GiB
parameters: 7.616 B -> FP16 weights 14.2 GiB
KV reads per step equal weight reads at 65 sequences of 4096 tokens
KV pool: 53.8 GiB = 1.01 M tokens
sequences, reserve 8192 tokens each: 123
sequences, 16-token blocks, 1000 tokens avg: 999

Qwen2.5-7B uses grouped-query attention (GQA, 4 KV heads), so a token needs only 57,344 bytes; compare OPT-13B in the vLLM paper at 800 KB per token (2×5120×40×22 \times 5120 \times 40 \times 2 bytes), 14 times as much. The fewer the KV heads and the shorter the context, the more requests fit in the same memory.

Reserving the Maximum Length vs Paging

How this memory is handed out to the requests matters just as much. The most direct way is to reserve a contiguous region of the maximum length (say max_model_len = 8192) as soon as a request arrives, because nobody knows in advance how long it will generate. By the estimate above, that approach holds only 123 requests; allocating by the real length (1000 tokens on average, rounded up to a multiple of 16) holds 999, 8 times as many.

Contiguous reservation compared with paged allocation Both strips show the same 24 units of KV-cache memory. The upper strip reserves a contiguous run of the maximum length for each request: three requests reserve 18 blocks but use only 7.8, and the 6 free blocks cannot hold the new request D that needs 8. The lower strip allocates fixed-size blocks on demand: the three requests hold 10 blocks that need not be adjacent, and the 8 blocks of D fit into scattered free positions. Contiguous reservation vs paging, same 24 blocks of memory Top: contiguous reservation, a run of the maximum length per request Request A reserves 6, uses 2.5 Request B reserves 6, uses 4.2 Request C reserves 6, uses 1.1 18 blocks reserved, 7.8 used (43%); the 6 free blocks cannot hold D, which needs 8. Bottom: paging, fixed-size blocks on demand, blocks need not be adjacent A B B C A D D B D A D D B B D C D D 10 blocks allocated, 7.8 used (78%); the 8 blocks of D can sit at any free positions. in use reserved, unused free blocks of D
Each block holds the KV cache of 16 tokens; the numbers are illustrative. The block table of PagedAttention maps a request's logical positions to physical blocks that need not be adjacent.

PagedAttention borrows the paging of virtual memory from operating systems: the KV cache is cut into fixed-size blocks (16 tokens by default in the vLLM paper), every request has a block table that maps its logical positions to physical blocks, the blocks need not be adjacent, and they are allocated as they are needed. A request wastes only the unused part of its last block. The vLLM paper measured that in earlier systems only 20.4% to 38.2% of the KV-cache memory held real tokens, against about 96.3% in vLLM; at the same latency, it reports 2 to 4 times the throughput of FasterTransformer and Orca. Several parallel samples of one prompt can share the blocks of the prompt and copy them only when they write (copy-on-write), which is also what makes prefix caching possible.

When memory really runs out, vLLM preempts some requests and frees their blocks, and recomputes the preempted requests later when there is room. The default in V1 is to recompute (RECOMPUTE) instead of swapping out to main memory, because recomputation has lower overhead in the V1 architecture (vLLM documentation). Frequent preemption warnings mean the KV cache is tight: the documentation suggests raising gpu_memory_utilization, lowering max_num_seqs or max_num_batched_tokens, or adding parallelism to free memory.

The Same Question in llama.cpp

The llama.cpp server has to answer the same question: how to divide one KV cache among 16 slots. Without --kv-unified, the total context -c is divided equally among the slots and every request can use only its own share; with --kv-unified all slots share one cache and whoever needs it uses it. Try the same 6000-token request with both ways of starting (-c 65536 -np 16):

import textwrap


async def slots():
    s, toks = await start()
    async with s.get(URL + "/props") as r:
        n_ctx = (await r.json())["default_generation_settings"]["n_ctx"]
    print("context available to one request:", n_ctx, "tokens")
    status, d = await post(s, "/completion", {
        "prompt": toks[:6000], "n_predict": 8, "temperature": 0})
    if status == 200:
        print(f"HTTP 200: {d['tokens_evaluated']} prompt tokens processed")
    else:
        print(f"HTTP {status}:")
        print(textwrap.fill(d["error"]["message"], 72))
    await s.close()


asyncio.run(slots())

With --kv-unified:

context available to one request: 65536 tokens
HTTP 200: 6000 prompt tokens processed

Without it:

context available to one request: 4096 tokens
HTTP 400:
request (6000 tokens) exceeds the available context size (4096 tokens),
try increasing it

In the first case every request can use the whole pool of 65536 tokens; in the second each slot has only 65536/16=409665536 / 16 = 4096, and the 6000-token request is rejected. That is the difference between “reserving” and “sharing”, at a much smaller scale than vLLM. Ollama’s approach is to multiply the context length by the number of parallel requests (the official FAQ’s example: a 2K context with 4 parallel requests is actually an 8K context, and memory grows accordingly).

Prefix Caching: an Identical Beginning Is Computed Once

Many requests start the same way: the system prompt, the tool definitions, the same document in RAG, all earlier turns of a multi-turn chat. The KV cache of these tokens depends only on themselves and the tokens before them, so once computed it can be kept for later requests. This is prefix caching, and it changes no output.

The experiment: a 2000-token document plus a 20-token question, sent 4 times with a different question each time. Three cases: A, the document first with the cache on; B, 8 tokens that change every time (a timestamp, say) in front of the document with the cache on; C, the document first with the cache off (cache_prompt is false in the request).

async def prefix():
    s, toks = await start()
    await warm_up(s, toks, 40)
    doc = toks[120_000:122_000]  # a 2000-token "system prompt / document"
    ask = lambda i: toks[125_000 + 50 * i:][:20]  # 20-token questions
    head = lambda i: toks[127_000 + 10 * i:][:8]  # 8 changing tokens
    cases = [("A doc first, cache on", True, lambda i: doc + ask(i)),
             ("B header first, cache on", True,
              lambda i: head(i) + doc + ask(i)),
             ("C doc first, cache off", False, lambda i: doc + ask(i))]
    print("case                       req  reused  computed  TTFT(s)")
    for name, cache, build in cases:
        for i in range(4):
            r = await request(s, build(i), 16, time.perf_counter(), cache)
            print(f"{name:<26} {i + 1:>3} {r['srv']['cache_n']:7d} "
                  f"{r['srv']['prompt_n']:9d} {r['ttft']:8.2f}")
    async with s.get(URL + "/metrics") as r:
        for line in (await r.text()).splitlines():
            if line.startswith("llamacpp:prompt_tokens"):
                print(line)
    await s.close()


asyncio.run(prefix())

Output (reused is the number of tokens reused and computed the number of tokens recomputed):

case                       req  reused  computed  TTFT(s)
A doc first, cache on        1       0      2020     4.10
A doc first, cache on        2    2000        20     0.10
A doc first, cache on        3    2000        20     0.13
A doc first, cache on        4    2000        20     0.13
B header first, cache on     1       0      2028     4.09
B header first, cache on     2       0      2028     4.07
B header first, cache on     3       0      2028     4.09
B header first, cache on     4       0      2028     4.11
C doc first, cache off       1       0      2020     4.40
C doc first, cache off       2       0      2020     4.37
C doc first, cache off       3       0      2020     4.36
C doc first, cache off       4       0      2020     4.37
llamacpp:prompt_tokens_total 34656
llamacpp:prompt_tokens_cached_total 6000
llamacpp:prompt_tokens_seconds 496.955

How to read the table:

  • A, document first: the first request computed the whole document (2020 tokens, 4.10 s); the next three reused 2000 tokens of cache and computed only the 20 new ones, and the time to first token drops to 0.10 to 0.13 s, about 30 times faster.
  • B, changing beginning: the first 8 tokens differ every time, so from the first token on the request differs from the previous one, the cache never hits, and every request recomputes 2028 tokens in 4.1 s. These 8 tokens cost almost nothing themselves, yet they invalidate the cache of the 2000 tokens that follow.
  • C, cache off: cache_prompt is false and every request is recomputed, 4.4 s. That is about 7% slower than the first request of A, which is a drift of the machine state under sustained load and not a difference caused by the cache; do not read anything into it. The comparison that matters is 4 s against 0.1 s.

The last three lines come from the server’s /metrics: in this run it processed 34656 prompt tokens in total, 6000 of them from the cache (each of the three requests of A reused 2000).

vLLM implements the same thing with a hash-based block cache: the hash of each block is determined jointly by the hashes of all the blocks before it (the parent hash), the tokens of the block and extra information (LoRA ID, hashes of multimodal inputs, a cache salt), so a hit requires an identical prefix; only full blocks are cached, and free blocks are evicted least recently used (LRU) first. SGLang’s RadixAttention manages the cached prefixes in a radix tree; the paper reports up to 6.4 times the throughput on workloads such as agent control, few-shot learning, JSON decoding, retrieval-augmented generation and multi-turn chat (RadixAttention is only one of its techniques). Multi-tenant deployments need care: whether the cache hits changes the latency, and an attacker can use that to infer other people’s prompts; the cache_salt parameter of vLLM mixes a salt into the hash of the first block so that only requests with the same salt share cache.

This gives a few rules for writing prompts:

  • Stable content first, changing content last: system prompt, tool definitions, few-shot examples and documents first, the user question at the end.
  • Do not put anything that changes at the beginning: timestamps, request IDs and random session identifiers invalidate all the cache that follows, even if they are only a few tokens.
  • In multi-turn chats and agents append every turn and do not rewrite the history: if the earlier turns stay identical character for character, each turn needs to compute only what is new.
  • In RAG put the same document before the question, so that repeated questions about one document can reuse it.

Summary and Exercises

Key points:

  1. Every decode step reads the weights once, and batching lets several requests share that read, so the total throughput grows with the batch while each request slows down; throughput and per-request speed trade off. Measured here, from concurrency 1 to 16 the throughput grows 3.6 times and the speed of one request falls to a quarter.
  2. Static batching waits for the longest request and leaves the slots of the short ones empty; continuous batching refills them at every step. Measured here, with 48 requests of different lengths continuous batching takes about a quarter less time; a simulation built on the measured step table is within a few percent of the measurement.
  3. The KV cache sets the ceiling of concurrency. Reserving the maximum length wastes most of the memory, and PagedAttention allocates fixed-size blocks on demand, reducing the waste to the last block.
  4. Prefix caching hits only if the prefix is identical token by token: stable content first, changing content last.
  5. As for parameters: in llama.cpp look at -np, -c, --kv-unified, -b and -ub; in vLLM look at --max-num-seqs, --max-num-batched-tokens, --max-model-len and --gpu-memory-utilization.

Quick quiz

1. In the ideal roofline model, how does the time of one step roughly change in decode when the batch size grows from 1 to 8?

  • It becomes about 8 times longer
  • It hardly changes
  • It becomes about 1/8
  • It depends on the sampling temperature

The time of a step is set by “reading the weights once”, and the extra sequences share that read, so below the knee of the roofline the time hardly changes. The measurements on this page are not flat between 1 and 8 (25 to 98 ms); that is a property of the kernel implementation on this machine.

2. Where does the main waste of static batching come from?

  • Every step has to read the weights again
  • After a short request finishes, its slot has to wait for the longest request before it can take a new one
  • The KV cache is too large
  • Prefill is too slow

Static batching starts and ends in units of a whole batch, and the longest request of the batch decides the time of the batch.

3. What is the main benefit of cutting the KV cache into blocks in PagedAttention?

  • It makes attention more accurate
  • Memory is allocated on demand, which reduces the waste from over-reservation and fragmentation, so the same memory holds more requests at once
  • It makes the weights smaller
  • It reduces the computation of prefill

The blocks need not be adjacent, and a request wastes only the unused part of its last block.

4. What must hold for a request to hit the prefix cache?

  • It is semantically similar to an earlier request
  • It has the same prefix as some earlier request, starting from the very first token
  • It uses the same sampling temperature
  • It uses the same HTTP connection

The cache matches token sequences. After the first token that differs, everything that follows has to be recomputed.

5. With llama-server started as -c 65536 -np 16 and without --kv-unified, what is the longest context a single request can have?

  • 65536 tokens
  • 4096 tokens
  • 16 tokens
  • Unlimited

The total context is divided equally among the 16 slots: 65536/16=409665536 / 16 = 4096.

Exercises:

  1. A model with 32 layers, 8 KV heads and a head dimension of 128 (the Llama 3 8B configuration) stores its KV cache in FP16. How many bytes does one token take? How much memory does a request of 8192 tokens take? After the FP16 weights (about 8.03 B parameters) are loaded on a 24 GiB card, how many such requests fit at the same time at most, ignoring activations and other usage?
  2. There are 4 slots and the step time is fixed (independent of the batch size). The output lengths of 10 requests are 100, 10, 10, 10, 10, 10, 10, 10, 10, 10. How many steps do static batching and continuous batching each need to process them all?
  3. A vLLM-style prefix cache, block size 16, only full blocks are cached. Request 1 is a 1000-token system prompt plus a 50-token question; request 2 is the same system prompt plus a different 50-token question; request 3 has a 1-token timestamp added in front of the system prompt and is otherwise the same as request 2. How many tokens of cache can request 2 and request 3 each reuse?
  4. llama-server is started with -c 32768 -np 8 and without --kv-unified. Will a 20000-token request be accepted? Give two ways to get it accepted.
  5. Why do services for online chat usually set vLLM’s max_num_batched_tokens smaller than offline batch inference does?
Reference answers
  1. The KV cache of one token is 2×32×8×128×2=1310722 \times 32 \times 8 \times 128 \times 2 = 131072 bytes (128 KiB); 8192 tokens are exactly 1 GiB. The weights are about 14.96 GiB (8.03×109×28.03 \times 10^9 \times 2 bytes), which leaves about 9.04 GiB on a 24 GiB card and room for at most 9 requests. In practice activations and the runtime need room too, so it is fewer.
  2. Static batching: the first batch [100, 10, 10, 10] takes 100 steps, the second [10, 10, 10, 10] takes 10 steps and the third [10, 10] takes 10 steps, 120 in all. Continuous batching: the long request occupies one slot for 100 steps, and the other three slots process the remaining 9 short requests in 9/3×10=309 / 3 \times 10 = 30 steps, all within those 100 steps, so 100 in all. Static batching takes 20% more; the long request “sandwiches” short ones in its batch, and that is where it wastes time.
  3. Request 2 shares the first 1000 tokens with request 1, and only full blocks can hit: ⌊1000/16⌋=62\lfloor 1000 / 16 \rfloor = 62 blocks, that is 992 tokens; the remaining 58 (including the 8 tokens of block 63 that are the same as in request 1) must be recomputed. The very first token of request 3 differs, so the hash of the first block differs, and the hashes of all later blocks depend on it: not one block hits and 0 tokens are reused.
  4. Each slot has only 32768/8=409632768 / 8 = 4096 tokens, so a 20000-token request is rejected. Ways: add --kv-unified so that all slots share the whole KV cache; or reduce -np (with -np 1 one request can use 32768); or raise -c to at least 20000×8=16000020000 \times 8 = 160000, at the price of correspondingly more KV-cache memory.
  5. With chunked prefill, every step first admits all the decode requests and then fills the remaining budget with prefill chunks. A small budget means less prefill is attached to each step, so the token gaps of requests that are already generating are steadier, which suits online chat where interactive latency matters; a large budget processes more prompt tokens per step, giving a faster first token and higher throughput, which suits offline jobs that only care about total throughput (the vLLM documentation advises larger values when aiming for throughput, above 8192 for smaller models).

Further Reading

FAQ

What is continuous batching, and how does it differ from static batching?
Continuous batching schedules at the granularity of one decode iteration: after every step, requests that have finished leave the batch and waiting requests immediately take the freed slots, which is why it is also called iteration-level scheduling. Static batching waits until the longest request of a batch has finished before it starts the next batch, so the slots of the short requests sit idle in the meantime. On this page 48 requests with different output lengths arrive at once on Qwen2.5-7B (Q4_K_M, M2 Max, 16 slots): with continuous batching the total time is about 51 s, with it turned off (-nocb) about 68 s, the total throughput rises from 68 to 91 tokens/s and the mean completion time falls by about a quarter.
What is PagedAttention and what problem does it solve?
PagedAttention cuts the KV cache of every request into fixed-size blocks (16 tokens by default in the vLLM paper), maps logical positions to physical blocks that need not be adjacent through a block table, and allocates them on demand. Earlier systems reserved a contiguous region of the maximum length for every request and wasted a lot of memory through over-reservation and fragmentation: the vLLM paper measured that only 20.4% to 38.2% of the KV-cache memory in existing systems held real tokens, against about 96.3% in vLLM, and reports 2 to 4 times the throughput of FasterTransformer and Orca at the same latency.
When does prefix caching hit?
Prefix caching matches token sequences: a new request can reuse the KV cache of an earlier one only if it is identical to it from the very first token; after the first token that differs, everything that follows must be recomputed. vLLM works in fixed-size blocks and caches only full blocks. On this page a 2000-token document placed first needs 2020 tokens and 4.1 s of time to first token on the first request, and later requests recompute only the 20 new tokens, about 0.1 s; putting 8 tokens that change every time in front of the document makes the cache miss every time, at 4.1 s.
Why does each request get slower when the concurrency rises?
A decode step computes one token for every sequence in the batch, so a bigger batch means a slower step. In the measurements of this page, raising the concurrency from 1 to 16 raises the step time from about 25 ms to about 100 ms, lowers the speed of one request from 40 to 10 tokens/s and raises the total throughput from 38 to 139 tokens/s. Throughput and per-request speed trade off: first decide how many tokens/s each user must get, then derive the concurrency limit from it.
What do -np and --kv-unified mean in the llama.cpp server?
-np sets the number of slots, that is, the number of requests handled at once, and -c is the total context length. Without --kv-unified the total context is divided equally among the slots: with -c 65536 -np 16 each request gets at most 4096 tokens, and longer requests are rejected (HTTP 400 in the measurement); with --kv-unified all slots share one KV cache, and the same 6000-token request is processed normally. The command-line help states that when -np is not given (the number of slots is automatic) the unified KV cache is on by default.