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
Machine Learning
Machine Learning Engineer
Meta
November 29, 2026
Machine Learning Engineer
Technical Screen
Machine Learning
Easy

0

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
self-attention
causal masking
softmax stability
transformers
NumPy
How to Approach This
  1. Understand the bias-variance trade-off. High training accuracy but low test accuracy signals overfitting.
  2. Choose evaluation metrics carefully based on the problem. Accuracy alone is often insufficient.
  3. Feature engineering is often more impactful than model selection.
  4. Know when to use tree-based models (tabular data) vs neural networks (unstructured data).
  5. 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 Prep
Sample Answer
Clarify

Inputs: queries Q∈Rn×dQ \in \mathbb{R}^{n \times d}, keys K∈Rm×dK \in \mathbb{R}^{m \times d}, values V∈Rm×dvV \in \mathbb{R}^{m \times d_v}. Output is n×dvn \times d_v. With a causal mask, query ii may only attend...

Approach

Attn(Q,K,V)=softmax(QK⊤d+M)V\text{Attn}(Q,K,V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d}} + M\right)V where MM is 0 for allowed positions and −∞-\infty for masked ones. Query row ii corresponds to absolute position $i + ...


Submit Your Answer
Markdown supported