How Transformers Work: Self-Attention Explained Step by Step
When you read a sentence, you do not understand every word independently. You use surrounding words to understand what each word means.
Consider this sentence:
"The cat sat on the mat because it was tired."
To understand the word "it", you connect it with "cat". The word "it" gets its meaning from the surrounding context.
Transformers use a mechanism called self-attention to build these contextual relationships between tokens.
Self-attention helps a model decide which other tokens are relevant when processing a particular token. It is one of the key mechanisms that make Transformer models effective at understanding and generating language.
Let's understand how it works, step by step.
1. First, Understand the Basic Idea of Self-Attention
In traditional language processing, a model often processes words sequentially. Transformers can process relationships between multiple tokens using attention.
For example:
"The cat sat on the mat because it was tired."
When processing the word "it", the model can assign different levels of attention to other words in the sentence.
It may give more attention to "cat" because that word helps identify what "it" refers to.
Self-attention performs this process for every token in the input.
In simple terms:
Self-attention allows each token to gather useful information from other tokens in the same sequence.
2. How a Transformer Prepares Tokens
Before attention can happen, text must be converted into numerical representations.
A Transformer follows two important steps:
Tokenization: The input sentence is divided into tokens. A token can be a complete word, part of a word, or punctuation.
Embedding: Each token is converted into a numerical vector. Positional information is also added so the model can distinguish token positions and understand their order.
For our example, the sentence might be represented as:
| Position | Token |
|---|---|
| 1 | The |
| 2 | cat |
| 3 | sat |
| 4 | on |
| 5 | the |
| 6 | mat |
| 7 | because |
| 8 | it |
| 9 | was |
| 10 | tired |
The Transformer now has numerical representations of these tokens, ready for self-attention.
3. Understanding Query, Key, and Value (Q, K, V)
This is the central idea behind self-attention.
For each token representation, the Transformer creates three vectors:
- Query (Q): What information is this token looking for?
- Key (K): What information does this token offer for matching?
- Value (V): What information should this token contribute if selected?
Think of it like searching through information.
A query is the search request, keys help determine which information is relevant, and values contain the information that gets collected.
Let's return to our sentence:
"The cat sat on the mat because it was tired."
When the model processes "it":
Query: The query represents what contextual information "it" needs.
Keys: The keys of other tokens help determine which tokens are relevant to that query. The key for "cat" may match strongly because it provides useful context.
Values: The value associated with "cat" carries information that can contribute to the updated representation of "it".
This is how Q, K, and V work together.
Importantly, these vectors are not manually assigned meanings. The model learns the transformations that produce them during training.
4. How Does the Model Decide Which Token Matters?
The model compares the query of one token with the keys of other tokens.
A higher similarity score generally means a stronger attention connection.
For example, when processing "it", the model calculates attention scores against the keys of all available tokens.
These scores are then passed through softmax, which converts them into normalized attention weights.
The weights indicate how much each token contributes to the final attention result.
5. Understanding the Attention Heatmap
An attention heatmap is a visual representation of these attention weights.
Let's look at an illustrative example for the word "it":
| Token | Attention weight |
|---|---|
| The | 0.01 |
| cat | 0.72 |
| sat | 0.02 |
| on | 0.01 |
| the | 0.01 |
| mat | 0.08 |
| because | 0.06 |
| it | 0.03 |
| was | 0.03 |
| tired | 0.03 |
These values are hypothetical and are only meant to explain the concept. They are not measured outputs from a trained Transformer.
In this example, "cat" receives the highest attention weight. This means its value contributes more strongly to the updated representation of "it" than the other tokens do.
A typical attention heatmap uses:
- Rows to represent query tokens.
- Columns to represent key tokens.
- Cell intensity to represent attention weight.
Darker or more intense cells generally indicate higher attention weights, depending on the visualization's colour scale.
Important: An attention heatmap shows how attention is distributed. It does not automatically explain everything the model understood or prove why it made a particular prediction.
6. How Does the Model Combine the Information?
After calculating attention weights, the Transformer uses them to combine the value vectors.
Each value vector is multiplied by its corresponding attention weight. The weighted values are then added together.
The result is a new representation for the token.
For example, the updated representation of "it" contains information gathered from other relevant tokens, including "cat" in our illustration.
This process happens for every token in the sequence.
That is why the mechanism is called self-attention: tokens attend to other tokens within the same sequence.
7. What Is Multi-Head Attention?
One attention operation can capture one type of relationship, but language contains many relationships.
For example, a sentence can contain:
- Pronoun-to-noun relationships.
- Subject-to-verb relationships.
- Relationships between nearby words.
- Dependencies between words far apart.
Transformers use multi-head attention to capture different relationships in parallel.
Instead of calculating attention only once, the model creates multiple attention heads. Each head has its own learned Query, Key, and Value projections.
The outputs from these heads are combined to produce the final attention representation.
Different heads can learn different patterns, although their roles are not always cleanly separated or easy to interpret.
8. What Happens After Self-Attention?
Self-attention is only one part of a Transformer block.
A typical Transformer block also contains:
Feed-Forward Network (FFN): Processes each token's updated representation independently through a small neural network.
Residual Connections: Help information and gradients flow through deeper networks.
Layer Normalization: Helps maintain stable activations during training.
A simplified view of a Transformer block is:
- Input token representations.
- Multi-head self-attention.
- Residual connection and normalization.
- Feed-forward network.
- Another residual connection and normalization.
Multiple Transformer blocks are stacked to build a deeper model.
9. Does Every Transformer Look at Every Token?
Not necessarily. It depends on the type of Transformer and its attention mask.
Bidirectional attention: Models such as BERT can attend to tokens on both sides of a given position.
Causal attention: Models such as GPT use a causal mask. A token can attend to itself and earlier tokens, but not future tokens.
For example, when GPT predicts the next token, it cannot use words that have not been generated yet.
This restriction is important for autoregressive text generation.
10. The Mathematics Behind Self-Attention
The previous sections explain the intuition. The mathematical formulation shows how the operation is calculated.
Let:
- (X) = input token representations.
- (W_Q) = Query projection matrix.
- (W_K) = Key projection matrix.
- (W_V) = Value projection matrix.
The Transformer calculates:
[ Q=XW_Q ]
[ K=XW_K ]
[ V=XW_V ]
Next, it calculates the similarity between queries and keys:
[ Scores=\frac{QK^T}{\sqrt{d_k}} ]
Here, (d_k) is the dimension of the key vectors. Dividing by its square root helps control the scale of the scores.
The scores are passed through softmax:
[ AttentionWeights=softmax\left(\frac{QK^T}{\sqrt{d_k}}\right) ]
Finally, the attention weights are multiplied by the value vectors:
[ Attention(Q,K,V)=softmax\left(\frac{QK^T}{\sqrt{d_k}}\right)V ]
For causal attention, a mask is added to the scores before softmax:
[ Attention(Q,K,V)=softmax\left(\frac{QK^T}{\sqrt{d_k}}+M\right)V ]
Here, (M) prevents a token from attending to future positions by assigning those positions a very large negative score.
This entire operation is known as Scaled Dot-Product Attention.
Conclusion
Self-attention allows Transformers to build contextual representations by connecting tokens with other relevant tokens in a sequence.
Query determines what a token is looking for, Key helps calculate relevance, and Value supplies the information that gets combined.
Multi-head attention performs this process through multiple learned attention operations, helping the model capture different relationships in language.
Understanding self-attention is an important first step toward understanding how modern Transformer-based models such as BERT and GPT process text.



