Example

Allocate paged KV blocks and watch them get reused

Map three sequences onto eight physical blocks, free one, reallocate its pages, and test the boundary where allocation must fail.

PagedAttention separates a sequence’s logical token positions from the physical blocks that hold its keys and values. A sequence of 10 tokens with a block size of 4 needs three logical blocks, whether or not the last one is full. The allocator hands out physical block ids, and a page table maps one to the other. The gain is that sequences no longer need contiguous memory; the cost is indirection, partially filled last blocks, and a policy that can still fail.

This example runs a deterministic allocator with eight blocks of size four. It allocates 10 tokens to seq1 and 6 to seq2, checks that their physical blocks are disjoint, frees seq1, and allocates 4 tokens to seq3. Every id is printed, so the mapping can be checked by hand. The example also exposes the boundary: an allocation larger than the free list raises MemoryError instead of silently overwriting another sequence.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch14/paged_attention.py --json

Python 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.

Implementation

allocate rounds the token count up to whole blocks, pops that many ids from the free list, and records them under the sequence id. free returns the ids and sorts the free list. fragmentation counts free blocks with no free neighbour. PagedKVStore checks that two sequences do not share a physical block.

class BlockAllocator:
    def __init__(self, num_blocks: int, block_size: int) -> None:
        if num_blocks < 1 or block_size < 1:
            raise ValueError("num_blocks and block_size must be positive")
        self.num_blocks = num_blocks
        self.block_size = block_size
        self.free_blocks: List[int] = list(range(num_blocks))
        self.allocated: Dict[str, List[int]] = {}

    def allocate(self, seq_id: str, num_tokens: int) -> AllocationResult:
        if seq_id in self.allocated:
            raise ValueError("sequence already allocated")
        num_blocks = (num_tokens + self.block_size - 1) // self.block_size
        if num_blocks > len(self.free_blocks):
            raise MemoryError("not enough free blocks")
        physical = [self.free_blocks.pop(0) for _ in range(num_blocks)]
        self.allocated[seq_id] = physical
        return AllocationResult(
            seq_id=seq_id,
            logical_blocks=num_blocks,
            physical_blocks=physical,
            fragmented=False,
            metadata={"block_size": self.block_size},
        )

    def free(self, seq_id: str) -> List[int]:
        if seq_id not in self.allocated:
            raise KeyError("unknown sequence")
        physical = self.allocated.pop(seq_id)
        self.free_blocks.extend(physical)
        self.free_blocks.sort()
        return physical

    def fragmentation(self) -> float:
        # Fraction of free blocks that are isolated (not contiguous with another free block).
        if not self.free_blocks:
            return 0.0
        isolated = 0
        for index in self.free_blocks:
            prev_free = (index - 1) in self.free_blocks
            next_free = (index + 1) in self.free_blocks
            if not prev_free and not next_free:
                isolated += 1
        return isolated / len(self.free_blocks)

Expected outcome

Observed with the command above (exit 0):

{
  "r1": {
    "seq_id": "seq1",
    "logical_blocks": 3,
    "physical_blocks": [
      0,
      1,
      2
    ],
    "fragmented": false,
    "metadata": {
      "block_size": 4
    }
  },
  "r2": {
    "seq_id": "seq2",
    "logical_blocks": 2,
    "physical_blocks": [
      3,
      4
    ],
    "fragmented": false,
    "metadata": {
      "block_size": 4
    }
  },
  "isolated": true,
  "freed_blocks": [
    0,
    1,
    2
  ],
  "reallocated": {
    "seq_id": "seq3",
    "logical_blocks": 1,
    "physical_blocks": [
      0
    ],
    "fragmented": false,
    "metadata": {
      "block_size": 4
    }
  },
  "fragmentation_before": 0.0,
  "fragmentation_after": 0.0,
  "free_blocks": [
    1,
    2,
    5,
    6,
    7
  ]
}

The mapping is exact: seq1 owns blocks 0-2, seq2 owns 3-4, and seq3 gets block 0 after seq1 is freed. isolated: true means the two live sequences use disjoint physical blocks. Two slots in seq1’s last block and two in seq2’s last block are allocated but unused: that is internal fragmentation, not a mapping error.

Mechanism and limitations

Documented: the allocator rejects non-positive block counts and block sizes, duplicate sequence ids and unknown frees. It raises MemoryError when the free list is too small. The fragmentation metric is the fraction of free blocks with no free neighbour. The store writes and reads whole blocks and has an isolation check. The tests cover allocation and freeing, isolation, the contiguous-free case, out-of-memory, the demo and JSON serialisation.

Observed: the command exited 0 with the full mapping above. The targeted tests.test_ch14_paged is part of the canonical suite; no independent test count is claimed here.

Not shown: a real KV cache, copy-on-write sharing, eviction, a page table used by an attention kernel, GPU memory, or throughput. The demo uses one allocation policy and one small free list. The fragmentation value is zero before and after because the free list happens to be contiguous after the operations; that does not mean the policy avoids fragmentation in general.

Challenge this result

Allocate three sequences that fit exactly, free the middle one, and allocate a sequence that needs two blocks. Predict whether it receives contiguous or split physical blocks, then check fragmentation(). Finally, allocate one block too many and confirm the MemoryError. Explain why a policy that never fails is not necessarily safe: it may be evicting live state or overcommitting memory.

Source and verification

Canonical source: examples/ch14/paged_attention.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch14_paged.py . Chapter: PagedAttention . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it uses a simulated allocator, not a GPU KV cache.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.