By Sagi Shaier · 10 November 2026 · 13 min read
Positional encoding explained
How the sine and cosine formula of the original transformer gives each position its own vector, worked through with numbers and PyTorch code, and how learned position tables compare.
Positional encoding is a vector added to each token's embedding that tells the model where that token sits in the sequence. Transformers need it because self-attention compares tokens by their content and has no built-in sense of which token came first. Models read tokens, which can be whole words or pieces of words, and the examples here use short words as tokens.
Why attention is order-blind
Recurrent neural networks (RNNs) read a sequence one step at a time. Order was built into the computation, since token 2 could only be processed after token 1. Transformers removed that step-by-step chain so all positions can be computed in parallel. The price is that the built-in sense of order went with it.
Self-attention builds each token's new vector by scoring it against the other tokens and blending them by those scores. It treats the token vectors like a set. The sequences the cute axolotl and axolotl cute the hand attention the same three token vectors in a different arrangement. With token content alone, the model can compare words but cannot tell position 0 from position 2. More attention heads give more ways to compare token vectors, and none of them adds a sense of position.

A small example shows it with numbers. Attention scores come from multiplying query vectors with key vectors, and both are made from the token vectors by learned matrices $W_Q$ and $W_K$. The block below uses three 6-feature token vectors and a toy pair of matrices that map each one to 2 features, small enough to read the scores:
1import torch
2
3X = torch.tensor([[1., -1., 2., 0., 1., -2.], # the
4 [0., 2., -1., 1., -3., 1.], # cute
5 [2., 1., 0., -1., 1., 3.]]) # axolotl
6W_Q = torch.tensor([[1., 0.], [0., 1.], [-1., 1.], [2., 0.], [0., -1.], [1., 1.]])
7W_K = torch.tensor([[0., 1.], [1., -1.], [1., 0.], [0., 2.], [-1., 1.], [1., 0.]])
8
9
10def scores(x):
11 return (x @ W_Q) @ (x @ W_K).T
12
13
14print(scores(X))
15print(scores(X.flip(0))) # the same tokens in reverse order1tensor([[ 0., -9., -9.],
2 [ 7., 5., 12.],
3 [ 3., 6., 9.]])
4tensor([[ 9., 6., 3.],
5 [12., 5., 7.],
6 [-9., -9., 0.]])Each score is the match between one pair of tokens, and reversing the tokens only reverses the rows and the columns. The score between the and cute is $-9$ in both orders. Nothing in $QK^\top$ by itself says which row is position 0.
![The cute axolotl at positions 0, 1 and 2 goes through W_Q and W_K to the score matrix [[0, -9, -9], [7, 5, 12], [3, 6, 9]]. Axolotl cute the gives [[9, 6, 3], [12, 5, 7], [-9, -9, 0]], the same pairwise scores rearranged, so QK transpose alone never says which row is position 0.](images/order_blind_scores_permuted.png)
The fix: add a position vector
Each token's vector has to carry two kinds of information: which token it is and where it sits. The token's identity comes from its embedding $e_{token_t}$. The position comes from a second vector $p_t$, and the two are added before attention runs:
$$x_t = e_{token_t} + p_t$$
The position vector has the same number of features as the token vector, $d_{model}$. Because the two are added and not stacked, attention still receives a matrix of shape $(B, T, d_{model})$: $B$ sequences in a batch, $T$ tokens each and $d_{model}$ features per token.

