Unit 4 of 11 · about 4 hours · explain, derive

Paged KV allocation and prefix reuse at kernel level

KV memory sets how many requests fit and which prefixes skip compute. Block tables and reuse identity decide both.

You'll be able to

  • Derive block-table translation, slot waste and per-token KV bytes for a stated model and block size.
  • Explain prefix-reuse cache identity, including what the hash covers and why partial blocks miss.
  • Quantify fragmentation and memory-capacity effects on one engine run.

Covers

Key-value allocation, paging, fragmentation and address mappingPrefix reuse, cache identity and kernel shape changes
1

Read

In this order, only the parts listed

0 of 3 done

  1. Blocks, manager and scheduling interactionPagedAttention and vLLM

    Sections 4.1 to 4.2, PagedAttention and KV Cache Manager with Figures 5 to 7; Section 4.5, Scheduling and Preemption

  2. Radix tree reuse and cache-aware schedulingSGLang

    Section 3, Efficient KV Cache Reuse with RadixAttention, with Figure 3; Appendix A.2, Algorithm 1 cache-aware scheduling pseudocode

  3. Allocation, pooling and radix reuse labAI Systems Performance Engineering companion code - Chapters 12 to 16

    BaselineKVCacheManagementBenchmark in baseline_kv_cache_management.py versus OptimizedKVCacheManagementBenchmark in optimized_kv_cache_management.py; RadixTree and KVCache in ch16/radix_attention_example.py

2

Focus on

  • A logical token position maps through a block table to a physical block. Blocks are fixed-size pages, so a 40-token sequence with block size 16 occupies three size-16 blocks holding 16, 16 and 8 tokens, with 8 wasted slots.
  • Only full blocks enter the reuse cache under a hash of parent hash plus block tokens plus extras such as image hashes. A partial final block never hits.
  • Sharing is reference-counted with LRU eviction. Freeing appends tail blocks first because they hash more context and are less likely to be reused.
Common mistakes · 3
  • Counting cached bytes as free memory. Shared blocks are live for every referencing request until all release them.
  • Expecting reuse for a shared prefix shorter than one block. Nothing is cached until a full block completes.
  • Treating the block hash as the tokens alone. Parent context and extras are part of identity; dropping them causes wrong reuse.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive per-token KV bytes as with layers, KV heads, head dim and bytes per value. For , , , FP16, get 131072 bytes (128 KiB) per token. Then place a 40-token sequence in block size 16 and report 3 blocks with 8 wasted slots.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does fixed-size paging beat one contiguous reservation per request?Answer

    It avoids external fragmentation from variable-length reservations. Waste is bounded to one partial block per sequence instead of one oversized reservation.

  2. 2.Two requests share 10 tokens with block size 16. Why is there no reuse?Answer

    Only full blocks are hashed and cached. The partial tail has no stable identity until it fills.

  3. 3.What does a vLLM prefix-cache hash cover beyond token IDs?Answer

    Parent hash plus block tokens plus extras such as LoRA IDs, image hashes or cache salts. Same text with a different image or salt hashes differently.

5

Practice

  • Companion code ch15 and ch16: KV management and radix reuse

    Run python -m cli.aisp bench run --targets ch15:kv_cache_management --profile minimal (plain python -m ch15.compare runs every pair in the chapter) and ch16/radix_attention_example.py; show a shared-prefix hit against a miss with block tables and hit counters retained

    Single-GPU run is enough. No public autograder checks reuse; retain block tables, hit rates and the capacity notes.

You're done when

You derive block placement, waste and KV bytes for an unseen shape and predict hit or miss for a stated prefix pair.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 11 more in the section
  • AI Systems Performance Engineering companion code - Chapters 12 to 16Chris Fregly · required

    Use compatible examples from code/ch12 through code/ch16. Trace whether each optimized path changes a kernel, graph, compiler choice, scheduler or library dispatch, then integrate one bounded custom path into a realistic operator or small endpoint.

  • PagedAttention and vLLMvLLM Authors · required

    Study block-based key-value allocation, sharing and scheduling interaction. Trace logical token positions to physical blocks in one engine run and quantify fragmentation and memory-capacity effects.

  • SGLangSGLang Authors · support

    Read the runtime and RadixAttention design, then inspect the repository path for one kernel or prefix-reuse interaction. Use it as an alternative architecture in the integration defense.

Also in this section

  • AI Systems Performance Engineering - Chapters 13, 15 and 16Chris Fregly · primary

    Read Chapter 13 on profiling and tuning PyTorch, Chapter 15 on inference parallelism, decoding and routing, and Chapter 16 on profiling and debugging inference. Keep Chapters 17 to 19 for GPU-9 and depth.

  • AI Performance Engineering - Inference EnginesWafer · reference

    A curated index. Use Section 4 only to find the introducing paper and implementation for the mechanism your measurement points to.

  • LeetGPU - Inference Kernel SetAlphaGPU · required

    Choose three bottleneck-matched challenges from 74 GPT-2 Block, 83 Fused Residual Add RMS Norm, 84 SwiGLU MLP Block, 87 Speculative Decoding Verification, 93 Llama Transformer Block and 96 INT8 KV Cache Attention. Integrate one result locally rather than stopping at the hosted submission.

  • FlashInferFlashInfer Project · support

    Use the repository as the serving-kernel baseline and interface reference. Reconstruct workspace planning, layouts, dispatch and stream behavior for one selected operation before comparing your path.

  • GPU Microbenchmark and Kernel Suite - IntegrationRoadmap-Final · support

    Complete the real tensor or model-operation integration, dispatch and fallback requirements. Report compilation and invocation overhead, workload frequency, correctness or quality and the end-to-end no-benefit regime.

  • PyTorch 2.14 ProfilerPyTorch · reference

    Read the Overview example plus the API reference for torch.profiler.profile (activities, schedule, on_trace_ready, record_shapes, with_stack), torch.profiler.record_function and export_chrome_trace. Use it for exact profiler and NVTX-range call contracts missing from the book.

  • Orca (OSDI 2022)USENIX · support

    Read Sections 3 to 4 for iteration-level scheduling and selective batching, and Section 6 for the engine microbenchmark and end-to-end latency-throughput method. Use it as the continuous-batching mechanism behind the book summary.

  • Sarathi-ServearXiv · support

    Read Sections 3 to 4 for chunked-prefill stall-free batching and token-budget selection, and Section 5 for capacity and overhead method. Use it as the chunked-prefill mechanism behind the book summary.

  • Fast Inference from Transformers via Speculative DecodingPMLR · support

    Read Sections 2 to 3 for the draft-verify-accept loop, the acceptance rule and the walltime-versus-operations analysis. Use it for the verification cost model behind the engine guides.

  • vLLM Documentation - Automatic Prefix CachingvLLM Project · reference

    Read Automatic Prefix Caching (vLLM v0.31.0) for hash-based block reuse, full-block caching, reverse-order freeing and the multimodal hashing example. Use it for engine behavior the papers do not version.

  • Transformer Inference ArithmeticKipply · reference

    Read kv cache, capacity, latency calculations, batch sizes and flops counting for per-token KV bytes, weight-capacity arithmetic and memory-bound versus compute-bound latency floors. Use it to derive endpoint bounds before measuring.