Hello! Welcome back to our fifth module on Transformer Architectures.
In the last lesson, we demystified the first step of the Transformer pipeline: converting raw text into a set of rich, numerical vectors using tokenization, token embeddings, and positional encodings. We now have a sequence of input vectors, where each vector represents a token and its position in the sentence.
This brings us to the next logical question: Now that we have these vectors, how does the model figure out the relationships between them? How does it know that in the sentence "The cat chased the mouse because it was fast," the word "it" refers to the "mouse" and not the "cat"?
This lesson will introduce the revolutionary mechanism that solved this problem: self-attention. You will learn how the Transformer uses the concepts of Queries, Keys, and Values to dynamically weigh the importance of every other word in an input sequence when processing a single word. This is the core mechanism that gives LLMs their deep contextual understanding of language.
1. The Core Idea: What is Self-Attention?
At a high level, self-attention is a mechanism that allows a model to look at other positions in the input sequence for clues that can help lead to a better encoding for the word it's currently processing.
For each token, the self-attention layer produces a new vector that is a weighted sum of the vectors of all tokens in the sequence. The "magic" is in how it calculates these weights. The weights determine how much "attention" or focus to place on each word when representing another.
Let's start with a high-level overview of why this is so powerful.
The blog post 'The Illustrated Transformer' provides one of the clearest explanations of self-attention. Let's start with the section that introduces the concept at a high level.
Please read the section 'Self-Attention at a High Level'. Focus on the example sentence about 'the animal' and 'the street' to build an intuition for what problem self-attention solves.
As the article illustrates, when the model processes the word "it", self-attention helps it associate "it" with "animal". The output vector for "it" will be heavily influenced by the vector for "animal", effectively "baking in" the context that "it" refers to the animal.
2. The Q, K, V Analogy: A Database Lookup
To calculate these attention weights, the model uses three special vectors for each input token: the Query, the Key, and the Value.
Since you have a background in backend development, you can think of this process as a kind of soft, differentiable database lookup that happens for every single word in the sequence.
- Query (Q): This vector represents the current word that is "asking" for information. It's the search query. For the word "it", its Query vector is essentially asking, "Who am I? What qualities should I look for in the words I might refer to?"
- Key (K): This vector is like the set of keywords or an index for a database record. Every word in the sequence generates a Key vector that says, "This is what I am about." The Key for "animal" might encode properties like "is a noun," "is animate," etc.
- Value (V): This vector is the actual content of the record. It represents the rich semantic meaning of the word. If a Query finds a matching Key, the associated Value is what gets passed along.
The process for a single word is:
- Its Query vector is compared against the Key vectors of all words in the sequence.
- The similarity between the Query and each Key produces a raw score. A higher score means a better match.
- These scores are normalized to determine how much of each word's Value should be pulled into the final representation of the current word.

3. The Self-Attention Calculation, Step-by-Step
Now, let's break down the calculation using the concepts of Q, K, and V. We'll follow the clear, visual steps from "The Illustrated Transformer."
This next section of 'The Illustrated Transformer' details the six steps of the self-attention calculation at the vector level. It's a foundational read for understanding the mechanism.
Read the section 'Self-Attention in Detail'. Follow the six steps from creating the Q, K, V vectors to summing the weighted value vectors. The diagrams here are extremely helpful.
Let's summarize and add some detail to those steps:
Step 1: Create Query, Key, and Value Vectors
For each input vector (the embedding + positional encoding from our last lesson), we create three new, smaller vectors: Q, K, and V. This is done by multiplying the input vector by three separate weight matrices: , , and .
Crucially, these weight matrices are learnable parameters. The model learns the best way to project the input vectors into these Q, K, and V spaces during training.

