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 NoneInspect 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)