Chapter 34
CUDA Kernels for LLM Inference
On this page
- Serving contracts restated for kernel work
- Embedding lookup and output projection
- RoPE
- KV-cache append
- Paged KV attention
- Bandwidth sketch for the running example
- Split-K decode attention
- GQA and MQA mapping
- KV-cache quantization
- Weight-only quantized GEMM
- MoE routing and grouped GEMM
- Sampling and token cadence
- Design Exercises
- Worked Solutions
- A page permutation exposes an address bug
LLM serving kernels operate on dynamic batches, ragged state, low precision, and strict token cadence. Layout and scheduler contracts are part of kernel design.
Prefill attention and GEMM covered the compute-rich path. This section specializes the schedule for decode and related serving kernels. The serving vocabulary is restated here so the section stands alone: what KV cache is, why it is paged, how GQA shares keys and values, and which contracts a kernel must honor.
Serving contracts restated for kernel work¶
For the running full-history GQA model, decode retains each layer's keys and values for tokens processed so far, including the prompt. That working set is the KV cache. Its lifetime follows requests, not training batches. The element payload is 2 * tokens * layers * KV_heads * head_dimension * bytes_per_element, summed over active sequences; the factor two counts K and V, and physical allocation adds overhead.
Other architectures need a different state ledger. Part I's hybrid example carries recurrent matrices and convolution history alongside attention KV; a port, prefix restore, or handoff must preserve them at the same accepted token boundary.
A paged KV cache stores tokens in fixed-size physical pages and maintains a block table from logical token blocks to physical pages. Kernels must translate (sequence, position) into a page and offset, then load K/V vectors. The page size trades fragmentation against contiguous access and metadata overhead.
Grouped-query attention (GQA) and multi-query attention (MQA) reduce KV heads relative to query heads. In the running example, H = 32 and H_kv = 8, so four query heads read one KV head. The kernel must map those query heads to reuse loaded K/V without silently mixing sequences or heads.
Token cadence is the product constraint that decode steps are short and frequent. A kernel that wins a microbenchmark but adds host synchronization, allocator traffic, or an extra full-tensor pass can miss inter-token latency even when its FLOP rate looks healthy.
Embedding lookup and output projection¶
Embedding lookup is a gather. Adjacent output dimensions for one token are contiguous; token IDs across requests are irregular. Assign lanes across the embedding dimension so one token's vector loads coalesce. Repeated token IDs may benefit from cache, but do not rely on it for the worst case.
The output projection is a GEMM against the vocabulary matrix. For small decode batch it can be bandwidth-bound. Tensor parallelism shards vocabulary or hidden dimension, after which top-k and sampling need distributed coordination.
RoPE¶
Rotary position embedding rotates pairs of query and key components. For pair (x_0, x_1) and angle theta:
The kernel can fuse RoPE into Q/K projection output handling or KV-cache write. Precomputed sine/cosine tables trade memory reads for transcendental arithmetic. Generate angles on the fly when table bandwidth or very long positions make it worthwhile.
Layout must define whether paired dimensions are adjacent or split into halves. A mismatch can produce numerically plausible but incorrect results.
Example status: CUDA excerpt; not compiled or benchmarked.
float2 pair = load_pair(q, token, head, pair_id);
float c = cos_table[position * pairs + pair_id];
float s = sin_table[position * pairs + pair_id];
float2 rotated = make_float2(
pair.x * c - pair.y * s,
pair.x * s + pair.y * c);
store_pair(q_out, token, head, pair_id, rotated);
KV-cache append¶
Each decode step writes one K and V vector per layer and sequence. The write is small and frequent. Fuse layout conversion, RoPE for K, and quantization when doing so reduces full-vector traffic without blocking the main attention path.
The address depends on logical sequence, token position, layer, KV head, page mapping, and dtype. Keep that indexing contract centralized. A one-off mismatch between append and read kernels corrupts attention silently.
For the running example, one decode step appends, per layer, B * H_kv vectors of length d. In FP16 that is 8 * 8 * 128 * 2 = 16 KiB of K plus the same for V - tiny compared with reading the full context, but correctness-critical because every later attention step depends on the written layout.
Paged KV attention¶
A block table maps logical token blocks to physical pages. Decode attention traverses pages, loads K/V vectors, computes query-key scores, performs online softmax, and accumulates values. This is the same (m, l, o) recurrence derived earlier; only the K/V addressing and parallelism differ from FlashAttention prefill.
Key design decisions:
- tokens per page;
- K/V head and dimension layout inside a page;
- vector width and alignment;
- how sequences map to blocks or warps;
- how GQA query heads share one KV head;
- how page-table lookups are cached or prefetched;
- where quantization scales reside;
- how partial results merge for long context.
Smaller pages reduce fragmentation and copy cost but increase page-table entries and discontinuities. Larger pages improve contiguous access but waste more tail capacity.
Derive the paged address before vectorizing it¶
For a contiguous physical cache K[page,head,offset,channel] with page length P, H_kv heads and head width d, logical token t resolves to physical page p=block_table[sequence,floor(t/P)] and offset o=t mod P. Its scalar index is ((p*H_kv+h)*P+o)*d+c; multiply by element size only when converting to byte addresses. Perform these products in an integer type wide enough for the complete allocation.
This formula defines one layout, not a universal cache ABI. A layout that groups vector packs or interleaves K and V changes strides. Test the logical-to-physical mapping independently of attention, with a deliberately nonmonotonic block table. Check the boundary tokens P-1, P, and P+1, and a last page with fewer than P valid tokens.
For append, publishing the new sequence length before the KV write completes allows a consumer to read uninitialized state. The visibility edge must run from completed payload writes to metadata that authorizes reads, with the appropriate stream/event or inter-kernel dependency. Recycling a page similarly requires completion of all old readers; changing the table entry does not cancel their already-issued loads.
Bandwidth sketch for the running example¶
For one layer of a decode attention step, an ideal schedule that reuses each KV head across its query heads reads roughly:
B * H_kv * S * d * bytes_per_element * 2 (K and V)
With B = 8, H_kv = 8, S = 4096, d = 128, FP16:
8 * 8 * 4096 * 128 * 2 * 2 = 134,217,728 bytes = 128 MiB
At an illustrative 3 TB/s HBM ceiling, streaming 128 MiB takes about 0.045 ms before scoring arithmetic, softmax, and writes. This is a per-layer lower bound assuming the KV reads reach HBM. Across Part III's 32 layers, the logical KV traffic is 4 GiB (about 4.3 GB), matching that part's decode ledger. Repeated loads across GQA query groups can raise traffic, while cache hits can reduce it. Useful bandwidth falls if page jumps destroy coalescing. This is why layout and paging dominate decode attention more than peak tensor-core throughput.
Split-K decode attention¶
One sequence with long context may not expose enough parallel work if one block owns the entire KV range. Partition context across blocks. Each block emits partial (m, l, o) state; a second phase merges states with the online-softmax recurrence.
This is analogous to split-K GEMM: more parallelism in exchange for a partial-result reduction. It helps long contexts and small batches, then loses when batch already supplies enough blocks.
GQA and MQA mapping¶
With grouped-query attention, several query heads read one KV head. Map those query heads close enough to reuse K/V cache lines or shared tiles. Excessive sharing can increase live output accumulators. The kernel chooses between reloading K/V for simpler ownership and retaining K/V while processing multiple query heads.
KV-cache quantization¶
Quantized K/V reduces stored bytes and potential read traffic, leaving room for more context or requests in a fixed memory budget. The kernel reads packed values plus scales, dequantizes into compute registers, and accumulates in higher precision. Scale granularity may be per tensor, head, channel, page, or token group.
Finer scales improve fidelity and increase metadata traffic. Dynamic token scales add append-time reduction. K and V can have different sensitivity and therefore different formats.
If the running example quantizes KV to 4 bits with modest scale metadata, theoretical KV read volume drops by roughly 4x before considering dequant instructions and scale loads. The optimization wins only when the unpack path still feeds the score pipeline faster than the FP16 baseline.
Weight-only quantized GEMM¶
For low-batch decode, weight bandwidth dominates many linear layers. A weight-only kernel loads packed weights, dequantizes them, and multiplies by higher-precision activations. The schedule must overlap unpack/dequant with MMA and load scales efficiently.
Compression is useful only if the hardware path processes packed data efficiently. A format can reduce stored bytes and still run slower because unpacking, irregular scales, or unsupported tensor-core instructions dominate.
MoE routing and grouped GEMM¶
Mixture-of-experts layers activate a subset of experts per token. Routing computes top experts, counts tokens per expert, scans counts into offsets, scatters tokens into expert-contiguous buffers, executes grouped GEMM, then scatters outputs back with routing weights.
The pipeline combines top-k, histogram, scan, gather/scatter, and GEMM - the primitives from earlier sections. Fusing every phase is rarely ideal. The important interfaces are compact routing metadata and layouts that let grouped GEMM consume contiguous expert batches.
Hot experts create imbalance. Capacity limits, token dropping, or expert replication change semantics and belong to the model contract, not only the kernel.
Sampling and token cadence¶
The decode iteration often ends with logits processing and sampling. At small batch, several tiny kernels can add visible launch latency. Graph capture and carefully scoped fusion help. Preserve request cancellation, dynamic sampling policies, and RNG mapping.
Design Exercises¶
- How would you fuse RoPE with KV-cache append?
- Explain the page-size tradeoff in paged KV attention.
- When does split-K decode attention help?
- How should a GQA kernel exploit K/V sharing?
- Why can KV quantization increase capacity but reduce speed?
- Walk through an MoE routing kernel pipeline.
Worked Solutions¶
1. RoPE plus append¶
The Q/K projection produces K in a temporary layout. Instead of writing K, rereading it for RoPE, then writing the cache, assign lanes across K pairs, apply the rotation in registers, convert to the cache layout, optionally quantize, and store directly to the physical page. Preserve a separate Q output path, correct position indexing, and the model's pair layout. Fusion loses if it delays a library GEMM epilogue or inflates registers excessively.
2. Page size¶
Small pages reduce internal fragmentation and make branch/copy operations cheaper, but increase block-table size, address translation, and discontinuous loads. Large pages improve contiguous vector access and reduce metadata but waste more memory in partially filled tails and make copy-on-write heavier. Choose from context distribution, kernel transaction efficiency, allocator pressure, and sharing behavior.
3. Split-K decode¶
It helps when batch and head count provide too few blocks while context is long enough to partition. Each block scans a KV range and emits partial softmax/output state; a second phase merges. It costs partial-state memory, another synchronization or launch, and extra arithmetic. It loses at high batch or short context.
4. GQA reuse¶
Map query heads that share one KV head into the same block or nearby warps so a loaded K/V tile serves several queries. Balance that reuse against more output accumulators and registers. Another design processes fewer query heads per block and reloads K/V, trading bandwidth for occupancy. Benchmark by head dimension, group size, context, and batch.
5. Quantized KV slower¶
Capacity grows because stored state is smaller, but latency can worsen if scale loads, address calculations, unpacking, type conversion, or uncoalesced packed layout exceed the bandwidth saved. The kernel may also lose vector width or tensor-core eligibility. Measure total bytes and instruction throughput on the exact decode shapes.
6. MoE pipeline¶
Compute router logits and top experts; form token-expert pairs; count pairs per expert; exclusive-scan counts into expert offsets; scatter token rows into expert-contiguous buffers; execute grouped GEMMs; multiply by routing weights; scatter-add outputs back to token order. Handle capacity, duplicate expert choices, load imbalance, quantization, and multi-GPU all-to-all explicitly.
A page permutation exposes an address bug¶
Let logical tokens 0–3 map through two pages of width two to physical page IDs [7,2]. Their physical addresses are (7,0),(7,1),(2,0),(2,1), not consecutive slots beginning at page 7. For eight query heads and two KV heads, the standard contiguous GQA mapping is kv_head = query_head // 4; substituting modulo alternates heads incorrectly.
A round-trip test should append distinguishable values encoding token, layer, KV head, and channel, then gather in logical order and compare with the dense reference. Add a fork on a partially filled page and cancel one branch. The Python page-pool test covers ownership and copy-on-write; a device implementation must additionally validate address arithmetic, strides, bounds, and synchronization. Plausible output values are insufficient evidence.