The Attention Mechanism (Self-Attention)
The self-attention mechanism is the fundamental component that distinguishes the Transformer architecture from earlier recurrent (RNN) and convolutional (CNN) networks. Whereas RNNs process sequences step by step (which hinders parallelization and the retention of long-term dependencies), self-attention allows the model to relate each word in the input sequence to all the other words simultaneously.
This chapter dissects Scaled Dot-Product Attention, the mathematical formula that governs this operation, and implements the masking required for generative language models (such as the GPT family).
6.1 Fundamental Concepts: Query, Key, and Value
To compute attention, we project the input (embeddings) into three distinct vectors for each token. This approach is inspired by information retrieval systems:
- Query (): What is the current token looking for? (It represents the current focus.)
- Key (): What does the current token offer? (It serves as an identifier for matching.)
- Value (): What is the actual content of the information? (The information that will be aggregated if the key matches the query.)
In a self-attention mechanism, , , and originate from the same source (the output of the previous layer), multiplied by learnable weight matrices ().
6.2 The Mathematical Formula
Attention is computed as a weighted sum of the values (), where the weight assigned to each value is determined by the compatibility between the query () and the corresponding key ().
6.2.1 Step-by-Step Computation:
- MatMul (): Computes the dot product between the Query and the transposed Key. This produces a score matrix (or affinity matrix). If the dot product is high, the vectors are aligned, indicating high relevance between the tokens.
- Scale (): We divide the scores by the square root of the key dimension ().
- Why scale? Without it, for large values of , the dot product grows in magnitude, pushing the softmax function into regions where gradients are extremely small (vanishing gradients), making training difficult.
- Mask (optional): A mask is applied (replacing values with ) to prevent the model from “seeing” certain tokens (e.g., future tokens or padding).
- Softmax: Converts the scores into probabilities (attention weights) that sum to 1.
- MatMul (): The weights are multiplied by the Values (). This filters out irrelevant information and preserves the relevant.
6.3 Visual Data Flow
The diagram below illustrates the flow of tensors inside the scaled attention block.

