Pidoku

Moving the KV Cache

Module 9 Lesson 9.e 1h Difficulty 3/5

Prerequisites 9.b, 9.c, 9.d, 12.e


Before you start: words you need#

WordPlain meaning
KV cacheThe keys and values a model computed for every earlier token, kept so it can generate the next token without recomputing them (12.e).
Disaggregated servingRunning prefill (reading the prompt) and decode (generating tokens) on separate GPU pools, so the KV cache must travel from one to the other (14.j).
OffloadingMoving KV blocks out of HBM to CPU memory or SSD, and back when needed (14.k).
Point-to-pointOne sender, one receiver, at any moment. The opposite of a collective, where a whole group moves data together in lockstep (9.f).
IncastMany senders sending to one receiver at once, so they share (and overflow) its link.
KV connectorThe plug-in interface an engine uses to send and receive KV blocks through a transfer library (19.b).
TTFTTime to first token: what the user waits before output starts (2.c).

1. What is it?#

Modern inference does not only move requests across the network. It moves KV caches: the keys and values a model computed for a prompt, which it needs to keep generating. A KV cache is large (tens to hundreds of kilobytes per token, gigabytes per long prompt) and it is needed now: the next token cannot be computed until it arrives.

This lesson covers when a KV cache has to move, how big it is, which links can carry it in time, and the software that moves it (GPUDirect RDMA, NIXL, Mooncake, LMCache). Module 12 explains what the KV cache is; here you only need to know it is a block of GPU memory that grows with every token of context.

Facts checked on 12 November 2026.


2. Why does it exist?#

In 2023 a KV cache was born, used and freed on the same GPU. In 2026 it routinely travels:

Reason it movesFrom → toTaught in
Disaggregated serving: prefill on one pool, decode on anotherprefill GPU → decode GPU14.j, 19.b
Offloading: not enough HBM for every active conversationGPU → CPU DRAM / SSD, and back14.k
Cluster-wide prefix reuse: another replica already computed this system promptreplica A → replica B, or shared store → GPU14.l, 21.h
Preemption and migration: free a GPU without losing workGPU → CPU or another GPU17.c
Failure recovery and elastic scalingsurviving replicas23.e

Each of these trades network transfer for recomputation. Whether the trade is worth it is arithmetic, and the arithmetic depends on the link.


3. Simple analogy#

A chef (prefill) prepares a dish’s components; a second chef (decode) plates and serves them. Splitting the work only helps if the components travel from one station to the other faster than the second chef could prepare them from scratch. A conveyor belt next to the stove (NVLink) makes almost any split worth it. Carrying trays across the street (a slow network) only makes sense for dishes that take a very long time to prepare.


4. Tiny example: how big is a KV cache?#

For a standard transformer (12.f):

KV bytes per token = 2 (K and V) × layers × KV heads × head dimension × bytes per element

For a 70B dense model with grouped-query attention (80 layers, 8 KV heads, head dimension 128) and an FP16 cache:

2 × 80 × 8 × 128 × 2 bytes = 327,680 bytes ≈ 320 KB per token
8,000-token prompt   ≈ 2.6 GB
128,000-token prompt ≈ 42 GB

Halve it for an FP8 KV cache, and roughly halve it again for FP4 (13.h). Architectures with MLA or hybrid attention store far less per token (12.g); the formula changes, but the method does not.


5. Technical explanation#

The hardware path: GPUDirect#

Without help, sending GPU memory over the network goes through host memory: GPU → CPU memory over PCIe, CPU memory → NIC, and the same in reverse, with the CPU involved each time (9.c).

flowchart LR
  subgraph A["Without GPUDirect"]
    direction LR
    G1["GPU HBM"] -->|"PCIe copy"| C1["CPU RAM<br/>bounce buffer"] -->|"PCIe"| N1["NIC"] --> W1(("network"))
  end
  subgraph B["With GPUDirect RDMA"]
    direction LR
    G2["GPU HBM"] -->|"NIC reads GPU memory<br/>directly over PCIe"| N2["NIC"] --> W2(("network"))
  end

  class G1,G2 memory
  class C1 warn
  class N1,N2 io
  • GPUDirect RDMA lets the NIC read and write GPU memory directly. No CPU copy, no CPU cycles. It needs RDMA-capable NICs (InfiniBand or RoCE, 9.c), and the NIC and GPU should sit under the same PCIe switch, which is why AI servers pair one NIC with each GPU (9.b).
  • CUDA IPC and NVLink move KV between GPUs in the same NVLink domain without the network at all. Inside an NVL72 rack, the “network” for KV transfer is NVLink (7.d).
  • GPUDirect Storage (GDS) lets NVMe drives read and write GPU memory directly, which matters for offloading KV to SSD.

