Attention and a small Transformer with a hand-written backward pass
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Tesla's technical phone screen, last asked Aug 2025. It tests transformers, attention and backpropagation.
Implement multi-head scaled dot-product attention and a Transformer block from scratch, with no autograd. Write both the forward and the backward pass for the attention module by hand, train it autoregressively, and check your gradients numerically. You may assume a softmax backward function is already available.
Part 1: forward
Unless you agree on a different interface with the interviewer, assume:
-
attention_forward(X, W_q, W_k, W_v, W_o, h) -> (out, cache)—Xhas shape(B, T, d_model); eachWhas shape(d_model, d_model);hheads withhead_dim = d_model / h. ComputeQ, K, V, split into heads(B, h, T, head_dim),scores = Q Kᵀ / sqrt(head_dim), apply the causal mask (positiontsees only positions<= t), softmax, multiply byV, merge the heads, project withW_o.cachekeeps what the backward pass needs. - For a full block, add the residual connection, LayerNorm and the position-wise feed-forward sublayer.
X: (2, 5, 16), h = 4 -> head_dim 4, scores (2, 4, 5, 5), out (2, 5, 16)
Part 2: backward
-
attention_backward(d_out, cache) -> (dX, dW_q, dW_k, dW_v, dW_o)— the gradients through the output projection, the head merge and split,attn @ V, the softmax (use the given backward), the mask, the scaling and the three input projections.
Part 3: autoregressive training
Define the next-token cross-entropy loss with teacher forcing, show where the causal mask is applied, and compute perplexity from the loss.
Part 4: verify
Check every gradient with finite differences on small tensors and report the largest relative error. Discuss numerical stability.
Constraints
- NumPy only. State the shape of every tensor at each step.
Clarifying questions
- Is
Xused forQ,KandV(self-attention)? - Are there biases on the projections?
- Pre-LayerNorm or post-LayerNorm in the block?
- Should masked positions use
-infor a large negative number?
What a strong answer covers
- Correct shapes and transposes for splitting and merging heads.
- The causal mask applied to the scores before softmax, and zero gradient flowing to masked positions.
- Gradients:
dW_o = concatᵀ · d_out;dV = attnᵀ · d_attn_out;d_attn = d_attn_out · Vᵀ; softmax backward to getd_scores;dQ = d_scores · K / sqrt(head_dim)anddK = d_scoresᵀ · Q / sqrt(head_dim); then back through the projections, withdXsumming the three paths. - A stable softmax that subtracts the row maximum, and log-sum-exp in the loss.
- Finite-difference checks with central differences in float64, and the relative-error threshold that counts as passing.
- Cost: O(B·T²·d_model) time and O(B·h·T²) memory for the attention weights.
Follow-ups
- Write the softmax backward yourself.
- Add a KV cache for generation. What changes in the forward pass?
- How would you reduce the T² memory of the attention matrix?
- Write the LayerNorm backward.
Where it's asked
- Tesla · Technical phone screen · Last asked Aug 202545 min · 10 to 20 minutes on your background, then one compact coding, debugging or design task in CoderPad that must run
What it tests
transformers · attention · backpropagation · numpy
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