Positional encoding sits outside the attention formula. It prepares the vectors that attention will compare. Token ids become token embeddings, the positional encoding is added, and only then does the sequence enter attention.
![Token ids [4, 7, 9] go through the token embedding lookup, the positional encoding p_t is added and the resulting input vectors X go into multi-head self-attention. Token ids, then token embeddings plus positional encoding, then MHA. Positional encoding prepares the vectors that attention compares and is not inside the softmax formula.](images/position_before_mha_transformer_block.png)
A tokenizer turns text into integer token ids that point into the embedding table. With a tiny made-up tokenizer, the cute axolotl becomes the ids $[4, 7, 9]$. The position ids are separate. They are the places in the sequence, $[0, 1, 2]$, and they are not vocabulary ids. A positional encoding method turns each position id into a vector with $d_{model}$ features, and this post uses $d_{model} = 6$.
![The token ids come from the vocabulary: the is 4, cute is 7 and axolotl is 9, so ids = [4, 7, 9]. The position ids are places in the sequence: the first slot is 0, the second 1 and the third 2, so positions = [0, 1, 2]. Position ids are not vocabulary ids. With T = 3 and d_model = 6, the next step is a method that turns 0, 1 and 2 into 6-feature position vectors.](images/token_ids_vs_position_ids.png)
Sinusoidal positional encoding
The original transformer from 2017 used fixed sine and cosine formulas. There is no learned table. Each position index goes into a formula, and the formula produces a vector with $d_{model}$ features. For the running example, the positions $0$, $1$ and $2$ become three 6-feature vectors $p_0$, $p_1$ and $p_2$. These vectors are fixed, and training updates the rest of the model but not them.

The formula
The features come in pairs. For position $t$ and feature pair $i$, the even feature $2i$ uses sine and the odd feature $2i+1$ uses cosine:
$$PE(t, 2i) = \sin\left(\frac{t}{10000^{2i/d_{model}}}\right)$$
$$PE(t, 2i+1) = \cos\left(\frac{t}{10000^{2i/d_{model}}}\right)$$
$t$ is the position index, $i$ picks a pair of features and $d_{model}$ is the total number of features. The denominator grows with $i$. A larger $i$ divides $t$ by a larger number, so its wave changes more slowly as $t$ goes up. Pair 0 changes fastest and the last pair changes slowest.

