Please break down the computational cost of attention.
Answer
Attention cost splits into a linear-in-n term from projections and a quadratic-in-n term from pairwise interactions. For sequence length and model dimension
, the total is
: projections dominate for short sequences, while the
score matrix dominates once
grows past
.
(1) Q/K/V + Output Projections: Four GEMMs over
tokens:
, linear in sequence length.
(2) Score Matrix and Value Mixing
: Pairwise
work:
, the quadratic bottleneck.
(3) Softmax: Elementwise over entries:
, cheap FLOPs but the
matrix drives memory traffic.
Mathematical Formulation (one attention layer, heads,
):
Where:
is the sequence length,
the model (hidden) dimension, and
the number of heads.
form scores
; attention weights
mix values
via
.
- Multi-head attention costs the same as single-head in big-O: per-head dimensions scale as
, so the
heads sum back to
.

Figure 1: Log-log cost curves at : projection
leads at short lengths, attention
takes over near
and dominates at long context.
Regimes: Short sequences (): the
projection term dominates. Long sequences (
): the
interaction term dominates; the two balance around
.
Leave a Reply