Write triton rope kernel

From wenyi-li/awesome-agent-kernel-skills · View interactive version

Write triton rope kernel is an AI agent skill from the GitHub repository wenyi-li/awesome-agent-kernel-skills. Guide the agent through implementing a correct Triton kernel that applies Rotary Position Embeddings (RoPE) to query and key tensors before attention. This covers the two incompatible layout conventio

How to use this skill

Skill file

Skill: Write a Triton RoPE Kernel

Purpose

Guide the agent through implementing a correct Triton kernel that applies Rotary Position Embeddings (RoPE) to query and key tensors before attention. This covers the two incompatible layout conventions (GPT-NeoX/HuggingFace-LLaMA vs GPT-J/original-paper), pre-computed cos/sin table consumption, per-token position handling for continuous batching, partial-RoPE masking, and the precision discipline required to keep cos/sin in fp32 while applying to fp16/bf16 activations. RoPE is the dominant positional encoding in LLaMA, Mistral, Qwen, Gemma, GPT-NeoX, and most decoder-only LLMs trained after 2022, so getting this kernel right is load-bearing for inference correctness.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Layout convention. Two conventions exist and they are not equivalent:

Picking the wrong layout silently produces broken model output. Confirm by reading the reference model code, not by guessing from the dtype or shape.

  1. Head dimension D. Must be even. If the model uses partial RoPE (rotate only the first rot_dim dimensions, leave D - rot_dim untouched), get rot_dim explicitly.
  2. Number of heads for Q (H_q) and K (H_kv). Often H_kv < H_q for GQA — the kernel must handle both head counts independently (they share the cos/sin table but loop over their own head range).
  3. Cos/sin table dtype. Should be fp32 at table-build time. If the framework hands you fp16 cos/sin tables, flag it — long-position precision loss is a real bug at sequence lengths > 8K.
  4. Q/K dtype. Usually fp16 or bf16. The kernel reads in this dtype, casts to fp32 for the rotation, and stores back in the original dtype.
  5. Position layout. Two cases:
  1. Partial RoPE ratio. Some models (e.g., certain DeepSeek variants) rotate only a fraction of D. If rot_dim < D, the kernel must leave the tail untouched.
  2. In-place vs out-of-place. HuggingFace and most serving stacks apply RoPE in place to save memory. Confirm whether the caller expects Q and K to be overwritten or written to separate output buffers.
  3. Whether Q and K share a launch. A combined kernel applies RoPE to both in one launch (avoids two launches' overhead but slightly complicates pointer arithmetic). Two separate launches is simpler and only marginally slower for typical shapes.

Required reasoning process

  1. Pin down the layout first, then the formula. Write out the rotation in the chosen layout before touching the kernel:
  1. Choose the program decomposition. A typical mapping is one program per (token, head) pair:

```python

grid = (total_tokens, num_heads)

pid_t = tl.program_id(0) # token index in the flat (B*N) layout

pid_h = tl.program_id(1) # head index for this Q or K tensor

```

For continuous batching, total_tokens is the sum of all request lengths, not B * N.

  1. Look up the position for this token. Load pos = tl.load(positions_ptr + pid_t). Do not compute pos = pid_t % seq_len — this is wrong for continuous batching and silently produces incorrect positional information for all tokens after the first request.
  1. Load the cos/sin row for this position. The cos/sin tables have shape [max_seq_len, D/2]. Compute the row pointer:

```python

d_offsets = tl.arange(0, BLOCK_D_HALF) # BLOCK_D_HALF >= D/2

d_mask = d_offsets < (rot_dim // 2) # for partial RoPE

cos_row = tl.load(cos_ptr + pos * (D // 2) + d_offsets, mask=d_mask, other=1.0)

sin_row = tl.load(sin_ptr + pos * (D // 2) + d_offsets, mask=d_mask, other=0.0)

```

other=1.0 for cos and other=0.0 for sin: at masked-out (non-rotated) positions, the rotation reduces to identity, which is what partial RoPE wants.

  1. Load the activation halves (NeoX layout).

```python

x_ptr_base = X + pid_t * stride_token + pid_h * stride_head

x_lo = tl.load(x_ptr_base + d_offsets, mask=d_mask, other=0.0).to(tl.float32)

x_hi = tl.load(x_ptr_base + d_offsets + (D // 2), mask=d_mask, other=0.0).to(tl.float32)

```

Cast to fp32 immediately. The rotation arithmetic must be fp32; doing it in fp16 loses precision at large positions (sin/cos of large angles are tiny).

  1. Apply the rotation in fp32.

```python

out_lo = x_lo * cos_row - x_hi * sin_row

out_hi = x_hi * cos_row + x_lo * sin_row

```

Sign convention: out_lo = x_lo*cos - x_hi*sin. If you write + x_hi*sin instead of - x_hi*sin, you have rotated in the wrong direction — the model will produce nonsense early-token attention but may not crash.

  1. Store results back. Cast to the activation dtype, apply the same boundary mask:

```python

tl.store(out_ptr_base + d_offsets, out_lo.to(x_dtype), mask=d_mask)

tl.store(out_ptr_base + d_offsets + (D // 2), out_hi.to(x_dtype), mask=d_mask)

```

For partial RoPE, the unrotated tail (d_offsets >= rot_dim/2) must either be skipped (in-place: leave as-is, do not store) or copied through (out-of-place: explicit copy load/store).

  1. GPT-J layout variant. Replace step 5 with strided loads:

```python

x_even = tl.load(x_ptr_base + 2 * d_offsets, mask=d_mask, other=0.0).to(tl.float32)

x_odd = tl.load(x_ptr_base + 2 * d_offsets + 1, mask=d_mask, other=0.0).to(tl.float32)

```

And step 6 produces out_even, out_odd stored back at the corresponding strided offsets. The cos/sin table indexing is the same.

  1. Apply to Q and K, not V. RoPE rotates Q and K. V is left untouched. If the kernel takes a single tensor pointer, the launcher calls it once for Q and once for K. If the kernel takes both Q and K pointers and processes them together, ensure V is never passed.
  1. Handle the head-count mismatch for GQA. Q has H_q heads, K has H_kv heads, where often H_kv = H_q / 4 or H_kv = H_q / 8. They share the cos/sin tables (same position, same D). The grid for the Q launch is (total_tokens, H_q); for K it is (total_tokens, H_kv).

Kernel design rules


Correctness requirements


Performance requirements

The agent must reason about:


Output format

The agent should produce:

  1. The Triton kernel function with @triton.jit, taking pointers (X or Q+K, output, cos, sin, positions), strides for each tensor's token/head/dim axes, shape parameters (D, rot_dim, H_q and/or H_kv), and BLOCK_D_HALF: tl.constexpr.
  2. A Python launcher that computes the grid as (total_tokens, H), validates that D is even and that rot_dim <= D, extracts strides, and invokes the kernel separately for Q and K (or jointly, if combined).
  3. An explicit comment naming the layout (NeoX or GPT-J) at the top of the kernel. This single comment prevents 90% of layout-confusion bugs in downstream usage.
  4. A correctness test comparing against transformers.models.llama.modeling_llama.apply_rotary_pos_emb (for NeoX layout) at fp16 with torch.allclose(atol=1e-3). For GPT-J layout, compare against a reference implementation derived from the original RoPE paper.
  5. A continuous-batching test with at least two requests of different lengths and non-zero starting positions, verifying that each token's rotation uses its correct position.
  6. Documentation of any partial-RoPE handling, including which dimensions are rotated and which are passed through.

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.