Implement Scaled Dot-Product Attention and Manual Backward Pass
Machine LearningModel answerLast updated
Derive and implement the forward and backward passes for scaled dot-product multi-head attention without autograd, alongside causal masking and numerical stability considerations.
Implement scaled dot-product multi-head causal attention and a manual backward pass without relying on automatic differentiation.
Assume an input sequence tensor $X \in \mathbb{R}^{B \times T \times d_{\text{model}}}$, $h$ heads ($d_{\text{head}} = d_{\text{model}} / h$), and learnable linear projections $W_q, W_k, W_v, W_o \in \mathbb{R}^{d_{\text{model}} \times d_{\text{model}}}$.
Your answer should cover the following four areas:
- Forward Pass: Detail step-by-step tensor operations and shapes for computing Query, Key, and Value projections, splitting into heads, scaled matrix multiplication, applying a causal mask, Softmax activation, head concatenation, and output projection. Show how this fits into a standard Transformer block.
- Backward Pass: Explicitly derive the analytical gradients with respect to input $X$ and projection matrices $W_q, W_k, W_v, W_o$, assuming standard Softmax backward gradient vector-Jacobian product (VJP) is provided as $\text{dS} = P \odot (\text{dP} - \text{sum}(\text{dP} \odot P, \text{axis}=-1))$.
- Autoregressive Masking and Loss: Explain how teacher forcing operates, where causal masking prevents look-ahead leakage, and how cross-entropy loss and perplexity are evaluated.
- Verification and Stability: Address numerical stability techniques (e.g., stabilized Softmax, log-sum-exp), gradient accumulation over batch and time dimensions, and how to verify implementation correctness via finite-difference gradient checking.
Hints
Hint 1
Recall the matrix calculus rules for matrix multiplication Y = A B: dA = dY B^T and dB = A^T dY.
Hint 2
When splitting dimensions for multi-head attention, keep track of transpose permutations: the gradient of a permutation is its inverse permutation.
Hint 3
Because parameters W_q, W_k, W_v, W_o are shared across the batch and sequence length dimensions, their gradients must be accumulated (summed) across the batch (B) and time (T) axes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Multi-Head Causal Self-Attention: Forward and Backward Mechanics
Below is a complete mathematical, analytical, and practical implementation guide for multi-head self-attention and its backward pass without automatic differentiation.
1. Forward Pass Specifications
Let the input sequence be $X \in \mathbb{R}^{B \times T \times D}$, where $B$ is batch size, $T$ is sequence length, and $D = d_{\text{model}}$.
Given $h$ heads, each head has dimension $d_h = D / h$.
Step-by-Step Operation and Shapes
-
Linear Projections: $$Q_{\text{full}} = X W_q, \quad K_{\text{full}} = X W_k, \quad V_{\text{full}} = X W_v \quad \in \mathbb{R}^{B \times T \times D}$$
-
Split Heads: Reshape $(B, T, D) \to (B, T, h, d_h)$ and transpose axes $(0, 2, 1, 3)$ to yield shape $(B, h, T, d_h)$ for $Q, K, V$.
-
Scaled Dot-Product Scores: $$S = \frac{Q K^T}{\sqrt{d_h}} \in \mathbb{R}^{B \times h \times T \times T}$$
-
Causal Masking: Apply an upper-triangular mask $M$ where $M_{ij} = -\infty$ for $j > i$, and $0$ otherwise: $$\tilde{S}{b,c,i,j} = S{b,c,i,j} + M_{i,j}$$
-
Softmax: $$P = \text{softmax}(\tilde{S}, \text{axis}=-1) \in \mathbb{R}^{B \times h \times T \times T}$$
-
Context Aggregation & Merge Heads: $$O_{\text{heads}} = P V \in \mathbb{R}^{B \times h \times T \times d_h}$$ Transpose axes $(0, 2, 1, 3) \to (B, T, h, d_h)$ and reshape to $M_{\text{merged}} \in \mathbb{R}^{B \times T \times D}$.
-
Output Projection: $$Y = M_{\text{merged}} W_o \in \mathbb{R}^{B \times T \times D}$$
2. Analytical Backward Pass Derivation
Using the chain rule in reverse order:
1. Output Projection $W_o$ and Merged Representation
For $Y = M_{\text{merged}} W_o$: $$\frac{\partial L}{\partial W_o} = \sum_{b=1}^{B} M_{\text{merged}, b}^T \cdot dY_b \quad \in \mathbb{R}^{D \times D}$$ $$dM_{\text{merged}} = dY W_o^T \quad \in \mathbb{R}^{B \times T \times D}$$
2. Head Un-merging
$dO_{\text{heads}}$ is obtained by reshaping $dM_{\text{merged}}$ to $(B, T, h, d_h)$ and transposing to $(B, h, T, d_h)$.
3. Attention Values and Softmax Probabilities
For $O_{\text{heads}} = P V$: $$dP = dO_{\text{heads}} V^T \quad \in \mathbb{R}^{B \times h \times T \times T}$$ $$dV = P^T dO_{\text{heads}} \quad \in \mathbb{R}^{B \times h \times T \times d_h}$$
4. Softmax and Scaling
The provided VJP for Softmax $\text{softmax_backward}(P, dP)$ computes $d\tilde{S}$: $$d\tilde{S} = P \odot \left( dP - \sum_{k} (dP \odot P){..., k} \right)$$ Because masked entries have $P{ij} = 0$, $d\tilde{S}_{ij} = 0$ automatically for masked positions.
Accounting for the scaling factor $\frac{1}{\sqrt{d_h}}$: $$dS = \frac{d\tilde{S}}{\sqrt{d_h}}$$
5. Queries and Keys
For $S = \frac{Q K^T}{\sqrt{d_h}}$: $$dQ = dS \cdot K \quad \in \mathbb{R}^{B \times h \times T \times d_h}$$ $$dK = dS^T \cdot Q \quad \in \mathbb{R}^{B \times h \times T \times d_h}$$
6. Head Re-merging and Parameter Gradients
Reshape and transpose $dQ, dK, dV$ back to $(B, T, D)$, yielding $dQ_{\text{full}}, dK_{\text{full}}, dV_{\text{full}}$.
For projections $Q_{\text{full}} = X W_q$, $K_{\text{full}} = X W_k$, $V_{\text{full}} = X W_v$: $$\frac{\partial L}{\partial W_q} = \sum_{b=1}^{B} X_b^T \cdot dQ_{\text{full}, b}, \quad \frac{\partial L}{\partial W_k} = \sum_{b=1}^{B} X_b^T \cdot dK_{\text{full}, b}, \quad \frac{\partial L}{\partial W_v} = \sum_{b=1}^{B} X_b^T \cdot dV_{\text{full}, b}$$
Because $X$ feeds into all three projection pathways (fan-out), its gradient accumulates all three components: $$dX = dQ_{\text{full}} W_q^T + dK_{\text{full}} W_k^T + dV_{\text{full}} W_v^T \quad \in \mathbb{R}^{B \times T \times D}$$
3. Python Implementation
import numpy as np
def softmax(x, axis=-1):
x_max = np.max(x, axis=axis, keepdims=True)
exp_x = np.exp(x - x_max)
return exp_x / np.sum(exp_x, axis=axis, keepdims=True)
def softmax_backward(P, dP):
"""
Computes gradient through softmax given forward probabilities P and upstream dP.
"""
sum_dP_P = np.sum(dP * P, axis=-1, keepdims=True)
return P * (dP - sum_dP_P)
def split_heads(x, h):
B, T, D = x.shape
return x.reshape(B, T, h, D // h).transpose(0, 2, 1, 3)
def merge_heads(x):
B, h, T, dh = x.shape
return x.transpose(0, 2, 1, 3).reshape(B, T, h * dh)
def mha_forward(X, weights, h):
"""
X: (B, T, D)
weights: dict containing Wq, Wk, Wv, Wo each of shape (D, D)
"""
B, T, D = X.shape
dh = D // h
scale = 1.0 / np.sqrt(dh)
# 1. Projections & Head splitting
Q = split_heads(X @ weights["Wq"], h) # (B, h, T, dh)
K = split_heads(X @ weights["Wk"], h) # (B, h, T, dh)
V = split_heads(X @ weights["Wv"], h) # (B, h, T, dh)
# 2. Score computation
S = (Q @ K.transpose(0, 1, 3, 2)) * scale # (B, h, T, T)
# 3. Causal masking
mask = np.triu(np.ones((T, T), dtype=bool), k=1)
S_masked = np.where(mask, -1e9, S)
# 4. Softmax
P = softmax(S_masked, axis=-1) # (B, h, T, T)
# 5. Output aggregation & projection
O = P @ V # (B, h, T, dh)
M = merge_heads(O) # (B, T, D)
Y = M @ weights["Wo"] # (B, T, D)
cache = (X, Q, K, V, P, M, scale, h)
return Y, cache
def mha_backward(dY, cache, weights):
X, Q, K, V, P, M, scale, h = cache
# Gradient of Wo and M
dW_o = np.einsum("btd,bte->de", M, dY)
dM = dY @ weights["Wo"].T
# Gradient through merge_heads
dO = split_heads(dM, h)
# Gradient through P @ V
dP = dO @ V.transpose(0, 1, 3, 2)
dV_heads = P.transpose(0, 1, 3, 2) @ dO
# Gradient through Softmax and Scaling
dS = softmax_backward(P, dP) * scale
# Gradient through Q @ K^T
dQ_heads = dS @ K
dK_heads = dS.transpose(0, 1, 3, 2) @ Q
# Re-merge heads for Q, K, V
dQ = merge_heads(dQ_heads)
dK = merge_heads(dK_heads)
dV = merge_heads(dV_heads)
# Gradients for linear projections
dW_q = np.einsum("btd,bte->de", X, dQ)
dW_k = np.einsum("btd,bte->de", X, dK)
dW_v = np.einsum("btd,bte->de", X, dV)
# Gradient for input X (accumulated over 3 projection branches)
dX = (dQ @ weights["Wq"].T) + (dK @ weights["Wk"].T) + (dV @ weights["Wv"].T)
grads = {"Wq": dW_q, "Wk": dW_k, "Wv": dW_v, "Wo": dW_o}
return dX, grads
4. Autoregressive Training & Numerical Considerations
Teacher Forcing and Loss Computation
In autoregressive language modeling, input tokens are shifted right relative to targets:
- Inputs: $\text{tokens}[:, :-1]$
- Targets: $\text{tokens}[:, 1:]$
The causal mask ensures prediction at index $t$ depends strictly on indices $\le t$.
Given output logits $L \in \mathbb{R}^{B \times T \times V}$, the cross-entropy loss and perplexity (PPL) are computed using numerically stable Log-Sum-Exp: $$\mathcal{L} = -\frac{1}{B \cdot T} \sum_{b, t} \left( L_{b, t, y_{b,t}} - \text{logsumexp}(L_{b, t, :}) \right)$$ $$\text{Perplexity} = \exp(\mathcal{L})$$
Finite-Difference Gradient Verification
To verify the analytical backward pass, check numeric gradients using central differences: $$f'(x) \approx \frac{f(x + \epsilon) - f(x - \epsilon)}{2\epsilon}$$
def check_gradient(f, x, analytic_grad, eps=1e-5, tol=1e-6):
numeric_grad = np.zeros_like(x)
it = np.nditer(x, flags=["multi_index"], op_flags=["readwrite"])
while not it.finished:
idx = it.multi_index
orig_val = x[idx]
x[idx] = orig_val + eps
pos_loss = f()
x[idx] = orig_val - eps
neg_loss = f()
x[idx] = orig_val
numeric_grad[idx] = (pos_loss - neg_loss) / (2 * eps)
it.iternext()
rel_error = np.abs(analytic_grad - numeric_grad) / np.maximum(
1e-8, np.abs(analytic_grad) + np.abs(numeric_grad)
)
max_err = np.max(rel_error)
print(f"Max Relative Gradient Error: {max_err:.2e}")
assert max_err < tol, f"Gradient check failed! Max relative error: {max_err}"
Time and Memory Complexity
| Phase | Operation | Time Complexity | Memory Complexity |
|---|---|---|---|
| Forward | Linear Projections ($W_q, W_k, W_v, W_o$) | $\mathcal{O}(B \cdot T \cdot D^2)$ | $\mathcal{O}(B \cdot T \cdot D)$ |
| Attention Scores & Context ($QK^T, PV$) | $\mathcal{O}(B \cdot h \cdot T^2 \cdot d_h) = \mathcal{O}(B \cdot T^2 \cdot D)$ | $\mathcal{O}(B \cdot h \cdot T^2)$ | |
| Backward | Full Pass | $\mathcal{O}(B \cdot T \cdot D^2 + B \cdot T^2 \cdot D)$ | $\mathcal{O}(B \cdot h \cdot T^2 + B \cdot T \cdot D)$ |
Note: The $\mathcal{O}(B \cdot h \cdot T^2)$ memory footprint for storing attention weights $P$ is the primary memory bottleneck during backpropagation. Algorithms like FlashAttention mitigate this by recomputing attention blocks on-the-fly during the backward pass instead of caching the full matrix $P$.