Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Positional Embeddings in Transformers

Recommended resources

Introduction

In our previous lesson on multi-head attention, we established that the self-attention mechanism is inherently permutation-invariant. It treats its input as an unordered set of vectors, meaning that a sentence like "The dog chased the cat" is indistinguishable from "The cat chased the dog" if we only consider the token embeddings. This is a fundamental limitation, as sequence order is critical for understanding everything from language to visual scenes.

This lesson will address that exact problem. Our goal is to explain the necessity of incorporating positional information into the Transformer architecture and to explore one of the primary mechanisms for doing so: learned positional embeddings. We will investigate how these embeddings are defined, integrated into the model, and what they learn during training. While other methods exist, such as the sinusoidal functions proposed in the original Transformer paper, we will focus on the learned approach, as it is conceptually straightforward and widely used in influential models you're interested in, including BERT, GPT, and the Vision Transformer (ViT).


The Problem of Permutation Invariance

The self-attention mechanism at the heart of the Transformer computes the relationships between all pairs of tokens in a sequence. As we saw, the output for each token is a weighted sum of the value vectors of all other tokens. The weights (attention scores) are calculated based on query-key similarities. Critically, these calculations do not depend on the absolute or relative positions of the tokens, only on their vector representations.

This means if you shuffle the input tokens, the set of output vectors from the attention layer will be identical—only their order will be shuffled. This property is known as permutation invariance. Your background in computer vision provides a useful contrast: Convolutional Neural Networks (CNNs) have a strong inductive bias for spatial locality. A convolutional filter always operates on a local, contiguous patch of an image, making its computations inherently sensitive to the spatial arrangement of pixels. Transformers lack this built-in spatial or sequential bias and must be explicitly provided with information about token order.

To see a clear explanation of this issue and why simple solutions like using raw indices fail, please watch the beginning of the following video.

Positional Encoding in Transformer | Sinusoidal Positional Encoding Explained

This video from ExplainingAI provides a concise and clear motivation for why positional information is essential in Transformers.

Watch from the beginning until the explanation of permutation invariance to solidify your understanding of the core problem. Continue watching the next segment on why naive approaches fail, which discusses the drawbacks of using raw or normalized indices.


Learned Positional Embeddings: The Mechanism

Instead of hand-crafting a function to encode position, a powerful and simple alternative is to let the model learn the positional representations from data. This approach aligns with the general philosophy of deep learning: provide the model with learnable parameters and let gradient descent discover the optimal representations for the task.

The mechanism is directly analogous to token embeddings:

  1. We define a position embedding table, which is a trainable matrix of size , where is the maximum sequence length the model can handle and is the embedding dimension.
  2. Each row in this matrix, , is a vector that will learn to represent the absolute position .
  3. This matrix is initialized with random values and its parameters are updated along with the rest of the model during training.

This concept is explained elegantly in the following article, which treats positional embeddings as first-class, learnable parameters.

Learned Position Embeddings: Training Transformers to ...

This article by Malte Brenndörfer provides an excellent conceptual and mathematical breakdown of learned positional embeddings.

Please read the section titled The Position Embedding Table. Focus on the definition of the table and the mathematical formulation, which treats it as a simple lookup operation, identical to how token embeddings are retrieved.


Integrating Positional Information

Once we have a token embedding and a positional embedding , we need to combine them to create a single input vector for the first Transformer layer. The standard approach is simple element-wise addition:

The resulting vector now contains information about both the token's identity and its position in the sequence. All subsequent layers of the Transformer will operate on this combined representation.

You might wonder why addition is used instead of concatenation. Concatenating [e_i, p_i] would keep the two sources of information separate but would double the embedding dimension, significantly increasing the parameter count and computational cost in every subsequent layer. Addition is more parameter-efficient and forces the token and positional embeddings to learn to coexist in the same vector space.

The following video discusses this trade-off between adding and concatenating embeddings.

Adding vs. concatenating positional embeddings & Learned positional encodings

This video from AI Coffee Break with Letitia delves into the practical considerations of combining word and positional embeddings.

Watch the segment from the start of the video which compares the pros and cons of adding versus concatenating positional embeddings.

