KatInterview

Implement Scaled Dot-Product Attention and Manual Backward Pass

Machine LearningModel answer
HardModel answerMachine Learningtransformersattentionbackpropagation

Last 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:

  1. 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.
  2. 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))$.
  3. 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.
  4. 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.