Module contents
Lesson 19 of 28Advanced 115 min

The KV cache as a resource: paged attention, shared prefixes and compression

Module m18 introduced KV cache for decoding; here it is treated as a serving resource. We measure waste from reserving maximum length, build PagedAttention with physical blocks, tables and a paged kernel, share blocks with copy-on-write and prefix caching, and study recomputation, CPU swapping and token eviction when cache does not fit. Everything is implemented from scratch and on the local GPU.

After this lesson you can

  • Quantify internal and external cache fragmentation with contiguous reservations and blocks.
  • Implement a block allocator with per-sequence tables, reference counts and copy-on-write.
  • Implement prefix caches with block hashes and a radix tree with LRU eviction, and measure hit rate.
  • Write a paged decoding attention kernel in Triton and verify it against contiguous cache.
  • Compare eviction with recomputation, CPU swapping and importance-based token eviction for memory and quality.

Before you start

A reservation for an uncertain future

KV cache grows with the conversation and occupies memory for each active sequence. If maximum output length is reserved in advance, a short response leaves memory unused while other requests wait. If little is reserved and a contiguous area is expanded, free space may be split into gaps too small to use. The first situation is internal fragmentation; the second is external fragmentation.

Cache fragmentation must be measured against a specific workload and budget. With 4096 reserved positions and 600 used, 3496 remain, 85.35% of the reservation. In blocks of 16, 600 positions require 38 blocks and 8 positions remain. If lengths modulo 16 are uniform, expected waste is 7.5 positions, not always 8. The difference matters: a theoretical mean does not describe every request.

InteractiveReserve or page
Contiguous reservation

1300 useful · 2796 reserved but unused · 0 free

Blocks

3695 useful · 97 reserved but unused · 304 free

Blue: useful tokens; orange: unused internal space; gray: free positions. The difference in requests depends on this trace and budget, not a general guarantee.

16
1024
Requests with reservation4
Paged requests10
Reservation waste68.3 %
Block waste2.6 %
A small trace with lengths known afterward. Bars separate useful tokens, internally reserved space, and free positions; capacity is 4096 positions.

A maximum reservation can protect against future memory shortages but reduces admission. Paging allocates as sequences grow and must decide what to do when blocks run out. Active block count, response lengths, free capacity, and admission policy determine concurrency. The figure does not simulate external gaps or length prediction; it compares two retrospective counts on the same trace.

Units matter when converting positions to bytes. Each position has K and V in every layer and KV head; size depends on precision and dimension. Block tables, metadata, attention temporaries, and weights also occupy memory. Free memory divided by bytes per position is thus a planning bound, not a guarantee that the system admits that many sequences. The partially filled final block adds up to b−1b-1 positions per sequence unless it can be physically shared.

Logical and physical addresses

In paged attention, logical position tt splits into block ⌊t/b⌋\lfloor t/b\rfloor and offset t mod bt\bmod b. The sequence’s table maps logical block to physical block. The kernel reads keys and values through that table and computes the same softmax as with contiguous cache. Physical pages can be in any order. Extra addressing work and memory locality affect performance; a small block reduces internal waste but may hurt kernel efficiency.

PagedAttention uses this organization to manage memory and share blocks. It is an analogy with virtual memory, not a claim that every token is an operating-system page. vAttention proposes another alternative: retain virtual contiguity while dynamically allocating physical memory using CUDA APIs. Both require management and have costs; which is better depends on kernel, platform, and load.

The lab kernel computes one query head per program and uses a small positions-by-dimensions matrix. It reads the physical ID, gathers K and V, masks positions beyond length, and normalizes with stable softmax. This educational implementation is limited to contexts fitting one logical Triton block, not a replacement for an engine’s optimized kernel. The lab checks random tensors and real keys, values, and query from SmolLM2’s last layer.

Share without overwriting

Copy-on-write lets multiple hypotheses point to the same prefix. Reference count increases on fork; if a branch writes to a shared partial block, it first allocates a private block, copies contents, and decrements the old one. A full block needs no copy when appending a token: a new one is allocated. Pruning a branch decrements every reference and frees it physically only at zero.

InteractiveTables and copy-on-write

