Paged KV cache and paged attention
Reorganize KV cache into fixed-size blocks with per-sequence tables, prefix sharing and copy-on-write, then implement attention through the table using PyTorch gather and a Triton kernel.
After this lesson you can
- Implement block allocation, per-sequence tables and release.
- Implement prefix sharing with reference counts and copy-on-write.
- Implement paged attention using gather and a Triton kernel.
- Measure fragmentation and simultaneous sequence capacity against contiguous cache.
Before you start
From maximum reservation to blocks
The p10-l02 cache reserves contiguous capacity per request. If a response finishes early, the remainder stays reserved while the request lives. With variable lengths, that internal fragmentation limits how many sequences fit. Allocating and freeing contiguous regions of different sizes can also leave separate holes unusable for a large reservation: external fragmentation.
A paged KV cache divides the pool into fixed-size blocks. Each sequence has a list of physical IDs, one per logical block. Position is translated using and : the table gives the physical block for and is its offset. With blocks of 16, position 34 is in the third logical block at offset 2. The table does not require physical blocks to be contiguous or ordered by ID.
For lengths 300, 1200 and 2500, reserving 4096 per sequence occupies 12288 positions for 4000 useful ones, wasting 8288. Paging with blocks of 16 reserves 304, 1200 and 2512 positions, wasting 16 in total. Each sequence wastes less than one block in its final block, excluding other reservations and metadata. The paged pool can have unallocated free space, but that is not a sequence’s internal fragmentation.
Translation applies per layer to the corresponding keys and values. A real engine may use tables for blocks containing many layers or separate per-layer pools; the format must specify exactly what each ID represents. The lab tests one attention layer at a time. Fixed-size page reservation removes the need to find a large contiguous hole in that pool, but adds tables, counters and last-block rounding. Memory reserved by PyTorch’s allocator is not necessarily equal to useful tensor bytes either.
Allocate, share and release
The block allocator maintains free IDs, a table per sequence and a reference count per block. When a sequence forks, both tables can share the prefix; the count increases. Writing the last shared partial block allocates another, copies its contents and updates only the writing table. When a sequence ends, its references are decremented and a block returns to the free list only when its count reaches zero.
During copying, if allocation fails for lack of memory, the prior table must remain valid. The lab reserves the new block before decrementing the old reference. A concurrent implementation also needs synchronization among table updates, kernel and release; the presented class is sequential. Identical text at another position or under another prefix is insufficient for sharing: K and V already depend on context and positions.
Sharing savings depend on trace structure. Full common-prefix blocks can remain shared, but a branch diverging in a partial block needs a copy. If three sequences share seven tokens in blocks of eight, extending two can require three physical copies of the last block. This does not contradict the internal-waste limit per sequence: copy-on-write and metadata are extra costs that must be counted separately.
Tests must include block boundaries. A sequence of eight tokens in blocks of eight creates a new block when adding the ninth; a sequence of seven shares a partial block and must copy it before a divergent write. Forking an empty sequence must not invent references. After releasing one branch, the other must still read the same data; releasing the last makes the ID available exactly once. Also check that an operation rejected for capacity or shape has not partially changed tables.
Attention through the table
The paged attention kernel uses the table to gather logical keys and values, computes query products, normalizes and combines values. With GQA, multiple query heads share a KV head; the correct index is cabeza_consulta // grupo. Reading the wrong KV head or using the previous block’s offset can produce plausible but incorrect numeric output.
First build a contiguous reference and another version gathering K and V through the table. They must recover original tensors exactly. The Triton kernel then receives one query per head, follows physical IDs and applies the length mask before softmax. The mask prevents unwritten positions in the partially filled last block from contributing. Compare using torch.allclose with atol=rtol=2e-5; bitwise equality is not claimed across differently implemented reductions.
The teaching kernel places all positions of one sequence in a single reduction with size rounded to a power of two. It suffices for small test lengths but is not a scalable long-context paged-attention implementation. Large contexts require splitting into blocks, combining maxima and sums of online softmax and controlling memory and registers. Triton documentation shows stabilization and reductions; PagedAttention describes KV management and sharing in a real engine.
Stable softmax subtracts the largest score before exponentiation. If context is split, each chunk produces its local maximum and normalized sum; combining two chunks requires rescaling both sums to the global maximum. Averaging per-chunk attention results without that rescaling is not the softmax of the full context. This lesson’s kernel avoids combination by loading the entire test context, so it must not be applied unchanged to arbitrary lengths.
Measure the pool and project a budget
The lab actually allocates on the RTX 3060 a pool of 40 synthetic eight-token blocks with three KV heads and dimension 64 in FP32. For repeated lengths 7, 17 and 31, contiguous reservations of 32 positions fit 10 sequences; the paged pool fits 15. Actual tensors are written and all blocks freed afterwards. This tests capacity of that small pool, not throughput or concurrency of a full model.
To compare an 8 GB decimal budget, subtract a reserved 1 GB and BF16 weights. With 23040 KV bytes per token for SmolLM2-135M’s 30 layers, a repeated trace of lengths 300, 1200 and 2500 fits by calculation 71 contiguous reservations of 4096 positions or 218 paged reservations of 16. The next test verifies capacity with physically allocated CUDA memory, but does not measure GPU tables, additional activations or service performance.
The calculation depends on whether the maximum is reserved, how long requests remain alive and how they grow. Paging permits on-demand reservation, but a system admitting more than it can sustain can exhaust its pool later. It needs a waiting, preemption or rejection policy. Reproducible comparison fixes model, precision, block size, load and reserved memory; sequence count alone describes neither latency nor quality.
The small measurement and 8 GB trial use different precision and shapes: the first stores one synthetic FP32 layer, while the second reserves bytes for SmolLM2’s 30 BF16 layers. Multiplying a speed measured in the small pool and presenting it as full-model performance is invalid. Service measurement must serve requests with the actual model and policy.
The next trial physically allocates real SmolLM2 BF16 weights, a 1 GB reserve and a pool initialized for all 30 layers on the RTX 3060, all within 8 decimal GB allocated by PyTorch. The same 300, 1200 and 2500 trace holds 71 contiguous 4096-position reservations or 218 paged reservations of 16; the latter waste 1156 positions. Endpoints of every reservation are written and checked. Content is synthetic and indices are on CPU: 218 simultaneous inferences have not been run, and GPU tables and service temporaries are excluded.
import gc, math, random, torch
from transformers import AutoModelForCausalLM
# Presupuesto decimal: pesos reales, reserva real y depósito KV de 30 capas.
torch.set_num_threads(1)
assert torch.cuda.is_available()
model = AutoModelForCausalLM.from_pretrained(
'HuggingFaceTB/SmolLM2-135M', local_files_only=True, dtype=torch.bfloat16
).eval().cuda()
torch.cuda.synchronize()
weights = sum(x.numel() * x.element_size() for x in model.parameters())
weights += sum(x.numel() * x.element_size() for x in model.buffers())
budget, reserve, block = 8_000_000_000, 1_000_000_000, 16
cfg = model.config
bytes_token = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * (cfg.hidden_size // cfg.num_attention_heads) * 2
bytes_block = block * bytes_token
guard = torch.empty(reserve, dtype=torch.uint8, device='cuda'); guard.fill_(19)
blocks = (budget - torch.cuda.memory_allocated()) // bytes_block
print('GPU', torch.cuda.get_device_name(), 'pesos', weights, 'reserva', reserve, 'bytes/token', bytes_token, 'bloques', blocks, flush=True)
pool = torch.empty(blocks * bytes_block, dtype=torch.uint8, device='cuda'); pool.fill_(23)
torch.cuda.synchronize()
print('asignación CUDA real', torch.cuda.memory_allocated(), 'bytes; pico', torch.cuda.max_memory_allocated(), flush=True)
print('CUDA memoria libre y total', *torch.cuda.mem_get_info(), flush=True)
assert torch.cuda.memory_allocated() <= budget
lengths = [300, 1200, 2500]
for mode in ('contigua', 'paginada'):
cursor = 0; tables = []; useful = 0
free_pages = list(range(blocks))
if mode == 'paginada': random.Random(71).shuffle(free_pages)
while True:
n = lengths[len(tables) % len(lengths)]
need = 4096 // block if mode == 'contigua' else math.ceil(n / block)
if cursor + need > blocks: break
tables.append((free_pages[cursor:cursor + need], n))
cursor += need; useful += n
assert len({p for pages, _ in tables for p in pages}) == cursor
# Cada secuencia permanece asignada simultáneamente; se tocan sus extremos.
for i, (pages, n) in enumerate(tables):
pool[pages[0] * bytes_block] = i % 251
pool[(pages[-1] + 1) * bytes_block - 1] = i % 251
torch.cuda.synchronize()
for i, (pages, n) in enumerate(tables):
assert pool[pages[0] * bytes_block].item() == i % 251
assert pool[(pages[-1] + 1) * bytes_block - 1].item() == i % 251
waste = cursor * block - useful
if mode == 'paginada': assert waste < len(tables) * block
print(mode, 'secuencias simultáneas', len(tables), 'bloques', cursor,
'tokens útiles', useful, 'desperdicio tokens', waste,
'bytes KV comprometidos', cursor * bytes_block, flush=True)
del pool, guard, model
torch.cuda.empty_cache(); gc.collect()npm run lab and open the connection link.Local lab
The block creates a CUDA allocator with references and copy-on-write, verifies three synthetic lengths and tests three real SmolLM2-135M prompts. For the model it retrieves the query and KV of the last layer and compares all query heads with the contiguous reference. In one RTX 3060 run, maximum kernel errors were 2.38e-7 on synthetic data and 8.94e-7 on the real layer; gather exactly matched reference tensors. This one-layer test does not validate all logits or a full engine.
It requires PyTorch with CUDA, Triton, Transformers and the cached checkpoint. An initial download can be made with a connection and local_files_only=False. The next cell compares the reduced physical pool with a capacity calculation; the previous test physically allocates the 8 GB pool.
import math, torch, triton, triton.language as tl
torch.set_num_threads(1);torch.manual_seed(72);assert torch.cuda.is_available();device='cuda'
class BlockAllocator:
def __init__(self,blocks,block_size,heads,dim,dtype=torch.float32):
self.b=block_size;self.h=heads;self.d=dim;self.keys=torch.empty((blocks,block_size,heads,dim),device=device,dtype=dtype);self.values=torch.empty_like(self.keys)
self.free_ids=list(reversed(range(blocks)));self.refs={};self.tables={};self.lengths={}
def allocate(self):
if not self.free_ids:raise MemoryError('sin bloques')
i=self.free_ids.pop();self.refs[i]=1;return i
def free(self,i):
if i not in self.refs:raise ValueError('bloque no asignado')
self.refs[i]-=1
if self.refs[i]==0:del self.refs[i];self.free_ids.append(i)
def create(self,name):
if name in self.tables:raise ValueError('nombre duplicado')
self.tables[name]=[];self.lengths[name]=0
def fork(self,source,target):
if target in self.tables:raise ValueError('nombre duplicado')
self.tables[target]=self.tables[source].copy();self.lengths[target]=self.lengths[source]
for i in self.tables[target]:self.refs[i]+=1
def copy_on_write(self,name):
old=self.tables[name][-1]
if self.refs[old]>1:
new=self.allocate();self.keys[new].copy_(self.keys[old]);self.values[new].copy_(self.values[old]);self.free(old);self.tables[name][-1]=new
def append(self,name,k,v):
if tuple(k.shape)!=(self.h,self.d) or tuple(v.shape)!=(self.h,self.d):raise ValueError('forma incorrecta')
n=self.lengths[name]
if n%self.b==0:self.tables[name].append(self.allocate())
else:self.copy_on_write(name)
i=self.tables[name][-1];self.keys[i,n%self.b].copy_(k);self.values[i,n%self.b].copy_(v);self.lengths[name]+=1
def release(self,name):
for i in self.tables.pop(name):self.free(i)
del self.lengths[name]
def gather(self,name):
n=self.lengths[name];positions=torch.arange(n,device=device);table=torch.tensor(self.tables[name],device=device)
return self.keys[table[positions//self.b],positions%self.b],self.values[table[positions//self.b],positions%self.b]
@triton.jit
def paged(Q,K,V,T,L,O, BS:tl.constexpr, HQ:tl.constexpr, HK:tl.constexpr,D:tl.constexpr,NB:tl.constexpr,S:tl.constexpr):
row=tl.program_id(0);seq=row//HQ;head=row%HQ;kvhead=head//(HQ//HK)
pos=tl.arange(0,S);d=tl.arange(0,D);length=tl.load(L+seq)
page=tl.load(T+seq*NB+pos//BS,mask=pos<length,other=0)
off=((page[:,None]*BS+(pos%BS)[:,None])*HK+kvhead)*D+d[None,:]
key=tl.load(K+off,mask=(pos<length)[:,None],other=0).to(tl.float32);value=tl.load(V+off,mask=(pos<length)[:,None],other=0).to(tl.float32)
query=tl.load(Q+row*D+d).to(tl.float32);score=tl.sum(key*query[None,:],1)/tl.sqrt(float(D));score=tl.where(pos<length,score,-float('inf'))
p=tl.exp(score-tl.max(score,0));p=p/tl.sum(p,0);out=tl.sum(p[:,None]*value,0);tl.store(O+row*D+d,out)
def compare(pool,names,q,reference):
hq=q.shape[1];nb=max(len(pool.tables[x]) for x in names);lengths=[pool.lengths[x] for x in names]
tables=torch.tensor([pool.tables[x]+[0]*(nb-len(pool.tables[x])) for x in names],device=device,dtype=torch.int32);lens=torch.tensor(lengths,device=device,dtype=torch.int32)
output=torch.empty_like(q);paged[(len(names)*hq,)](q,pool.keys,pool.values,tables,lens,output,BS=pool.b,HQ=hq,HK=pool.h,D=pool.d,NB=nb,S=triton.next_power_of_2(max(lengths)))
expected=[];gathered=[]
for i,name in enumerate(names):
gk,gv=pool.gather(name);rk,rv=reference[name];rows=[];grows=[]
assert torch.equal(gk,rk) and torch.equal(gv,rv)
for head in range(hq):
kv=head//(hq//pool.h);rows.append(torch.softmax(rk[:,kv]@q[i,head]/math.sqrt(pool.d),0)@rv[:,kv]);grows.append(torch.softmax(gk[:,kv]@q[i,head]/math.sqrt(pool.d),0)@gv[:,kv])
expected.append(torch.stack(rows));gathered.append(torch.stack(grows))
expected=torch.stack(expected);gathered=torch.stack(gathered);torch.cuda.synchronize();e=float((output-expected).abs().max());g=float((gathered-expected).abs().max())
assert torch.allclose(output,expected,atol=2e-5,rtol=2e-5) and torch.equal(gathered,expected)
return e,g
def synthetic():
b=8;hk=3;hq=6;d=64;pool=BlockAllocator(32,b,hk,d);names=['a','b','c'];pool.create('a');ref={}
k=torch.randn(7,hk,d,device=device);v=torch.randn_like(k)
for x,y in zip(k,v):pool.append('a',x,y)
pool.fork('a','b');pool.fork('a','c');assert list(pool.refs.values())==[3]
ref['c']=(k.clone(),v.clone())
for name,count in [('a',10),('b',24)]:
a=torch.randn(count,hk,d,device=device);z=torch.randn_like(a)
for x,y in zip(a,z):pool.append(name,x,y)
ref[name]=(torch.cat([k,a]),torch.cat([v,z]))
assert pool.tables['a'][0]!=pool.tables['b'][0] and pool.tables['c'][0] not in (pool.tables['a'][0],pool.tables['b'][0])
q=torch.randn(len(names),hq,d,device=device);e,g=compare(pool,names,q,ref);print('largos',[pool.lengths[x] for x in names],'Triton error',e,'gather error',g,'refs',pool.refs)
for name in names:assert (pool.b-pool.lengths[name]%pool.b)%pool.b<pool.b
for name in names:pool.release(name)
assert len(pool.free_ids)==32 and not pool.refs
print('memoria depósito CUDA bytes',pool.keys.numel()*pool.keys.element_size()*2,'todos los bloques liberados')
def measured_small_pool():
# Mismo depósito físico en GPU, 40 bloques; longitudes 7, 17 y 31, máximo contiguo 32.
lengths=[7,17,31];blocks=40;b=8;hk=3;d=64;k=torch.zeros(hk,d,device=device);v=torch.ones_like(k)
fixed=BlockAllocator(blocks,b,hk,d);reserved=[];fixed_useful=0;fixed_count=0
while len(fixed.free_ids)>=4:
reserved.extend(fixed.allocate() for _ in range(4));fixed_useful+=lengths[fixed_count%3];fixed_count+=1
for page in reserved:fixed.keys[page].zero_();fixed.values[page].zero_()
paged_pool=BlockAllocator(blocks,b,hk,d);paged_count=0;paged_useful=0
while True:
n=lengths[paged_count%3];needed=math.ceil(n/b)
if len(paged_pool.free_ids)<needed:break
name=str(paged_count);paged_pool.create(name)
for _ in range(n):paged_pool.append(name,k,v)
paged_useful+=n;paged_count+=1
torch.cuda.synchronize();fixed_waste=blocks*b-fixed_useful;paged_waste=(blocks-len(paged_pool.free_ids))*b-paged_useful
print('depósito real GPU',blocks,'bloques: contiguo',fixed_count,'paginado',paged_count,'desperdicio tokens',fixed_waste,paged_waste)
assert paged_count>fixed_count and paged_waste<paged_count*b
for page in reserved:fixed.free(page)
for name in list(paged_pool.tables):paged_pool.release(name)
assert len(fixed.free_ids)==blocks and len(paged_pool.free_ids)==blocks
def actual_model():
from transformers import AutoModelForCausalLM,AutoTokenizer
from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
name='HuggingFaceTB/SmolLM2-135M';tokenizer=AutoTokenizer.from_pretrained(name,local_files_only=True)
model=AutoModelForCausalLM.from_pretrained(name,local_files_only=True,dtype=torch.float32).eval().cuda();layer=model.model.layers[-1].self_attn;hk=model.config.num_key_value_heads;hq=model.config.num_attention_heads;d=layer.head_dim
pool=BlockAllocator(32,8,hk,d);names=['r0','r1','r2'];reference={};queries=[]
for label,text in zip(names,['Short prompt.','Another prompt with several more tokens.','A third example with a different length and context.']):
ids=tokenizer(text,return_tensors='pt').input_ids.cuda();captured={}
def hook(module,args,kwargs):
h=kwargs.get('hidden_states',args[0] if args else None);cos,sin=kwargs['position_embeddings'];shape=(*h.shape[:-1],-1,module.head_dim)
q=module.q_proj(h).view(shape).transpose(1,2);k=module.k_proj(h).view(shape).transpose(1,2);q,_=apply_rotary_pos_emb(q,k,cos,sin);captured['q']=q[0,:,-1].detach()
handle=layer.register_forward_pre_hook(hook,with_kwargs=True)
with torch.inference_mode():out=model(input_ids=ids,use_cache=True)
handle.remove();cache=out.past_key_values.layers[-1];k=cache.keys[0].transpose(0,1).contiguous();v=cache.values[0].transpose(0,1).contiguous()
pool.create(label)
for x,y in zip(k,v):pool.append(label,x,y)
reference[label]=(k,v);queries.append(captured['q'])
e,g=compare(pool,names,torch.stack(queries),reference)
print('SmolLM2 última capa, longitudes',[pool.lengths[x] for x in names],'cabezas consulta/KV',hq,hk,'Triton error',e,'gather error',g)
for n in names:pool.release(n)
assert len(pool.free_ids)==32
def budget():
weights=269030016;available=8_000_000_000-1_000_000_000-weights;kv=23040;b=16;lengths=[300,1200,2500]
def count(paged_mode):
used=0;n=0
while True:
length=lengths[n%len(lengths)];allocated=math.ceil(length/b)*b if paged_mode else 4096;need=allocated*kv
if used+need>available:return n,used
used+=need;n+=1
fixed=count(False);paged_count=count(True)
print('presupuesto 8 GB decimal, reserva 1 GB y pesos BF16: contiguo',fixed,'paginado',paged_count,'estimación contable, no asignación real')
assert paged_count[0]>fixed[0]
if __name__=='__main__':synthetic();measured_small_pool();actual_model();budget()
npm run lab and open the connection link.Exercises
class BlockAllocator:
def __init__(self,n,b):
...
def create(self,name):
...
def allocate(self):
...
def free(self,i):
...
def fork(self,source,target):
...
def copy_on_write(self,name):
...
def append(self,name,token):
...
def release(self,name):
...