One row by hand
Take $d_{model} = 6$ and position $t = 2$. There are three sine and cosine pairs, $i = 0$, $1$ and $2$, with these denominators:
$$10000^{0/6} = 1 \qquad 10000^{2/6} \approx 21.544 \qquad 10000^{4/6} \approx 464.159$$
For $i = 0$ the angle is $2 / 1 = 2$, so the pair is $\sin(2) = 0.909$ and $\cos(2) = -0.416$. For $i = 1$ it is $2 / 21.544 \approx 0.093$, giving $0.093$ and $0.996$. For $i = 2$ it is $2 / 464.159 \approx 0.004$, giving $0.004$ and $1.000$. Together:
$$PE(2) \approx [0.909, -0.416, 0.093, 0.996, 0.004, 1.000]$$
The first pair has already moved a long way from where it started at $t = 0$, which was $[0, 1]$. The last pair has barely moved.
![d_model = 6 and t = 2, three sine and cosine pairs. Feature slots 0 to 5 alternate sin and cos. For i = 0 the denominator is 1 and the values are sin(2) = 0.909 and cos(2) = -0.416. For i = 1 the denominator is 21.544 and the values are 0.093 and 0.996. For i = 2 it is 464.159 and the values are 0.004 and 1.000. PE(2) = [0.909, -0.416, 0.093, 0.996, 0.004, 1.000], and different feature pairs change at different speeds.](images/sinusoidal_row_t2_numbers.png)
Adding the positions to the tokens
The three token vectors of the running example and their sinusoidal position vectors, rounded to two decimals:
$$\begin{aligned} p_0 &= [0.00, 1.00, 0.00, 1.00, 0.00, 1.00] \\ p_1 &= [0.84, 0.54, 0.05, 1.00, 0.00, 1.00] \\ p_2 &= [0.91, -0.42, 0.09, 1.00, 0.00, 1.00] \end{aligned}$$
Adding each token vector to the position vector of its slot gives the input to attention:
$$\begin{aligned} x_{the} &= [1, -1, 2, 0, 1, -2] + p_0 = [1, 0, 2, 1, 1, -1] \\ x_{cute} &= [0, 2, -1, 1, -3, 1] + p_1 = [0.84, 2.54, -0.95, 2, -3, 2] \\ x_{axolotl} &= [2, 1, 0, -1, 1, 3] + p_2 = [2.91, 0.58, 0.09, 0, 1, 4] \end{aligned}$$
The token matrix and the position matrix are both $3 \times 6$, and so is their sum.
![A table of token vectors for the (id 4), cute (id 7) and axolotl (id 9), plus a table of the sinusoidal position vectors p_0, p_1 and p_2, equals the table X with the rows x_the = [1, 0, 2, 1, 1, -1], x_cute = [0.84, 2.54, -0.95, 2, -3, 2] and x_axolotl = [2.91, 0.58, 0.09, 0, 1, 4]. Each is 3 × 6, row by row token vector plus position vector.](images/sinusoidal_positions_added_to_tokens.png)
The scores change
Running the same toy projection on the position-aware vectors gives new queries, new keys and a new score matrix:
$$QK^\top = \begin{bmatrix} 0.00 & 0.00 & 0.00 \\ 26.34 & 46.71 & 50.49 \\ 14.69 & 42.26 & 37.20 \end{bmatrix}$$
Before the positions were added, the scores were $[[0, -9, -9], [7, 5, 12], [3, 6, 9]]$, and every row is different now. In this toy case the query for the happens to come out as all zeros, so its scores are all 0 and it attends evenly to the three positions. The same tokens in different slots now give different vectors, so the scores depend on position.
![Before positional encoding the score matrix is [[0, -9, -9], [7, 5, 12], [3, 6, 9]]. After adding sinusoidal position vectors, the same toy projection with d_k = 2 gives Q = [[0.00, 0.00], [7.79, 6.58], [6.81, 3.67]] and K = [[0.00, 4.00], [6.58, -0.70], [3.67, 3.32]], and QK transpose = [[0.00, 0.00, 0.00], [26.34, 46.71, 50.49], [14.69, 42.26, 37.20]]. Only the input X changed.](images/sinusoidal_positions_change_qk_scores.png)
Why sine and cosine waves help
Sine and cosine give each position its own pattern of values. Fast-changing pairs separate nearby positions, because they move a lot from one position to the next. Slow-changing pairs give a smooth signal that changes little over long distances. Together, the fast and slow features give each position a different combination of values. Attention can then compare token content and see a position signal in the same $d_{model}$ vector.

