Block KV Paged Attention in vLLM’s NKI Kernel

vLLM stores the KV cache in fixed-size blocks of tokens. Each request owns a list of blocks, recorded in a block table, and blocks can be shared between requests that start with the same prefix. This layout, introduced with PagedAttention, lets memory grow with the number of tokens actually in use, and it is the basis for automatic prefix caching and chunked prefill. An attention kernel for this layout has to read keys and values through the block table instead of from one contiguous buffer.

vLLM’s Neuron backend includes such a kernel, written in the Neuron Kernel Interface (NKI): flash_paged_attention in vllm/attention/ops/nki_flash_attn.py. The code excerpts below come from that file at the linked commit.

Inputs and layout

The kernel signature lists the tensors it works on:

@nki.jit
def flash_paged_attention(
    query,          # (1, n_heads, d, seq_q)
    key,            # (1, n_kv_heads, d, seq_k)
    value,          # (1, n_kv_heads, seq_v, d)
    kv_cache,       # (2, num_blocks, n_kv_heads, block_size, d)
    block_tables,   # (num_active_blocks, )
    mask,           # (seq_q, num_active_blocks * block_size + seq_q)
    softmax_scale=None,
    mixed_precision=True,
    LARGE_TILE_SZ=2048,
    return_debug_tensors=False,
):

Four properties of this interface shape the rest of the kernel:

  • Continuous batching with a batch size of 1. The batch dimension is always 1. The tokens of all requests in a step are concatenated along the sequence dimension, so seq_q is the total number of new tokens in the step.
  • A flat block table. block_tables lists every cache block that any request in the step reads, in one array. It is not a per-request table.
  • A mask that encodes the requests. mask has one row per new token and one column per cached token plus one per new token. A token may attend to a cached position only if that position belongs to the same request. Each request’s prefix-cache hits and chunked-prefill history therefore appear as ordinary cached blocks in this mask.
  • A fused K/V cache. Keys and values share one tensor, with keys at index 0 and values at index 1 of the first dimension.

The kernel launches on a two-dimensional grid of batch and KV head. For grouped-query attention, each program handles one KV head and loops over the query heads that share it:

batch_id = nl.program_id(axis=0)
head_id = nl.program_id(axis=1)
...
q_h_per_k_h = h // k_h

The kernel asserts a head dimension of at most 128, which matches the 128 partitions of the on-chip SBUF memory.

Two passes over the keys

The kernel computes attention in two passes, both feeding the same online-softmax accumulators:

  1. A loop over the cached context, one tile of LARGE_TILE_SZ tokens (2,048 by default) at a time. These tiles use the mask and no causal structure.
  2. One pass over the new tokens of the step, using key and value directly and applying the causal mask.

The first pass looks like this, with the loads and indexing trimmed:

for large_k_tile_idx in nl.sequential_range(0, num_large_k_tile):
    load_kv_tile_from_cache(cur_k_tile, cur_v_tile, kv_cache,
                            block_tables_sbuf, large_k_tile_idx, ...)
    for i in nl.affine_range(n_tile_q):
        cur_mask = nl.load(mask[nl.ds(i * B_P_SIZE, B_P_SIZE),
                                nl.ds(large_k_tile_idx * LARGE_TILE_SZ,
                                      LARGE_TILE_SZ)])
        for i_q_h in nl.affine_range(q_h_per_k_h):
            ...
            _flash_attention_core(q_tile, cur_k_tile, cur_v_tile,
                                  o_buffer[i, i_q_h], l_buffer[i, i_q_h],
                                  m_buffer[i, i_q_h], ...,
                                  tile_mask=cur_mask,
                                  use_causal_mask=False,
                                  initialize=large_k_tile_idx == 0, ...)

The outer loop is a sequential_range because each tile updates the accumulators that the next tile reads. The query tiles and query heads inside it are independent, so they use affine_range, which lets the compiler reorder and overlap them.

The cached context length must be a multiple of LARGE_TILE_SZ, and the number of blocks in a tile must be a power of two. The caller must pad the block table to meet these conditions, and the mask hides the padded positions.

Reading blocks with vectorized DMA

Loading a tile means gathering up to LARGE_TILE_SZ / block_size blocks that can sit anywhere in the cache. The kernel turns this gather into indirect DMA loads that use the block table as the index.

First, load_block_tables copies the block table from HBM into SBUF, reshaped to one row per tile. Then transform_block_tables_for_indirect_load prepares the indices for the loads. It folds the KV head into the block index, because the cache is flattened to three dimensions, and it transposes the table so that the block indices for a tile lie along the 128 SBUF partitions:

if num_head > 1:
    # fuse num_block and num_head dimension
    block_tables_partition = block_tables_partition * num_head + head_id

A single load then fetches one block per partition:

loaded = nl.load(kv_cache[0, block_tables[load_idx, i_p, large_k_tile_idx], i_f])

