Skip to content
Inference Academy

RoPE and LayerNorm kernels in Triton

Two more memory-bound kernels every inference engine needs. A fused rotary-embedding kernel that rotates Q and K in place in one launch, with grouped-query attention and the half-split convention, and what float32 does to angles at long positions. Then a LayerNorm kernel that keeps each row in registers, and the padding bug that breaks its variance. Both tested against PyTorch in the Triton interpreter.

By

Key takeaways

  • RoPE is elementwise and memory bound: fusing Q and K into one in-place launch moves each value once in and once out.
  • Know the pairing convention. Half-split (NeoX) pairs dimension i with i + d/2; interleaved (GPT-J) pairs 2i with 2i + 1. Mixing them up gives plausible but wrong outputs.
  • At long positions the angle is thousands of radians, so how you compute the frequency changes results in float32. Engines use a precomputed cos and sin table for exactly this reason, and for speed.
  • LayerNorm differs from RMSNorm by a mean and a bias. When the block is wider than the row, the padded lanes must be excluded from the variance.
  • Test against a float32 reference at awkward sizes: odd token counts, non-power-of-two widths, position zero.
25 min · verified 2026-111 animated diagramHands-on labPro
Share

Goal: write and test two kernels that sit in almost every transformer layer: rotary position embedding for Q and K, and LayerNorm. Both are memory bound, so the work is about moving each value once and getting the indexing exactly right.

You need: the Triton programming model and the fused RMSNorm lesson. The code is in the companion repository under gpu_kernels/. Clone it, and on a machine without a GPU run the tests in Triton's interpreter:

bash
git clone https://github.com/maitysandip/inference-academy-code && cd inference-academy-code
pip install torch triton            # Linux; on a Mac or Windows use Colab or WSL
python3 -m unittest tests.test_gpu_kernels -v

Honest limits. We tested every kernel in this pack against PyTorch in the Triton interpreter on a CPU (Triton 3.9, PyTorch 2.15). The interpreter checks indexing and maths, not speed, and it does not exercise GPU-only paths such as tensor-core code generation. Timings in this lesson are bandwidth arithmetic, not measurements; run the benchmark harness on your GPU for real numbers.

#Kernel 1: RoPE for Q and K, in place

Rotary position embedding rotates pairs of dimensions of each query and key by an angle that depends on the token's position pp and the pair's index ii:

θi=p⋅b−2i/d,(x1′x2′)=(cos⁡θi−sin⁡θisin⁡θicos⁡θi)(x1x2)\theta_i = p \cdot b^{-2i/d}, \qquad \begin{pmatrix} x'_1 \\ x'_2 \end{pmatrix} = \begin{pmatrix} \cos\theta_i & -\sin\theta_i \\ \sin\theta_i & \cos\theta_i \end{pmatrix} \begin{pmatrix} x_1 \\ x_2 \end{pmatrix}

where dd is the head dimension and bb is the base (10,000 in the original paper; Llama 3 uses 500,000 with an extra scaling). Which dimensions form a pair is a convention, and models disagree:

  • Half split (GPT-NeoX, Llama in Hugging Face's layout, vLLM's default): dimension ii pairs with i+d/2i + d/2.
  • Interleaved (GPT-J, the original Meta Llama checkpoints): dimension 2i2i pairs with 2i+12i+1.

Mixing them up gives outputs that look plausible and are wrong. The kernel below uses half split.

The design: one program per (token, head). Heads 00 to Hq−1H_q - 1 are query heads, the rest are key heads, so with grouped-query attention (say 32 query heads and 8 KV heads) one launch covers all 40. Each program computes its token's angles, loads the two halves, rotates and stores back in place.

gpu_kernels/rope.py · MIT licensed, on GitHub

python
"""Rotary position embedding (RoPE) for Q and K in one Triton kernel, in place.

Layout: q is [tokens, q_heads, head_dim], k is [tokens, kv_heads, head_dim], positions is [tokens].
Uses the "half split" (GPT-NeoX) convention: dimension i pairs with dimension i + head_dim/2.
One program handles one (token, head) pair; heads 0..q_heads-1 are Q, the rest are K.

Runs on a GPU, or on a CPU with TRITON_INTERPRET=1 set before importing triton.
"""
import torch
import triton
import triton.language as tl


