Write triton attention kernel

From tensormux/kernel-skills · View interactive version

Write triton attention kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a Flash Attention 2-style fused attention kernel in Triton. This covers the outer loop over KV sequence blocks, online softmax with running max and log-sum-exp tra

How to use this skill

Skill file

Skill: Write a Triton Attention Kernel

Purpose

Guide the agent through implementing a Flash Attention 2-style fused attention kernel in Triton. This covers the outer loop over KV sequence blocks, online softmax with running max and log-sum-exp tracking, numerically stable incremental output accumulation, causal masking, score scaling, output rescaling at the end, and correct stride arithmetic for batch and head dimensions. This is not a tutorial on attention mechanics — it is a decision framework for a correct Triton implementation.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Shapes — batch size B, number of Q heads H_q, number of KV heads H_kv, Q sequence length N_q, KV sequence length N_kv, head dimension D.
  2. dtype — fp16 or bf16 for Q/K/V. Output dtype (usually same as input).
  3. Causal masking — is it required? Is it standard lower-triangular causal, or sliding window / block-diagonal / custom?
  4. Score scaling — is the softmax temperature 1/sqrt(D) or a custom value? Is it folded into Q at call time or applied inside the kernel?
  5. GQA/MQA — if H_kv < H_q, what is the grouping factor H_q // H_kv? K and V strides for the head dimension must reflect this.
  6. Variable sequence lengths — are all sequences in the batch padded to the same length, or do you need a CSR-style variable-length layout?
  7. Output layout — does the output need to be in (B, H, N, D) or (B, N, H, D) order?
  8. Whether logsumexp needs to be saved — required if implementing training and need the backward pass later.

Required reasoning process

  1. Establish the tiling strategy. Each Triton program handles one (query_block, head, batch) tile. The grid is:

```python

grid = (triton.cdiv(N_q, BLOCK_Q), H_q, B)

```

Inside the kernel:

```python

pid_q = tl.program_id(0) # which query block

pid_h = tl.program_id(1) # which Q head

pid_b = tl.program_id(2) # which batch element

```

For GQA, the KV head index is pid_h // (H_q // H_kv).

  1. Compute base pointers. For Q in layout (B, H_q, N_q, D):

```python

Q_ptr = Q + pid_b * stride_qb + pid_h * stride_qh + pid_q * BLOCK_Q * stride_qn

```

For K/V in layout (B, H_kv, N_kv, D), the head index is kv_head = pid_h // group_size.

All strides must be passed as kernel arguments.

  1. Load the query tile.

```python

q_offsets = tl.arange(0, BLOCK_Q)

d_offsets = tl.arange(0, BLOCK_D)

q_mask = (pid_q * BLOCK_Q + q_offsets)[:, None] < N_q

Q_tile = tl.load(Q_ptr + q_offsets[:, None] * stride_qn + d_offsets[None, :], mask=q_mask & (d_offsets[None, :] < D), other=0.0)

```

  1. Initialize the online softmax state.

```python

m_i = tl.full((BLOCK_Q,), float('-inf'), dtype=tl.float32) # running max per query

l_i = tl.zeros((BLOCK_Q,), dtype=tl.float32) # running sum of exp

O_i = tl.zeros((BLOCK_Q, BLOCK_D), dtype=tl.float32) # running output accumulator

```

  1. Loop over KV blocks. For each KV block kv_start in range(0, kv_end, BLOCK_KV):

a. Load K and V tiles.

b. Compute scores. S = tl.dot(Q_tile, tl.trans(K_tile)) * scale. Result shape: (BLOCK_Q, BLOCK_KV). Accumulate in fp32.

c. Apply causal mask (if required). Positions where kv_pos > q_pos are set to -float('inf'):

```python

q_positions = pid_q * BLOCK_Q + tl.arange(0, BLOCK_Q)

kv_positions = kv_start + tl.arange(0, BLOCK_KV)

causal_mask = q_positions[:, None] >= kv_positions[None, :]

S = tl.where(causal_mask, S, float('-inf'))

```

d. Compute the block max. m_block = tl.max(S, axis=1) — shape (BLOCK_Q,).

e. Update running max. m_new = tl.maximum(m_i, m_block).

f. Rescale running output and sum.

```python

alpha = tl.exp(m_i - m_new) # (BLOCK_Q,)

O_i = O_i * alpha[:, None] # rescale accumulated output

l_i = l_i * alpha # rescale accumulated sum

```

g. Compute exp of scores relative to new max.

```python

P = tl.exp(S - m_new[:, None]) # (BLOCK_Q, BLOCK_KV), in fp32

```

h. Accumulate output. O_i += tl.dot(P.to(V_tile.dtype), V_tile). Note: tl.dot requires fp16/bf16 for tensor core dispatch; cast P back to input dtype before the dot.

i. Update running sum. l_i += tl.sum(P, axis=1).

j. Update running max. m_i = m_new.

  1. Normalize the output. After the KV loop: O_final = O_i / l_i[:, None].
  1. Store the output. Apply Q and D boundary masks. Cast to output dtype before storing.
  1. Save logsumexp (if training). lse = m_i + tl.log(l_i) — shape (B, H_q, N_q). Store indexed by batch, head, and query position.
  1. Handle the causal KV loop end condition. For causal attention, only KV blocks with kv_start <= pid_q * BLOCK_Q + BLOCK_Q - 1 are needed. Optimize by bounding the loop to min(kv_start_max, N_kv).

Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through the following:


Output format

The agent should produce:

  1. The Triton kernel function with @triton.jit, taking all Q/K/V/O pointers, all strides (stride_qb, stride_qh, stride_qn, stride_qd, and K/V/O equivalents), shape parameters (B, H_q, H_kv, N_q, N_kv, D), scale, causal flag (or static constexpr), BLOCK_Q, BLOCK_KV, BLOCK_D as constexpr.
  2. The Python launcher that sets up the grid (cdiv(N_q, BLOCK_Q), H_q, B), validates shapes, and calls the kernel.
  3. An inline comment for the online softmax state update explaining why O_i *= alpha is applied before accumulating the new block.
  4. A correctness test comparing against torch.nn.functional.scaled_dot_product_attention with torch.allclose(atol=1e-2) for fp16 (attention outputs have accumulated rounding error).
  5. GQA handling documented — either implemented or explicitly noted as out of scope.

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.