2. Multi-Head Attention
From Single to Multi-Head Attention
Standard self-attention forces a single set of attention weights to capture all dependencies between tokens, which limits the model to a single 'view' of the sequence. Multi-head attention addresses this by splitting the embedding space into multiple subspaces, allowing the model to jointly attend to information from different representation subspaces at different positions.
By projecting the Queries, Keys, and Values into $h$ distinct head dimensions, the model can simultaneously focus on different features—for instance, one head might specialize in syntactic dependencies while another focuses on coreference resolution or local semantic alignment.
import torch import torch.nn as nn # Configuration d_model = 512 num_heads = 8 head_dim = d_model // num_heads # Multi-head projections W_q = nn.Linear(d_model, d_model) W_k = nn.Linear(d_model, d_model) W_v = nn.Linear(d_model, d_model) def split_heads(x, batch_size): return x.view(batch_size, -1, num_heads, head_dim).transpose(1, 2) # Example input: batch size 1, sequence length 10, embedding 512 x = torch.randn(1, 10, d_model) q = split_heads(W_q(x), 1) print(f'Shape after splitting heads: {q.shape}')
Architecture: The Add & Norm Block
Deep Transformers rely heavily on residual connections and Layer Normalization to stabilize training. Each multi-head attention block is wrapped in an 'Add & Norm' operation, which performs a residual connection: LayerNorm(x + Sublayer(x)). This prevents vanishing gradients in deep networks by providing a direct identity path for backpropagation.
Layer Normalization operates across the feature dimension, rather than the batch dimension, ensuring that the statistics of the activations remain stable even when sequence lengths vary significantly across a training batch.
class AddNorm(nn.Module): def __init__(self, d_model): super().__init__() self.ln = nn.LayerNorm(d_model) def forward(self, x, sublayer_output): # Residual connection + LayerNorm return self.ln(x + sublayer_output) # Example usage input_tensor = torch.randn(1, 10, 512) attention_out = torch.randn(1, 10, 512) layer = AddNorm(512) output = layer(input_tensor, attention_out) print(f'Output shape: {output.shape}')
Computational Complexity
The complexity of a self-attention layer is $O(n^2 d)$, where n is sequence length and d is the hidden dimension. Compared to recurrent layers, which have $O(n d^2)$ complexity and require sequential processing, attention allows for complete parallelization across the temporal dimension.
While self-attention becomes memory-intensive at very long sequences, it significantly outperforms RNNs on modern GPU hardware by eliminating the dependency on the previous hidden state, enabling massive throughput during both training and inference phases.
# Conceptual comparison of FLOPs growth import numpy as np def complexity_comparison(n_range): for n in n_range: attn_complexity = n**2 * 512 rnn_complexity = n * 512**2 print(f'SeqLen {n}: Attn={attn_complexity}, RNN={rnn_complexity}') complexity_comparison([16, 64, 256])
Knowledge Check
Ready to test your understanding of 2. Multi-Head Attention?