Decoding 'Attention Is All You Need': Scaled Dot-Product & Multi-Head Mechanisms
- Core Innovation: Replaces recurrent neural networks (RNNs) and convolution entirely with self-attention mechanisms, enabling massive parallelization during training.
- Key Equation:
- Why Scaling Matters: Scaling by prevents dot products from growing excessively large in high dimensions, keeping gradients out of regions with extremely small softmax derivatives.
1. The Core Motivation
Prior to Transformers, dominant sequence transduction models relied on complex recurrent or convolutional neural networks (LSTMs, GRUs). While effective, sequential computation creates a fundamental bottleneck:
Sequential Bottleneck: Computing hidden state strictly requires . This precludes parallelization within training examples, becoming critical at longer sequence lengths .
The Transformer discards recurrence entirely, drawing connections between all positions in constant sequential operations.
2. Scaled Dot-Product Attention
The model maps a query and a set of key-value pairs to an output vector. When dimensions are large, the dot product grows large in magnitude, pushing the softmax function into regions with tiny gradients.
To counteract this, the inner product is scaled by the inverse square root of key dimension :
PyTorch Implementation
Here is how scaled dot-product attention is implemented in code:
import torch
import torch.nn as nn
import math
def scaled_dot_product_attention(query, key, value, mask=None):
d_k = query.size(-1)
# Compute raw attention scores: (batch, heads, seq_len, seq_len)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
# Softmax along key dimension
p_attn = torch.softmax(scores, dim=-1)
# Weight values by attention probabilities
return torch.matmul(p_attn, value), p_attn3. Multi-Head Attention
Instead of performing a single attention function with -dimensional keys, queries, and values, Multi-Head Attention projects linearly times with different learned linear projections to dimensions:
where .
This allows the model to jointly attend to information from different representation subspaces at different positions.