Positional Encodings
Imagine feeding a sentence into a model that treats every word as if it floated in an unordered bag. "The dog bit the man" and "The man bit the dog" would look identical to such a model. This happens because Self-Attention Mechanism computes weighted sums over a set of tokens, not a sequence. This is not a hypothetical concern. It is the literal mathematical fact that self-attention, as a function of its inputs, is permutation-equivariant. Without extra machinery, a Transformer has no built-in sense of "first," "second," or "adjacent." Positional encodings solve this problem by injecting information about token order directly into the input representations. This happens before attention ever runs. The idea is deceptively simple: add (or otherwise combine) a vector that depends on position with the vector that depends on content. The resulting representation then encodes both "what" and "where." This single design choice is what allows Transformers to replace recurrent networks entirely. It still models word order, syntax, and long-range structure. This article explains two dominant families of positional encoding. These are fixed sinusoidal functions and learned position embeddings. It also covers the mathematical reasoning for why sinusoids have elegant algebraic properties. These properties make relative positions easy for attention to exploit. We derive the formulas and trace a worked numeric example. We also examine the tradeoffs that have driven newer variants. These include relative and rotary encodings used in modern large language models. By the end, you should be able to implement either scheme from scratch. You should be able to explain why plain self-attention needs help with order at all. You should also be able to reason about the complexity and generalization tradeoffs. These tradeoffs determine which encoding a real system should choose.
- Self-attention alone is permutation-equivariant, so Transformers need an explicit signal for token order.
- Positional encodings are vectors added to token embeddings, one per sequence position.
- Sinusoidal encodings use fixed sine/cosine functions at geometrically spaced frequencies — no learned parameters.
- A key algebraic property: the sinusoidal encoding at position is a linear function of the encoding at , letting attention learn relative offsets.
- Learned encodings are trainable embedding tables per position — flexible, but limited to sequence lengths seen in training.
- Modern LLMs largely use variants like RoPE or ALiBi, which bake relative position directly into the attention computation.
Positional encodings turn order-blind self-attention into an order-aware mechanism by adding a position-dependent vector to each token's embedding before the first attention layer.
The idea
A Transformer layer computes attention scores from dot products between query and key vectors derived from token embeddings. If you permute the input tokens and permute the output labels correspondingly, the attention mechanism's output is permuted the same way — it does not "notice" that anything changed. Formally, self-attention is a permutation-equivariant function: for any permutation matrix . This equivariance is a direct consequence of the same weight matrices being applied identically at every position, with no notion of position built into the computation itself. A positional encoding is a vector associated with each sequence index , that is combined with the token embedding — almost always by addition — to form the actual input to the Transformer:
Because differs across positions, the combined vector breaks the symmetry that made pure token embeddings permutation-invariant. Attention now operates on vectors that encode both content and location, and the model can, in principle, learn to attend differently to "the third token" versus "the tenth token," or to prefer nearby tokens over distant ones. There are two broad design families. Sinusoidal (fixed, non-learned) encodings, introduced in the original Transformer paper, define using sine and cosine functions of geometrically increasing wavelengths — no parameters are trained for this piece at all. Learned (absolute) positional embeddings instead treat as a row of a trainable embedding matrix, exactly analogous to a word embedding table but indexed by position instead of vocabulary id. A third, increasingly dominant family — relative positional schemes such as RoPE (Rotary Position Embedding) and ALiBi — abandon the "absolute position vector added at the input" pattern entirely and instead inject position information directly into the attention score computation, which foreshadows design choices used throughout the Transformer Encoder Stack.
How it works
Sinusoidal encoding. For a model dimension (even), position , and dimension index , define:
Each pair of dimensions oscillates at its own frequency . Low-index pairs ( small) oscillate rapidly (short wavelength), giving fine-grained information about nearby positions; high-index pairs oscillate slowly (long wavelength), giving coarse information that distinguishes far-apart positions. The base is a hyperparameter chosen so that wavelengths range from about up to about , comfortably covering typical sequence lengths.
Learned encoding. Maintain a trainable matrix , where is the maximum sequence length the model supports. Position 's encoding is simply row of this matrix, updated by gradient descent along with every other parameter. Both are added to the token embedding at the bottom of the network, once, before the first attention layer: ``` function build_input_representations(tokens, embedding_table, pos_encoding_fn, d_model):
# tokens: list of token ids, length L
# embedding_table: vocab_size x d_model matrix
# pos_encoding_fn: function(position, d_model) -> vector in R^d_model
# (either the sinusoidal formula or a lookup into a
# learned position-embedding table) L = length(tokens) H = zero_matrix(L, d_model) for p in 0 .. L-1: token_vec = embedding_table[tokens[p]] # content pos_vec = pos_encoding_fn(p, d_model) # position H[p] = token_vec + pos_vec # combine return H
# H is fed as the initial layer input to the Transformer stack ``` ``` function sinusoidal_pe(p, d_model, base=10000): vec = zero_vector(d_model) for i in 0 .. (d_model/2 - 1): freq = 1.0 / (base ** (2i / d_model)) vec[2i] = sin(p freq) vec[2i + 1] = cos(p * freq) return vec ``` Once is built, ordinary self-attention layers proceed unchanged: queries, keys, and values are linear projections of , and attention weights come from scaled dot products. The positional signal now rides inside every query/key dot product, so attention scores implicitly depend on the relative offset between positions — this is the entire mechanism; nothing about the attention formula itself needs to change.
Complexity & correctness
Time and space complexity. Computing sinusoidal encodings for a sequence of length with model dimension takes time and space if materialized, though in practice the values can be precomputed once (they don't depend on the input tokens or on training) and cached or even generated on the fly with extra memory per position beyond the -dimensional output. Learned encodings cost the same to look up, plus parameters that must be stored and trained — an asymptotically small addition compared to the parameters in each attention/feed-forward layer, but a real cost that scales with the maximum supported sequence length. Both schemes add negligible overhead compared to the cost of self-attention itself, so positional encoding is essentially free relative to the rest of the Transformer's computation.
Why sinusoidal encodings let attention recover relative position. The key mathematical property is that can be written as a linear function of for any fixed offset , with coefficients depending only on (not on ). This follows from the angle-addition identities:
For each frequency pair , this is exactly a rotation matrix applied to :
Since this rotation matrix depends only on , a linear projection (such as the query/key projections inside attention) can in principle learn to extract relative-offset information from the difference between two positions' encodings, without ever seeing or explicitly labeled. This is the mathematical justification behind the oft-repeated claim that "sinusoidal encodings let the model generalize to relative positions" — it is not a vague intuition but a concrete linear-algebraic fact about the encoding's structure.
Correctness in the sense of injectivity. For a positional encoding scheme to do its job, it must at minimum assign (near-)distinct vectors to distinct positions within the range the model will see, so that attention can actually distinguish them. Sinusoidal encodings satisfy this as long as the range over which the chosen frequencies avoid aliasing — with frequencies spanning wavelengths from to , positions up to several thousand remain distinguishable in practice, though at very large the lowest frequencies barely change and encodings for very distant positions can become numerically close along those slow dimensions. Learned encodings are trivially injective by construction (distinct rows), but only exist for ; there is no principled way to compute for , which is precisely the extrapolation failure mode discussed below.
Tradeoffs, honestly stated. Sinusoidal encodings need no training and can (in theory) be evaluated at positions beyond those seen during training, giving some extrapolation ability, but empirically Transformers trained on fixed-length sequences still struggle to generalize well to much longer ones, since the attention weights that use these encodings were only ever trained on the shorter-range patterns. Learned encodings are more flexible and often perform as well or better within the trained range, but cannot handle positions past at all, and they add real (if modest) parameter count. Neither purely-additive scheme is perfectly suited to relative reasoning, which is why relative-position and rotary schemes (RoPE, ALiBi, T5's relative bias) have become the default in many current large-scale models — they inject position directly into the attention score as a function of , sidestepping some of the extrapolation weaknesses of absolute encodings while keeping the attention cost unchanged.
Worked example
Let's trace sinusoidal encodings by hand for a tiny model with (so two frequency pairs, ) and base . Frequencies: , and .
| Position | ||||
|---|---|---|---|---|
| 0 | 0.000 | 1.000 | 0.000 | 1.000 |
| 1 | 0.841 | 0.540 | 0.010 | 1.000 |
| 2 | 0.909 | -0.416 | 0.020 | 1.000 |
| 3 | 0.141 | -0.990 | 0.030 | 1.000 |
Observe two things directly in the table. First, dimensions 0–1 (fast frequency, ) change dramatically from position to position — this pair is sensitive to local order, distinguishing token 1 from token 2 sharply. Second, dimensions 2–3 (slow frequency, ) barely move across these four positions — this pair only becomes informative for distinguishing positions that are hundreds apart. Together, the fast and slow pairs give the model a multi-resolution "clock" for position, much like how a digital clock's seconds hand and hour hand jointly encode both fine and coarse time. Now check the rotation identity for offset using dimensions 0–1 at :
Wait — let's compute numerically with , :
This matches and up to rounding — confirming that the encoding at is exactly the rotation-by- image of the encoding at , as the angle-addition math predicted. For contrast, a learned encoding scheme in this toy setup would simply store four independent trainable vectors , initialized randomly (e.g., small Gaussian noise) and updated by backpropagation through the language-modeling loss — no rotation structure is guaranteed, and the model must discover any useful relative-position structure purely from data and gradient descent.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting positional encodings entirely | Self-attention silently "works" (runs without error) even without them | Always verify token order actually affects model output on a sanity-check sentence pair |
| Assuming sinusoidal encodings extrapolate perfectly to long sequences | The formula is defined for any , but attention weights were trained only on shorter ranges | Test explicitly on out-of-training-range lengths; consider relative/rotary schemes for long-context models |
| Using learned embeddings and evaluating past | No row exists for ; frameworks may silently index out of bounds or wrap around | Pad/truncate to , or switch to a scheme with a closed-form formula for arbitrary |
| Concatenating instead of adding without adjusting dimensions | Changes unexpectedly, breaking downstream matrix shapes | Decide add-vs-concatenate deliberately and keep dimensions consistent throughout the stack |
| Using too small a base (e.g., 10) with long sequences | Frequencies repeat too quickly, causing aliasing — distant positions get confusably similar encodings | Choose base large enough that the slowest frequency's wavelength exceeds the maximum expected sequence length |
Pioneers & history
Positional encoding as a formal component of attention-based sequence models was popularized by the "Attention Is All You Need" paper, which proposed sinusoidal encodings specifically so that the model could be trained without recurrence or convolution while still respecting word order.
Origins · 1 minAshish Vaswani and how this was discovered
Where this matters
Every major Transformer-based system depends on some positional encoding scheme to make word order matter. BERT and its descendants use learned absolute position embeddings up to a fixed maximum sequence length. GPT-style autoregressive language models historically used learned positional embeddings as well, while many recent large language models — including LLaMA-family and similar open models — use RoPE, which rotates query and key vectors as a function of position directly inside the attention dot product, giving strong relative-position behavior and better length extrapolation in practice. Encoder-decoder machine translation systems, the original use case for sinusoidal encodings, still rely on the same core insight even as the specific formula has been superseded in many production systems. Understanding positional encodings is a prerequisite for understanding how the full Transformer Encoder Stack processes ordered text, and it connects directly to broader questions in Sequence Modeling about how architectures represent structure without explicit recurrence.
Ask the tutor: How does Rotary Position Embedding mathematically guarantee that attention scores depend only on relative position, and why does that improve length generalization compared to sinusoidal encodings?
Why can't a Transformer just infer word order from the training data without explicit positional encodings?
Without positional encodings, self-attention computes the same set of dot products and weighted sums regardless of how the input tokens are ordered — mathematically, permuting the input tokens permutes the output identically, meaning the function itself is symmetric under reordering. No amount of training data can change this structural fact, because it is a property of the architecture, not something learned from examples. The model would need to memorize positional cues from token identity and co-occurrence alone, which is far weaker and less general than an explicit signal. This is why positional encodings are added as a deliberate architectural component rather than left to emerge from data.
Are sinusoidal and learned positional encodings ever combined or used together?
Yes, some architectures combine ideas from both families, and many production systems that started with one have experimented with hybrids or replaced them with newer relative schemes. It's also common to see sinusoidal encodings used as a fixed initialization for what is otherwise a learned embedding table, letting training fine-tune the values while starting from a structured, non-random point. More commonly today, however, systems choose one dominant approach — often a relative scheme like RoPE — for its extrapolation behavior, rather than mixing absolute sinusoidal and absolute learned encodings within a single model. The choice depends heavily on expected sequence lengths and deployment constraints.
Why do sinusoidal encodings use both sine and cosine rather than sine alone?
Using a paired sine/cosine at each frequency is what gives the rotation-matrix structure described in the correctness argument: the pair transforms linearly under a shift by , which would not hold for sine alone. A lone sine value at a given frequency cannot distinguish, say, position from position shifted by a full period, and it loses the clean linear relationship between and . The cosine component effectively serves as sine's phase-shifted partner, together forming a 2D vector that rotates smoothly and invertibly as position increases, analogous to a point moving around a unit circle.
Does adding positional encodings to token embeddings destroy information, since it mixes two different signals into one vector?
In principle, addition could cause interference if the two signals occupied overlapping "directions" in the embedding space, but in practice high-dimensional vector spaces have enough room for both signals to coexist with limited interference — a phenomenon related to the near-orthogonality of random high-dimensional vectors. The learned projection matrices in subsequent layers can also partially disentangle the combined signal, since gradient descent optimizes the whole pipeline jointly. Empirically, additive positional encoding performs well across many architectures, which is why it became the default, though some models experiment with concatenation to avoid interference at the cost of extra dimensions.
How does Rotary Position Embedding (RoPE) differ fundamentally from sinusoidal encodings?
Sinusoidal encodings add a position-dependent vector to the token embedding at the input, meaning position is baked into the representation before attention runs at all. RoPE instead rotates the query and key vectors themselves, inside every attention layer, by an angle proportional to position, so that the dot product between a rotated query at position and rotated key at position depends only on the relative offset . This makes RoPE inherently a relative-position scheme, applied fresh at every layer rather than once at the input, which tends to generalize better to sequence lengths beyond those seen in training.
Can a model trained with learned positional embeddings be extended to handle longer sequences later?
Not without additional work, because the embedding table simply has no rows defined for positions beyond its trained maximum length. Common workarounds include interpolating existing position embeddings to stretch them across a longer range, or fine-tuning with newly initialized extra rows for the added positions, both of which require additional training rather than working automatically. This limitation is one of the practical reasons relative and rotary schemes have become more popular for large language models expected to handle very long or highly variable-length contexts.
What would happen if positional encodings had identical values for two different positions?
Self-attention would then have no way to distinguish those two positions based on positional information alone, since their combined input representations would differ only in token content, not location. In the extreme case where all positions shared the same encoding, the model would behave close to a bag-of-words model with respect to position, at least for the positional signal component. This is precisely why frequency ranges in sinusoidal encodings, or distinct rows in learned tables, are chosen to keep encodings well-separated across the positions the model is expected to process.