The DMA engines reach full parallelism when a load spans all 128 partitions. When a tile has fewer than 128 blocks, for example 2,048 tokens in blocks of 32 tokens gives 64 blocks, the kernel splits each block into block_size_tiling_factor smaller pieces so that one load still covers 128 partitions:

if num_blocks_per_large_tile < B_P_SIZE:
    block_size_tiling_factor = B_P_SIZE // num_blocks_per_large_tile
    assert block_size % block_size_tiling_factor == 0
else:
    block_size_tiling_factor = 1
tiled_block_size = block_size // block_size_tiling_factor

This split changes the order in which tokens arrive in SBUF. The tensor engine consumes a tile column by column, so after the split it visits tokens with a stride instead of in sequence. The host-side helper reorder_context_mask transposes the context part of the mask to the same order. The caller must apply it before launching the kernel, or the mask and the keys refer to different tokens.

Keys are loaded with tokens on the partitions and then transposed with nl.transpose, because the Q @ K^T matmul needs the head dimension on the partitions. Values stay in the loaded layout, which already matches the P @ V matmul.

Online softmax

_flash_attention_core processes one 128-token query tile against one key tile with the online softmax of FlashAttention. Each query row keeps three accumulators in SBUF: the running maximum score m_buffer, the log of the running softmax denominator l_buffer, and the unnormalized output o_buffer.

For each key tile, the core computes the scores in 512-column pieces and replaces masked positions with a large negative constant:

qk_res_buf[:, k_i_b_f_slice] = nl.where(
    tile_mask[:, k_i_b_f_slice],
    qk_psum[:, nl.ds(0, B_F_SIZE)],
    -9984.0,
    dtype=acc_type,
)

It then takes the new row maximum, rescales the previous output by exp(m_previous - m_current), computes exp(score - m_current) with a fused activation and row sum, multiplies by V, and adds the result to the output. The log-denominator is updated in log space:

l_exp = nl.add(nl.exp(nl.subtract(l_prev, m_current)), ps)
l_buffer[:, 0] = nl.add(m_current, nl.log(l_exp))

After both passes, the kernel normalizes the output once per query tile:

out = nl.multiply(o_buffer[i, i_q_h],
                  nl.exp(m_buffer[i, i_q_h] - l_buffer[i, i_q_h]),
                  dtype=kernel_dtype)

Because the accumulators carry the full softmax state, the order of the tiles does not change the result. The cached context can come first and the new tokens last.

With mixed_precision=True, the matmuls run in BF16 and the scores, maxima and sums accumulate in FP32.

Skipping work in the causal pass

In the second pass, the new tokens attend to each other causally. The core skips a 512-column piece of the score matrix entirely when every key in it comes after every query in the tile:

if use_causal_mask:
    multiplication_required_selection = (q_tile_idx * B_P_SIZE
                                         >= k_i * B_F_SIZE)

Skipped pieces are filled with the large negative constant without a matmul. For a long prefill this removes up to half of the score computation in the second pass. The mask still handles the diagonal pieces and the boundaries between requests.

Writing the new tokens to the cache

The attention kernel reads the cache but does not write to it. A separate function, reshape_and_cache, writes the keys and values of the new tokens. vLLM gives each new token a slot number in slot_mapping. The block is the slot divided by the block size, and the offset within the block is the remainder:

block_indices = torch.div(slot_mapping, block_size, rounding_mode="floor")
block_offsets = slot_mapping % block_size
head_indices = torch.arange(n_kv_head, device=key.device)

kv_cache.index_put_(
    (torch.tensor([0], device=key.device), block_indices[:, None],
     head_indices[None, :], block_offsets[:, None]), key)

The same call with index 1 writes the values. This function is plain PyTorch, not an NKI kernel.

How serving features map onto the kernel

Prefix caching. When requests share a prefix, the scheduler points their block tables at the same physical blocks. The kernel only sees block indices and a mask, so shared blocks need no special handling.

Chunked prefill. A prompt that is split into chunks reaches the kernel as a sequence of steps. In each step, the chunk’s tokens are the new tokens and the earlier chunks are cached blocks. Decode tokens from other requests can share the same step, since each request is a range of rows and columns in the mask.

Grouped-query attention. The grid runs over KV heads, and each program reuses one loaded key and value tile for all the query heads that share it.

References


If you found this useful, please cite this post using

Senthilkumar Gopal. (Jul 2025). Block KV Paged Attention in vLLM’s NKI Kernel. sengopal.me. https://sengopal.me/posts/block-kv-paged-attention-in-vllms-nki-kernel

or

@article{gopal2025blockkvpagedattention,
  title   = {Block KV Paged Attention in vLLM’s NKI Kernel},
  author  = {Senthilkumar Gopal},
  journal = {sengopal.me},
  year    = {2025},
  month   = {Jul},
  url     = {https://sengopal.me/posts/block-kv-paged-attention-in-vllms-nki-kernel}
}