📘
Analyze Transformer Self-Attention Complexity
MediumAlgorithms, 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:
Input:
N=100, D=512, K=3
Output:
("O(N^2*D)", "O(N*D^2*K^2)")Reasoning:
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
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.