Step 2: Calculate Scores
To find the relevance of other words to our current word (let's say, word #1), we take the dot product of its query vector () with the key vector of every word in the sequence (). The first score is , the second is , and so on. The dot product is a measure of vector similarity; a larger value implies greater relevance.
Step 3: Scale the Scores
The scores are divided by the square root of the dimension of the key vectors, . Why? The dot product is a sum of products. As gets larger, the variance of the dot product also gets larger, which can lead to extremely small gradients after the softmax function (next step). Scaling brings the variance back to 1, stabilizing the training process. This is a small but critical detail for making deep transformers trainable.
Step 4: Apply Softmax
We pass the scaled scores through a softmax function. This normalizes the scores, turning them into positive values that all sum to 1. These normalized scores are the final attention weights. A high weight (e.g., 0.85) means the model has decided that word is very important for understanding the current word.
Step 5: Multiply by Value Vectors
Each Value vector () is multiplied by its corresponding attention weight. This has the effect of amplifying the Values of relevant words and drowning out the Values of irrelevant ones (by multiplying them by very small numbers).
Step 6: Sum the Weighted Value Vectors
Finally, all the weighted value vectors are summed up. This produces the output of the self-attention layer for our current word. This output vector is a new representation of the word that is now enriched with contextual information from all the other words it paid attention to.
Test your understanding!
Imagine in the sentence "The server is down," the word "server" is being processed. After the softmax step, you get the following attention weights for each word:
- "The": 0.05
- "server": 0.50
- "is": 0.15
- "down": 0.30
Which word's Value vector will contribute the most to the final output vector for "server"? Which will contribute the least?
Show answer
The word "server" itself will contribute the most (50%), as its Value vector is multiplied by the largest attention weight (0.50). This is very common; a word usually pays a lot of attention to itself. The word "down" will be the second-largest contributor (30%), adding important context. "The" will contribute the least (5%).
4. Making it Fast: Matrix Calculations
Performing these calculations with loops over vectors would be incredibly slow. As a software engineer, you know that vectorized operations are key to performance. Self-attention is implemented using matrix multiplications to process the entire sequence of tokens at once.
The formula for this is elegant and compact:
Let's see how this works in practice.
The final part of the 'Illustrated Transformer' section on self-attention shows how the vector-wise steps are consolidated into a single matrix formula for efficient computation.
Read the section 'Matrix Calculation of Self-Attention'. This will connect the step-by-step logic you just learned to the efficient matrix-based formula used in real models.
In this formulation:
- The input vectors are stacked together into a single matrix .
- , , and become matrices, calculated as , , and .
- The dot products of all queries with all keys are computed in one go with the matrix multiplication .
- The softmax is applied, and the result is multiplied by the matrix to get the final output matrix, where each row is the new context-aware vector for a token.
5. From Theory to Code
Seeing the underlying code can make these concepts even more concrete. The following resource walks through a PyTorch implementation of the steps we just covered. You don't need to run the code yourself, but reading through it will solidify your understanding of how the math translates into a practical program.
Understanding and Coding the Self-Attention Mechanism ...
Dr. Sebastian Raschka's article provides a fantastic from-scratch coding explanation. Let's read the parts that map directly to the concepts we've discussed.
Please read the following three sections: 'Defining the Weight Matrices', 'Computing the Unnormalized Attention Weights', and 'Computing the Attention Scores'. Notice how the code mirrors the steps: defining W_query, W_key, W_value; calculating 'omega' (the raw scores); scaling and applying softmax; and finally, creating the context vector by multiplying with 'values'.
Conclusion
In this lesson, you've unpacked the core mechanism of the Transformer architecture. You saw how self-attention enables a model to create context-aware representations by selectively focusing on the most relevant words in a sequence.
Key Takeaways:
- Self-attention computes a new representation for each token as a weighted average of all token representations in the sequence.
- The process uses three learned projections of the input: Query (what I'm looking for), Key (what I have), and Value (what I offer).
- The attention score is calculated by taking the dot product of a token's Query with every other token's Key.
- Scores are scaled by for stability and then normalized into attention weights using a softmax function.
- The final output vector is the sum of the Value vectors, weighted by the attention weights.
- This entire process is performed efficiently using a single matrix formula: .
Next up:
We explored how a single set of Q, K, and V matrices can find one type of relationship. But what if a word needs to pay attention to different things for different reasons? For example, a verb might need to attend to its subject (a grammatical relationship) and also to a word that modifies its meaning (a semantic relationship). To handle this, Transformers use multi-head attention, which is just running the self-attention process we learned today multiple times in parallel with different weight matrices. We'll dive into that in our next lesson.