REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Apply rotary positions without losing relative geometry

Rotary positions encode relative offsets through rotations of paired query and key coordinates.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Apply rotary positions without losing relative geometry →

Your task

x is [B,H,T,D] with positive even D. positions is long [T], nonnegative. For adjacent coordinate pairs (2i,2i+1), rotate by position*base**(-2i/D). Return a new differentiable tensor in the same shape; do not mutate x. Require finite base>1. Tests check zero positions, norms, a shared offset of query/key positions and input gradients. This is adjacent-pair RoPE, not the split-half convention.

Starter

import torch


def rotary_positions(x, positions, base=10000.0):
    return None
Inspect the worked answer
import math
import torch


def rotary_positions(x, positions, base=10000.0):
    if x.ndim != 4 or x.shape[-1] < 2 or x.shape[-1] % 2:
        raise ValueError('a positive even head width required')
    if positions.ndim != 1 or positions.shape[0] != x.shape[-2] or positions.dtype != torch.long or bool((positions < 0).any()):
        raise ValueError('one nonnegative integer position per token required')
    if not math.isfinite(base) or base <= 1:
        raise ValueError('finite frequency base greater than one required')
    width = x.shape[-1]
    frequency = base ** (-torch.arange(0, width, 2, dtype=x.dtype, device=x.device) / width)
    angle = positions.to(dtype=x.dtype, device=x.device)[:, None] * frequency
    cosine, sine = angle.cos(), angle.sin()
    even, odd = x[..., 0::2], x[..., 1::2]
    pairs = torch.stack((even * cosine - odd * sine, even * sine + odd * cosine), dim=-1)
    return pairs.flatten(-2)

About this algorithm

How Apply rotary positions without losing relative geometry works

The idea

Rotary position embedding (RoPE) tells attention where tokens are by rotating query and key vectors instead of adding a position vector to them. Coordinates are taken in neighbouring pairs (2i, 2i+1). Each pair is treated as a point in a plane and turned by an angle equal to the token's position times a frequency, base ** (-2i / D), so the first pair turns fastest and later pairs more slowly.

The insight is that the dot product of two rotated pairs depends only on the difference between their angles. The attention score between a query at position m and a key at position n therefore depends on m - n, not on the absolute positions. Rotation also leaves every vector's length unchanged.

How it works

  1. Validate that x is [B, H, T, D] with even D, positions is a long [T] tensor with no negatives, and base is finite and above one.
  2. Build one frequency per coordinate pair as base ** (-arange(0, D, 2) / D), in the dtype of x.
  3. Multiply positions[:, None] by frequency to get an angle for every token and pair, then take cosine and sine.
  4. Split x into even and odd coordinates with x[..., 0::2] and x[..., 1::2].
  5. Rotate each pair: even * cosine - odd * sine and even * sine + odd * cosine.
  6. torch.stack the two halves on a new last axis and flatten(-2) to interleave them back into the original shape.

What it costs

Time
O(B·H·T·D)
Angle table
O(T·D/2)
Parameters
none learned

Every coordinate is touched once, and the cosine and sine tables depend only on positions and width, so they can be computed once and reused.

Where it is used

  • Su et al. introduced rotary position embedding in the RoFormer paper (2021).
  • Meta's Llama models apply RoPE to the queries and keys of every attention layer.
  • Mistral 7B uses rotary position embeddings in its attention layers.

Watch out for

  • Pairing coordinate i with i + D/2, the split-half layout some libraries use, when this Lab pairs neighbours (2i, 2i+1); the two layouts are not interchangeable.
  • Rotating in place or returning x itself at position zero: the Lab checks that x is unchanged and that the result has its own storage.
  • Giving the two coordinates of a pair different angles, for example one frequency per coordinate instead of per pair, which is no longer a rotation and changes vector norms.