1. The Attention Mechanism
Beyond Recurrence: The Bottleneck Problem
Traditional Recurrent Neural Networks (RNNs) and LSTMs process input sequences sequentially, maintaining a hidden state that is updated at each step. This architecture suffers from a significant 'sequential bottleneck' because computing the state at time t requires the state at time t-1, preventing parallelization during training. Furthermore, these networks suffer from information compression; all historical information must be squeezed into a fixed-length hidden vector, leading to the vanishing gradient problem and the 'forgetting' of early input tokens in long sequences.
The Attention mechanism fundamentally shifts this paradigm by allowing the model to look at all input positions simultaneously. Instead of relying on a compressed history, the model creates a direct path between any two tokens in the sequence, regardless of their distance. This global perspective solves the gradient signal degradation issue and allows the architecture to capture long-range dependencies explicitly, which is the cornerstone of Transformer-based models.
import torch # Simulating the sequential bottleneck in RNNs vs Parallelism in Attention seq_len = 10 d_model = 64 # RNN-like hidden states (sequential dependency) h = torch.zeros(d_model) for i in range(seq_len): x = torch.randn(d_model) h = torch.tanh(x + h) # Must wait for h_{i-1} # Self-Attention input (all tokens available at once) x_full = torch.randn(seq_len, d_model) # (Batch, Seq, Dim) # Attention can compute all correlations in a single matrix multiplication
Scaled Dot-Product Attention Mechanics
At the core of the Transformer is the Scaled Dot-Product Attention. For every input token, we define three vectors: Query (Q), Key (K), and Value (V). The Query acts as the 'search request,' the Key is the 'index' or 'label' for other tokens, and the Value represents the 'content' we want to retrieve. We compute the dot product of the Query with all Keys to find a compatibility score. This score indicates how much focus we should place on other tokens when processing the current one.
We scale the dot product by the square root of the dimension of the Keys, d_k. This scaling is crucial to prevent the dot product from growing too large in magnitude, which would push the Softmax function into regions with extremely small gradients, effectively stalling training. After scaling, we apply Softmax to normalize these scores into probabilities (weights), which are then used as a weighted sum over the Value vectors.
import torch.nn.functional as F def scaled_dot_product(q, k, v, d_k): # Calculate raw scores scores = torch.matmul(q, k.transpose(-2, -1)) / (d_k ** 0.5) # Normalize to probabilities attn_weights = F.softmax(scores, dim=-1) # Compute context vector return torch.matmul(attn_weights, v) # Mock setup d_k = 16 q = torch.randn(1, 4, d_k) k = torch.randn(1, 4, d_k) v = torch.randn(1, 4, d_k) output = scaled_dot_product(q, k, v, d_k)
Self-Attention vs. Cross-Attention
While the mathematical foundation of attention is identical, the origin of the inputs defines its role. In 'Self-Attention,' Q, K, and V all originate from the same source sequence. This allows the model to map the internal structure of the input, identifying dependencies between tokens within a single sentence or image, such as resolving pronoun references (e.g., 'it' referring to 'the dog').
In contrast, 'Cross-Attention' (or Encoder-Decoder Attention) involves a query from one sequence (typically the target decoder sequence) and keys/values from another (the source encoder sequence). This mechanism enables the model to 'align' the target output with relevant information from the input. For instance, in machine translation, as the decoder generates each word, the Cross-Attention layer looks at the encoder output to find the corresponding source language tokens to translate.
# Conceptual difference in PyTorch modules import torch.nn as nn # Self-attention module usage self_attn = nn.MultiheadAttention(embed_dim=64, num_heads=4) # Q, K, V all come from the same 'x' out = self_attn(x, x, x) # Cross-attention module usage # Query from decoder (tgt), Keys/Values from encoder (mem) out = self_attn(tgt, mem, mem)
Knowledge Check
Ready to test your understanding of 1. The Attention Mechanism?