LearnBenchStart learning →

AI Research Scientist · Attention Mechanisms & Kernels

Attention mechanism computational complexity

Real lesson card · Page 1 of 4

Attention mechanism computational complexity

Deriving Attention’s n² Cost

  1. 1
    Form Q, K, VEach of the n tokens is projected into a query, key, and value vector, giving matrices Q,K,VRn×dQ, K, V \in \mathbb{R}^{n \times d}.
  2. 2
    Compute QKTQK^TMultiplying QQ by KTK^T produces an n×nn \times n matrix of scores — one entry per token pair. This single matmul already has n2n^2 entries.
  3. 3
    Softmax each rowSoftmax normalizes every row of that n×nn \times n matrix into attention weights, touching all n2n^2 entries again.
  4. 4
    Weight and sum VThe n×nn \times n weights multiply VV to mix values per token. The n2n^2 term fixed in step 2 propagates through every later stage.

Recall check from the same lesson

The O(n^2) cost of self-attention originates from computing the QK^T score matrix over every pair of tokens, and this quadratic scaling is precisely why memory-efficient kernels and alternative attention architectures exist as separate mitigation work.

Sources

· Editorial policy

One sitting · 20–30 minutes

A focused session on your AI Research Scientist interview

LearnBench starts from what you already know — skip what you have, master what you’re missing.

Start now

More Attention Mechanisms & Kernels questions