Shifting a position by a fixed offset $k$ turns each (sine, cosine) pair by the same fixed angle, whatever $t$ was. So one fixed linear map takes $PE(t)$ to $PE(t + k)$ anywhere in the sequence, and a model can learn to read relative offsets instead of only absolute slots. The formula is also defined for any $t$, so the vector for a longer position can always be computed. The model still has to have been trained on sequences that long to use it well.
Sinusoidal encoding in PyTorch
The position vectors are fixed, so they should not be trainable nn.Parameter values. PyTorch stores a fixed tensor that belongs to a module with register_buffer. A buffer moves with the model when it changes device and is saved with the model, but the optimizer does not train it.
1import math
2import torch
3import torch.nn as nn
4
5
6class SinusoidalPositionalEncoding(nn.Module):
7 def __init__(self, d_model, max_len=5000):
8 super().__init__()
9 pe = torch.zeros(max_len, d_model)
10 position = torch.arange(max_len).unsqueeze(1)
11 div_term = torch.exp(
12 torch.arange(0, d_model, 2)
13 * (-math.log(10000.0) / d_model)
14 )
15 pe[:, 0::2] = torch.sin(position * div_term)
16 pe[:, 1::2] = torch.cos(position * div_term)
17 pe = pe.unsqueeze(0)
18 self.register_buffer("pe", pe)
19
20 def forward(self, x):
21 return x + self.pe[:, :x.shape[1]]
22
23
24pos_enc = SinusoidalPositionalEncoding(d_model=6)
25print(pos_enc.pe[0, :3].round(decimals=2))
26print(len(list(pos_enc.parameters())))
27x = torch.zeros(2, 3, 6) # 2 sequences, 3 tokens, 6 features
28print(pos_enc(x).shape)1tensor([[ 0.0000, 1.0000, 0.0000, 1.0000, 0.0000, 1.0000],
2 [ 0.8400, 0.5400, 0.0500, 1.0000, 0.0000, 1.0000],
3 [ 0.9100, -0.4200, 0.0900, 1.0000, 0.0000, 1.0000]])
40
5torch.Size([2, 3, 6])The first three rows match $p_0$, $p_1$ and $p_2$ from above, and the module has no trainable parameters. position holds the indices $t$ with shape (max_len, 1). div_term holds one factor $1/10000^{2i/d_{model}}$ per feature pair, with shape (d_model / 2,). It is written with exp and log because $e^{-2i\ln(10000)/d_{model}}$ equals $1/10000^{2i/d_{model}}$. Multiplying the two broadcasts to a (max_len, d_model / 2) grid with one angle per position and pair. 0::2 selects columns 0, 2 and 4 for sine and 1::2 selects columns 1, 3 and 5 for cosine. unsqueeze(0) adds a batch axis, and forward adds only the first x.shape[1] rows, one per position in the input.
The module also checks the score change from earlier, with scores and X from the first code block:
1X_pos = pos_enc(X.unsqueeze(0))[0]
2print(scores(X_pos).round(decimals=2))1tensor([[ 0.0000, 0.0000, 0.0000],
2 [26.3400, 46.7100, 50.4900],
3 [14.6900, 42.2600, 37.2000]])
Learned position embeddings
A later common variation replaces the formula with a trainable table. Each position index looks up a row in a position embedding table, the same way each token id looks up a row in the token embedding table:
$$E_{token} \in \mathbb{R}^{\text{vocab size} \times d_{model}} \qquad E_{pos} \in \mathbb{R}^{\text{max seq len} \times d_{model}}$$
Both tables start random and training updates them. Suppose training has given position 0 the row $[0, 0, 1, 0, -1, 0]$. The first input vector is then
$$x_0 = E_{token}[4] + E_{pos}[0]$$
$$= [1, -1, 2, 0, 1, -2] + [0, 0, 1, 0, -1, 0] = [1, -1, 3, 0, 0, -2]$$
![Learned positions use a table: the position index looks up a row in a trainable table. E_token has shape vocab size × d_model and E_pos has shape max seq len × d_model. E_token[4] = [1, -1, 2, 0, 1, -2] plus E_pos[0] = [0, 0, 1, 0, -1, 0] gives x_0 = [1, -1, 3, 0, 0, -2], added elementwise with d_model = 6.](images/learned_position_two_tables.png)
The same addition for all three positions, with made-up rows for positions 1 and 2:
$$\begin{aligned} x_0 &= [1, -1, 2, 0, 1, -2] + [0, 0, 1, 0, -1, 0] = [1, -1, 3, 0, 0, -2] \\ x_1 &= [0, 2, -1, 1, -3, 1] + [1, 0, 0, -1, 0, 1] = [1, 2, -1, 0, -3, 2] \\ x_2 &= [2, 1, 0, -1, 1, 3] + [0, 1, -1, 0, 2, 0] = [2, 2, -1, -1, 3, 3] \end{aligned}$$
Attention then receives content and position in the same vector.
![Position 0, token the: [1, -1, 2, 0, 1, -2] + [0, 0, 1, 0, -1, 0] = [1, -1, 3, 0, 0, -2]. Position 1, token cute: [0, 2, -1, 1, -3, 1] + [1, 0, 0, -1, 0, 1] = [1, 2, -1, 0, -3, 2]. Position 2, token axolotl: [2, 1, 0, -1, 1, 3] + [0, 1, -1, 0, 2, 0] = [2, 2, -1, -1, 3, 3].](images/position_addition_running_numbers.png)
In a GPT-style model the token ids and the position ids go through two separate nn.Embedding tables. The position ids are built from the sequence length:
1import torch
2import torch.nn as nn
3
4vocab_size, max_seq_len, d_model = 10, 1024, 6
5tok_emb = nn.Embedding(vocab_size, d_model)
6pos_emb = nn.Embedding(max_seq_len, d_model)
7
8input_ids = torch.tensor([[4, 7, 9]]) # the cute axolotl
9B, T = input_ids.shape
10positions = torch.arange(T, device=input_ids.device)
11tok = tok_emb(input_ids)
12pos = pos_emb(positions)[None, :, :]
13x = tok + pos
14print(tok.shape, pos.shape, x.shape)
15
16try:
17 pos_emb(torch.tensor([1024]))
18except IndexError as err:
19 print("IndexError:", err)1torch.Size([1, 3, 6]) torch.Size([1, 3, 6]) torch.Size([1, 3, 6])
2IndexError: index out of range in selftorch.arange(T) gives the position ids [0, 1, 2]. The [None, :, :] adds a batch axis, so the same position vectors broadcast across every sequence in the batch.
![self.tok_emb = nn.Embedding(vocab_size, d_model) and self.pos_emb = nn.Embedding(max_seq_len, d_model). In forward: B, T = input_ids.shape, positions = torch.arange(T), tok = self.tok_emb(input_ids), pos = self.pos_emb(positions)[None, :, :] and x = tok + pos. input ids have shape B × T, and tok, pos and x have shape B × T × d_model. The None index adds a batch axis so the same position vectors broadcast across every example in the batch.](images/learned_position_code_shapes.png)
The IndexError comes from the fixed size of a learned table. With max_seq_len = 1024 it has rows for positions 0 through 1023, and position 1024 has no row to look up unless the implementation changes the table or uses another position method. A sinusoidal table has no such stopping point, because the formula gives a vector for any position. That only means the vectors exist. A model trained on sequences up to 1024 tokens has never seen what attention does at position 5000 either way, and accuracy usually drops past the training length whichever method is used.