A sequence occupies one full block and one partial block.

Tables per sequence
rootAB
Physical pool
A · refs 1
0 1 2 3
B · refs 1
4 5
0
Occupied physical blocks2
Live sequences1
Walk through creation, forking, writes, and pruning. Letters are physical IDs; counters correspond to active tables.

If two children retain a reference to the same partial block and one modifies it directly, it changes the other’s past. Forgetting to decrement on pruning loses capacity; freeing too early makes another sequence read reused memory. The lab maintains a free-block list, per-sequence tables, and counts. It also checks that freeing every branch returns all blocks to the pool.

A useful test forks from a partial block, writes different tokens to each child, and verifies both contents and counts. Another forks just after a full block: both retain the same block and the child’s first write creates a new one. Exhausting the pool before copying must produce an error without changing the original reference. In a concurrent engine these operations and publication of the new table need synchronization; this lesson’s classes are sequential.

Reuse a prefix

Prefix caching reuses already processed system prompts, examples, and turns. Keys and values depend on preceding context and position: an identical fragment elsewhere is not automatically reusable. Changing the system prompt invalidates subsequent blocks even if later text is identical. Editing a turn preserves at most the prefix before the first difference, provided model, tokenizer, and other execution conditions match.

A hash table can chain the previous block’s identity with the next block’s contents. Thus the same token block under another prefix gets a different key. A real implementation must handle collisions, model version, adapters, and user isolation. A radix tree compresses token sequences into edges and shares prefixes; lookup ends at the first mismatch. SGLang uses RadixAttention to reuse KV across programs with common prefixes.

InteractivePrefix paths and LRU
Prefix trace
1.SABC0 hits
2.SABD3 hits
3.SAE2 hits
4.SABC4 hits
5.TX0 hits · evicts S → A → B → D
6.SABD3 hits · evicts S → A → E

Green: reused prefix; gray: new tokens. Compressed tree of resident routes (● marks end):

root
T → X ●
S → A → B
C ●
D ●

The limit counts complete routes, not pages of a real engine.

3
6
Reused tokens12 / 21
Reused fraction57.1 %
Dense FLOPs avoided36 billion
Letters represent tokens. Green marks the found prefix; the limit counts complete paths, a simplification of physical-block management.

In the figure, LRU eviction removes the least recently used path. Sharing a trunk requires the manager not to free blocks still referenced by another path. A real cache also has active requests, pinned blocks, and byte capacity; removing the wrong path could invalidate an ongoing request. The lab rebuilds a small tree after evicting paths and states this simplification.

If 100 requests share a 2000-token prefix, the first computes it and 99 reuse it. With 1.5B parameters and 2 dense FLOPs per parameter and token, ideal savings are 99⋅2000⋅2⋅1.5⋅109=5.94⋅101499\cdot2000\cdot2\cdot1.5\cdot10^9=5.94\cdot10^{14} FLOPs. This excludes attention, lookup, transfers, and cache maintenance; nor does it imply the same time reduction. If cache were already warm before the 100 requests, 100 prefills would be saved instead of 99.

When memory runs out

Eviction and swapping offer alternatives to rejecting a request. Its KV can be freed and the prefix recomputed later, or cache copied to CPU memory and retrieved. Recomputation consumes compute and can increase TTFT; swapping consumes bandwidth and requires space and synchronization. Asynchronous copies overlap only when independent work, pinned memory, and transfer resources permit. Measuring bytes, time, and SLO impact matters more than choosing by intuition.

FlexGen studies placement across GPU, CPU, and disk for throughput-oriented workloads; Mooncake considers a KV cache hierarchy in a distributed architecture. These designs do not make transfer free or guarantee improved interactive latency for every load. The eviction policy must respect blocks in use and privacy and isolation requirements.

Decide what to forget

Compression by eviction retains only some tokens and changes accessible context. H2O combines recent tokens with others selected by accumulated attention; SnapKV uses an observation window to identify important positions per head. StreamingLLM retains initial sink tokens in addition to a recent window. Sinks receive attention even without being the semantic information of interest.

InteractiveA real attention and eviction example

