Which operations in a transformer forward pass scale linearly with sequence length and which scale quadratically?

Last updated 22 November 2026

  • Linear in sequence length n: all per-token work (embeddings, Q/K/V/output projections, the FFN, norms, residuals, unembedding). Per layer this is about 24·n·d² FLOPs, with the FFN the largest part.

  • Quadratic in n: only self-attention's token-pair interactions (computing QKᵀ, softmax over the n×n matrix, and multiplying by V). This costs about 4·n²·d and dominates once n exceeds roughly 6d.

  • FlashAttention makes attention memory linear but FLOPs stay quadratic. With a KV cache each decoded token costs O(n·d), yet a full generation is still O(n²).

  • https://medium.com/@kiranvutukuri/69-sparse-attention-making-transformers-efficient-for-long-sequences-859aa03b03f6
  • https://dev.to/jackm_345442a09fb53b/llm-interview-series3-transformers-explained-attention-is-all-you-need-523o
  • https://waylandz.com/llm-transformer-book-en/chapter-15-full-forward-pass/
All Transformers interview questions