3.3 Position Encoding Strategy
Use the same three tokens in two orders, dogs chase cats and cats chase dogs. In an encoder with full self-attention, no positional inputs and no mask, swapping dogs and cats swaps their output vectors. The middle word chase gets exactly the same output in both sentences. That is a problem if the task is to decide who is doing the chasing.
Where does order enter?
An RNN changes state after each word, so the second word already sees the first. A convolution assigns separate weights to the left, middle and right positions of its filter. Unmasked self-attention uses the same query, key and value projections at every position. Reordering the rows reorders the pairwise scores and values together. This property is called permutation equivariance. A causal mask changes the argument because the set of earlier tokens that each position can read depends on its index.
The original Transformer added a position vector to each token embedding before the first encoder or decoder layer. Put dogs at position 0 in one sentence and at position 2 in another, and its input vector changes even though its token embedding stays the same. [1]
One clock per dimension pair
Let be a zero-based position and the embedding width. Each pair index supplies two coordinates, and , with the same angular frequency in radians per position. For even , the pairs run from through . [1]
At position zero, every complete pair is . Move one position to the right with . Pair 0 turns by one radian and becomes approximately . Pair 8, in dimensions 16 and 17, turns by only radians and becomes . A single shift changes the fast pair visibly while the slow pair hardly moves.
Example: The Encoding Matrix
Each row is one position. Each pair of adjacent columns uses sine on the left and cosine on the right. Start at position 1 and switch the frequency pair from 0 to 8. Then set the position to 0 and predict which values will be identical across all 16 pairs. With JavaScript enabled, both controls work with the arrow keys.
Angle 1.000000 radians
Dimension 0 · sin 0.841471
Dimension 1 · cos 0.540302
Moving a fixed number of positions
Can we compute a pair at position from the same pair at ? The sine and cosine addition formulas give the following matrix for an offset .
Once and the frequency pair are chosen, the matrix stays the same for every starting position. This was one reason the Transformer authors tried sine and cosine features. Their translation experiments found similar results for learned and sinusoidal position embeddings. The formula alone cannot predict how well a trained model will use a longer context. [1]
Where four approaches change the computation
| Method | What changes in the model? | What happens at a new position or distance? |
|---|---|---|
| Absolute position | Add a learned table row or a fixed sinusoidal vector to the token embedding. | A learned table needs a row for the index. A sinusoid is defined at any index, though an implementation can cache only a finite table. [1] |
| Relative representations | Add learned representations of token displacement to the key and optionally the value. | In Shaw et al., offsets outside the clipping distance share their outermost learned representation. [3] |
| Rotary position embedding (RoPE) | Rotate projected query and key pairs before taking their dot product. | Their relative rotation depends on the signed offset. [2] |
| Attention with Linear Biases (ALiBi) | Apply a head-specific distance penalty to the attention score. | The causal distance penalty continues linearly over longer ranges. The final weight also depends on token content. [4] |
What a rotary attention score measures
Consider one query pair at position and one key pair at position . Write for a rotation by , where is this pair’s angular frequency. RoPE rotates both vectors. The two rotations combine inside the dot product. [2]
Move the query and key together from positions to while holding their content vectors fixed. Both scores now use , so they are equal. Change the key vector and the scores can differ even at the same separation. In a longer deployment, test retrieval or answer quality at the target length and at several evidence positions before extending the serving limit.
When one position apart becomes zero or two
Feed two tokens, red cat, into SmolLM2-135M. How much attention does “cat” give “red” in layer 0, head 0? Assign both tokens higher position IDs without adding any prefix tokens. The prompt, the causal mask and the two visible keys stay the same. [5]
With integer IDs the measured weight stays near 33.814% as the pair moves. Now round the position IDs through BF16 before computing the rotations, then convert them back to integers. BF16 represents both 255 and 256 exactly. Between 256 and 512 the representable integers are spaced two apart. The halfway value 257 rounds to 256. Converting it back to an integer cannot recover the missing position.
| Position path | Two IDs | Weight |
|---|---|---|
| Integer IDs | 256, 257 | 33.814% |
| Via BF16 | 256, 256 | 29.034% |
Move the start from 255 to 256 and then 257. The rounded pairs are [255, 256], [256, 256] and [256, 258]. Their gaps are one, zero and two positions. The measured weights are 33.814%, 29.034% and 37.178%. The weights of the model and its rotary calculation stay in FP32 in both runs. The experiment deliberately introduces the early cast to isolate its effect. A real Transformers fix addressed a related failure in which autocast lowered the precision of the matrix product used to compute rotary angles. [6]
When porting a serving implementation, shift the position IDs of a fixed two-token prompt with the same mask. If the result changes substantially, record the IDs just before rotation and the dtype of the angle calculation. Long-document retrieval needs a separate evaluation. The chart uses CPU measurements from 2026-11-25 with PyTorch 2.15.0 and Transformers 5.24.1. CPU experiment (Python) · Measurements at 17 offsets (JSON)
PyTorch Implementation
This CPU example adds a cached position table to floating-point embeddings shaped for batch size , sequence length and width . The first token in every row has position 0. For an odd width, the example keeps the final unpaired sine coordinate. The relative-shift identity above applies to complete pairs. Batched decoding with different cache offsets would need explicit per-request positions.
import math
import torch
from torch import nn
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
if d_model < 1 or max_len < 1:
raise ValueError("d_model and max_len must be positive")
position = torch.arange(max_len, dtype=torch.float32)[:, None]
even = torch.arange(0, d_model, 2, dtype=torch.float32)
angle = position * torch.exp(-math.log(10000.0) * even / d_model)
table = torch.zeros(max_len, d_model)
table[:, 0::2] = angle.sin()
# An odd width has one fewer cosine column.
table[:, 1::2] = angle[:, :d_model // 2].cos()
self.register_buffer("pe", table.unsqueeze(0))
def forward(self, x):
if x.ndim != 3 or x.size(2) != self.pe.size(2):
raise ValueError("expected [batch, positions, d_model]")
if x.size(1) > self.pe.size(1):
raise ValueError("sequence exceeds max_len")
return x + self.pe[:, :x.size(1)].to(dtype=x.dtype)
encoder = PositionalEncoding(32, max_len=20)
y = encoder(torch.zeros(2, 20, 32))
torch.testing.assert_close(y[0, 1, :2], torch.tensor([0.841471, 0.540302]))
torch.testing.assert_close(y[0, 1, 16:18], torch.tensor([0.00999983, 0.999950]))
odd = PositionalEncoding(3, max_len=2)(torch.zeros(1, 2, 3))
torch.testing.assert_close(odd[0, 0], torch.tensor([0., 1., 0.]))
The checks reproduce the two pairs from the diagram and exercise an odd-width input. Try increasing above 20 with this instance. The formula still exists, but this module’s saved table has no row for the next token.
Quizzes
Quiz 1: Why does the output for chase stay the same when the two nouns swap in the opening example?
The middle query is unchanged. The keys and values swap together, so the same values receive the same weights in the weighted sum. A position-dependent input or mask can change that result.
Quiz 2: At position zero, what values do dimensions 30 and 31 have?
They form pair 15. Its angle is zero regardless of frequency, giving sin(0) = 0 and cos(0) = 1.
Quiz 3: Why does a one-position move change dimensions 16 and 17 less than dimensions 0 and 1 in the example?
Pair 8 turns through 0.01 radians per position, while pair 0 turns through 1 radian per position. Both pairs use unit-amplitude waves.
Quiz 4: Why could a position fail in the CPU example even though the sinusoid is mathematically defined there?
The module precomputes a finite table. Registering it as a buffer saves it with the module and moves it with the module, but it does not extend the table.
Quiz 5: If a query and key stay three tokens apart, when does RoPE preserve their dot product?
For the same frequency schedule and unchanged pre-rotation query and key vectors, the relative rotation is unchanged. New content or a change in earlier hidden states can change the score.
Quiz 6: Two tokens have different integer positions but receive identical rotation angles. Where would you look first?
Inspect the position IDs immediately before rotation and the dtype of the angle calculation. An early BF16 cast maps 256 and 257 to the same value. Compare against a run that preserves the integer IDs with the same tokens, mask and weights.
References
- Vaswani, A., et al. (2017). Attention Is All You Need, §3.5.
- Su, J., et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding.
- Shaw, P., Uszkoreit, J., & Vaswani, A. (2018). Self-Attention with Relative Position Representations.
- Press, O., Smith, N. A., & Lewis, M. (2021). Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation.
- Hugging Face TB. SmolLM2-135M, pinned base checkpoint configuration.
- Hugging Face Transformers. RoPE precision under autocast for Llama and Gemma, PR 29285.