Senior interview questionAsked at Tesla · interview write-up
Implement scaled dot-product multi-head attention and a Transformer block from scratch, including the backward pass for attention, without autograd.
Model answer
Have the forward pass cache what the backward pass needs: the softmax probabilities P.
def attn_fwd(Q, K, V): # (T, d) each
S = Q @ K.T / np.sqrt(Q.shape[-1])
S = S - S.max(-1, keepdims=True)
P = np.exp(S)
P /= P.sum(-1, keepdims=True)
return P @ V, P
def attn_bwd(dO, Q, K, V, P):
dV = P.T @ dO
dP = dO @ V.T
dS = P * (dP - (dP * P).sum(-1, keepdims=True))
dS /= np.sqrt(Q.shape[-1])
return dS @ K, dS.T @ Q, dV # dQ, dK, dV
The key line is the softmax backward: each row's gradient is P times dP minus its P-weighted mean. Multi-head attention reshapes into heads around this, and a block adds residuals, LayerNorm and an MLP, each with its own backward. Prove it with a finite-difference gradient check.
Practise the rest
20 Attention questions, 492 in all, each with a model answer. Free.
More from Tesla interview questions.
More Attention interview questions
- Walk me through scaled dot-product attention. What are queries, keys and values, and why divide by the square root of d?
- What's inside one transformer block, and where do most of its parameters sit?
- What does the causal mask do, and what does it imply for a decoder model reading 'The ladder did not reach the window because it was too short'?
- A teammate shows you a GPT-2 head that puts most of a pronoun's attention on the right noun and concludes that the head resolves pronouns. How do you respond?
- Product wants to double the context you support, from 1,000 to 2,000 tokens. From the attention side, what gets more expensive, and what families of fixes would you weigh?
- Implement batched multi-head self-attention with a causal mask.