393. Count attention FLOPs for a sequence
Why it matters This term is why long-context models need FlashAttention and sparse attention.
The quadratic part of attention is the QK^T and AV matmuls.
Write attn_flops(seq_len, d_model, n_layers, causal=False). Count 2 * seq_len^2 * d_model FLOPs for QK^T and the same for AV per layer (a multiply-add is 2 FLOPs). If causal, halve the total. Return the total over layers as an int.
def attn_flops(seq_len, d_model, n_layers, causal=False)Example 1
Input: attn_flops(1024, 4096, 1)
Output: 4 * 1024^2 * 4096 = 17179869184
Example 2
Input: seq_len = 2048, d_model = 4096, n_layers = 32, causal = True
Output: 1099511627776
Example 3
Input: seq_len = 8, d_model = 16, n_layers = 2
Output: 8192
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Per layer: 4 * L^2 * d.
Hint 2
Two matmuls of 2 L^2 d each.
Common mistakes
- Counting only QK^T.
- Forgetting that a multiply-add is 2 FLOPs.
Understand the idea
Attention has two matrix multiplies whose cost grows with the square of sequence length: scores QK^T and the weighted sum AV. A multiply-add counts as 2 FLOPs. QK^T multiplies (L, d) by (d, L), giving L * L outputs, each needing d multiply-adds, so 2 * L^2 * d FLOPs. AV costs the same. Causal masking lets an efficient kernel skip about half the work.
seq_len 512, d_model 1024, 2 layers. Per layer: 4 * 512^2 * 1024 = 4 * 262,144 * 1,024 = 1,073,741,824. Two layers give 2,147,483,648. With causal=True, halve it to 1,073,741,824.
total = n_layers * 4 * seq_len^2 * d_model, halved if causal, returned as an int (use integer arithmetic so the result is exact)
This counts only the quadratic part, not the Q, K, V and output projections, which grow linearly with length. Used in: estimating when long context becomes attention-bound, planning GPU budgets, and explaining why FlashAttention and sparse attention matter.
Companies1
- Meta the topic appears in interview reports Machine Learning interview questions, page 10 (KatKat)
From public interview reports and guides. Not affiliated with or endorsed by these companies.