Unit 7 of 10 · about 5 hours · implement

Key-value append, gather, layout conversion and quantized loads

Attention can be correct while reading the wrong generation of a cache slot. Cache updates need position, allocation, stream and scale contracts of their own.

You'll be able to

  • Implement KV append, gather and layout conversion with explicit slot ownership.
  • Validate cache writes across page boundaries and preserve untouched entries.
  • Explain the optional quantized-load contract and check reconstruction error separately from indexing correctness.

Covers

Key-value append, gather, layout conversion and cache writesQuantized key-value loads and dequantization
1

Read

In this order, only the parts listed

0 of 2 done

  1. FlashInfer page append and logical positionsFlashInfer

    Commit f2794d5: get_batch_indices_positions, get_seq_lens and append_paged_kv_cache, including its Example and Note

    Trace the ordinary append operation. Skip MLA and NVFP4 append paths. The caller allocates pages and updates final lengths before append; the append function is not an allocator.

  2. FlashInfer layouts and optional quantized decode scalesFlashInfer

    Commit f2794d5: single_decode_with_kv_cache, kv_layout, q_scale, k_scale, v_scale docstrings and the scale applications in its implementation

    Inspect FP8 scale semantics, not a promise of FP8 acceleration on your GPU. Use a small software dequantization reference for the optional path; no Blackwell-only packed format is required.

2

Focus on

  • Append maps each new row to a request and absolute token position. Check allocation, page capacity and bounds before launch. Two writers must not own the same destination slot.
  • For each separate cache tensor, NHD orders page, token, head, channel; HND orders page, head, token, channel. A changed view of strides is not a physical layout conversion. Test gather before and after the actual conversion.
  • Initialize unused slots to sentinels, append known rows, gather valid tokens and check that all other slots remain unchanged. Preserve stream ordering and keep storage alive until consumers finish.
  • Optional quantized loads must specify format, reconstruction scale and granularity for keys and values. Per-tensor key scale can enter score scaling and per-tensor value scale can enter output scaling; token- or group-varying scales cannot generally be moved outside those reductions.
Common mistakes · 3
  • Appending with old last-page lengths or unallocated next pages. The final page metadata must already describe the destination capacity and length.
  • Overwriting shared prefix pages. A serving allocator needs copy-on-write or an ownership rule before mutable append; the kernel cannot infer that from addresses.
  • Applying the quantization error bound to clipped outliers. Saturation introduces additional error, and small reconstruction error does not by itself bound attention-output or task-quality error.
3

Try it yourself

Closed-book, before checking anything

Implement a small append/gather round trip with separate key/value caches, page size 4, two heads of width 3, and a seven-token request on physical pages [3, 1]. Fill unused storage with -99.0; append increasing integer-valued rows and verify exact gathered values and untouched slots. Convert NHD storage to HND and repeat. For optional symmetric integer quantization, reconstruct finite unclipped values as with positive scale , and check the bound up to rounding tolerance.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.How can an append test detect a write that does not affect today's output?Answer

    Check sentinels in every unowned slot. Otherwise a stray write can remain invisible until that slot is reused or read later.

  2. 2.Can one output scale represent independently scaled value tokens?Answer

    Not in general. Each token contributes with its own scale inside the weighted sum. Only a common value scale can be factored out.

  3. 3.Does changing the layout label move the cache data?Answer

    No. The label tells the consumer how to interpret storage. A physical conversion must rearrange data or produce correctly strided storage that the consumer supports.

You're done when

Append, gather and conversion preserve token identity across partial and full pages, with untouched-slot and bounds checks; any optional quantized path reports clipping and output error separately.

Only when you can do this without notes.

Leads to

Notes

Resources · 1 for this unit, 12 more in the section
  • FlashInferFlashInfer Project · support

    Inspect the attention, sampling and serving-kernel interfaces. Reconstruct one dispatch path and compare its layout and workspace contracts with your reduced kernel instead of copying the optimized implementation.

Also in this section

  • FlashAttentionTri Dao and collaborators · primary

    Read the IO-awareness argument, exact attention algorithm and complexity analysis. Derive the online state and block dataflow, then implement a reduced forward kernel or trace a trusted implementation across at least causal and noncausal cases.

  • FlashAttention-2Tri Dao · required

    Study reduced non-matmul work, sequence parallelism and warp work partitioning. Compare the schedule with the first paper and predict which shapes benefit before checking measurements.

  • Online Normalizer Calculation for SoftmaxOnline Softmax Authors · required

    Re-derive the recurrence inside tiled attention and prove rescaling correctness. Add extreme-logit, all-masked, odd-head and partial-tile tests before any performance comparison.

  • CS336 Assignment 2 - Section 4 FlashAttention-2 in TritonStanford University · required

    Do the weighted-sum warm-up, then flash_forward (a PyTorch tiled version and the Triton kernel) and flash_backward against tests/test_attention.py. Run flash_benchmarking on sizes that fit your GPU instead of the handout's B200 sweep.

  • TensorTonic Language Modeling from Scratch - Blockwise Online SoftmaxTensorTonic · support

    Solve it before the tiled attention kernel as a check on the rescaling recurrence.

  • LeetGPU - Attention and Transformer ChallengesAlphaGPU · required

    Solve 6 Softmax Attention and 12 Multi-Head Attention or 53 Causal Attention. Then choose two of 50 RMS Normalization, 54 SwiGLU, 61 RoPE, 80 Grouped Query Attention, 83 Fused Residual Add RMS Norm and 84 SwiGLU MLP Block. Keep correctness tests beyond the hosted score.

  • GPU MODE - Attention and Fused KernelsGPU MODE · support

    Use Lectures 12, 13, 18, 36 and 40 for FlashAttention, Ring Attention, fusion, FlashAttention-3 and FlashInfer. Reproduce one schedule or fusion idea under the stage shape matrix and a strong baseline.

  • FlashAttention-3FlashAttention Authors · depth

    Study Hopper-specific asynchronous execution and low-precision design after the portable kernel. Implement only with the required architecture, and separate algorithmic from hardware-specific gains.

  • Modern GPU Programming for MLSys - Flash Attention 4MLC · depth

    Read the complete Blackwell attention chapter, including two MMAs, online softmax, causal masking and GQA. Run it only on compatible sm_100a hardware with the pinned TIRx stack; otherwise use the code for architecture reconstruction.

  • PyTorch SDPA contracts and integration tutorialPyTorch · reference

    The PyTorch 2.14 SDPA API page gives mask polarity, rectangular causal alignment, GQA and backend limitations. The SDPA tutorial (https://docs.pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html, read 2026-10-13) gives Explicit Dispatcher Control, Causal Self Attention, Using SDPA with torch.compile and Using SDPA with attn_bias subclasses. Correct the tutorial's evaluation-time causal flag before integration.

  • Triton 3.8.0 Layer NormalizationTriton Project · required

    Motivations and _layer_norm_fwd_fused in tutorial 05, pinned to v3.8.0. Study centered variance, float32 reductions, valid-column masks and the forward wrapper's supported-width guard. Defer backward and the benchmark sweep.

  • vLLM serving latency and goodput definitionsvLLM Project · reference

    vLLM v0.31.0: Benchmark CLI, Understanding the Latency Metrics and Load Pattern Configuration; serving benchmark CLI, goodput service-level objectives. Use definitions to translate kernel evidence into request metrics, not as a required serving-engine installation.