4.1.13Transformer Architecture

Computational complexity of attention

2,319 words11 min readdifficulty · medium3 backlinks

The fundamental cost breakdown

Memory and operations in standard self-attention

The self-attention mechanism computes three matrices for each token: queries (Q), keys (K), and values (V). The complexity comes from computing the attention scores between all pairs of tokens.

Let's derive the complexity from scratch.

Deriving the time complexity

Step 1: Linear projections

For input XRn×dX \in \mathbb{R}^{n \times d} and weight matrices WQ,WK,WVRd×dkW_Q, W_K, W_V \in \mathbb{R}^{d \times d_k}:

Q=XWQQ = XW_Q

This is a matrix multiplication: (n×d)×(d×dk)=n×dk(n \times d) \times (d \times d_k) = n \times d_k output.

Cost: Each output element requires dd multiplications, total: ndkdn \cdot d_k \cdot d operations.

For all three projections (Q, K, V): 3nddk3nd \cdot d_k operations.

Why this step? We're transforming each token's embedding into query/key/value space. This is linear in sequence length—not the problem.

Step 2: Computing attention scores S=QKTS = QK^T

S=QKTRn×nS = QK^T \in \mathbb{R}^{n \times n}

Matrix dimensions: (n×dk)×(dk×n)=n×n(n \times d_k) \times (d_k \times n) = n \times n

Cost: Each of the n2n^2 output elements requires dkd_k multiplications.

Total: n2dkn^2 \cdot d_k operations.

Why this step? This is where every token compares itself to every other token. The n×nn \times n output is inherently quadratic—this is the bottleneck.

Step 3: Softmax

For each row of SS (one query), compute:

Aij=exp(Sij/dk)j=1nexp(Sij/dk)A_{ij} = \frac{\exp(S_{ij}/\sqrt{d_k})}{\sum_{j=1}^n \exp(S_{ij}/\sqrt{d_k})}

Cost: O(n)O(n) per row, nn rows total: O(n2)O(n^2) operations.

Why this step? Normalizing attention weights. Still quadratic in the number of scores.

Step 4: Weighted sum Output=AV\text{Output} = AV

(n×n)×(n×dk)=n×dk(n \times n) \times (n \times d_k) = n \times d_k

Cost: n2dkn^2 \cdot d_k operations.

Why this step? Each output token is a weighted combination of all value vectors.

Step 5: Output projection Out=ZWO\text{Out} = ZW_O

After concatenating heads back into a dd-dimensional vector, we apply the output projection WORd×dW_O \in \mathbb{R}^{d \times d}:

(n×d)×(d×d)=n×d(n \times d) \times (d \times d) = n \times d

Cost: ndd=nd2n \cdot d \cdot d = nd^2 operations.

Why this step? The output projection mixes information across heads and maps back to model dimension. It contributes another O(nd2)\mathcal{O}(nd^2) term—don't forget it when counting linear-projection cost.

Memory complexity

Figure — Computational complexity of attention

Why each component matters

Linear projections: O(nd2)\mathcal{O}(nd^2)

This scales linearly with sequence length. Doubling nn doubles the work. Not a bottleneck for long sequences but dominates for very short sequences where ndn \ll d. This term covers the Q, K, V projections and the output projection WOW_O—together roughly 4nd24nd^2 operations, but asymptotically O(nd2)\mathcal{O}(nd^2).

Attention matrix: O(n2dk)\mathcal{O}(n^2 d_k)

This is the core problem. The n2n^2 term means:

  • 2× sequence length →4× compute
  • 10× sequence length → 100× compute

Why it's unavoidable in standard attention: Every token needs a score with every other token to decide "who to pay attention to."

Multi-head attention scaling

With hh attention heads, each of dimension dk=d/hd_k = d/h:

  • Attention cost: hh heads each cost n2dkn^2 d_k, so total hn2dk=n2dh \cdot n^2 d_k = n^2 d (since hdk=dh d_k = d).
  • Projection cost: The Q, K, V projections and output projection each operate on the full dd-dimensional space once, not once per head. So the projection cost stays O(nd2)\mathcal{O}(nd^2) — it is not multiplied by hh.

Total=O(hn2dk+nd2)=O(n2d+nd2)\boxed{\text{Total} = \mathcal{O}(h\,n^2 d_k + nd^2) = \mathcal{O}(n^2 d + nd^2)}

Key insight: Using more heads doesn't change the asymptotic complexity (still O(n2d+nd2)\mathcal{O}(n^2 d + nd^2)), and does not add a factor of hh to the projection term. Splitting into heads just reshapes the same dd-dimensional projections.

Comparison with other architectures

| Architecture | Time complexity | Memory | Receptive field | |------------|-----------------|-----------------| | Self-attention | O(n2d)\mathcal{O}(n^2 d) | O(n2)\mathcal{O}(n^2) | Global (all tokens) | | RNN (LSTM/GRU) | O(nd2)\mathcal{O}(nd^2) | O(d)\mathcal{O}(d) | Sequential (limited) | | CNN (kernel kk) | O(nkd2)\mathcal{O}(nkd^2) | O(nd)\mathcal{O}(nd) | Local (kk tokens) | | Sparse attention | O(nnd)\mathcal{O}(n \sqrt{n} d) | O(nn)\mathcal{O}(n \sqrt{n}) | Structured patterns | | Linear attention | O(nd2)\mathcal{O}(nd^2) | O(nd)\mathcal{O}(nd) | Global (approximation) |

Trade-off: Self-attention gets global context instantly (depth-1 path between any tokens) but pays quadratic cost. RNNs are linear but require nn sequential steps to connect distant tokens.