Example: expected color is blue; with full cache the next token was blue. Higher blue intensity indicates greater mean attention; orange border indicates retention by the selected policy. Scroll the map to see all tokens.

The·secret·color·is·blue.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·The·train·passed·the·station·while·people·watched·the·clouds.·Question:·What·is·the·secret·color?·Answer:·The·secret·color

Evaluation uses one next token on eight synthetic sentences and does not measure general quality or establish published techniques’ performance.

2
Retained tokens32 / 151
Top-1 hits8 / 8
Full cache8 / 8
SmolLM2-135M data. Accumulation and observation strategies are simplified versions; the test uses eight sentences and one next token, not a general evaluation.

The map shows mean last-layer attention over the last eight prefill queries. One selection per policy is used for all layers and heads in the example, a simplification that does not reproduce per-head mechanisms or every paper decision. Each policy retains eight recent tokens and fills the budget with sinks, accumulated score, or observation. Then one token is rerun at original positions and the most likely token compared with the expected color. Full cache is the reference. The set is small and artificial and the answer fits one token; long retrieval, perplexity, and other workloads may lead to different conclusions.

In this sample, full cache and all three policies got 8 of 8 correct for all three budgets. The result does not distinguish policies. Eviction also occurs after prefill: retained states may already incorporate information from deleted tokens. This is neither recomputing the prompt without those tokens nor measuring long generation; interpreting those successes as guaranteed retrieval after many eviction steps would be incorrect.

Observed attention is not a direct causal measure of importance either. A head can assign high weight to a position without removing it having the same effect in every task; useful information can be distributed across layers and positions. A more informative evaluation would vary answer location, length, distractors, and seeds and check complete answers. Include a no-eviction reference and separate model failures from those induced by the policy.

Lab: allocation and prefixes

The next manager implements blocks, references, and copy-on-write; it then compares a chained-hash cache with a small radix tree. The tree’s LRU counts complete paths and rebuilds the tree on eviction. This demonstrates semantics, not a concurrent serving-engine implementation.

[ ]Blocks, hashes and radixBrowser
import hashlib, math
from collections import OrderedDict

class BlockAllocator:
    def __init__(self,count,b):
        self.b=b;self.free_ids=list(reversed(range(count)));self.data={};self.refs={};self.seq={}
    def allocate(self):
        if not self.free_ids:raise MemoryError('sin bloques libres')
        i=self.free_ids.pop();self.data[i]=[];self.refs[i]=1;return i
    def free(self,i):
        self.refs[i]-=1
        if self.refs[i]==0:del self.refs[i];del self.data[i];self.free_ids.append(i)
    def create(self,name):
        if name in self.seq:raise ValueError('nombre duplicado')
        self.seq[name]=[]
    def fork(self,source,target):
        if target in self.seq:raise ValueError('nombre duplicado')
        self.seq[target]=self.seq[source].copy()
        for i in self.seq[target]:self.refs[i]+=1
    def append(self,name,token):
        table=self.seq[name]
        if not table or len(self.data[table[-1]])==self.b:table.append(self.allocate())
        elif self.refs[table[-1]]>1:
            old=table[-1];new=self.allocate();self.data[new]=self.data[old].copy();self.free(old);table[-1]=new
        self.data[table[-1]].append(token)
    def remove(self,name):
        for i in self.seq.pop(name):self.free(i)
    def tokens(self,name):return [token for i in self.seq[name] for token in self.data[i]]

class HashPrefixes:
    def __init__(self,b,capacity):self.b=b;self.capacity=capacity;self.cache=OrderedDict()
    def access(self,tokens):
        parent=b'';hits=0;missing=False
        for offset in range(0,len(tokens)-self.b+1,self.b):
            block=tuple(tokens[offset:offset+self.b]);key=hashlib.sha256(parent+repr(block).encode()).digest()
            if not missing and key in self.cache:hits+=self.b;self.cache.move_to_end(key)
            else:
                missing=True;self.cache[key]=block;self.cache.move_to_end(key)
                while len(self.cache)>self.capacity:self.cache.popitem(last=False)
            parent=key
        return hits

class Node:
    def __init__(self):self.edges={};self.end=False
