Practice in Lab: Apply rotary positions without losing relative geometry →
Apply rotary positions without losing relative geometry
Rotary positions encode relative offsets through rotations of paired query and key coordinates. Coordinate pairing is part of the model convention: two plausible layouts can disagree while preserving shapes. This Lab specifies adjacent pairs and checks their geometry directly. Each rotation preserves a token vector norm, and adding a common position offset to queries and keys preserves their dot products. Position identities must match the cache offset during incremental decoding; applying a correct rotation with the wrong absolute positions still changes attention.
import torch
x = torch.tensor([1., 0.])
angle = torch.tensor(1.)
pair = torch.stack([angle.cos(), angle.sin()])
print(pair)Review the design
Record frequency base, pair convention, position offsets and any long-context scaling in the model artifact. Shape compatibility alone cannot establish RoPE compatibility.
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.
The explanation opens here once every check passes.