Skip to main content

Welcome to a Grasp lesson

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

Lesson 9

Understanding Self-Attention

Recommended resources

Hello! Welcome to our third lesson in the "Attention Mechanism" module.

Introduction

In our last lesson, we did a deep dive into the scaled dot-product attention formula:

We focused exclusively on the scaling factor, , and understood its critical role in stabilizing training by preventing vanishing gradients in the softmax function.

However, we left some fundamental questions unanswered:

  • What are the Query (Q), Key (K), and Value (V) matrices?
  • Where do they come from?
  • And why is this mechanism called self-attention?

Today's lesson will answer these questions. Our learning objective is to describe self-attention and how it allows each token to attend to all other tokens in a sequence. We will build the entire mechanism from the ground up, starting with a powerful intuition.



1. The Core Problem: Words Need Context

Imagine the word "bank". Its meaning is ambiguous without context.

  • "I swam across the river to get to the other bank." (a riverbank)
  • "I drove across the road to get to the other bank." (a financial institution)

A simple word embedding provides a static representation, which struggles to capture these contextual nuances. The goal of self-attention is to create a new, contextualized representation for each word by allowing it to "look at" and "draw information from" other words in the same sentence.

To see this idea explained, let's watch a short, intuitive video.

Intuition Behind Self-Attention Mechanism in Transformer Networks

This clip from the Ark channel provides an excellent motivation for self-attention, using the 'bank' example to illustrate why context is crucial for understanding language.

Watch from 00:53 to 04:01. Focus on how the meaning of a word changes based on its surrounding words and the core question: can we build a mechanism that weighs neighboring words to enhance meaning?



2. The Intuition: A Weighted Sum of Context

The video frames the core idea perfectly. How can we enhance the embedding of "bank"? We can create a new embedding for it that is a weighted sum of the embeddings of all words in the sentence.

For the sentence "River bank flows," the new, contextualized embedding for "bank" would be:

The key question is: How do we calculate the weights ()?

Intuitively, the weights should reflect relevance. For the word "bank," the weight for "River" should be high, while the weight for a less relevant word might be low. The most straightforward way to measure relevance or similarity between two vectors is the dot product. A larger dot product implies greater similarity.

This leads to a simple, two-step process for each word in the sentence:

  1. Compute Scores: Calculate the dot product of the target word's embedding with every other word's embedding in the sentence. This gives us a set of raw "relevance scores."
  2. Normalize to Weights: Pass these scores through a softmax function. This converts the raw scores into a probability distribution, ensuring the weights sum to 1.

The following reading walks through this exact first-principles approach.

Deep Drive into Self-Attention (Learn like Researcher)

This article from 'Towards AI' provides a clear, step-by-step construction of self-attention, starting from this idea of a contextual representation as a weighted sum.

Read the subsections 'First Principles Approach' and 'Mathematical Framing'. This will solidify the core concept of creating a new embedding as a weighted sum of all other embeddings in the sequence.



3. The Mechanism: Query, Key, and Value

Our simple weighted-sum model is powerful, but it has a limitation: a word's embedding is used for three different purposes:

  1. To compare against other words to generate scores.
  2. To be compared by other words.
  3. As the content that gets summed up in the final representation.

To make the model more flexible and powerful, self-attention introduces a small but crucial modification. Instead of using the same embedding vector for all three roles, it first projects the original embedding into three separate vectors:

  • Query (): Represents the current word's "question" as it looks for context. It asks: "Who is relevant to me?"
  • Key (): Represents a word's "label" or "identity" that can be matched against a query. It answers: "Here's what I am; see if I'm relevant to you."
  • Value (): Represents the actual content or information of the word. This is what gets passed into the final weighted sum if the key is deemed relevant.

The process then becomes:

  1. A token's Query vector is compared (via dot product) with every other token's Key vector to compute attention scores.
  2. The scores are passed through softmax to get the weights.
  3. The weights are used to create a weighted sum of all tokens' Value vectors.

For a great analogy, let's watch the following clip.

