Skip to main content

Welcome to a Grasp lesson

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

Lesson 13

Understanding Sinusoidal Positional Encodings

Recommended resources

Hello! Welcome to your final lesson in the "Attention Mechanism" module.

Introduction

In our previous lesson, we examined the learnable projection matrices () that empower multi-head attention. We saw how they project input embeddings into specialized subspaces, allowing each head to focus on different types of relationships.

However, the self-attention mechanism, even with these projections, has a fundamental blind spot: it is a set operation. It processes all tokens in parallel and doesn't inherently know their order. For example, to a basic self-attention layer, the sentences "man bites dog" and "dog bites man" look like the same bag of words, despite their meanings being entirely opposite. The model has no concept of "first," "second," or "third."

This lesson addresses that gap. Our learning goal is to describe sinusoidal positional encodings and why position information must be explicitly injected. We will explore:

  1. Why transformers need an external mechanism for positional information.
  2. How sinusoidal functions provide an elegant and effective solution.

Let's begin by solidifying our understanding of the problem.



1. The Problem: Permutation Equivariance

Self-attention is permutation equivariant, meaning if you shuffle the input tokens, the corresponding output embeddings are shuffled in the same way, but their values don't change. This is a problem because sequence order is vital for meaning.

The following short video provides a great visual intuition for why this is a critical issue that needs solving.

How do Transformer Models keep track of the order of words? Positional Encoding

Let's watch this clip from Serrano.Academy to see why word order is so important and how vanilla embeddings fail to capture it.

Watch from 00:23 to 01:24. Notice how two sentences with opposite meanings result in the exact same set of embedding vectors for the model to process.

To solve this, we must "enrich" the input embeddings with information about their position in the sequence.

You could have designed state of the art positional encoding

This Hugging Face blog post formally introduces the problem and outlines the desirable properties for any potential solution. It's a great way to frame our thinking as we design a solution.

Read the sections 'Problem Statement', 'Motivating Example', and 'Desirable Properties'. This will formalize the concept of permutation equivariance and give us a checklist for what a good positional encoding scheme should achieve.

As the resources highlight, we need a method that gives each position a unique, deterministic signal, allows the model to understand relative distances, and ideally generalizes to sequences of any length.



2. The Solution: Sinusoidal Positional Encoding

The original "Attention Is All You Need" paper introduced a clever solution using sine and cosine functions. The core idea is to create a unique vector, the positional encoding (PE), for each position in the sequence. This PE vector is then added to the corresponding token's input embedding.

Building the Intuition

Instead of just adding the position number (e.g., 0, 1, 2...), which could lead to arbitrarily large and unstable values, the authors used periodic functions. Think of it like this: for each position, we generate a vector of values by sampling from a set of sine and cosine waves with different frequencies.

  • The low-frequency waves change slowly, giving a rough sense of position (e.g., beginning vs. end of a sentence).
  • The high-frequency waves change rapidly, providing fine-grained information to differentiate adjacent positions.

This combination of frequencies creates a unique "fingerprint" for each position.

How do Transformer Models keep track of the order of words? Positional Encoding

The following video does an excellent job of building the intuition from the ground up, starting with simple 2D rotations and scaling up to the full, high-dimensional encoding.

Watch from 03:27 to 06:20. This section explains how sine and cosine curves are used and how this concept is extended to higher dimensions by stretching the waves.

The Formulas

This intuition is captured by the following formulas for a positional encoding vector of dimension at position :

For even-indexed dimensions ():

For odd-indexed dimensions ():

Let's break this down:

  • pos: The position of the token in the sequence (0, 1, 2, ...).
  • i: The dimension index within the encoding vector (0, 1, 2, ... up to ).
  • d_model: The dimension of the embeddings (e.g., 512).
  • 10000: A large constant chosen to create a wide range of frequencies, from very high () to very low ()).

The result is a matrix where each row is a unique positional vector for a specific position in the sequence.

Heatmap of Sinusoidal Positional Encodings
A heatmap visualizing sinusoidal positional encodings. Each row corresponds to a position in the sequence, and each column to a dimension in the encoding. The oscillating patterns create a unique vector for every position.


3. Why Sinusoidal Encoding Works: The Power of Relative Position

We've established what sinusoidal encodings are, but why this specific formulation with paired sine and cosine functions? The answer lies in a key property: it makes it incredibly easy for the model to learn relative positions.

The attention score between two tokens at positions and depends on the dot product of their Query and Key vectors. The authors of the original Transformer paper chose this sine/cosine formulation because the positional encoding for pos + k can be expressed as a linear transformation of the encoding for pos.

This means the relationship between any two positions is consistent, regardless of where they are in the sequence. The "distance" from position 5 to 7 is encoded in the same way as the distance from position 50 to 52.

The linear transformation that achieves this is, fascinatingly, a rotation.

You could have designed state of the art positional encoding

The trigonometric identity that proves this linear relationship is a key insight. Let's walk through the derivation.

Read the section 'Sinusoidal positional encoding'. It starts by presenting the formulas we just saw and then dives into the trigonometric derivation. Focus on how the use of a sine-cosine pair allows us to find a transformation matrix M_k that relates the encoding at position 'p' to the encoding at position 'p+k'. Recognizing this matrix as a rotation matrix is the main takeaway.

This property is crucial. Because the attention score is based on a dot product, and dot products are preserved under rotation, the model can learn to compute attention based on the relative rotation between two positional encodings, which directly corresponds to their relative distance in the sequence.

Let's read a concise summary that crystallizes why this method is so effective.

Positional Encoding Explained

This article from The Deep Hub nicely summarizes the properties that make sinusoidal encoding work.

Read the short subsection titled 'Why Sinusoidal Encoding Works'. It lists three key properties that we've discussed: Uniqueness, Relative Position Information, and Bounded Range.



Conclusion

In this lesson, we tackled the fundamental problem of order in Transformers. We established that because self-attention is permutation-equivariant, we must explicitly inject position information into the model.

Key Takeaways:

  • The Problem: Self-attention treats an input sequence as an unordered set of tokens, making it blind to word order.
  • The Solution: We add a positional encoding vector to each token's embedding. This vector is unique to its position in the sequence.
  • Sinusoidal Encoding: A specific method using sine and cosine functions of varying frequencies to generate these unique positional vectors. The use of sine/cosine pairs is not arbitrary.
  • Relative Positions: This formulation allows the positional encoding of pos + k to be represented as a simple rotation of the encoding at pos. This makes it easy for the model to learn relationships based on relative distances between tokens.

Preview of the Next Lesson:
We have now examined all the key components of the vanilla attention mechanism: Q, K, V projections, multi-head attention, and positional encoding. In our next lesson, we will move to Module 3: Transformer Architecture and LLM Basics. We will assemble these pieces into a full Transformer Block, introducing the final architectural elements—residual connections and layer normalization—that make deep Transformers trainable.