Analyze Transformer Self-Attention Complexity
The self-attention mechanism is a critical component of the Transformer architecture. It processes a sequence of input vectors (tokens or patches), each with embedding dimension .
The computation requires calculating pairwise affinities between every element (query ) and every other element (key ) in the sequence, typically followed by scaling and multiplying by the value matrix .
Given:
- : Sequence length
- : Embedding dimension
- : Convolution kernel size (for comparison)
Task: Determine the asymptotic time complexity for:
- A single layer of self-attention:
- A standard convolution layer:
Return a tuple of strings representing both complexities.
Write each complexity as a string with no spaces, using ^ for powers and ***** for multiplication, exactly as shown in the example output.
Example
N=100, D=512, K=3
("O(N^2*D)", "O(N*D^2*K^2)")- Inputs: tokens of dimension , and a kernel () for the comparison.
- Self-attention: every query is compared with every key, giving an score matrix. Each score is a dot product of length , so that costs multiply-adds; weighting the value vectors by those scores costs the same again, in total. The constant factor 2 drops, leaving .
- Convolution: at each of the positions, each of output channels sums over input channels times kernel taps: , i.e. .
- Output: the two answers as strings,
O(N^2*D)andO(N*D^2*K^2), attention first. They never change with the inputs: they describe growth, not a count. - Notice that for this short sequence the convolution is about 23 times costlier (), but attention grows quadratically in and overtakes it once , i.e. .
Constraints
- (Sequence Length):
- (Embedding Dimension):
- (Kernel Size):