6.4 Masking
There are two critical types of masks in the Transformer:
- Padding mask: Ignores padding tokens used to equalize the length of sentences in a batch.
- Look-ahead (causal) mask: Essential for decoders (as in GPT). When predicting the token at position , the model must not have access to the tokens at positions .
The causal mask is an upper triangular matrix (excluding the diagonal) filled with . When added to the scores before the softmax:
This guarantees that attention to future tokens is zero.
6.5 Implementation in PyTorch
Below, we implement a robust class for Scaled Dot-Product Attention, capable of handling causal masks.
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class ScaledDotProductAttention(nn.Module):
"""
Computes scaled dot-product attention.
Formula: Softmax(QK^T / sqrt(d_k)) * V
"""
def __init__(self, dropout_rate=0.1):
super(ScaledDotProductAttention, self).__init__()
self.dropout = nn.Dropout(dropout_rate)
def forward(self, query, key, value, mask=None):
"""
Args:
query: Tensor of shape (Batch, Heads, Seq_Len_Q, Head_Dim)
key: Tensor of shape (Batch, Heads, Seq_Len_K, Head_Dim)
value: Tensor of shape (Batch, Heads, Seq_Len_K, Head_Dim)
mask: Mask tensor (Batch, 1, Seq_Len_Q, Seq_Len_K) or similar.
True values indicate positions to be masked (or 1s/0s depending on the logic).
Returns:
context: Weighted output tensor
attention_weights: Attention weights (for visualization)
"""
# 1. Get dimensions
d_k = query.size(-1)
# 2. Compute scores (Q * K^T)
# We transpose the last two dimensions of K to allow the multiplication
scores = torch.matmul(query, key.transpose(-2, -1))
# 3. Scaling
scores = scores / math.sqrt(d_k)
# 4. Apply the mask (if provided)
if mask is not None:
# Replaces values where the mask is 0 (or True, depending on the implementation) with -inf
# Here we assume mask=0 means "hide"
scores = scores.masked_fill(mask == 0, float('-inf'))
# 5. Softmax to obtain probabilities
# Applied on the last dimension (the target sequence dimension)
attention_weights = F.softmax(scores, dim=-1)
# 6. Dropout (optional, but common for regularization)
attention_weights = self.dropout(attention_weights)
# 7. Multiplication by the Values (Weights * V)
context = torch.matmul(attention_weights, value)
return context, attention_weights
# --- Usage Example with a Causal Mask ---
def create_causal_mask(seq_len):
"""Creates a lower triangular mask to prevent 'looking into the future'."""
# tril returns the lower triangular part of the matrix
mask = torch.tril(torch.ones(seq_len, seq_len))
return mask
# Test configuration
batch_size = 1
heads = 1
seq_len = 4
d_k = 8
# Dummy data
q = torch.randn(batch_size, heads, seq_len, d_k)
k = torch.randn(batch_size, heads, seq_len, d_k)
v = torch.randn(batch_size, heads, seq_len, d_k)
# Create the causal mask (1s visible, 0s hidden)
causal_mask = create_causal_mask(seq_len)
# Expand dimensions for broadcasting: (1, 1, seq_len, seq_len)
causal_mask = causal_mask.unsqueeze(0).unsqueeze(0)
# Instantiate and run
attention_layer = ScaledDotProductAttention()
output, weights = attention_layer(q, k, v, mask=causal_mask)
print("Attention weights (with causal mask):")
print(weights[0][0])
# Note that the upper right part will be 0.
6.5.1 Analysis of the Code Output
If we run the code above, the attention weight matrix (weights) will have a lower triangular structure. For example, for a sequence of length 4:
- Token 1 attends only to token 1.
- Token 2 attends to tokens 1 and 2.
- Token 3 attends to tokens 1, 2, and 3.
- Positions where (the future) will have weight (after the softmax of ).
6.6 Chapter Conclusion
The Scaled Dot-Product Attention mechanism is computationally efficient, since it relies on highly optimized matrix operations. The introduction of the scale factor ensures numerical stability, and the use of masks allows the same architecture to be used both for encoding (understanding the whole context) and for decoding (generating text sequentially). In the next chapter, we will see how to extend this concept to Multi-Head Attention, allowing the model to focus on different representation subspaces simultaneously.
6.7 Auditing Shapes and Invariants
For , the product has shape . The softmax must be applied on the last dimension, since each query distributes weight over the keys. Multiplying by returns .
Three simple tests catch many bugs: each row of the weights should sum to approximately 1; future positions should receive zero after the causal mask; and the gradient should reach the projections of , , and . Inverted masks and softmax on the wrong axis often produce code that runs but is semantically incorrect.
Mask before the softmax
Replace forbidden scores with a very negative value before the softmax. Zeroing weights after it breaks the normalization unless the row is renormalized.
6.8 Self-Attention, Cross-Attention, and Cost
In self-attention, queries, keys, and values are obtained from the same sequence. In cross-attention, the queries come from one sequence, while keys and values come from another. This second case appears in encoder-decoder architectures and in multimodal models, in which image or audio representations guide text generation.
The score matrix has elements per head. Therefore, dense attention has quadratic memory cost with respect to the length . Local, sparse, and block attention and linear approximations seek to reduce this bottleneck, generally trading global reach, exactness, or simplicity for efficiency.
Minimal numerical example
For , , and , the scores are and . The softmax gives greater weight to the first value, but does not turn the operation into a hard choice: the output remains a weighted combination of the two value vectors.
6.9 Efficient Attention Without Changing the Formula
A naive implementation materializes the entire matrix in the GPU’s global memory. FlashAttention reorganizes the computation into small blocks that fit in fast memory, computes softmax statistics incrementally, and avoids storing large intermediates. The mathematical result remains exact attention; the gain comes from the memory access pattern.
This distinction is important: asymptotic complexity and actual time are not synonyms. An operation with the same number of multiplications can be much faster by reducing transfers between memory levels. For this reason, analyzing FLOPs alone does not explain all of the performance.
6.9.1 Sliding Window and Global Reach
In window attention, each token attends only to a neighborhood of width . The cost goes from approximately to , but a distant dependency must cross several layers or use global tokens. The choice of defines a trade-off between memory, latency, and the speed at which context propagates.
Hybrid models can alternate local and global layers. Another possibility is to use linear attention, which reorganizes or approximates the computation to avoid the quadratic matrix. These variants are not universal substitutes: long-range retrieval tasks should be part of the evaluation.
Long-context test
Insert a unique piece of information at the beginning of a document and ask questions at increasing distances. Measure accuracy and latency; merely stating the maximum window size does not reveal how much context the model effectively uses.