Building and Analyzing Scaled Dot-Product Attention
Machine LearningModel answerLast updated
Implement a production-grade multi-head attention module in PyTorch, handle numerical precision and causal masking, and analyze performance trade-offs for large sequences.
In modern Transformer architectures, scaled dot-product attention serves as the core building block for context modeling.
- Implementation: Write a complete, vectorized PyTorch implementation of Multi-Head Scaled Dot-Product Attention (MHA) from scratch using
torch.nn.Module. Your implementation should support arbitrary batch dimensions, arbitrary sequence lengths, linear projection layers, optional dropout, dynamic padding masks, and causal masking options. - Numerical & Architectural Details:
- Explain why the scaling factor $1 / \sqrt{d_k}$ is mathematically necessary.
- Explain how to maintain numerical stability during mixed-precision execution (e.g., FP16/BF16) when applying soft-max over masked entries.
- Explain the gradient implications when adding a static linear bias to key vectors.
- Complexity & Scaling: Analyze the computational complexity (FLOPs) and memory footprint with respect to sequence length $N$ and hidden dimension $D$. Describe two algorithmic strategies used to scale attention to long context lengths ($N \gg 10^4$).
Hints
Hint 1
Recall that the variance of the dot product of two independent random vectors with zero mean and variance 1 scales with the vector dimension.
Hint 2
Consider how -inf values interact with float16 range limits and how subtraction of maximum row values stabilizes exponentiation.
Hint 3
For memory analysis, pay attention to the space required to store intermediate attention matrices during the forward pass for backpropagation.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Architectural & Theoretical Analysis
The $1 / \sqrt{d_k}$ Scaling Factor
Let $q, k \in \mathbb{R}^{d_k}$ be query and key vectors whose elements are independent random variables with zero mean ($\mathbb{E}[q_i] = \mathbb{E}[k_i] = 0$) and unit variance ($\text{Var}(q_i) = \text{Var}(k_i) = 1$).
The dot product is $S = \sum_{i=1}^{d_k} q_i k_i$.
- Expectation: $\mathbb{E}[S] = \sum_{i=1}^{d_k} \mathbb{E}[q_i k_i] = 0$
- Variance: $\text{Var}(S) = \sum_{i=1}^{d_k} \text{Var}(q_i k_i) = \sum_{i=1}^{d_k} \mathbb{E}[q_i^2] \mathbb{E}[k_i^2] = d_k$
As $d_k$ grows large, the variance of the dot products scales linearly with $d_k$, pushing the inputs to the $\text{softmax}$ function into regions with extremely small gradients (saturation). Scaling by $1 / \sqrt{d_k}$ ensures that $\text{Var}(S / \sqrt{d_k}) = 1$, preventing gradient vanishing during early training phases.
Numerical Stability in Mixed Precision
When using half-precision formats (torch.float16), large logit magnitudes produce overflow (+inf) during exp(). Furthermore, applying $-\infty$ masks directly in lower precision can result in NaN values when evaluating standard softmax forms like $\frac{e^{-\infty}}{\sum e^{-\infty}} = \frac{0}{0}$.
To guarantee stability:
- Upcast internal calculations: Compute scaled scores and softmax operations in
torch.float32. - Safe Max Subtraction: Compute $\tilde{S}{ij} = S{ij} - \max_j(S_{ij})$. For completely masked rows (where all entries are $-\infty$), set the shifted max to $0$ via masking to avoid $(-\infty) - (-\infty) = \text{NaN}$.
- Clamp Denominator: Clamp the sum of exponentials with a small positive constant $\epsilon = \text{finfo}(\text{fp32}).\text{tiny}$ to avoid division by zero.
Gradient Behavior on Key Bias
If a bias vector $b_k \in \mathbb{R}^{d_k}$ is added to every key vector ($k_j \leftarrow k_j + b_k$), the resulting logit score becomes: $$S_{ij} = \frac{q_i^\top (k_j + b_k)}{\sqrt{d_k}} = \frac{q_i^\top k_j}{\sqrt{d_k}} + \frac{q_i^\top b_k}{\sqrt{d_k}}$$ For a fixed query $i$, the term $c_i = \frac{q_i^\top b_k}{\sqrt{d_k}}$ is constant across all key indices $j$. Because $\text{softmax}(z + c)_j = \text{softmax}(z)_j$, adding a uniform vector bias to keys leaves the post-softmax attention distributions completely unchanged. As a result, the partial derivative of the loss with respect to key linear projections' additive bias components is zero.
2. PyTorch Implementation
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def scaled_dot_product_attention(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
mask: torch.Tensor = None,
dropout_p: float = 0.0,
is_causal: bool = False,
training: bool = True
):
"""
Computes Scaled Dot-Product Attention over multi-head tensor inputs.
q, k, v: (B, H, L, d_k)
mask: Optional boolean tensor broadcastable to (B, H, L_q, L_k). True indicates valid context.
Returns: (output tensor of shape (B, H, L_q, d_v), weights tensor of shape (B, H, L_q, L_k))
"""
d_k = q.size(-1)
L_q, L_k = q.size(-2), k.size(-2)
orig_dtype = q.dtype
# Cast scores to float32 for stable log-sum-exp behavior across mixed precision
q_32, k_32 = q.to(torch.float32), k.to(torch.float32)
scores = torch.matmul(q_32, k_32.transpose(-2, -1)) / math.sqrt(d_k)
# Combine user padding mask with causal lower-triangular mask
if is_causal:
causal_mask = torch.tril(torch.ones((L_q, L_k), dtype=torch.bool, device=q.device))
mask = causal_mask if mask is None else (mask & causal_mask)
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
# Numerically safe softmax computation
max_scores = scores.amax(dim=-1, keepdim=True).detach()
# Handle rows where all elements are masked out (-inf)
max_scores = torch.where(torch.isfinite(max_scores), max_scores, torch.zeros_like(max_scores))
exp_scores = torch.exp(scores - max_scores)
if mask is not None:
exp_scores = exp_scores.masked_fill(~mask, 0.0)
sum_exp = exp_scores.sum(dim=-1, keepdim=True)
attn_weights = exp_scores / sum_exp.clamp_min(torch.finfo(torch.float32).tiny)
if training and dropout_p > 0.0:
attn_weights = F.dropout(attn_weights, p=dropout_p)
output = torch.matmul(attn_weights, v.to(torch.float32))
return output.to(orig_dtype), attn_weights.to(orig_dtype)
class MultiHeadAttention(nn.Module):
def __init__(self, d_model: int, n_heads: int, dropout: float = 0.0):
super().__init__()
assert d_model % n_heads == 0, "d_model must be divisible by n_heads"
self.d_model = d_model
self.n_heads = n_heads
self.d_k = d_model // n_heads
# Combined projection for efficiency
self.qkv_proj = nn.Linear(d_model, 3 * d_model)
self.out_proj = nn.Linear(d_model, d_model)
self.dropout = dropout
def forward(
self,
x: torch.Tensor,
mask: torch.Tensor = None,
is_causal: bool = False
) -> torch.Tensor:
"""
x: (B, N, d_model)
mask: Optional boolean tensor of shape (B, 1, 1, N) or broadcastable
"""
B, N, D = x.shape
# 1. Linear Projections and reshape to (B, H, N, d_k)
qkv = self.qkv_proj(x) # (B, N, 3 * D)
qkv = qkv.view(B, N, 3, self.n_heads, self.d_k).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
# 2. Scaled Dot-Product Attention
context, _ = scaled_dot_product_attention(
q, k, v, mask=mask, dropout_p=self.dropout, is_causal=is_causal, training=self.training
)
# 3. Concatenate heads and project back to d_model
context = context.permute(0, 2, 1, 3).contiguous().view(B, N, D)
return self.out_proj(context)
3. Complexity & Scaling Analysis
Time and Memory Complexity
For batch size $B$, sequence length $N$, and model dimension $D$ across $H$ heads ($d_k = D/H$):
-
FLOPs (Time Complexity):
- Linear Projections ($Q, K, V$): $\mathcal{O}(B \cdot N \cdot D^2)$
- Matrix Multiplication ($Q K^\top$): $\mathcal{O}(B \cdot H \cdot N^2 \cdot d_k) = \mathcal{O}(B \cdot N^2 \cdot D)$
- Softmax & Dropout: $\mathcal{O}(B \cdot H \cdot N^2)$
- Weight Projection ($A V$): $\mathcal{O}(B \cdot N^2 \cdot D)$
- Final Linear Projection: $\mathcal{O}(B \cdot N \cdot D^2)$
- Total Computation: $\mathcal{O}(B \cdot N \cdot D^2 + B \cdot N^2 \cdot D)$
-
Memory Footprint:
- Without memory optimization, storing intermediate activations for the attention score matrix $S \in \mathbb{R}^{B \times H \times N \times N}$ requires $\mathcal{O}(B \cdot H \cdot N^2)$ memory during backpropagation.
- At $N = 32,000$ and $H = 32$, a single precision $N \times N$ matrix per head takes over $130\text{ GB}$ of VRAM, making naive attention infeasible.
Optimization Strategies for Long Sequences
-
FlashAttention (Tiling & Online Softmax):
- Mechanism: FlashAttention avoids materializing the $N \times N$ attention matrix in HBM (High Bandwidth Memory). It computes attention block by block using SRAM via an online incremental softmax technique.
- Impact: Reduces activation memory overhead from $\mathcal{O}(N^2)$ to $\mathcal{O}(N)$, yielding a $2\times$–$4\times$ speedup by drastically cutting memory access bottlenecks without modifying mathematical outputs.
-
Linear & Sparse Approximations (e.g., Kernelized Attention / Local Windowing):
- Mechanism: Replaces standard dot-product attention with kernel feature maps $\phi(Q)\phi(K)^\top V$ to leverage matrix associativity $(\phi(Q) (\phi(K)^\top V))$, computing context in $\mathcal{O}(N \cdot D^2)$ time.
- Alternative: Sliding window (local) attention restricts each token's receptive field to a fixed window $w \ll N$, dropping computation complexity down to $\mathcal{O}(N \cdot w \cdot D)$.
4. Verification & Testing Suite
def test_attention_correctness():
# 1. Gradient flow and Autograd compliance test
q = torch.randn(2, 2, 4, 8, dtype=torch.float64, requires_grad=True)
k = torch.randn(2, 2, 4, 8, dtype=torch.float64, requires_grad=True)
v = torch.randn(2, 2, 4, 8, dtype=torch.float64, requires_grad=True)
def func(q_in, k_in, v_in):
out, _ = scaled_dot_product_attention(q_in, k_in, v_in, training=False)
return out
assert torch.autograd.gradcheck(func, (q, k, v)), "Gradcheck failed!"
# 2. Causality leakage verification
mha = MultiHeadAttention(d_model=16, n_heads=2)
mha.eval()
x1 = torch.randn(1, 8, 16)
x2 = x1.clone()
x2[:, 4:, :] += 10.0 # Modify future tokens starting at index 4
out1 = mha(x1, is_causal=True)
out2 = mha(x2, is_causal=True)
# Prefix outputs up to index 4 must remain identical
assert torch.allclose(out1[:, :4, :], out2[:, :4, :], atol=1e-5), \
"Causal masking leak detected! Future token modifications affected past outputs."
print("All unit tests passed successfully!")
if __name__ == "__main__":
test_attention_correctness()