RoPE Implementation
PremiumInverse frequency computation, cos/sin caching, and a vectorized apply_rotary_pos_emb
Get code accessInverse Frequency Precomputation
The previous chapter reduced RoPE to "rotate each two-dimensional subspace." Turning that sentence into code means three concrete steps: work out how fast each subspace rotates, multiply that rate by the position to get an angle, then turn the angle into / tensors you can multiply directly.
The first step is easy to wave through as a one-line formula, but it is what governs the model's extrapolation behaviour. Recall the formula:
Note that this is an exponentially decaying sequence: at , and the pair spins fastest, covering a full radian per position; by , is down around and needs tens of thousands of positions to complete one turn. Low dimensions resolve neighbouring tokens, high dimensions encode long-range distance — and that division of labour is exactly what every length-extrapolation method (NTK-aware, YaRN) reaches in and modifies.
In code we usually compute inverse frequency (which is itself):
# Step 1: compute inverse frequency
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
# inv_freq shape: (dim // 2,)
# inv_freq[0] = 1.0, inv_freq[1] ≈ 0.85, ..., inv_freq[-1] ≈ 0.00011
# Step 2: build position-frequency matrix
t = torch.arange(max_seq_len).float()
freqs = torch.outer(t, inv_freq) # (max_seq_len, dim // 2)
# freqs[m, i] = m * theta_iWhat does torch.outer do?
# Assume max_seq_len = 4, dim = 6 (3 pairs)
t = [0, 1, 2, 3]
inv_freq = [θ₀, θ₁, θ₂]
# outer product:
# freqs[m, i] = m * θᵢ
freqs = [[0·θ₀, 0·θ₁, 0·θ₂], # position 0: no rotation
[1·θ₀, 1·θ₁, 1·θ₂], # position 1
[2·θ₀, 2·θ₁, 2·θ₂], # position 2
[3·θ₀, 3·θ₁, 3·θ₂]] # position 3With freqs, take cos/sin for each position :
Log in to continue reading
This is premium content. Please log in to access the full article.