Unit 4 of 12 · about 4 hours · implement
KV append, gather and layout, and RoPE positions and offsets
Key-value append, gather, layout conversion and quantized loads already established the storage primitives. Serving adds a lifecycle: reuse of a physical slot must not reuse the previous request's position or key state.
You'll be able to
- Implement append and gather over page boundaries while preserving untouched KV slots.
- Preserve absolute RoPE positions through cached chunks, request compaction and slot reuse.
- Trace where the model rotates keys and where the backend stores them to prevent double rotation.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Caller-owned append metadataFlashInfer Documentation
FlashInfer documentation: Parameters, Example and Note of
append_paged_kv_cache(page read 2026-10-14, release 0.7.1) - Rotation before backend dispatchMini-SGLang - Kernel, Model Runner and Overlap Boundaries
AttentionLayer.forward: projection split, optional head norms, rotation usingctx.batch.positions, then attention-backend call - KV storage and rotation conventionsMini-SGLang - Kernel, Model Runner and Overlap Boundaries
MHAKVCache.__init__andstore_kv; thenRotaryEmbedding.__init__andforwardin the linked rotation implementationOpen https://github.com/sgl-project/mini-sglang/blob/9a91cfafe754aa85daee49998176275667eb58f2/python/minisgl/layers/rotary.py for the second locator. Stop before model-specific scaling branches in
_get_rope.
Focus on
- The append API assumes allocation and final page metadata already include the new tokens. Validate capacity before writing; it neither allocates pages nor protects shared-prefix ownership for you.
- Cache addresses and RoPE positions are separate mappings. A compacted batch index, physical page or recycled slot cannot replace a request's logical position.
- Mini-SGLang rotates queries and keys before storing keys; its FlashInfer path uses
pos_encoding_mode="NONE". In another integration, inspect this boundary before enabling rotation inside attention. - Keep the model's pairing, frequency base, scaling and rotary width fixed. Layout conversion changes storage, not those conventions; test full-prefix and chunked execution on the same represented inputs.
Common mistakes · 3
- Using chunk-local positions starting at zero for a suffix that follows a cached prefix.
- Rotating stored keys again on every decode step, or rotating both before append and inside attention.
- Writing into a shared page before the allocator has made the destination private. Kernel correctness cannot repair an ownership violation.
Try it yourself
Closed-book, before checking anything
[3, 1] for a request growing from length 3 to 5. With seed 0 standard-normal double-precision keys and values, rotate new keys at logical positions 3 and 4 using a half-split RoPE reference with width 8 and base 10000. Append across the page boundary, gather and compare with rotating the full five-token prefix once at rtol=1e-12, atol=1e-12. Verify every untouched slot exactly. Recycle the pages for a new request beginning at position 0 and repeat; do not inherit the old position offset.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A request has three cached tokens. What positions belong to its next two tokens?Answer
3 and 4 under zero-based absolute positions, regardless of physical pages or batch order.
2.What metadata does append consume: old lengths or lengths after append?Answer
Lengths and page lists after append. All destination space must already be allocated.
3.Is RoPE norm preservation enough to verify positions?Answer
No. A rotation at the wrong position also preserves norm. Compare against the correct absolute-position reference and cached/full-prefix outputs.
You're done when
Chunked and full-prefix keys agree under the position contract, untouched slots are preserved, and a recycled-slot test detects a deliberately stale offset.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 12 more in the section
- FlashInfer DocumentationFlashInfer Project · required
Use the current attention, PageAttention, sampling, JIT and CUDA Graph interfaces while implementing. Pin the version and supported GPU architecture, and validate dispatch and fallback over the real workload shape distribution.
- Mini-SGLang - Kernel, Model Runner and Overlap BoundariesSGLang Project · support
Trace how FlashAttention or FlashInfer, KV layouts, tensor parallel communication and overlap scheduling meet the model runner. Identify the fallback and state-reset boundary before attempting a change.
Also in this section
- FlashInfer: Efficient and Customizable Attention Engine for LLM Inference ServingFlashInfer Project · primary
Read the storage heterogeneity, plan and run separation, load-balanced scheduling, customization, CUDA Graph compatibility and end-to-end evaluation. Use it to connect serving-shaped attention kernels to dynamic workloads and dispatch constraints.
- AI Systems Performance Engineering - Chapters 18 and 19, decode kernels and engine optimizationsChris Fregly (O'Reilly) · required
Read "Optimized Decode Kernels" in Chapter 18 (FlashMLA, ThunderMLA, FlexDecoding), then the Chapter 19 sections on kernel autotuning, occupancy-aware kernel selection, hot-swappable kernels and CUDA-graph prewarming. Choose one bounded critical path to verify.
- AI Systems Performance Engineering companion code - Chapter 18Chris Fregly · required
Start with paged_attn_common.py, the dense versus paged layout pair, CUDA graph bucketing and the vLLM integration pair. Run correctness tests first, then a hardware-compatible benchmark with newly captured artifacts.
- FlashAttention-2: Faster Attention with Better Parallelism and Work PartitioningTri Dao · required
Derive online-softmax state, memory traffic and work partitioning. Implement only a small oracle-backed version or use the CS336 assignment; production kernel tuning belongs to the GPU track.
- CS336 Assignment 2 - FlashAttention and Triton SectionsStanford University · required
Complete the relevant derivation, PyTorch reference and Triton sections using your own code. Follow assignment integrity: use external help for concepts, invariants, tests and profiling, not copied solutions or edited answer code.
- UCSD CSE 291A (Spring 2026) - Guest lecture: Engineering vLLMUC San Diego · support
Read the scribe notes, Sections 4 and 5: CPU overhead, the API server and renderer, synchronous and asynchronous engine-core scheduling, GPU-side input preparation, piecewise CUDA graphs and the hybrid kernel strategy.
- vLLM CUDA Graphs design (v0.31.0)vLLM Project · support
Use the capture modes, batch-size buckets and piecewise splitting around attention to explain what a graph replay can and cannot include.
- LLM Inference: From scratch, one token at a time - Module 07Tushar Amrit · support
Work the Attention Kernels module for the decode-attention memory traffic and the paged-attention gather before the matching units.
- AI Performance Engineering - Kernel Optimization, Profiling and AttentionWafer · reference
A curated index. Use Sections 2 and 3 only to find a kernel or profiler source the other entries lack.
- TensorRT-LLM Architecture OverviewNVIDIA · support
Use the runtime-optimization section to compare graph replay, overlap scheduling and backend dispatch with your selected engine. Record current version and hardware support before treating a path as available.
- vLLM structured outputs (v0.31.0)vLLM Project · required
Read Offline Inference and the API-field migration warning; trace grammar bitmask application before sampling in the versioned model-runner API.
- PyTorch compiler troubleshooting guide (2.14)PyTorch · reference
Read Graph break, Guards, Recompilation and Dynamic Shapes; run
TORCH_LOGSset tograph_breaksandrecompileson a small serving-shaped function.