The choice of addition has a direct mathematical consequence on the self-attention calculation. When we compute the dot product between a query from position i and a key from position j, it decomposes into four terms:

This decomposition shows that the attention score is influenced by pure content interaction, pure positional interaction, and the interaction between the content of one token and the position of another. The model can use all four signals to determine attention weights.


What Do Positional Embeddings Learn?

Since positional embeddings start as random noise, what structure emerges during training? Through backpropagation, the model updates the position vectors to encode whatever positional patterns help minimize the loss.

Empirical analysis of trained models reveals fascinating regularities:

  • Smoothness and Proximity: Nearby positions tend to learn very similar embedding vectors. The similarity (e.g., cosine similarity) between and typically decreases as the distance increases. This makes intuitive sense—the role of a token at position 5 is more similar to that of a token at position 6 than at position 50.
  • Periodicity: In some models, especially autoregressive ones like GPT, periodic patterns emerge. This suggests the model may be learning something akin to the frequency-based structure of sinusoidal encodings, but tailored to the data.

The "Learned Position Embeddings" article provides excellent visualizations that contrast the random initialization with the structured patterns that emerge after training.

Learned Position Embeddings: Training Transformers to ...

This reading will help you visualize the structure that the model discovers during training.

First, read the section How Position Embeddings Learn and examine the accompanying heatmaps that show the difference between random and simulated trained embeddings. Next, read the section Position Similarity Analysis to see how cosine similarity can be used to analyze the learned structure and how it typically decays with distance.


Application in Vision Transformers (ViT)

The concept of learned positional embeddings translates directly to the vision domain and is a cornerstone of the Vision Transformer (ViT). Instead of a sequence of words, a ViT processes a sequence of flattened image patches.

The architecture of a Vision Transformer (ViT). An image is divided into patches, which are linearly projected into embeddings. A learnable position embedding is added to each patch embedding before the sequence is fed to the Transformer Encoder.

As shown in the diagram above, each image patch is projected into a vector. To provide the model with spatial information, a unique, learnable positional embedding is added to each patch embedding. For a 3x3 grid of patches, there would be 9 distinct positional embeddings, one for each spatial location. This allows the self-attention mechanism to learn spatial relationships between patches, such as "the patch above" or "the patch in the corner."


The Constraint of Maximum Sequence Length

A key trade-off with learned positional embeddings is their inflexibility regarding sequence length. Because the embedding table has a fixed size , the model cannot process sequences longer than this out-of-the-box. There is simply no embedding defined for position or beyond.

This contrasts with sinusoidal encodings, which can be generated for any position pos using a mathematical formula. The fixed length of learned embeddings is a fundamental design constraint. If you need to process sequences longer than what the model was trained for, you must resort to techniques like:

  • Truncation: Simply cutting off the sequence at .
  • Fine-tuning: Extending the position embedding table with new random vectors and fine-tuning the model on longer sequences.
  • Position Interpolation: "Stretching" the existing learned embeddings to fit a longer context by interpolating between them.

Learned Position Embeddings: Training Transformers to ...

This final reading explores the practical implications of the fixed-length nature of learned position embeddings.

Please read the section The Maximum Sequence Length Constraint. This part clearly explains the fundamental limitation and the design choices it imposes.


Conclusion

In this lesson, we have explored why positional information is not just beneficial but essential for Transformer models, and we have delved into the mechanics of learned positional embeddings.

Here are the key takeaways:

  • The self-attention mechanism is permutation-invariant, making it blind to sequence order unless explicitly provided with positional information.
  • Learned positional embeddings are a simple and effective solution, where a unique, trainable vector is learned for each position up to a maximum length.
  • These embeddings are typically added element-wise to the token (or image patch) embeddings before the first Transformer layer.
  • Through training, these initially random vectors learn a smooth structure where nearby positions have similar representations, allowing the model to reason about relative positions.
  • A major limitation is the fixed maximum sequence length, which requires special techniques to handle longer inputs during inference.

Now that we understand how to create position-aware input representations and how the multi-head attention mechanism processes them, we are ready to assemble a full Transformer block. In the next lesson, we will examine the two remaining crucial components: residual connections and layer normalization, which are vital for enabling the deep stacking of these blocks and ensuring stable training.