If any of these is missing or misconfigured (the wrong PCIe topology, the peer-memory path disabled, RDMA devices not exposed to the container), transfers silently fall back to the slow path. The symptom is disaggregation that is slower than not disaggregating.

The software path: transfer libraries#

Engines do not talk to NICs directly. They use a transfer library behind a KV connector (19.b):

LibraryWhat it isUsed by
NIXL (NVIDIA Inference Xfer Library)One asynchronous API for moving memory between GPUs, CPUs, files and object stores, with plug-in backends (UCX, GDS, libfabric, Mooncake, POSIX, object storage and others). Open source; v1.0.0 on 13 March 2026, v1.5.2 on 29 October 2026.NVIDIA Dynamo (21.j), vLLM’s NixlConnector, SGLang, llm-d
UCXA long-standing HPC communication library that picks the best transport (NVLink, RDMA, TCP) automaticallythe main backend under NIXL and others
Mooncake Transfer EngineMoonshot AI’s transfer layer, part of the Mooncake KV-cache-centric architecture behind KimiSGLang, vLLM, LMCache; also a NIXL backend
LMCacheA KV cache management layer: stores, finds and moves KV across GPU, CPU, disk, Redis/Valkey, S3 and MooncakevLLM, SGLang, llm-d
NCCLCollective communication (9.f)used for parallelism, sometimes for KV

The difference between these and NCCL is the communication pattern. NCCL is built for collectives: every GPU in a group takes part in each step, in lockstep. KV transfer is point-to-point and irregular: any prefill GPU may send to any decode GPU at any moment, and GPUs join and leave as the fleet scales. That is why a separate class of libraries exists. AMD’s equivalents (MORI-IO, or Mooncake on ROCm) fill the same role on Instinct GPUs (7.h).

Hiding the transfer#

Three techniques keep transfer time off the critical path:

  1. Layer-by-layer streaming. Prefill computes layer 1 and starts sending its KV, computes layer 2 while layer 1 is on the wire, and so on. Transfer overlaps computation; only the last layer’s transfer is exposed.
  2. Pull, not push. The decode side reserves memory first and then reads the blocks it needs, so a slow decode node never receives data it has no room for.
  3. Asynchronous scheduling. While a request’s KV is in flight, the decode engine keeps generating tokens for the requests it already has (17.d).

The program compares the time to move a KV cache over common links with the time to recompute it on a prefill pool that processes 10,000 prompt tokens per second. The link speeds are achieved one-direction rates, not datasheet peaks.

Go
// kvmove: how long does it take to move a KV cache, and is it faster than recomputing it?
package main

import "fmt"

type model struct {
	name     string
	layers   int
	kvHeads  int
	headDim  int
	bytesPer float64 // bytes per element: 2 = FP16/BF16, 1 = FP8
}

// kvBytesPerToken = 2 (K and V) x layers x kvHeads x headDim x bytes.
func (m model) kvBytesPerToken() float64 {
	return 2 * float64(m.layers*m.kvHeads*m.headDim) * m.bytesPer
}

type link struct {
	name string
	gbps float64 // achieved GB/s in one direction, not the datasheet peak
}

func main() {
	m := model{name: "70B dense, GQA (80 layers, 8 KV heads, dim 128), FP16 KV", layers: 80, kvHeads: 8, headDim: 128, bytesPer: 2}
	links := []link{
		{"NVLink5", 700},
		{"PCIe5x16", 50},
		{"RDMA800G", 90},
		{"RDMA400G", 45},
		{"TCP100G", 10},
	}
	const prefillTokPerSec = 10000.0 // recompute speed of the prefill pool, tokens/s

	perTok := m.kvBytesPerToken()
	fmt.Printf("%s\nKV per token: %.0f KB\n\n", m.name, perTok/1024)
	fmt.Printf("%-8s %9s %10s", "prompt", "KV size", "recompute")
	for _, l := range links {
		fmt.Printf(" %10s", l.name)
	}
	fmt.Println()
	for _, n := range []int{1000, 8000, 32000, 128000} {
		size := perTok * float64(n)
		fmt.Printf("%-8d %7.2fGB %8.0fms", n, size/1e9, float64(n)/prefillTokPerSec*1000)
		for _, l := range links {
			fmt.Printf(" %8.0fms", size/(l.gbps*1e9)*1000)
		}
		fmt.Println()
	}
}

