None
%load_ext watermark
%load_ext autoreload
%autoreload 2
import os
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
%watermark -a 'Ethen' -d -u -v -iv
This notebook introduces KV cache, as well as paged KV cache popularized by vLLM.
A decoder language model predicts the next token given the tokens so far, $p(x_{t+1} \mid x_{1:t})$. Once a token is chosen, it's appended to the sequence, and becomes input context for the next generation step. Take a prompt "the cat sat on" as an example, during inference stage, each decoder layer's attention score matrix $QK^T$ is a dot product between one token's query and key.
Step 1 Prefill: Model inference runs in two phases, the first one is referred to as prefill stage where we process all input prompt tokens in parallel.
The cat sat on
The q₁·k₁
cat q₂·k₁ q₂·k₂
sat q₃·k₁ q₃·k₂ q₃·k₃
on q₄·k₁ q₄·k₂ q₄·k₃ q₄·k₄
Step 2 Generation (a.k.a Decode): During prefill, our model predicted next token, "the". This is appended back in the sequence for predicting the next token. As we will explain below, this phase is where KV cache matters.
The cat sat on the
The q₁·k₁ ┐
cat q₂·k₁ q₂·k₂ │ identical to step 1
sat q₃·k₁ q₃·k₂ q₃·k₃ │
on q₄·k₁ q₄·k₂ q₄·k₃ q₄·k₄ ┘
the q₅·k₁ q₅·k₂ q₅·k₃ q₅·k₄ q₅·k₅ ← the only new row
While appending "the" and recomputing everything, we will notice the top 4 rows are the exact same matrix from step 1. This is decoder model's property, where causal masking ensures no information can flow from future positions back to earlier ones. i.e. each $q_i$ and $k_j$ depends on tokens up to its own position, appending new tokens afterwards never changes prior values. So to compute new row from "the", we need:
In contrast, a bidirectional encoder doesn't have the notion of KV cache since it passes through the whole input in one forward pass. i.e. It isn't autoregressive hence there's no decode step and nothing to reuse.
We'll build a small decoder only model with KV cache. To keep the focus on KV cache, model architecture is deliberately simpler than modern LLM, and the weights are random, which doesn't matter here since we're checking mechanics not output quality.
kv cache We keep one K and V tensor per layer, each with the shape of [batch size, num_heads, seq_len, head_dim]. The implementation preallocates space up to max_seq_len and tracks how much is filled.
class KVCache:
"""Preallocated per-layer KV cache"""
def __init__(self, num_layers, batch_size, num_kv_heads, max_seq_len, head_dim,
dtype=torch.float32, device='cpu'):
shape = (num_layers, batch_size, num_kv_heads, max_seq_len, head_dim)
self.k = torch.zeros(shape, dtype=dtype, device=device)
self.v = torch.zeros(shape, dtype=dtype, device=device)
# keep tracks of number of positions that are cached
self.seq_len = 0
def update(self, layer_idx, k_new, v_new):
"""write the new position for one layer, and return the layer's entire kv cache history"""
start = self.seq_len
end = self.seq_len + k_new.shape[2]
self.k[layer_idx, :, :, start:end] = k_new
self.v[layer_idx, :, :, start:end] = v_new
return self.k[layer_idx, :, :, :end], self.v[layer_idx, :, :, :end]
def advance(self, num_new_tokens):
"""called once after every layer has written its k/v cache"""
self.seq_len += num_new_tokens
def nbytes(self, used_only=True):
n = self.seq_len if used_only else self.k.shape[3]
return 2 * self.k[:, :, :, :n].numel() * self.k.element_size()
Attention with a cache:
[seq len query, seq len past + seq len query]. During decoding seq len query = 1, so our new token can attend to everything in the past.class Attention(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.n_heads = n_heads
self.head_dim = d_model // n_heads
self.q_proj = nn.Linear(d_model, d_model, bias=False)
self.k_proj = nn.Linear(d_model, d_model, bias=False)
self.v_proj = nn.Linear(d_model, d_model, bias=False)
self.o_proj = nn.Linear(d_model, d_model, bias=False)
def forward(self, x, cache=None, layer_idx=None):
batch_size, seq_len, _ = x.shape
# [batch_size, num_heads, seq_len, head_dim]
# transpose is done to match scaled_dot_product_attention's expected input shape
q = self.q_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(x).view(batch_size, seq_len, self.n_heads, self.head_dim).transpose(1, 2)
if cache is not None:
k, v = cache.update(layer_idx, k, v)
#print(q.shape)
attn_out = causal_attention(q, k, v)
out = attn_out.transpose(1, 2).reshape(batch_size, seq_len, -1)
return self.o_proj(out)
def causal_attention(q, k, v):
seq_len_query = q.shape[2]
seq_len_kv = k.shape[2]
past = seq_len_kv - seq_len_query
# positive diagonal shifts columns to the right, so query tensor sees everything cached plus itself
# scaled_dot_product_attention(), True indicates values to participate in attention.
mask = torch.ones(seq_len_query, seq_len_kv, dtype=torch.bool, device=q.device).tril(diagonal=past)
# print(mask.shape)
# print(mask)
return F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
d_model = 8
batch_size = 1
num_layers = 1
max_seq_len = 32
attention = Attention(d_model=d_model, n_heads=2)
cache = KVCache(num_layers, batch_size, attention.n_heads, max_seq_len, attention.head_dim)
x = torch.rand((batch_size, 4, d_model))
out = attention(x, cache, layer_idx=0)
print(out.shape)
cache.advance(x.shape[1])
x_new = torch.rand((batch_size, 1, d_model))
out = attention(x_new, cache, layer_idx=0)
out.shape
class DecoderBlock(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.norm1 = nn.RMSNorm(d_model)
self.attn = Attention(d_model, n_heads)
self.norm2 = nn.RMSNorm(d_model)
self.mlp = nn.Sequential(
nn.Linear(d_model, 4 * d_model, bias=False),
nn.SiLU(),
nn.Linear(4 * d_model, d_model, bias=False),
)
def forward(self, x, cache=None, layer_idx=None):
out = self.attn(self.norm1(x), cache, layer_idx)
x = x + out
return x + self.mlp(self.norm2(x))
class LLM(nn.Module):
def __init__(self, vocab_size=1000, d_model=256, n_layers=4, n_heads=8, max_positions=2048):
super().__init__()
self.n_layers = n_layers
self.embed = nn.Embedding(vocab_size, d_model)
# learned absolute positions
self.pos_embed = nn.Embedding(max_positions, d_model)
# all layers have identical decoder blocks
self.layers = nn.ModuleList(DecoderBlock(d_model, n_heads) for _ in range(n_layers))
self.norm = nn.RMSNorm(d_model)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
def forward(self, input_ids, cache=None):
batch_size, seq_len = input_ids.shape
# note the position index needs to be offset by cache length
start = cache.seq_len if cache else 0
positions = torch.arange(start, start + seq_len, device=input_ids.device)
x = self.embed(input_ids) + self.pos_embed(positions)
for i, layer in enumerate(self.layers):
x = layer(x, cache, i)
if cache is not None:
cache.advance(seq_len)
return self.lm_head(self.norm(x))
def new_cache(self, batch_size, max_seq_len):
attn = self.layers[0].attn
return KVCache(self.n_layers, batch_size, attn.n_heads, max_seq_len, attn.head_dim, device=device)
vocab_size = 1000
batch_size = 1
seq_len = 16
model = LLM(vocab_size=vocab_size).to(device)
prompt_ids = torch.randint(0, vocab_size, (batch_size, seq_len)).to(device)
print(prompt_ids.shape)
outputs = model(prompt_ids)
outputs.shape
Check 1: Cached decoding matches full computation
We compute logits in two ways:
The two should agree up to a certain degree of floating point noise.
prompt_len = 8
with torch.no_grad():
# [batch size, seq len, vocab size]
full_logits = model(prompt_ids)
# prefill
cache = model.new_cache(batch_size=batch_size, max_seq_len=seq_len)
step_logits = [model(prompt_ids[:, :prompt_len], cache)]
# decode one token at a time
for t in range(prompt_len, seq_len):
step_logit = model(prompt_ids[:, t:t+1], cache)
step_logits.append(step_logit)
incremental_logits = torch.cat(step_logits, dim=1)
print('cache length:', cache.seq_len)
print('logits match:', torch.allclose(full_logits, incremental_logits, atol=1e-4))
Check 2: Generation with and without a cache
Next, we have a greedy inference loop, written both ways. Without a cache, every step needs to process the entire sequence. Whereas, with a cache, prefill runs once and every later step process a single token.
@torch.no_grad()
def generate_no_cache(model, input_ids, max_new_tokens):
ids = input_ids
for _ in range(max_new_tokens):
logits = model(ids)
next_id = logits[:, -1].argmax(dim=1, keepdim=True)
ids = torch.cat([ids, next_id], dim=1)
return ids
@torch.no_grad()
def generate_with_cache(model, input_ids, max_new_tokens):
batch_size, seq_len = input_ids.shape
cache = model.new_cache(batch_size=batch_size, max_seq_len=seq_len + max_new_tokens)
# prefill
logits = model(input_ids, cache)
next_id = logits[:, -1].argmax(dim=1, keepdim=True)
out = [input_ids, next_id]
# decode one (newest) token at a time
# prefill stage already produced one new next token, so loop should run
# max new tokens - 1 times
for _ in range(max_new_tokens - 1):
step_logit = model(next_id, cache)
next_id = step_logit[:, -1].argmax(dim=1, keepdim=True)
out.append(next_id)
return torch.cat(out, dim=1)
batch_size = 1
seq_len = 1024
max_new_tokens = 512
model = LLM(vocab_size=vocab_size, d_model=512, n_layers=8).to(device)
prompt_ids = torch.randint(0, vocab_size, (batch_size, seq_len)).to(device)
start = time.perf_counter()
out_no_cache = generate_no_cache(model, prompt_ids, max_new_tokens)
time_no_cache = time.perf_counter() - start
start = time.perf_counter()
out_cache = generate_with_cache(model, prompt_ids, max_new_tokens)
time_cache = time.perf_counter() - start
print('same tokens:', torch.equal(out_no_cache, out_cache))
print(f'no cache: {time_no_cache:.2f}s')
print(f'with cache: {time_cache:.2f}s')
Actual wall-clock timing will depend on hardware and setting. Here we created a slightly larger model, and longer sequence length to illustrate the benefit of running inference with KV cache. If our workload is too small, then these timings will be dominated by per-call overhead.
KV cache trades compute for memory footprint, for a standard self attention model, the cache size for one sequence is:
$$ M_{KV} = 2 \cdot T \cdot L \cdot H_{KV} \cdot D_h \cdot b $$This is why we often times hear a LLM serving system's throughput is memory bound, bounded by both memory capacity and bandwidth:
To get the ball rolling, our KV cache implementation above preallocates one contiguous buffer per request, sized for its maximum possible length. With a single request, this was probably fine. An actual production LLM inference engine, on the other hand, holds many requests at once, each with different prompt length, output length, arrival and finish times. Paged Attention (vLLM) [2] identified three kinds of waste with existing serving frameworks that expect a tensor to live in contiguous memory:

The paper measured existing system at that time and showed that only 20.4 - 38.2% of the allocated KV cache memory is actually being used to store token states.

In light of this, Paged Attention paper draws inspiration from operating system's virtual memory paging, and proposes splitting KV cache into small, fixed-sized blocks that are allocated on demand. One can think of blocks as pages, tokens as bytes, and requests as processes.
Let's start with a concrete example: Suppose we have 8 physical blocks each with block size of 4, all allocated once at startup. Each slot holds a token's K and V.
If a request arrives containing 6 tokens, it first gets split into chunks of 4 tokens, its logical blocks. As for physical blocks, it takes whichever are free, they don't have to be next to each other. A block table records the mapping.
logical block 0: tokens 0-3
logical block 1: tokens 4-5
block table: [3, 7]
↑ ↑
│ └─ logical block 1 lives in physical block 7
└──── logical block 0 lives in physical block 3
To find/place a token, say token 5, we would calculate:
logical block = 5 // 4 (block size) = 1 -> block_table[1] = 7
offset = 5 % 4 = 1 -> second slot inside that block
slot = 7 * 4 + 1 = 29 (flat index into the pool)
This design aims to ensure:
block_size - 1 slots.class PagedKVPool:
"""Shared physical memory: the whole collection of physical blocks that every sequence shares"""
def __init__(self, num_blocks, block_size, num_kv_heads, head_dim):
self.block_size = block_size
self.k = torch.zeros(num_blocks, block_size, num_kv_heads, head_dim)
self.v = torch.zeros(num_blocks, block_size, num_kv_heads, head_dim)
self.free_blocks = list(range(num_blocks))
# counter for keeping track of how many sequence are at each block
self.ref_counts = [0] * num_blocks
def allocate(self):
if not self.free_blocks:
raise RuntimeError("out of free KV blocks. A real scheduler would typically preempt a request here")
block = self.free_blocks.pop(0)
self.ref_counts[block] = 1
return block
def write(self, slot, k, v):
"""write k/v with flat slot index"""
self.k.view(-1, *self.k.shape[2:])[slot] = k
self.v.view(-1, *self.v.shape[2:])[slot] = v
def release(self, block):
self.ref_counts[block] -= 1
if self.ref_counts[block] == 0:
self.free_blocks.append(block)
class PagedSequence:
"""logical, one per request. It doesn't store K and V itself. It knows its own token order and which physical block hold
which chunk. Block table is the only extra book-keeping, which is one small list of integers per request.
Method names follows paged attention paper, where vLLM implements various decoding algorithm
using 3 key methods: fork, append, free
"""
def __init__(self, pool):
self.pool = pool
# logical block to physical block mapping
self.block_table = []
self.num_tokens = 0
def append(self, k, v):
"""Make sure the block has room, and write a token's K/V"""
block_size = self.pool.block_size
offset = self.num_tokens % block_size
# offset = 0, the previous block is full, or this is the first token. Take any free block
# from the centralized pool, and add it to the block table
if offset == 0:
block = self.pool.allocate()
self.block_table.append(block)
# when a block is shared from forking, get a private copy before writing
elif self.pool.ref_counts[self.block_table[-1]] > 1:
self._copy_on_write()
# new token gets assigned in the last logical block
# physical block number, each block size and offset gives the exact location
# in the pool
slot = self.block_table[-1] * block_size + offset
self.pool.write(slot, k, v)
self.num_tokens += 1
def gather(self):
"""re-assemble logical history [seq length, num kv heads, head dimension]. Only used for parity check"""
k = self.pool.k[self.block_table].flatten(0, 1)[:self.num_tokens]
v = self.pool.v[self.block_table].flatten(0, 1)[:self.num_tokens]
return k, v
def free(self):
"""request completed, release all tokens block from this sequence"""
for block in self.block_table:
self.pool.release(block)
self.block_table = []
self.num_tokens = 0
def fork(self):
"""create a new sequence sharing all existing blocks. e.g. multiple samples from the same prompt"""
child = PagedSequence(self.pool)
child.block_table = list(self.block_table)
child.num_tokens = self.num_tokens
for block in self.block_table:
self.pool.ref_counts[block] += 1
return child
def _copy_on_write(self):
shared = self.block_table[-1]
private = self.pool.allocate()
self.pool.k[private] = self.pool.k[shared]
self.pool.v[private] = self.pool.v[shared]
self.pool.release(shared)
self.block_table[-1] = private
num_blocks = 8
num_kv_heads = 2
head_dim = 4
block_size = 4
pool = PagedKVPool(num_blocks, block_size, num_kv_heads, head_dim)
seq_a, seq_b = PagedSequence(pool), PagedSequence(pool)
# mimic two requests decoding concurrently, tokens arriving in interleaved manner
ref_a = [torch.randn(num_kv_heads, head_dim) for _ in range(10)]
ref_b = [torch.randn(num_kv_heads, head_dim) for _ in range(6)]
for i in range(10):
seq_a.append(k=ref_a[i], v=ref_a[i])
if i < len(ref_b):
seq_b.append(k=ref_b[i], v=ref_b[i])
print('A block table:', seq_a.block_table, '| tokens:', seq_a.num_tokens)
print('B block table:', seq_b.block_table, '| tokens:', seq_b.num_tokens)
print('A history matches:', torch.equal(seq_a.gather()[0], torch.stack(ref_a)))
print('B history matches:', torch.equal(seq_b.gather()[0], torch.stack(ref_b)))
print('A unused slots (only in its last block):', len(seq_a.block_table) * block_size - seq_a.num_tokens)
In the example above, we show two requests' tokens interleaved across the paged KV cache pool. Yet, each sequence's logical history remains intact while minimizing the amount of un-used slots within a block.
This paging design also lets requests share memory. Say we sample multiple completions from one prompt, which is common for use cases such as parallel sampling, beam search, GRPO style RL rollout. These samples have identical prompt K/V state, and with block tables, both sequences can point to the same starting physical blocks, and reference count keeps track of how many sequences use each one.
While implementing this, the rule is shared for reading, private for writing.
fork.pool = PagedKVPool(num_blocks, block_size, num_kv_heads, head_dim)
sample_1 = PagedSequence(pool)
# 6-token prompt: one full block + one half-full block
for _ in range(6):
sample_1.append(torch.randn(num_kv_heads, head_dim), torch.randn(num_kv_heads, head_dim))
# second sample from the same prompt,
# in practice we can imagine if we specify sampling parameter to
# be > 1, then one request becomes a group of sequences forked from
# a single prefill
sample_2 = sample_1.fork()
print('after fork')
print(' sample 1:', sample_1.block_table, '| sample 2:', sample_2.block_table)
print(' ref counts:', {b: pool.ref_counts[b] for b in sample_1.block_table})
# each sample generates a different next token
sample_1.append(torch.randn(num_kv_heads, head_dim), torch.randn(num_kv_heads, head_dim))
sample_2.append(torch.randn(num_kv_heads, head_dim), torch.randn(num_kv_heads, head_dim))
print('after each sample appends one token')
print(' sample 1:', sample_1.block_table, '| sample 2:', sample_2.block_table)
print(' ref counts:', {b: pool.ref_counts[b] for b in set(sample_1.block_table + sample_2.block_table)})
# the shared prompt tokens are unchanged in both samples
k1, _ = sample_1.gather()
k2, _ = sample_2.gather()
print('prompt K identical in both samples:', torch.equal(k1[:6], k2[:6]))
Block 0, the full prompt block, stays shared, with reference count 2. On the other hand, the non-full block was copied once so one of the requests gets a fresh private block, and the other request became original block's sole owner.
Up until this point, we've only stored K/V in blocks. Paged attention is what happens on the compute side that goes hand in hand with paged KV cache. Standard attention assumes keys/values for a sequence sit in one contiguous tensor, if we followed that approach and used gather at every decode step, it would only bring back the contiguous memory assumption that paging set out to avoid. The actual paged attention kernel computes attention directly from blocks on the fly. For each query, it traverses through block table in its logical order, and combines these partial results together.
def paged_attention_two_pass(q, seq):
block_size = seq.pool.block_size
scale = q.shape[-1] ** -0.5
scores = []
for logical_idx, block in enumerate(seq.block_table):
# last block may be partly filled
n_valid = min(block_size, seq.num_tokens - logical_idx * block_size)
# collect [n, head, hidden dim] from individual blocks
k_block = seq.pool.k[block, :n_valid]
score = torch.einsum('hd,nhd->hn', q, k_block) * scale
scores.append(score)
# how much one query attends to each cached token
# concatenate all block's score [head, seq len]. seq len is all
# the number of tokens that are currently cached for this sequence
# compare to gathering entire k/v, it keeps [seq len] scores instead of
# gathering the extra hidden dim [head, seq len, hidden dim] as well
weights = torch.cat(scores, dim=-1).softmax(dim=-1)
# output is [head, hidden dim]
out = torch.zeros_like(q)
for logical_idx, block in enumerate(seq.block_table):
n_valid = min(block_size, seq.num_tokens - logical_idx * block_size)
v_block = seq.pool.v[block, :n_valid]
w_block = weights[:, logical_idx * block_size : logical_idx * block_size + n_valid]
out += torch.einsum('hn,nhd->hd', w_block, v_block)
return out
q = torch.randn(num_kv_heads, head_dim)
out = paged_attention_two_pass(q, seq_b)
out.shape
def dense_attention(q, k, v):
"""Reference: ordinary attention over a contiguous history k, v: [T, H, D]."""
scores = torch.einsum('hd,thd->ht', q, k) * q.shape[-1] ** -0.5
return torch.einsum('ht,thd->hd', scores.softmax(dim=-1), v)
k_full, v_full = seq_b.gather()
print('two-pass == dense:', torch.allclose(paged_attention_two_pass(q, seq_b), dense_attention(q, k_full, v_full), atol=1e-6))
It's worthwhile to mention the idea of paging is effective in LLM serving because the number of output token is not known a priori, hence the workload naturally benefits from dynamic memory allocation. Blindly introducing this technique for other inference scenarios may not result in any performance improvement due to the overhead of non-contiguous block memory.
Paged attention paper performed kernel benchmarking and mentioned it leads to a 20% higher attention kernel latency. Despite this overhead, it's still able to achieve a 2-4x throughput improvement over existing systems, as this only affects attention operator but not other operators such as Linear, and efficiently managing memory usage enable batching more requests.
We'll end this section with a note mentioning choices around block size, recovery mechanism, and gpu_memory_utilization.
Block size is a tradeoff with no universally best value as it depends on workload.
In the paper, vLLM sets its default block size at 16.
Recovery mechanism. Since requests grow with demand, our pool can fill up while sequences are still decoding. For simplicity, our allocate implementation above just raises an error. A real scheduler preempts a request instead by freeing all of that request's blocks so others can keep running, then resumes it later. The paper describes two ways to bring the evicted K/V back.
vLLM showed that swapping incurs excessive overhead with small block size since it often results in numerous small data transfers between CPU and GPU. As for medium block size from 16-64, the two methods exhibit comparable end to end performance.
gpu_memory_utilization. this vllm parameter received some confusion during the early days.
budget = total_gpu_memory × gpu_memory_utilization
kv_memory = budget − weights − peak activations (from a profiling run) − other overhead (e.g. CUDA graphs)
num_blocks = kv_memory // bytes_per_block
From the formula above, GPU memory utilization determines "fraction of GPU memory to be used for model executor". Weights, activations, CUDA graph memory are accounted for first, and the rest for reserved for KV cache pool. Memory size decides the maximum number of requests that can be batched together in one iteration, which directly determines the maximum throughput we can achieve. Therefore, the typical suggestion is to allocate as much memory for KV cache as possible. Caveat:
num_blocks × block_size ≥ max_model_len. Meaning, it's a promise to accept requests that long, and engine checks at startup that KV cache pool can hold for at least one request.