class RadixPrefixes:
    # Capacidad de rutas completas; reconstruir al expulsar mantiene intactos prefijos compartidos.
    def __init__(self,capacity):self.capacity=capacity;self.entries=OrderedDict();self.root=Node()
    def _insert(self,seq):
        node=self.root;remaining=tuple(seq)
        while remaining:
            edge=node.edges.get(remaining[0])
            if edge is None:child=Node();node.edges[remaining[0]]=(remaining,child);node=child;break
            label,child=edge;n=0
            while n<min(len(label),len(remaining)) and label[n]==remaining[n]:n+=1
            if n==len(label):node=child;remaining=remaining[n:];continue
            middle=Node();node.edges[remaining[0]]=(label[:n],middle);middle.edges[label[n]]=(label[n:],child)
            remaining=remaining[n:]
            if remaining:new=Node();middle.edges[remaining[0]]=(remaining,new);node=new
            else:node=middle
            break
        node.end=True
    def longest(self,seq):
        node=self.root;seq=tuple(seq);matched=0
        while matched<len(seq) and seq[matched] in node.edges:
            label,child=node.edges[seq[matched]];n=0
            while n<len(label) and matched+n<len(seq) and label[n]==seq[matched+n]:n+=1
            matched+=n
            if n<len(label):break
            node=child
        return matched
    def access(self,seq):
        seq=tuple(seq);hit=self.longest(seq)
        # Todas las rutas que contienen el prefijo reutilizado se consideran tocadas.
        for key in list(self.entries):
            if key[:hit]==seq[:hit] and hit:self.entries.move_to_end(key)
        self.entries[seq]=None;self.entries.move_to_end(seq)
        while len(self.entries)>self.capacity:self.entries.popitem(last=False)
        self.root=Node()
        for key in self.entries:self._insert(key)
        return hit

def demo():
    a=BlockAllocator(12,4);a.create('raiz')
    for t in range(6):a.append('raiz',t)
    a.fork('raiz','haz1');a.fork('raiz','haz2');a.append('haz1',90);a.append('haz2',91)
    assert a.tokens('raiz')==list(range(6)) and a.tokens('haz1')==list(range(6))+[90] and a.tokens('haz2')==list(range(6))+[91]
    assert sorted(a.refs.values())==[1,1,1,3]
    a.remove('haz2');assert sorted(a.refs.values())==[1,1,2]
    a.remove('raiz');a.remove('haz1');assert len(a.free_ids)==12 and not a.refs
    prompts=[list('abcdefgh'),list('abcdefxy'),list('abcdefzz'),list('abcdefgh'),list('mnopabcd'),list('abcdefxy')]
    h=HashPrefixes(2,8);r=RadixPrefixes(4);hh=[h.access(x) for x in prompts];rh=[r.access(x) for x in prompts]
    print('tokens reutilizados por hashes',hh,'radix',rh,'total posibles',sum(map(len,prompts)))
    print('fragmentación de 600 en bloques de 16',math.ceil(600/16)*16-600,'tokens')
    assert hh[1]==6 and rh[1]==6 and len(r.entries)==4 and a.free_ids
if __name__=='__main__':demo()

On an RTX 3060, a pool for 30 BF16 layers was physically allocated alongside real weights and 1 GB headroom within 8 decimal GB. The length trace 300, 1200, and 2500 admits 71 contiguous reservations of 4096 positions or 218 paged reservations of 16. Each reservation’s endpoints are written and read and the entire pool initialized in CUDA. These are simultaneous caches with synthetic contents, not 218 inferences or a service benchmark; additional tables and activations are excluded from the budget.

[ ]Physical cache capacity in 8 GBLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: paged attention on GPU

The test needs PyTorch CUDA, Triton, Transformers, and cached SmolLM2-135M. If not downloaded, an initial load with local_files_only=False requires a connection. On an RTX 3060 the kernel compared lengths 45, 61, and 18 with PyTorch gather and achieved maximum error 1.79e-7. The test also captures real query and cache from the model’s final layer. The 8 GB capacity count is analytical: it includes weights and a 1 GB reserve, comparing reservation of 4096 with paging 600 tokens; it is not a concurrency or throughput measurement.

