Implement Scaled Dot-Product Attention With a Causal Mask
Last updated: November 29, 2026
Quick Overview
Implement scaled dot-product attention in NumPy, with an optional causal mask, and explain why the scores are divided by the square root of the key dimension.
Meta
November 29, 20260
0
0 solved
Implement scaled dot-product attention in NumPy, with an optional causal mask, and explain why the scores are divided by the square root of the key dimension.
Meta's Llama work makes transformer internals fair game in MLE screens, often as a short coding exercise. The interviewer checks shapes, numerical stability, correct masking, and that you can justify the scaling factor rather than memorize it.
What the Interviewer Expects
- Get the shapes right for Q, K, V and the output
- Apply the causal mask before the softmax with negative infinity
- Subtract the row max for numerical stability
- Explain the variance argument for dividing by sqrt(d)
- State time and memory complexity in sequence length
Key Topics to Cover
How to Approach This
- Understand the bias-variance trade-off. High training accuracy but low test accuracy signals overfitting.
- Choose evaluation metrics carefully based on the problem. Accuracy alone is often insufficient.
- Feature engineering is often more impactful than model selection.
- Know when to use tree-based models (tabular data) vs neural networks (unstructured data).
- Handle class imbalance with SMOTE, class weights, or appropriate loss functions.
Possible Follow-up Questions
- How does this change for multi-head attention?
- Why does the mask offset matter when decoding with a KV cache?
- How does FlashAttention avoid materializing the n by m score matrix?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Explore ML Interview PrepSample Answer
Clarify
Inputs: queries , keys , values . Output is . With a causal mask, query may only attend...
Approach
where is 0 for allowed positions and for masked ones. Query row corresponds to absolute position $i + ...