Write triton kv cache append kernel

From tensormux/kernel-skills · View interactive version

Write triton kv cache append kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a Triton kernel that writes newly computed K and V tensors into a pre-allocated KV cache during LLM inference. This covers two cache layouts (contiguous and paged

How to use this skill

Skill file

Skill: Write a Triton KV Cache Append Kernel

Purpose

Guide the agent through implementing a Triton kernel that writes newly computed K and V tensors into a pre-allocated KV cache during LLM inference. This covers two cache layouts (contiguous and paged / vLLM-style PagedAttention), unified prefill and decode handling via a slot_mapping tensor, GQA/MQA where the cache stores fewer heads than Q, optional fp8/int8 quantized KV cache with scaling, coalesced versus scattered write patterns, and the boundary checks required to avoid corrupting other requests' cache regions. The kernel runs once per layer per forward step; correctness is the dominant concern, throughput is secondary because the data volume per call is small.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Cache layout — contiguous [batch, num_kv_heads, max_seq_len, head_dim], or paged. If paged, which paged layout: [num_blocks, block_size, num_kv_heads, head_dim] (vLLM v1 flash style) or [num_blocks, num_kv_heads, head_dim // x, block_size, x] (older vLLM with vectorized inner dim) or block_v1 dual-stacked [num_blocks, 2, num_kv_heads, block_size, head_dim].
  2. block_size — paged layout only. Typically 16, 32, or 64. Must divide the cache evenly.
  3. num_kv_heads, num_heads, head_dim — confirm GQA grouping. The cache only stores num_kv_heads; the kernel never replicates K to num_heads.
  4. Input dtype and cache dtype — usually identical (fp16 or bf16). If fp8 or int8 KV cache, confirm the scale dtype (fp32) and granularity: per-tensor, per-token, per-head, or per-block.
  5. Batch shape of new K/V — [num_tokens, num_kv_heads, head_dim] where num_tokens is the total number of new tokens across all requests in this step. For decode, num_tokens == batch_size. For prefill, num_tokens is the sum of prompt lengths.
  6. slot_mapping — int64 tensor of shape [num_tokens] giving the destination slot index for each new token. For contiguous layout, this is a flat slot index into [batch * num_kv_heads * max_seq_len] or equivalent. For paged layout, it is the global slot index block_id * block_size + slot_in_block.
  7. block_table — paged layout only. Int32 tensor [batch, max_blocks_per_req] mapping logical block index to physical block ID. Usually consumed in Python to build slot_mapping; confirm whether the kernel takes block_table directly or only slot_mapping.
  8. Quantization scales — required if cache dtype is fp8/int8. Shape, dtype, and indexing convention.
  9. Stride information — strides of the new K/V tensors and the cache tensor. Never assume contiguity, especially for K/V which may come from a transposed projection.

Required reasoning process

  1. Pick the kernel interface. The clean, unified interface is: take new K and V tensors of shape [num_tokens, num_kv_heads, head_dim], a slot_mapping tensor of shape [num_tokens], the cache tensors, and (optional) quantization scales. The Python launcher is responsible for translating block_table + per-request positions into a flat slot_mapping. This makes prefill and decode go through the same kernel.
  1. Choose the grid. One program per (token, kv_head) pair is the simplest and most flexible:

```python

grid = (num_tokens, num_kv_heads)

```

Each program writes one head_dim vector to the cache. For very small head_dim (e.g., 64) and large num_kv_heads, fusing along the head dimension can reduce launch overhead, but the (num_tokens, num_kv_heads) decomposition is what most production kernels use.

  1. Resolve program ids and the destination slot.

```python

token_idx = tl.program_id(0)

head_idx = tl.program_id(1)

slot = tl.load(slot_mapping_ptr + token_idx)

```

If slot < 0, the launcher has marked this token as a no-op (used in CUDA-graph capture with padded batches). Skip the write:

```python

if slot < 0:

return

```

  1. Compute the source pointer for the new K/V vector.

```python

d_offsets = tl.arange(0, BLOCK_D)

d_mask = d_offsets < head_dim

k_src_ptr = k_new_ptr + token_idx * stride_k_token + head_idx * stride_k_head

k_vec = tl.load(k_src_ptr + d_offsets * stride_k_d, mask=d_mask, other=0.0)

```

Same for V. BLOCK_D is the next power of 2 >= head_dim (typically 64, 128, or 256).

  1. Compute the destination pointer based on cache layout.

Contiguous layout [batch, num_kv_heads, max_seq_len, head_dim]. The launcher must encode (req_idx, position) into slot, e.g. slot = req_idx * max_seq_len + position, and the kernel reconstructs:

```python

req_idx = slot // max_seq_len

position = slot % max_seq_len

k_dst = k_cache_ptr

```

Paged layout [num_blocks, block_size, num_kv_heads, head_dim]:

```python

block_id = slot // BLOCK_SIZE # constexpr divisor

slot_in_block = slot % BLOCK_SIZE

k_dst = k_cache_ptr

```

For block_v1 dual-stacked [num_blocks, 2, num_kv_heads, block_size, head_dim], K and V share the same buffer and are selected by an extra index 0 (K) or 1 (V).

  1. Apply quantization if cache dtype is fp8 or int8. For per-tensor scale:

```python

k_q = (k_vec / k_scale).to(cache_dtype) # fp8 or int8

```

For per-token or per-block scale, load the appropriate scalar first. For fp8 with e4m3 or e5m2, use tl.cast(..., tl.float8e4nv) (or the bf16 equivalent), and never quantize before applying the scale — scale division must happen in fp32.

  1. Store the vectors.

```python

tl.store(k_dst + d_offsets * stride_kc_d, k_q, mask=d_mask)

tl.store(v_dst + d_offsets * stride_vc_d, v_q, mask=d_mask)

```

Use the same d_mask as the load. No other masking is required because the program is a no-op when slot < 0 and slot_mapping is otherwise expected to be valid.

  1. Decide K and V kernel sharing. K and V have identical layouts and slot mappings; do them in the same kernel to halve launch overhead. The only divergence is the optional separate scale tensors.
  1. In the launcher, build slot_mapping correctly. This is where most bugs live — see the failure modes section. For paged decode with one new token per request:

```python

# context_lens[req] = number of tokens already in cache (i.e., position of the new token)

logical_block = context_lens // block_size

slot_in_block = context_lens % block_size

block_id = block_table[torch.arange(batch), logical_block]

slot_mapping = block_id * block_size + slot_in_block

```

For prefill, expand per-request positions into per-token slots.


Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through the following:


Output format

The agent should produce:

  1. The Triton kernel with @triton.jit, parameterized by BLOCK_D: tl.constexpr, BLOCK_SIZE: tl.constexpr (paged layout only), all relevant strides, head_dim, and a IS_FP8: tl.constexpr flag (or separate kernels) for quantized variants.
  2. The Python launcher that constructs slot_mapping from block_table and context_lens (or accepts a precomputed slot_mapping), validates K/V shapes, asserts slot_mapping.dtype == torch.int64 (or int32 with documented range), and launches with grid = (num_tokens, num_kv_heads).
  3. A docstring on the launcher stating: cache layout, slot_mapping convention (paged: block_id * BLOCK_SIZE + slot_in_block; contiguous: req * max_seq_len + pos), and the no-op behavior for slot == -1.
  4. A correctness test that:
  1. Optional fp8 variant with a roundtrip-error check after dequantization.
  2. No fused QKV-projection version on the first pass. Note explicitly that fusion is a separate optimization gated on profiling.

Common failure modes


Review checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.