Add Positional Encoding to a Transformer Language Model
Machine LearningModel answerLast updated
Implement sinusoidal or learned positional encodings in PyTorch, explain the math and tensor shapes, integrate them into a Transformer LM, and diagnose what breaks without them.
Background
A Transformer's self-attention mechanism computes weighted combinations of value vectors using query-key dot products. Nothing in that computation references the order of the input tokens — if you shuffle the sequence, the output is shuffled the same way. For any language task where word order carries meaning, this is a serious problem.
Positional encodings solve it by injecting an order-aware signal into the token embeddings before they enter the attention layers.
Your Task
Part 1 — Implementation
Implement a SinusoidalPositionalEncoding module in PyTorch. Your implementation should:
- Accept a tensor of shape
(B, T, d_model)(batch-first) and return a tensor of the same shape. - Correctly apply the sinusoidal formulas for even and odd embedding dimensions.
- Use a non-trainable buffer so the table moves with the model across devices but is not updated by the optimizer.
- Support an
offsetargument for incremental (KV-cached) decoding.
Also sketch a LearnedPositionalEncoding alternative using nn.Embedding, and note how it differs.
Part 2 — Integration
Show how to wire the positional encoding into a small Transformer language model class. Highlight where in the forward pass it sits, how token embedding scaling interacts with it, and the weight-tying pattern between the embedding table and the output projection.
Part 3 — Diagnosis and Verification
Suppose a colleague removes positional encodings from a trained model. Describe:
- What observable symptoms would appear at inference time, separately for a bidirectional encoder and a causal decoder.
- How you would verify empirically that adding positional encodings back fixes the issue — go beyond "loss went down."
What You Are Expected to Cover
- The sinusoidal equations and the intuition behind them (frequency spectrum, relative-offset linearity).
- Tensor shapes at each step and how broadcasting works.
- The
register_buffervsnn.Parameterdistinction. - The KV-cache offset bug.
- A brief comparison of sinusoidal, learned absolute, and modern relative schemes (RoPE / ALiBi) with trade-offs.
- Concrete, measurable verification strategies.
Hints
Hint 1
Self-attention is permutation-equivariant: write out the attention formula applied to PX (a permuted input) to see exactly why position information cannot emerge from the weights alone.
Hint 2
For the sinusoidal formula, think about what the wavelengths look like across dimension indices. Low-index dimensions oscillate fast; high-index dimensions oscillate slowly — similar to how binary digits change at different rates. Also ask yourself: what property of sin and cos makes relative positions easy to represent?
Hint 3
The KV-cache offset bug is subtle: when decoding token t given a cache of t-1 tokens, the new token must receive positional encoding for index t-1, not index 0. Trace through the forward method with offset=0 vs offset=t-1 to see why the distinction matters.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Why Transformers Need Positional Information
Self-attention computes $\text{softmax}(QK^\top / \sqrt{d_k})V$ where $Q = XW_Q$, $K = XW_K$, $V = XW_V$. For any permutation matrix $P$:
$$\text{Attn}(PX) = P \cdot \text{Attn}(X)$$
The outputs are just a reshuffled version of what you would get on the original sequence. The model has no way to distinguish "cat eats fish" from "fish eats cat." Positional encodings break this symmetry by adding a position-dependent signal before the first attention layer.
The Sinusoidal Equations
For position $pos \in [0, T)$ and dimension pair index $i \in [0, d/2)$:
$$PE_{(pos,,2i)} = \sin!\left(\frac{pos}{10000^{2i/d}}\right), \qquad PE_{(pos,,2i+1)} = \cos!\left(\frac{pos}{10000^{2i/d}}\right)$$
Intuitions worth stating explicitly:
- Each dimension pair forms a 2D rotation at a distinct frequency. Low-index pairs rotate fast (high frequency), high-index pairs rotate slowly — a continuous analogue of a binary counter.
- Wavelengths are spaced geometrically from $2\pi$ to $10000 \cdot 2\pi$, giving a rich, non-repeating code across the typical sequence lengths a model sees.
- Relative offsets are linear transformations. $PE_{pos+k}$ equals a fixed rotation matrix (depending only on $k$, not $pos$) applied to $PE_{pos}$. That means the attention dot product $PE_{pos} \cdot PE_{pos+k}$ depends only on the gap $k$, not on the absolute positions. Relative patterns are therefore easy for the model to learn.
- No parameters, no maximum length at definition time — values are computed for any $pos$.
Tensor shapes:
| Tensor | Shape |
|---|---|
| Token ids | (B, T) |
| Token embeddings | (B, T, d_model) |
| PE table (precomputed) | (max_len, d_model) |
| PE slice used at runtime | (T, d_model) → broadcast to (B, T, d_model) |
PyTorch Implementation
import math
import torch
import torch.nn as nn
class SinusoidalPositionalEncoding(nn.Module):
def __init__(self, d_model: int, max_len: int = 4096, dropout: float = 0.1):
super().__init__()
self.dropout = nn.Dropout(dropout)
# position indices: (max_len, 1)
position = torch.arange(max_len, dtype=torch.float32).unsqueeze(1)
# 1 / 10000^(2i/d), computed in log-space for numerical stability
# shape: (ceil(d_model/2),)
div_term = torch.exp(
torch.arange(0, d_model, 2, dtype=torch.float32)
* (-math.log(10000.0) / d_model)
)
pe = torch.zeros(max_len, d_model)
pe[:, 0::2] = torch.sin(position * div_term) # even dims
pe[:, 1::2] = torch.cos(position * div_term[: d_model // 2]) # odd dims (guards odd d_model)
# register_buffer: persisted in state_dict, moved by .to(device), not trained
self.register_buffer("pe", pe, persistent=False)
def forward(self, x: torch.Tensor, offset: int = 0) -> torch.Tensor:
"""
x : (B, T, d_model)
offset : number of tokens already in the KV cache; critical for
autoregressive decoding — forgetting this encodes every
new token as position 0.
"""
T = x.size(1)
if offset + T > self.pe.size(0):
raise ValueError(
f"Sequence length {offset + T} exceeds max_len {self.pe.size(0)}"
)
# unsqueeze(0) → (1, T, d_model) broadcasts over batch dim
x = x + self.pe[offset : offset + T].unsqueeze(0).to(x.dtype)
return self.dropout(x)
class LearnedPositionalEncoding(nn.Module):
"""One trainable vector per absolute position (GPT-2 / BERT style)."""
def __init__(self, d_model: int, max_len: int = 1024, dropout: float = 0.1):
super().__init__()
self.pos_emb = nn.Embedding(max_len, d_model)
nn.init.normal_(self.pos_emb.weight, std=0.02)
self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor, offset: int = 0) -> torch.Tensor:
T = x.size(1)
pos = torch.arange(offset, offset + T, device=x.device)
return self.dropout(x + self.pos_emb(pos).unsqueeze(0))
Key register_buffer vs nn.Parameter distinction: a buffer travels with the model when you call .to(device) or .cuda() and is saved in checkpoints, but the optimizer never touches it. A parameter is trained. Sinusoidal PE belongs in a buffer; learned PE weights belong as a parameter inside nn.Embedding.
Integrating into a Transformer LM
class TransformerLM(nn.Module):
def __init__(self, vocab_size, d_model=512, n_heads=8, n_layers=6,
max_len=4096, dropout=0.1):
super().__init__()
self.d_model = d_model
self.tok_emb = nn.Embedding(vocab_size, d_model)
self.pos_enc = SinusoidalPositionalEncoding(d_model, max_len, dropout)
layer = nn.TransformerEncoderLayer(
d_model, n_heads, dim_feedforward=4 * d_model, dropout=dropout,
batch_first=True, norm_first=True,
)
self.blocks = nn.TransformerEncoder(layer, n_layers)
self.norm = nn.LayerNorm(d_model)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
self.lm_head.weight = self.tok_emb.weight # weight tying: halves parameters
def forward(self, idx: torch.Tensor, offset: int = 0) -> torch.Tensor:
# Scale embeddings before adding PE so their magnitudes are compatible
x = self.tok_emb(idx) * math.sqrt(self.d_model) # (B, T, d)
x = self.pos_enc(x, offset=offset) # (B, T, d)
T = x.size(1)
causal_mask = nn.Transformer.generate_square_subsequent_mask(
T, device=idx.device
)
x = self.blocks(x, mask=causal_mask, is_causal=True)
return self.lm_head(self.norm(x)) # (B, T, vocab)
The * math.sqrt(d_model) scaling from Vaswani et al. is easy to overlook. Fresh embeddings are initialized with small values; without scaling, the PE (bounded in $[-1, 1]$) can overwhelm them early in training, making the model position-sensitive but semantics-blind.
Symptoms Without Positional Encodings
Bidirectional encoder: becomes a strict bag-of-words model. Any task that depends on token order — syntactic parsing, negation scope, subject-verb agreement — collapses toward chance. You can verify this by constructing contrastive pairs (e.g., "A is larger than B" vs "B is larger than A") and measuring whether the model's outputs are identical after controlling for token frequency.
Causal decoder: the failure is subtler and worth discussing carefully. Causal masking already blocks future tokens, so the model retains some ordering signal through the mask alone. What it loses is the ability to distinguish how far back a previous token is. The next-token distribution flattens for order-sensitive completions (e.g., pronoun resolution, idiom completion). Perplexity may not collapse dramatically, but targeted probing — e.g., a cloze test where the correct answer depends on which of two identical tokens appeared more recently — will reveal the degradation.
Empirical Verification
"Loss went down" is not enough. Concrete checks:
- Permutation invariance test. With positional encodings disabled, feed a sequence and its shuffled version; the output logits should be permuted copies of each other (up to floating-point noise). Re-enable PE and confirm this symmetry breaks.
- Contrastive accuracy. Construct a small dataset of semantically reversed sentence pairs. A model without PE should score ~50%; a model with PE should score significantly above that.
- Probing classifier. Train a linear probe on hidden states to predict absolute token position. Without PE the probe should perform near chance; with PE it should predict position with high accuracy.
- Ablation curve. Train two otherwise identical models — one with, one without PE — and compare perplexity on a held-out set and on the contrastive benchmark above at multiple checkpoints.
Sinusoidal vs. Learned vs. Modern Variants
| Sinusoidal | Learned absolute | RoPE / ALiBi | |
|---|---|---|---|
| Trainable params | 0 | max_len × d | 0 |
Sequences beyond max_len | Defined; extrapolates poorly | Index error | Degrades more gracefully |
| Typical quality | ~Equivalent to learned | ~Equivalent | Better for long-context LMs |
Most production LMs (LLaMA, Mistral, GPT-NeoX) now use RoPE, which encodes position by rotating Q and K vectors inside the attention dot product rather than adding a signal to embeddings. This makes relative position enter the dot product directly and generalizes better to lengths unseen during training.
Common Mistakes
- Forgetting
offsetduring KV-cached decoding. Each incremental token gets encoded as position 0, corrupting all positional information after the first step. - Applying PE after attention instead of before the first layer.
- Registering the PE table as a parameter — it gets fed to the optimizer, wastes compute, and may diverge.
- Omitting the embedding scaling factor, leading to PE dominating the signal early in training.
- Using
batch_first=Falsewith a table sliced forbatch_first=True, causing a silent shape mismatch that broadcasts incorrectly.