Output:

70B dense, GQA (80 layers, 8 KV heads, dim 128), FP16 KV
KV per token: 320 KB

prompt     KV size  recompute    NVLink5   PCIe5x16   RDMA800G   RDMA400G    TCP100G
1000        0.33GB      100ms        0ms        7ms        4ms        7ms       33ms
8000        2.62GB      800ms        4ms       52ms       29ms       58ms      262ms
32000      10.49GB     3200ms       15ms      210ms      117ms      233ms     1049ms
128000     41.94GB    12800ms       60ms      839ms      466ms      932ms     4194ms

Three things to read off this table:

  1. Moving beats recomputing on every RDMA link, by more than 10x. That is why disaggregation and KV offload are practical at all. Both transfer time and recompute time grow linearly with the prompt here, so the ratio stays the same; in reality prefill grows faster than linearly (attention is quadratic), which favours moving even more for long prompts.
  2. TCP without RDMA is marginal. At 100 Gb/s, moving 8k tokens takes a third of the time of recomputing them and adds a quarter of a second to TTFT. Disaggregation over ordinary TCP rarely pays off.
  3. Transfer time adds directly to TTFT unless it is hidden. A 466 ms transfer for a 128k prompt is small next to 12.8 s of prefill, but at 8k a 29 ms transfer is a real fraction of the latency budget.

7. Performance implications#

  • Links are shared. Eight GPUs sharing four NICs get half of the per-GPU numbers above, and the same NICs carry parallelism traffic.
  • Incast. A decode GPU receiving from several prefill GPUs at once shares its one NIC among them and can get much less than the table shows.
  • Smaller caches move faster. An FP8 KV cache halves transfer time as well as memory; MLA models move several times less (12.g).
  • Topology-aware placement wins. Prefill and decode in the same NVLink domain move KV at hundreds of GB/s; on the same leaf switch at NIC speed; across the spine with added contention.

8. Production implications#

  1. Keep prefill and decode close. Same NVLink domain if possible; otherwise the same leaf switch or rail (9.d). Every extra hop adds latency and contention.
  2. Size the network for KV, not only for requests. At 10 prefills per second of 8k tokens on the model above, the KV stream is 26 GB/s, more than a quarter of an 800 Gb/s NIC, before any parallelism traffic.
  3. Match layouts. If prefill runs with tensor parallelism 4 and decode with 8, every KV block must be split differently on the way. Engines support mismatched layouts, but it costs extra transfers; keep them aligned unless there is a reason not to.
  4. Quantise what you send (13.h).
  5. Measure the real link. Run a point-to-point bandwidth test (ib_write_bw, or NIXL’s own benchmark tool) between the actual prefill and decode nodes before trusting any table.

9. Common mistakes#

  1. Disaggregating over TCP. It works in a demo and loses in production.
  2. Forgetting incast. Many prefill GPUs sending to one decode GPU share that GPU’s NIC.
  3. Counting datasheet bandwidth. An 800 Gb/s port is 100 GB/s on paper and less in practice, in one direction, shared with whatever else the GPU is doing.
  4. Missing GPUDirect in containers. RDMA devices and peer memory must be exposed to the pod (21.c); without them the transfer quietly uses the CPU path.
  5. Using NCCL for irregular KV traffic. Collectives assume fixed groups in lockstep; use a point-to-point transfer library.

10. Hands-on exercise#

  1. Run the program. Change bytesPer to 1 (FP8 KV cache), then change the model to an MLA model whose cache is about 70 KB per token. How does the case for TCP change?
  2. Add a column for “transfer as a fraction of a 500 ms TTFT budget” and find the longest prompt each link can handle within budget.
  3. On a machine with GPUs and NICs, run nvidia-smi topo -m and identify which GPU–NIC pairs share a PCIe switch (PIX) and which cross the CPU (SYS). Which pairs would you use for KV transfer?
  4. Model incast: four prefill GPUs send 8k-token caches to one decode GPU at the same moment over 800G. How long until the last one arrives?

11. Interview questions#

  1. Why is KV transfer a point-to-point problem rather than a collective one, and why does that matter for library choice?
  2. Derive the KV cache size per token for a model with 64 layers, 8 KV heads and head dimension 128 in FP8.
  3. What is GPUDirect RDMA, and what happens when it is not available?
  4. How does layer-by-layer streaming hide transfer latency? What remains exposed?
  5. When would you not disaggregate prefill and decode?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

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