def rope_reference(q, k, positions, base=10000.0):
    """Plain PyTorch, computed in float32. Returns new tensors."""
    d = q.shape[-1]
    inv_freq = base ** (-torch.arange(0, d // 2, dtype=torch.float32, device=q.device) * 2 / d)
    angles = positions.float()[:, None] * inv_freq[None, :]          # [tokens, d/2]
    cos, sin = angles.cos()[:, None, :], angles.sin()[:, None, :]    # broadcast over heads

    def rotate(x):
        x1, x2 = x.float()[..., : d // 2], x.float()[..., d // 2:]
        return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1).to(x.dtype)

    return rotate(q), rotate(k)


@triton.jit
def _rope_kernel(q_ptr, k_ptr, pos_ptr,
                 q_stride_t, q_stride_h, k_stride_t, k_stride_h,
                 n_q_heads, log_base,
                 HALF: tl.constexpr):
    t = tl.program_id(0)                     # token
    h = tl.program_id(1)                     # head: Q heads first, then K heads
    pos = tl.load(pos_ptr + t).to(tl.float32)

    i = tl.arange(0, HALF)
    inv_freq = tl.exp(-(2.0 * i.to(tl.float32) / (2 * HALF)) * log_base)
    angle = pos * inv_freq
    cos, sin = tl.cos(angle), tl.sin(angle)

    if h < n_q_heads:
        base_ptr = q_ptr + t * q_stride_t + h * q_stride_h
    else:
        base_ptr = k_ptr + t * k_stride_t + (h - n_q_heads) * k_stride_h

    x1 = tl.load(base_ptr + i).to(tl.float32)
    x2 = tl.load(base_ptr + HALF + i).to(tl.float32)
    out_dtype = base_ptr.dtype.element_ty
    tl.store(base_ptr + i, (x1 * cos - x2 * sin).to(out_dtype))
    tl.store(base_ptr + HALF + i, (x2 * cos + x1 * sin).to(out_dtype))


def rope_(q, k, positions, base=10000.0):
    """Rotate q and k in place. head_dim must be a power of two (64 and 128 are typical)."""
    tokens, n_q, d = q.shape
    n_kv = k.shape[1]
    assert k.shape[0] == tokens and k.shape[2] == d and d % 2 == 0
    assert (d // 2) & (d // 2 - 1) == 0, "head_dim / 2 must be a power of two"
    assert q.stride(-1) == 1 and k.stride(-1) == 1
    grid = (tokens, n_q + n_kv)
    _rope_kernel[grid](q, k, positions,
                       q.stride(0), q.stride(1), k.stride(0), k.stride(1),
                       n_q, float(torch.log(torch.tensor(base))),
                       HALF=d // 2)
    return q, k
RoPE: rotate by position, compare by angle
Interactive
qk

Distance m − n = 3

Score q·k = -0.2756

Without the shift: -0.2756 (identical)

The query is rotated by its position, the key by its own. Their dot product depends only on the angle between them, so only the distance m − n matters. Shift both positions and the score does not move.

The rest is Pro

Keep reading this full lab

Pro unlocks this full lab, every advanced lesson, the hands-on labs and completion certificates.

One year

$25

365 days, no auto-renewal

Lifetime Best value

$75

pay once, keep it forever

7-day refund, no questions asked. One payment, no auto-renewal.Compare plansHave a licence key?

Sandip MaityBuilt by Sandip Maity, who runs self-hosted LLM inference in production.

Not ready? Keep learning free

Or follow the free roadmap →

Not ready? Take the free 5-day email course

One short email a day for five days, each built on a free lesson, then the occasional new lesson or offer. Unsubscribe in one click.

Still to come in this lab

  1. Kernel 2: LayerNorm
  2. Testing
  3. What you can now do
  4. Common mistakes
  5. Exercise
  6. Going deeper

You will be able to answer

  • Why rotate Q and K in the same kernel launch?
  • Your RoPE kernel matches the reference for head_dim 128 at short positions, but attention quality drops at 30,000 tokens. What is a likely cause?
  • A LayerNorm kernel uses BLOCK = 1024 for rows of width 1000. Its mean is right but its variance is wrong. Why?