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.

Signaturedef attn_flops(seq_len, d_model, n_layers, causal=False)

Example

attn_flops(1024, 4096, 1) is 4 * 1024^2 * 4096 = 17179869184.

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. Worked example: 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. Rule: 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleattn_flops(1024, 4096, 1)
  • Sample 2: causalattn_flops(2048, 4096, 32, causal=True)
  • Test 3: smallattn_flops(8, 16, 2)