Positional Encoding
Injecting order into an architecture that is otherwise blind to the position of each token.
The previous article showed that the embedding operation maps each token ID to a dense vector. The same token always produces the same vector, regardless of where it appears in the sequence. This is exactly the problem the Tokenization article warned about: the embeddings carry no positional information.
This matters because an architecture that cannot distinguish positions cannot distinguish meanings that depend on order. "The cat chased the dog" and "The dog chased the cat" would produce identical sets of embedding vectors, only in different order — and if the model has no way to see that order, it cannot distinguish the two sentences.
Positional encoding adds a position-specific signal to each token's embedding before the sequence enters the model.
The Permutation Problem
Consider the token sequence after embedding: . A model that processes this sequence using only these vectors cannot tell, for example, whether appeared in the middle or at the beginning. If the model applies the same computation to each position without any positional signal, then swapping two tokens changes only which vectors are present — not how any single vector is processed.
This means the model cannot answer questions that depend on word order: who is the subject of a verb, which adjective modifies which noun, whether a negation appears before or after what it negates. Order is not optional information in language — it is fundamental.
What a Positional Encoding Needs
A suitable positional encoding should satisfy several properties:
- Uniqueness. Each position must have a distinct representation, so the model can tell any two positions apart.
- Bounded values. The positional vectors should not dominate the token embeddings. Values in pair naturally with random-initialised embeddings.
- Consistent across lengths. Position should mean "fifth from the start" whether the sequence has or tokens — not "near the start" in a short sequence nor "near the middle" in a long one.
- Generalisability. Ideally, the model can handle sequences longer at inference time than at training time.
Sinusoidal Positional Encoding
The original Transformer (Vaswani et al., 2017) proposed a fixed, parameter-free encoding using sinusoidal functions at exponentially spaced frequencies. For position and dimension index :
Each pair of dimensions forms a sinusoidal oscillation at a particular frequency. The frequencies span a range of :
- Low-index dimensions (): frequency , period positions. These oscillate rapidly and distinguish neighbouring positions.
- High-index dimensions (): frequency , period positions. These oscillate so slowly they are nearly constant over typical sequence lengths, providing coarse position information.
The clock analogy. Think of multiple clocks running at exponentially different speeds. A fast clock distinguishes individual seconds; a slow clock distinguishes hours. Together they give a unique reading for any moment within a wide range. The sinusoidal encoding uses clocks — one per frequency — and their combined readings uniquely identify each position.
This is a continuous, differentiable analogue of binary counting. In binary, the rightmost bit alternates (highest frequency), and each bit to the left halves that frequency. Sinusoidal PE does the same, but smoothly.
For a small model with , dimension 0 cycles through three full oscillations over 20 positions; dimension 2 completes roughly one half-wave; dimension 4 barely moves. Combined, the sinusoids give each position a fingerprint that no other position shares.
The Relative Position Property
A useful algebraic property of sinusoidal encodings: can be written as a linear function of , for any fixed offset . This means the model can, in principle, learn a linear transformation that shifts a position encoding by steps. A well-trained model may therefore learn to recognise relative positions — "three tokens earlier" — even without explicit relative-position machinery.
Applying Positional Encoding
The positional encoding is added element-wise to the token embedding before the first layer of the model. For position with token ID :
Both vectors have dimension , so the addition is straightforward. The token embedding carries what the token is; the positional encoding carries where it is. Their sum carries both.
The sinusoidal encoding has no trainable parameters. The values are computed once and fixed for all sequences. Gradients flow through the addition during backpropagation and update the token embedding , but the positional encoding itself does not change.
Learned Positional Embeddings
An alternative is to treat positions as a second vocabulary: maintain a table where row is the learned positional vector for position . The combined input is then:
This is exactly what BERT and GPT-2 use. The table is initialised randomly and trained jointly with the rest of the model.
Trade-offs.
| Property | Sinusoidal (fixed) | Learned |
|---|---|---|
| Parameters | None | |
| Generalises beyond | Yes (decays gracefully) | No |
| Fits training distribution | Fixed | Perfectly |
| Interpretability | Analytic formula | Opaque |
Learned positional embeddings often perform comparably or better within the training sequence length, because they can adapt to patterns in the training data. Beyond that length, they may fail unpredictably. Sinusoidal encodings degrade more smoothly outside the training range.
In practice, the difference between the two is usually small for tasks where sequences rarely exceed the training length. GPT-2 uses learned embeddings with ; the original Transformer paper used sinusoidal encodings.
In Code
import torch
import torch.nn as nn
import math
class SinusoidalPositionalEncoding(nn.Module):
def __init__(self, d_model: int, max_len: int = 5000):
super().__init__()
PE = torch.zeros(max_len, d_model)
position = torch.arange(max_len).unsqueeze(1) # (max_len, 1)
div_term = torch.exp(
torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)
) # (d_model/2,)
PE[:, 0::2] = torch.sin(position * div_term) # even dims
PE[:, 1::2] = torch.cos(position * div_term) # odd dims
self.register_buffer("PE", PE) # not a parameter
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: (batch, seq_len, d_model)
return x + self.PE[:x.size(1)] # broadcast over batch dimension
# Sinusoidal encoding (no trainable parameters)
embedding = nn.Embedding(num_embeddings=50257, embedding_dim=64)
pos_encode = SinusoidalPositionalEncoding(d_model=64)
token_ids = torch.tensor([[4285, 641, 389, 1049]]) # (1, 4)
x = pos_encode(embedding(token_ids)) # (1, 4, 64)
print(x.shape) # torch.Size([1, 4, 64])
# Learned positional embeddings (GPT-2 style)
token_emb = nn.Embedding(num_embeddings=50257, embedding_dim=64)
pos_emb = nn.Embedding(num_embeddings=1024, embedding_dim=64)
token_ids = torch.tensor([[4285, 641, 389, 1049]])
positions = torch.arange(4).unsqueeze(0) # [[0, 1, 2, 3]]
x = token_emb(token_ids) + pos_emb(positions) # (1, 4, 64)
# Verify: same token at different positions gets different final vector
print(token_emb(torch.tensor([[389, 389]])).shape) # (1, 2, 64)
same_tok = token_emb(torch.tensor([[389, 389]]))
print(torch.allclose(same_tok[:, 0], same_tok[:, 1])) # True — same embedding
combined = same_tok + pos_emb(torch.arange(2).unsqueeze(0))
print(torch.allclose(combined[:, 0], combined[:, 1])) # False — different after PE
Each token in the sequence now carries two kinds of information: what it is, from the embedding table, and where it is, from the positional encoding. With this position-aware input in place, the next question is how the model should combine information across positions. A token at position might be most relevant to the token at position , barely relevant to position , and irrelevant to position . The mechanism that learns these relevance scores is the attention mechanism.