Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Parallelizing Attention for Long-Range Dependencies

Introduction

In our previous lesson, we established the mathematical and computational framework for scaled dot-product attention. We defined it as a general-purpose mechanism, , that functions like a differentiable, soft dictionary lookup. It computes a weighted sum of Value vectors based on the similarity between a Query vector and a set of Key vectors. So far, we've treated Q, K, and V as abstract inputs.

This lesson addresses a pivotal question: what happens when the queries, keys, and values are all derived from the same source sequence? This is the core concept of self-attention. We will derive this mechanism from first principles and explore how it revolutionizes sequence processing. Specifically, you will see how self-attention directly addresses the fundamental limitations of recurrent models, enabling the capture of complex, long-range dependencies across an entire sequence in a massively parallel fashion—a crucial feature for the high-performance systems that interest you.

Why Self-Attention? The Limits of Recurrence

Before deriving the mechanism, it's essential to understand the problems it was designed to solve. Recurrent Neural Networks (RNNs), including LSTMs and GRUs, were the dominant paradigm for sequence modeling. However, their architecture imposes two major constraints.

First, RNNs are inherently sequential. To compute the hidden state at timestep , you must have already computed the state at . This dependency prevents parallelization across the sequence length, creating a significant computational bottleneck.

Second, information has to travel linearly through the sequence. For two words at opposite ends of a long sentence to interact, their information must pass through every intermediate step. This long path makes it difficult for the model to learn long-range dependencies and can lead to the attenuation of gradient signals.

Let's watch a segment from a Stanford lecture that clearly articulates these two core issues.

Stanford CS224N NLP with Deep Learning | 2023 | Lecture 8 - Self-Attention and Transformers

The lecturer, John Hewitt, introduces self-attention by first analyzing the drawbacks of the RNN-based approaches that preceded it.

Watch the segment from this section on RNN issues. Focus on the explanations of "linear interaction distance" and the lack of "parallelizability." The diagrams shown provide a clear visual of these constraints.

Self-attention proposes a radical alternative: what if every word could interact directly with every other word in the sequence in a single step?

This diagram starkly contrasts the computational graphs of an RNN (top) and self-attention (bottom). The RNN requires a number of sequential operations that grows with the sequence length, making it difficult to consider long-range context. In contrast, self-attention allows all tokens to interact in parallel in a constant number of operations, making it easy to consider the entire context.

Deriving Self-Attention from First Principles

Let's build the self-attention mechanism from the ground up. We start with a sequence of input token embeddings, which we stack into a matrix .

In self-attention, this single input matrix is the source for our queries, keys, and values. We don't use directly; instead, we create three distinct linear projections of it by using three unique, learnable weight matrices:

  • A query weight matrix:
  • A key weight matrix:
  • A value weight matrix:

For simplicity, it's common to set the key and value dimensions to be equal, .

The Query, Key, and Value matrices for the entire sequence are then computed as:

Socratic Question: Why do we need these three separate projection matrices? What would be the limitation if we simply used the input embeddings for all three roles (i.e., )?