In the model run, query head zero and its corresponding KV head with nine tokens gave a maximum difference of 1.19e-7 against contiguous attention. This agreement checks one step and one head, not the whole model or a concurrent service. Reproducing the retrieval figure also requires running its dataset construction; visible values come from the eight described runs, not the cited papers.

The same block copies 414720 KV bytes for those nine positions to pinned CPU buffers and back, checks exact equality, and compares with prefix recomputation. Copies are asynchronous but synchronized for measurement without overlap; buffer allocation is outside the timer. This is one short sample on a shared GPU. Together with figure accuracy it illustrates three decisions and their magnitudes but does not establish which policy wins under production load.

[ ]Paged attention in TritonLocal GPU
import math, time, torch, triton, triton.language as tl

@triton.jit
def paged(Q,K,V,T,L,O, D:tl.constexpr, BS:tl.constexpr, NB:tl.constexpr, S:tl.constexpr):
    row=tl.program_id(0)
    pos=tl.arange(0,S);d=tl.arange(0,D)
    length=tl.load(L+row);page=pos//BS;within=pos%BS
    physical=tl.load(T+row*NB+page,mask=pos<length,other=0)
    off=(physical[:,None]*BS+within[:,None])*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)
    scores=tl.sum(key*query[None,:],1)/tl.sqrt(float(D));scores=tl.where(pos<length,scores,-float('inf'))
    p=tl.exp(scores-tl.max(scores,0));p=p/tl.sum(p,0)
    result=tl.sum(value*p[:,None],0)
    tl.store(O+row*D+d,result)

