Explain the mechanics of self-attention and how it allows models to weigh the importance of different parts of the input data relative to each other.
Self-attention computes contextual token representations by projecting inputs into Query (Q), Key (K), and Value (V) vectors and taking a softmax-weighted sum over values using scaled dot products QK^T / sqrt(d_k). Dividing by sqrt(d_k) keeps dot-product variance near 1 so softmax does not saturate with vanishing gradients at large head dimensions. While enabling O(1) parallel path length across any distance, full self-attention scales at O(n^2 d) compute and O(n^2) memory.
Study Card: Mechanics of Self-Attention
Direct Answer
Self-attention computes dynamic, input-dependent pairwise interactions across all tokens in a sequence . Each token representation is projected via three learned weight matrices and into Queries (), Keys (), and Values (), then combined via scaled dot-product attention (Vaswani et al., 2017):
Three architectural principles govern self-attention:
- Why divide by ? If components of and are independent with zero mean and unit variance, their dot product has mean and variance (standard deviation ). For large , unscaled dot products grow large in magnitude, pushing softmax into extreme saturation regions where gradients nearly vanish. Scaling by restores unit variance.
- Complexity & Path Length: Unlike RNNs ( sequential steps), self-attention connects any two tokens in path length with full parallelism across sequence positions, at a cost of compute and attention-matrix memory (mitigated in hardware via FlashAttention tiling).
- Masking (): Encoders (BERT) allow bidirectional attention (), whereas autoregressive decoders (GPT/LLaMA) add above the main diagonal so token cannot attend to future tokens .
Key Terms
- Query (), Key (), Value (): Linear projections representing what information a token seeks (), what attributes a token advertises (), and what content it contributes ().
- Scaled Dot-Product Attention: Pairwise compatibility scoring followed by row-wise softmax normalization.
- Causal Mask: Upper-triangular mask preventing autoregressive decoders from peeking at future tokens during parallel training.
- Quadratic Complexity (): Memory and compute bottleneck on long sequences motivating FlashAttention, sparse/sliding-window attention, and KV caching.
Example
Consider "The animal didn't cross the street because it was too tired":
- When updating the representation for
"it", the query vector for"it"computes high dot products against the key vector for"animal"(and"tired"), producing a high attention weight on"animal"and near-zero weights on function words like"the". - Taking the weighted sum of value vectors injects semantic attributes of
"animal"directly into"it"in a single layer—even across arbitrary token distance.
Code Implementation
import torch
import torch.nn as nn
def scaled_dot_product_attention(q, k, v, mask=None):
"""
Args:
q: (batch_size, seq_len, d_k)
k: (batch_size, seq_len, d_k)
v: (batch_size, seq_len, d_v)
mask: Optional boolean/0-1 mask (1 = keep, 0 = mask out) broadcastable to (B, L, L)
"""
d_k = q.size(-1)
scores = torch.matmul(q, k.transpose(-2, -1)) / (d_k ** 0.5)
if mask is not None:
# Use -inf (safe across fp16/bf16/fp32 unlike -1e9 which overflows fp16)
scores = scores.masked_fill(mask == 0, float("-inf"))
attn_weights = torch.softmax(scores, dim=-1)
output = torch.matmul(attn_weights, v)
return output, attn_weights
class SelfAttention(nn.Module):
def __init__(self, d_model, d_k=None, d_v=None):
super().__init__()
d_k = d_k or d_model
d_v = d_v or d_model
self.W_q = nn.Linear(d_model, d_k, bias=False)
self.W_k = nn.Linear(d_model, d_k, bias=False)
self.W_v = nn.Linear(d_model, d_v, bias=False)
def forward(self, x, causal=False):
q, k, v = self.W_q(x), self.W_k(x), self.W_v(x)
mask = None
if causal:
seq_len = x.size(1)
mask = torch.tril(torch.ones(seq_len, seq_len, device=x.device)).unsqueeze(0)
return scaled_dot_product_attention(q, k, v, mask=mask)
torch.manual_seed(0)
x = torch.randn(2, 4, 64) # (batch_size=2, seq_len=4, d_model=64)
self_attn = SelfAttention(d_model=64, d_k=64, d_v=128)
output, weights = self_attn(x, causal=True)
print("Output shape:", output.shape) # (2, 4, 128)
print("Attention weights shape:", weights.shape) # (2, 4, 4)
print("Causal weights (batch 0):\n", weights[0].detach().round(decimals=3))
Related Concepts
- Multi-Head Attention: Runs independent Q/K/V projections in parallel subspaces, preventing a single softmax map from averaging distinct relations.
- FlashAttention: Fuses tiling, online softmax, and recomputation in GPU SRAM to eliminate HBM materialization without changing exact math.
- KV Caching: Stores past and tensors during autoregressive decoding so each generated token computes only attention rather than recomputing the full prefix.
- Positional Encoding & RoPE: Essential companion since pure self-attention is permutation-equivariant.