A Transformer Block
🧱 What is a transformer block? A transformer block is the unit a transformer repeats: attention, which mixes information across positions, then a small feed-forward network, which processes each position on its own. Each sublayer adds its output back to its input (a residual connection) and a layer norm keeps the scale under control. Stack N of them between an embedding and an output layer and you have the whole model.
Waymo asked a senior machine learning engineer to write a transformer encoder that runs in CoderPad
(x -> qkv -> MHA -> FFN -> y), then asked why scores are divided by sqrt(d_k), encoder-decoder against
decoder-only, and complexity (the question). Anthropic's
research scientist online assessment, in pure NumPy, built a one-layer transformer in five parts, starting with
softmax, an attention head and a single-layer transformer, followed by a part with token embeddings, attention
scores and bigram scores (the question). An Anthropic ML
phone screen gave a figure from the Attention Free Transformer paper to implement, then asked for hand-written
tests that turned out to be about overflow and numerical stability (the question).
The Prompt
The block is short, so the interviewer grades the wiring: where the norms and residuals go, what the feed-forward layer looks like, the padding mask, and whether you can say why each piece is there.
"Implement a transformer encoder layer in PyTorch: multi-head self-attention and a feed-forward network, with residual connections and layer norm. Input and output are
(B, T, D)."
Clarifying Questions
You: Pre-norm or post-norm? The original paper normalizes after each residual add; most current models normalize the input to each sublayer.
Interviewer: Support both with a flag, and tell me which you'd use.
You: What is the feed-forward layer? I'll assume D -> 4D -> D with GELU, and biases everywhere.
Interviewer: Fine. Make the hidden width a parameter.
You: Is there a padding mask? An encoder has no causal mask.
Interviewer: A (B, T) boolean, True for real tokens. No causal mask.
You: Dropout, and can I test against nn.TransformerEncoderLayer?
Interviewer: No dropout. Yes, test against it, but don't use it in your code.
What You'll Build
MultiHeadAttention(D, H):forward(x, key_mask)maps(B, T, D)to(B, T, D).FeedForward(D, hidden):D -> hidden -> Dwith GELU, applied to each position.EncoderLayer(D, H, hidden, pre_norm): one block,(B, T, D) -> (B, T, D).- A depth experiment that shows why the residuals and the norm placement matter.