Analyze Transformer Self-Attention Complexity
The self-attention mechanism is a critical component of the Transformer architecture. It processes a sequence of N input vectors (tokens or patches), each with embedding dimension D.
The computation requires calculating pairwise affinities between every element (query q) and every other element (key k) in the sequence, typically followed by scaling and multiplying by the value matrix V.
Given:
- N: Sequence length
- D: Embedding dimension
- K: Convolution kernel size (for comparison)
Task: Determine the asymptotic time complexity for:
- A single layer of self-attention: O(N2â‹…D)
- A standard convolution layer: O(Nâ‹…D2â‹…K2)
Return a tuple of strings representing both complexities.
Example:
N=100, D=512, K=3
("O(N^2*D)", "O(N*D^2*K^2)")Self-attention computes QK^T V where complexity is dominated by N×N attention matrix computation: O(N²D). Convolution operates on N spatial locations with D² channel interactions and K² kernel elements.
Constraints:
- N (Sequence Length): 1≤N≤105
- D (Embedding Dimension): 1≤D≤1024
- K (Kernel Size): 1≤K≤10
1. Background Knowledge
The Transformer architecture, introduced in "Attention is All You Need" (2017), relies on self-attention to process sequences without recurrence or convolution. For a sequence of N tokens each with D-dimensional embeddings X∈RN×D:
Self-attention computes:
- Query (Q), Key (K), Value (V) matrices: Q=XWQ​, K=XWK​, V=XWV​ where W∈RD×D
- Attention scores: A=\text{softmax}\left(\frac{QK^T}{D​}\right) \in \mathbb{R}^{N \times N}
- Output: Z=AV∈RN×D
This captures all pairwise interactions between tokens, enabling long-range dependencies but at quadratic cost.
Standard convolution slides a K×K kernel over input, computing local interactions with complexity linear in sequence length.
2. Algorithm Approach
Direct matrix computation for self-attention:
Q, K, V = linear_projection(X) # O(N × D²)
attention = softmax(Q @ K.T / √D) # O(N² × D) [matrix mult] + O(N²) [softmax]
output = attention @ V # O(N² × D)
Total: O(N2⋅D+N⋅D2), dominated by O(N2⋅D) when N≫D.
Convolution for 1D sequence:
For each position i in N:
For each output channel cout in D:
For each input channel cin in D:
For each position in kernel K:
output[i] += input[i:i+K] * kernel[cin, cout]
Total: O(Nâ‹…D2â‹…K2).
3. Step-by-Step Strategy
- Count Q, K, V projections: 3 matrix multiplies, each O(Nâ‹…D2)
- Analyze attention matrix: QKT is N×D × D×N=O(N2⋅D), softmax O(N2)
- Attention × V: N×N × N×D=O(N2⋅D)
- Dominant term: O(N2â‹…D) from quadratic N2 terms
- Convolution: Per position: K positions × D2 channels = O(N⋅D2⋅K2)
Expected output: ("O(N² · D)", "O(N · D² · K²)")
4. Common Pitfalls
- Forgetting projection costs: O(N⋅D2) exists but is subdominant when N≫D (constraints: N≤105, D≤1024)
- Multi-head confusion: h heads → O(h⋅N2⋅\frac{D}{h}+N⋅h⋅\frac{D}{h}⋅D)=O(N2⋅D+N⋅D2), same asymptotics
- Ignoring softmax: O(N2) but negligible vs. N2â‹…D
- Convolution dimensionality: Verify 1D vs. 2D; problem implies 1D sequence (N tokens)
- Space complexity: Self-attention stores O(N2) attention matrix (65GB for N=105!)
| Operation | Self-Attention | Convolution |
|---|---|---|
| Time | O(N² · D) | O(N · D² · K²) |
| Space | O(N²) | O(N · D) |
| Scaling | Quadratic explosion | Linear scaling |
5. Time & Space Complexity
Self-attention single layer:
└── Time: O(N² · D) [QKᵀ + AV dominate]
└── Space: O(N²) [attention matrix]
Standard convolution:
└── Time: O(N · D² · K²)
└── Space: O(N · D)
Key insight: Self-attention's global pairwise computation (N2 pairs × D work/pair) vs. convolution's local sliding window (N positions × K2⋅D2 work/position).