def run():
    assert torch.cuda.is_available();torch.manual_seed(71)
    bs=16;d=64;lengths=[45,61,18];nblocks=4;pool=24;N=len(lengths)
    key=torch.randn(pool,bs,d,device='cuda');value=torch.randn_like(key);q=torch.randn(N,d,device='cuda')
    table=torch.randperm(pool,device='cuda')[:N*nblocks].reshape(N,nblocks).int();lens=torch.tensor(lengths,device='cuda',dtype=torch.int32)
    output=torch.empty_like(q);paged[(N,)](q,key,value,table,lens,output,D=d,BS=bs,NB=nblocks,S=64)
    reference=[]
    for i,length in enumerate(lengths):
        positions=torch.arange(length,device='cuda');physical=table[i,positions//bs].long();idx=positions%bs
        k=key[physical,idx];v=value[physical,idx];reference.append(torch.softmax(k@q[i]/math.sqrt(d),0)@v)
    reference=torch.stack(reference);torch.cuda.synchronize();err=(output-reference).abs().max().item()
    print('GPU',torch.cuda.get_device_name(),'longitudes',lengths,'bloques físicos',table.tolist())
    print('Triton vs gather máximo error absoluto',err);assert torch.allclose(output,reference,atol=2e-5,rtol=2e-5)
    bytes_per_token=2*30*3*64*4  # SmolLM2-135M: 30 capas, 3 cabezas KV de 64, FP32
    weights=538060032;reserve=1_000_000_000;budget=8_000_000_000;ctx=4096
    contiguous=(budget-weights-reserve)//(ctx*bytes_per_token)
    paged_count=(budget-weights-reserve)//(math.ceil(600/bs)*bs*bytes_per_token)
    print('8 GB decimales, solo estimación de capacidad: reserva 4096',contiguous,'paginado 600 tokens',paged_count,'KV bytes/token',bytes_per_token)
def real_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()
    ids=tokenizer('A small cached example for paged attention.',return_tensors='pt').input_ids.cuda();layer=model.model.layers[-1].self_attn;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,0,-1].detach()
    handle=layer.register_forward_pre_hook(hook,with_kwargs=True)
    with torch.inference_mode():
        initial=model(input_ids=ids[:,:-1],use_cache=True)
        out=model(input_ids=ids[:,-1:],past_key_values=initial.past_key_values,use_cache=True)
    handle.remove();k=out.past_key_values.layers[-1].keys[0,0];v=out.past_key_values.layers[-1].values[0,0]
    n=k.shape[0];d=k.shape[-1];bs=16;blocks=math.ceil(n/bs);pool=blocks+3
    physical=torch.randperm(pool,device='cuda')[:blocks];K=torch.zeros(pool,bs,d,device='cuda');V=torch.zeros_like(K)
    positions=torch.arange(n,device='cuda');K[physical[positions//bs],positions%bs]=k;V[physical[positions//bs],positions%bs]=v
    q=captured['q'][None,:].contiguous();T=physical.int()[None,:].contiguous();L=torch.tensor([n],device='cuda',dtype=torch.int32);O=torch.empty_like(q)
    paged[(1,)](q,K,V,T,L,O,D=d,BS=bs,NB=blocks,S=triton.next_power_of_2(n))
    reference=torch.softmax(k@q[0]/math.sqrt(d),0)@v;torch.cuda.synchronize();error=(O[0]-reference).abs().max().item()
    print('SmolLM2 última capa, cabeza de consulta 0/KV 0, tokens',n,'error Triton',error)
    assert torch.allclose(O[0],reference,atol=2e-5,rtol=2e-5)
    # Comparar transferencia de la caché completa y recomputación, en una sola muestra.
    pairs=[(x.keys,x.values) for x in out.past_key_values.layers]
    pinned=[(torch.empty_like(k,device='cpu',pin_memory=True),torch.empty_like(v,device='cpu',pin_memory=True)) for k,v in pairs]
    restored=[(torch.empty_like(k),torch.empty_like(v)) for k,v in pairs]
    torch.cuda.synchronize();start=time.perf_counter()
    for (k,v),(ck,cv) in zip(pairs,pinned):ck.copy_(k,non_blocking=True);cv.copy_(v,non_blocking=True)
    torch.cuda.synchronize();to_cpu=time.perf_counter()-start;start=time.perf_counter()
    for (ck,cv),(gk,gv) in zip(pinned,restored):gk.copy_(ck,non_blocking=True);gv.copy_(cv,non_blocking=True)
    torch.cuda.synchronize();to_gpu=time.perf_counter()-start;start=time.perf_counter()
    with torch.inference_mode():recomputed=model(input_ids=ids,use_cache=True).past_key_values
    torch.cuda.synchronize();recompute=time.perf_counter()-start
    assert all(torch.equal(k,gk) and torch.equal(v,gv) for (k,v),(gk,gv) in zip(pairs,restored))
    assert all(torch.allclose(k,layer.keys,atol=1e-4,rtol=1e-4) and torch.allclose(v,layer.values,atol=1e-4,rtol=1e-4) for (k,v),layer in zip(pairs,recomputed.layers))
    size=sum(k.numel()*k.element_size()+v.numel()*v.element_size() for k,v in pairs)
    print('KV bytes',size,'CPU ida ms',round(to_cpu*1000,2),'GPU vuelta ms',round(to_gpu*1000,2),'recomputación ms',round(recompute*1000,2),'una muestra, sin solapamiento')
if __name__=='__main__':run();real_model()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next optional block reproduces figure data in retrieval.json. It uses PyTorch, Transformers 5.23, and the CUDA GPU; it stores selections, attention, and successes for each configuration.

import json, torch
from transformers import AutoModelForCausalLM,AutoTokenizer
from transformers.cache_utils import DynamicCache
torch.set_num_threads(1);name='HuggingFaceTB/SmolLM2-135M';tok=AutoTokenizer.from_pretrained(name,local_files_only=True)
model=AutoModelForCausalLM.from_pretrained(name,local_files_only=True,dtype=torch.float32,attn_implementation='eager').eval().cuda()
colors=['blue','green','red','yellow','purple','orange','white','black']
budgets=[16,32,64];results={p:{str(b):0 for b in budgets} for p in ['sum','observation','sink']};baseline=0;example=None
def indices(policy,budget,n,attn):
    recent=min(8,budget);selected=set(range(n-recent,n));room=budget-len(selected)
    if policy=='sink':selected.update(range(min(room,n-recent)))
    else:
        # Simplificaciones didácticas: una puntuación promedio de la última capa para todas las cabezas KV.
        score=(attn.sum(dim=(0,1)) if policy=='sum' else attn[:,-8:,:].sum(dim=(0,1))).clone()
        if selected:score[list(selected)]=-1
        selected.update(torch.topk(score,min(room,n-len(selected))).indices.tolist())
    return sorted(selected)
for color in colors:
    target=tok.encode(' '+color,add_special_tokens=False);assert len(target)==1,(color,target)
    filler=' The train passed the station while people watched the clouds.'*12
    prompt=f'The secret color is {color}.'+filler+' Question: What is the secret color? Answer: The secret color is'
    ids=tok(prompt,return_tensors='pt').input_ids.cuda();n=ids.shape[1]-1;assert n>64
    with torch.inference_mode():
        pre=model(input_ids=ids[:,:-1],use_cache=True,output_attentions=True)
        attn=pre.attentions[-1][0].float();layers=[(layer.keys,layer.values) for layer in pre.past_key_values.layers]
        def decode(idx):
            index=torch.tensor(idx,device='cuda');cache=DynamicCache(ddp_cache_data=[(k.index_select(2,index),v.index_select(2,index)) for k,v in layers]);mask=torch.ones((1,len(idx)+1),device='cuda',dtype=torch.long)
            return model(input_ids=ids[:,-1:],attention_mask=mask,position_ids=torch.tensor([[n]],device='cuda'),past_key_values=cache,use_cache=True).logits[0,-1]
        full=decode(list(range(n)));straight=model(input_ids=ids,use_cache=False).logits[0,-1]
        assert torch.allclose(full,straight,atol=1e-4,rtol=1e-4)
        baseline+=int(int(full.argmax())==target[0]);selection={}
        for policy in results:
            selection[policy]={}
            for budget in budgets:
                idx=indices(policy,budget,n,attn);selection[policy][str(budget)]=idx
                logits=decode(idx);results[policy][str(budget)]+=int(int(logits.argmax())==target[0])
        if example is None:
            # Puntuaciones agregadas para el mapa de atención, no texto de una generación inventada.
            example={'tokens':[tok.decode([int(t)]) for t in ids[0,:-1]],'attention':attn[:,-8:,:].mean(dim=(0,1)).cpu().tolist(),'selection':selection,'expected':color,'full_top1':tok.decode([int(full.argmax())])}
    print(color,'longitud',n,'top1 completo',tok.decode([int(full.argmax())]),flush=True)
print('aciertos top1 de 8:',json.dumps({'full':baseline,**results}),flush=True)
payload={'model':name,'gpu':torch.cuda.get_device_name(),'budgets':budgets,'n':len(colors),'results':results,'baseline':baseline,'example':example}
with open('retrieval.json','w',encoding='utf8') as f:json.dump(payload,f,ensure_ascii=False)

Exercises

Numeric
What percentage of a 4096-token reservation is wasted when 600 are used?
Numeric
With uniform remainders for blocks of 16, how many tokens are wasted on average per sequence?
Numeric
If the first of 100 requests computes a 2000-token prefix and the other 99 reuse it, with 1.5B parameters and 2 FLOPs per parameter and token, how many trillion FLOPs are saved? One trillion is 10^12.
Proof
Prove: Prove average fragmentation when length modulo b is uniform.
The proof will appear here as you work.

Step 1 of 2. What waste values are possible?

Code
Implement BlockAllocator(n,b) with create(name), allocate(), free(id), fork(source,target), append(name,token), remove(name) and tokens(name). Attributes data and refs are dictionaries by physical ID and seq contains lists of IDs. allocate returns an ID with reference count 1; free decrements and releases at zero. fork shares blocks and increments references. append copies a shared partial final block before modifying it, or allocates a new one if full.
class BlockAllocator:
  def __init__(self,n,b):
      ...
  def create(self,name):
      ...
  def allocate(self):
      ...
  def free(self,i):
      ...
  def fork(self,source,target):
      ...
  def append(self,name,token):
      ...
  def remove(self,name):
      ...
  def tokens(self,name):
      ...
Shift+Enter to run
Quiz
What part of a cache can be reused after editing a conversation turn?
Key idea
Paging changes memory management without changing attention; sharing needs references and copy-on-write. Evicting information does change context and requires measuring task quality.