PythiloLesson 2 of 9 · progress kept in this browser

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)
This example uses torch. Run it in the Pythilo app, where these features are available.
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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.