EasyDeepLearn

Why is standard self-attention O(n2)O(n^{2}) in sequence length?

medium

Answer

  • For each of n query tokens, compute a dot product with each of n key tokens → n2n^{2} dot products, each of size d.
  • Then a softmax over n weights per query.
  • Both compute and memory are O(n2    d)O(n^{2}\; \cdot \;d).
  • Fine at n = 512-2048; painful at n = 32k+.
  • Motivates efficient / sparse / linear-attention variants and paging tricks (Flash Attention doesn't reduce complexity but cuts memory dramatically via tiling).
Check yourself — multiple choice
  • Attention is O(n)
  • Every query attends to every key → n2n^{2} dot products → O(n2d)O(n^{2} \cdot d) compute and memory
  • Attention is O(1)
  • Attention is O(n log n)

Self-attention: n queries × n keys  =  O(n2d)\mathrm{keys}\; = \;O(n^{2} \cdot d) compute + memory.

#attention#transformers#efficient-attention

Practise Deep Learning

214 interview questions in this topic.

Related questions