Efficient attention variants

The O(n2)\mathcal{O}(n^2) bottleneck has sparked a research area:

  1. Sparse attention (Sparse Transformer, Longformer): Only compute attention for subset of token pairs (e.g., local windows + global tokens). Reduces to O(nlogn)\mathcal{O}(n \log n) or O(nn)\mathcal{O}(n \sqrt{n}).

  2. Linear attention (Performers, Linear Transformers): Approximate attention with kernel methods, achieving O(nd2)\mathcal{O}(nd^2) by never materializing the n×nn \times n matrix.

  3. Flash Attention: Keeps O(n2d)\mathcal{O}(n^2 d) complexity but optimizes memory access patterns using tiling, reducing memory from O(n2)\mathcal{O}(n^2) to O(n)\mathcal{O}(n) by not storing the full attention matrix.

Practical implications

Training vs. inference

Training: Requires storing SS for backpropagation. Memory is often the limiting factor, not compute.

Inference: Can attention on-the-fly without storing full matrices. KV-caching helps: store past keys/values to avoid recomputing them for each new token.

Why context length is expensive

Quadratic scaling means:

  • GPT-3 (2K context): manageable
  • GPT-4 (32K context): 16× memory and compute vs. 8K in the attention term
  • 100K context: 625× cost vs. 4K

This is why long-context models either use sparse attention or are extremely expensive to run.

Recall Explain to a 12-year-old

Imagine you're in a class of nn students, and everyone needs to pass a note to everyone else to share information (that's attention). If there are 10 students, you need 10×10=10010 \times 10 = 100 notes. Double the class to 20 students? Now you need 20×20=40020 \times 20 = 400 notes—four times as many!

That's why transformers slow down with long texts: every word has to "talk to" every other word, so doubling the length quadruples the work. Smart researchers are finding ways to let words talk to only their neighbors or use tricks to avoid passing all those notes, making it much faster.

Connections

  • 4.1.1-Self-attention-mechanism: The mechanism that causes this complexity
  • 4.1.7-Multi-head-attention: How splitting heads affects computational cost
  • 4.3.2-Sparse-attention-patterns: Solutions to reduce quadratic complexity
  • 4.5.1-Memory-optimization-techniques: Flash Attention and gradient checkpointing
  • 5.2.3-Positional-encoding-scaling: Why long sequences need efficient attention

#flashcards/ai-ml

What is the time complexity of standard self-attention? :: O(n2dk+nd2)\mathcal{O}(n^2 d_k + nd^2), dominated by O(n2dk)\mathcal{O}(n^2 d_k) for long sequences where the QKTQK^T computation requires n2dkn^2 d_k operations.

Why is self-attention quadratic in sequence length?
Because computing attention scores S=QKTS = QK^T produces an n×nn \times n matrix where every token must compute a score with every other token, requiring n2dkn^2 d_k operations.
What is the memory complexity of self-attention?
O(n2+nd)\mathcal{O}(n^2 + nd). The n2n^2 term comes from storing the attention score matrix for backpropagation, which can dominate for long sequences.
How does doubling sequence length affect attention compute?
It quadruples the compute because attention is O(n2)\mathcal{O}(n^2). Going from nn to 2n2n increases cost from n2n^2 to (2n)2=4n2(2n)^2 = 4n^2.

Compare time complexity of self-attention vs. RNN :: Self-attention is O(n2d)\mathcal{O}(n^2 d) but parallel; RNN is O(nd2)\mathcal{O}(nd^2) but sequential. For long sequences (n>dn > d), attention is slower but has global receptive field in one step.

Does multi-head attention multiply the projection cost by h?
No. The Q, K, V and output projections operate once over the full dd-dimensional space, so their cost is O(nd2)\mathcal{O}(nd^2)not hnd2h \cdot nd^2. Only the attention term sums over heads, giving hn2dk=n2dh \cdot n^2 d_k = n^2 d.

What is the computational bottleneck in self-attention? :: The QKTQK^T matrix multiplication, which is O(n2dk)\mathcal{O}(n^2 d_k). This all-to-all comparison between tokens is inherently quadratic and dominates for long sequences.

Which projections contribute to the O(nd^2) term?
The query, key, value projections and the output projection WOW_O. Together they are roughly 4nd24nd^2 operations, but asymptotically O(nd2)\mathcal{O}(nd^2).
How much memory for attention scores in one layer with n=2048?
204824.22048^2 \approx 4.2 million floats. At FP32 (4 bytes each), roughly 16 MB per attention head. With multiple heads and layers, this adds up quickly.
Why can't you feed a full book into GPT naively?
Quadratic complexity: a book might have 100K tokens. That's 100K2=10100K^2 = 10 billion attention computations per layer, requiring massive memory (10B10B floats ≈ 40 GB just for attention matrices) and compute.

Concept Map

step 1

step 2

feeds

feeds

then

costs

every pair compared

adds

costs

costs nd^2

causes

doubling n quadruples compute

Self-attention mechanism

Linear projections Q K V

Scores S = QK^T

Softmax normalization

Value aggregation AV

Output projection W_O

Linear cost 3nd*dk

Quadratic cost n^2*dk

Quadratic bottleneck

Efficient attention variants

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Transformer attention ka sabse bada issue hai quadratic complexity—matlab jab ap sequence length double karte ho, compute aur memory requirement chaar guna ho jati hai. Kyun? Kyunki self-attention mein har token ko har dusre token ke saath compare karna padta hai

Go deeper — visual, from zero

Test yourself — Transformer Architecture

Connections