Answer The projection matrices $W_Q, W_K, W_V$ allow the model to project the input embeddings into three different, more specialized subspaces. This gives the model flexibility. A token's role as a "query" (what information it's looking for) might be very different from its role as a "key" (what information it's signaling it has) or its "value" (the actual content it should provide). For instance, in the sentence "The robot picked up the ball, because **it** was red," the pronoun "it" might *query* for nouns in its context. Its *key* might represent that it is a pronoun looking for an antecedent. Its *value* would be the actual embedding of "it." The separate projections allow each token to learn to play these three distinct roles effectively.

With , , and defined, we can now substitute them into the scaled dot-product attention formula we derived in the previous lesson. This gives us the complete equation for a self-attention layer:

The output of this operation is a new matrix , where each row is a new, contextually-rich representation of the corresponding input token. Each output vector is a weighted sum of all value vectors in the sequence, where the weights are determined by how well that token's query matches every other token's key.

The following diagram provides an excellent visualization of this entire process.

This diagram illustrates the flow of a self-attention mechanism. The input word embeddings are multiplied by the weight matrices \(W_q, W_k, W_v\) to produce the Query, Key, and Value vectors. The dot product of Queries and Keys produces a score matrix, which is normalized by softmax to get attention weights. These weights are then used to create a weighted sum of the Values, resulting in the final contextualized hidden states.

To solidify your understanding of this mathematical flow, the following reading from the Stanford CS224n course notes provides a concise and formal derivation.

[draft] Note 10: Self-Attention & Transformers 1

This document formally introduces the key-query-value self-attention mechanism.

First, briefly review the section titled "Attention, broadly construed," which provides the high-level definition. Then, carefully study the section titled "The key-query-value mechanism" which contains the full mathematical derivation (Equations 7 and 8).

Capturing Dependencies in Parallel

Now we can see precisely how self-attention achieves its two main goals.

1. Constant Path Length for Long-Range Dependencies:
The core of the interaction happens in the matrix multiplication . This operation computes an score matrix, where the element at position is the dot product of the query for token and the key for token . This is a direct connection between token and token , regardless of how far apart they are in the sequence. The path length between any two tokens is . This allows gradients to flow directly between distant tokens, making it vastly easier to learn long-range dependencies compared to the path length in an RNN.

2. Parallel Computation:
The entire self-attention formula consists of a series of matrix multiplications. There are no sequential loops or dependencies across the time/sequence dimension (). The computation for all tokens can be executed simultaneously on a GPU. This is in stark contrast to an RNN, where the computation for token must wait for token . This massive parallelizability is a primary reason for the success and scalability of Transformer models.

The table below, from a comprehensive survey on attention, summarizes these critical differences.

Attention Mechanisms in Neural Networks A ...

This section of the paper provides a table comparing the properties of self-attention, recurrent, and convolutional architectures.

Focus on the table under the heading "Comparison with Recurrent Networks." Pay close attention to the rows for "Sequential Operations" and "Maximum Path Length," as these highlight the fundamental advantages of self-attention.

The Missing Piece: Positional Information

As derived, our self-attention mechanism has a significant flaw: it is permutation equivariant. This means if you shuffle the order of the words in the input sequence, the output will be a correspondingly shuffled set of the same vectors. The model has no inherent sense of word order; it treats the input as an unordered "bag" of vectors. This is because the score depends only on the tokens and , not their positions.

To solve this, we must explicitly inject information about the position of each token into the model. This is done using positional encodings. The idea is to create a vector for each position (1, 2, 3, ...) and add it to the corresponding token embedding before it's fed into the self-attention layer.

There are two common approaches:

  • Sinusoidal Positional Encodings: Using a fixed set of sine and cosine functions of different frequencies to create unique positional vectors.
  • Learned Positional Encodings: Creating a simple embedding layer (a lookup table) where each position index has a learnable vector.

This added positional information allows the self-attention mechanism to differentiate between "The dog chased the cat" and "The cat chased the dog."

Stanford CS224N NLP with Deep Learning | 2023 | Lecture 8 - Self-Attention and Transformers

This segment of the Stanford lecture explains why self-attention is position-agnostic and introduces the concept of positional encodings as the solution.

Please watch from this section. The lecturer provides a clear example of why shuffling words doesn't change the attention output and then describes the two main methods for encoding position.

Conclusion

In this lesson, you've derived the self-attention mechanism from first principles, understanding it as a specific and powerful application of the general attention framework from our previous session. We've seen how it directly addresses the shortcomings of recurrent models by enabling parallel computation and providing constant-time access between any two tokens in a sequence.

Key Takeaways:

  • Self-Attention Derivation: Queries, Keys, and Values () are all generated from the same input sequence via three distinct, learnable linear projections ().
  • Parallel Dependency Capture: Self-attention computes a relevance score between every pair of tokens in a single matrix operation (), allowing for massive parallelization and creating a direct path for modeling long-range dependencies.
  • Computational Advantage: Unlike the sequential operations in RNNs, self-attention's complexity is dominated by matrix multiplications (), which is highly efficient on modern accelerators for sequences where is smaller than the model's feature dimension .
  • Positional Encodings are Essential: Because the self-attention operation itself is permutation equivariant, explicit positional information must be added to the input embeddings to give the model a sense of sequence order.

Preview of the Next Lesson:

A single self-attention mechanism learns one way for tokens to interact. But what if there are multiple types of relationships we want to capture simultaneously? For example, one set of attention weights might capture syntactic dependencies, while another captures semantic similarity. In our next lesson, we will explore multi-head attention, an elegant and computationally efficient way to run multiple self-attention operations in parallel, allowing the model to jointly attend to information from different representation subspaces at different positions.

Can't find a good explanation? Sign up and we'll make it for you

Sign up