Other position methods
There are several ways to give a transformer order information, and these four come up often:
- Sinusoidal absolute positions. The position index goes through a fixed sine and cosine formula, as above.
- Learned absolute positions. The position index looks up a row of a trainable table.
- Relative position methods. The distance between two positions changes the attention score between them.
- RoPE (rotary position embedding). The position rotates the query and key vectors before the dot product, so position affects the score itself.
All four exist for the same reason: attention alone compares vectors without knowing the order of the sequence.

When to use which, and common mistakes
A transformer that reads text needs some position method, since attention by itself cannot tell the cute axolotl from axolotl cute the. The sinusoidal formula adds no parameters and gives a vector for any position. A learned table is simple to write and lets training pick the vectors, at the cost of a fixed maximum length.
Mistakes that come up often:
- Mixing up token ids and position ids. Token ids index the vocabulary and position ids are
torch.arange(T). Passing token ids to the position table gives each token the position vector of its id. - Storing fixed sinusoidal positions as
nn.Parameter. The optimizer then trains them.register_bufferkeeps them fixed and still saves them with the model. - Adding the whole table.
x + self.pewith 5,000 rows does not match an input of a few tokens, soforwardslicesself.pe[:, :x.shape[1]]first. - Giving the position vector a different size. It is added feature by feature, so it needs $d_{model}$ features like the token vector.
- Going past the table. A learned table with 1,024 rows raises an
IndexErrorat position 1024.
Related concepts
Self-attention is the operation that positional encoding prepares its input for, and multi-head attention runs several self-attention computations side by side, none of which adds order on its own. What are word embeddings covers the token vectors that the position vectors get added to. How transformers work shows where the embeddings and positional encoding sit before the first transformer layer.
QuiddityML teaches positional encoding as its own concept in the Intro to NLP track. The exercises on it include filling in the SinusoidalPositionalEncoding module, spotting the bugs in a token plus position embedding module and typing a reusable TokenAndPositionEmbedding from scratch.