Attention is all you need (Transformer) - Model explanation (including math), Inference and Training

This segment from Umar Jamil's video uses a database analogy to clarify the distinct roles of Query, Key, and Value.

Watch from 35:27 to 37:46. This will help you build a strong mental model for why we separate the input into these three components.

Making it Learnable

But where do these Q, K, and V vectors come from? They are generated by multiplying the original input embedding () by three separate, learnable weight matrices ():



This is the most important step! These weight matrices are the learnable parameters of the self-attention layer. During training, the model learns the best way to project the input embeddings into Q, K, and V spaces to solve the task at hand (e.g., translation, summarization).

The following resources explain this critical step. The video provides an excellent visual walkthrough, while the article gives the same information in a text format with code snippets.

Intuition Behind Self-Attention Mechanism in Transformer Networks

This clip from the Ark channel explains how and why these learnable weight matrices are introduced, transforming our simple mechanism into a trainable neural network layer.

Watch from 21:19 to 26:19. Pay close attention to how linear layers are used to create the Query, Key, and Value vectors while preserving dimensions.

Understanding and Coding the Self-Attention Mechanism

For a text-based reference, this article by Sebastian Raschka explains the same concept of defining the weight matrices and projecting the inputs.

Read the section 'Defining the Weight Matrices'. It shows exactly how the Q, K, and V vectors are computed from the input embeddings and the projection matrices W_q, W_k, and W_v.



4. Putting It All Together

Now we can assemble the complete picture of self-attention for a sequence of tokens. The process happens for every token in parallel.

For any given token in the input sequence, its final contextualized representation is computed by:

  1. Projecting its embedding into a Query vector.
  2. Projecting every token's embedding (including its own) into Key and Value vectors.
  3. Calculating the dot product of its Query with every other token's Key to get attention scores.
  4. Scaling the scores by and applying softmax to get the final attention weights.
  5. Multiplying these weights by the corresponding Value vectors and summing them up to get the final context vector.

This diagram provides a fantastic overview of the entire process.

Visualizing the Self-Attention Mechanism
This diagram shows the complete data flow. An input sequence is embedded, then projected into Q, K, and V matrices. The Q and K matrices produce attention scores via dot-product and softmax, which then weight the V matrix to produce the final contextualized hidden states.

To see this process in action on a matrix-level, the following video provides a comprehensive animation.

Attention is all you need (Transformer) - Model explanation (including math), Inference and Training

Let's return to Umar Jamil's video for a detailed walkthrough of the entire self-attention calculation for a full sequence.

Watch from 20:11 to 25:31. This clip shows how the Q, K, and V matrices (initially treated as the same input) are used in the scaled dot-product formula to produce a new matrix of contextualized embeddings.

Because each token's Query vector is compared against every other token's Key vector, this mechanism fully enables each token to attend to all other tokens in the sequence, fulfilling our learning objective.



Conclusion

In this lesson, we deconstructed the self-attention mechanism, the engine that powers modern Transformers. We went from the high-level need for context to the specific mechanics of Queries, Keys, and Values.

Key Takeaways:

  • Purpose: Self-attention creates contextualized word embeddings by allowing each token to dynamically draw information from all other tokens in the sequence.
  • Mechanism: It achieves this by projecting each input embedding into three roles: a Query (what I'm looking for), a Key (what I have), and a Value (what I'll give).
  • Calculation: For each token, its Query is compared to every other token's Key to compute attention weights. These weights then determine how much of each token's Value contributes to the final output embedding.
  • Learnability: The projections into Q, K, and V spaces are done via learnable weight matrices (), which allows the model to learn task-specific contextual relationships.

Preview of the Next Lesson:
We've established that self-attention allows a token to look at all other tokens, including those that come after it. For tasks like sentence classification, this is great. But for autoregressive language modeling—where we predict the next word one at a time—allowing a token to "see the future" would be cheating.

In our next lesson, we will explore causal (or masked) self-attention, a modification that prevents tokens from attending to subsequent positions in the sequence, making it suitable for generative tasks.