Count the matrix-multiply FLOPs of one transformer layer's forward pass for sequence length n=2048, model width d=1024 and feed-forward width dff=4d (one sequence, ignoring softmax, layer norm and biases). Which part dominates, and at what n does attention's n2 term equal the linear-in-n part?

Sequence models and transformers, Transformers
Level L3 Intermediate. Length Long. Nature Mat Mathematical.

What's being asked

Whether you can count multiply–adds for each matrix product and compare the O(nd2) and O(n2d) parts.

Key idea

Multiplying an m×k matrix by a k×p matrix costs 2mkp FLOPs. One layer costs 24nd2+4n2d FLOPs, so the n2 part equals the rest at n=6d.

Steps

  1. Q, K, V and output projections are four products (n×d)(d×d): 4×2nd2=8nd2.
  2. Scores QK⊤ over all heads together: (n×d)(d×n) costs 2n2d. Applying weights to V: (n×n)(n×d) costs another 2n2d. Total 4n2d.
  3. Feed-forward with dff=4d: two products (n×d)(d×4d) and (n×4d)(4d×d) cost 2×2n⋅d⋅4d=16nd2.
  4. Total: 24nd2+4n2d.
  5. Numbers: 24×2048×10242=5.15×1010 and 4×20482×1024=1.72×1010. The total is about 6.87×1010 FLOPs. The FFN alone (16nd2=3.44×1010) is 50% and dominates; the four projections are 25% and the attention scores and weighted sum are 25%.
  6. Equality: 24nd2=4n2d⇒n=6d=6144. For shorter sequences the projections and FFN dominate; for longer ones the n2 term does.

Common mistakes

How long your answer should be

Half a page; 5 minutes.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: For a GRU with ht=(1−zt)⊙ht−1+zt⊙h~t, what is the direct term in ∂ht/∂ht−1, and why does a small zt let gradients survive many steps? If zt=0.01 at every step, what does that direct path contribute over 100 steps?
Next in Sequence models and transformers: Assume GPT-2 small has 12 layers, d=768, feed-forward width 3072, vocabulary 50,257 and context length 1024 with learned positional embeddings, and output weights tied to the token embedding, where each projection has a bias and each layer has two layer norms. How many parameters does it have?