v9.1.1
Menu

Analyze Transformer Self-Attention Complexity

mediumFREETransformersAlgorithms, ComplexityAdvanced Architectures

The self-attention mechanism is a critical component of the Transformer architecture. It processes a sequence of NN input vectors (tokens or patches), each with embedding dimension DD.

The computation requires calculating pairwise affinities between every element (query qq) and every other element (key kk) in the sequence, typically followed by scaling and multiplying by the value matrix VV.

Given:

  • NN: Sequence length
  • DD: Embedding dimension
  • KK: Convolution kernel size (for comparison)

Task: Determine the asymptotic time complexity for:

  1. A single layer of self-attention: O(N2⋅D)O(N^2 \cdot D)
  2. A standard convolution layer: O(N⋅D2⋅K2)O(N \cdot D^2 \cdot K^2)

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

Input
N=100, D=512, K=3
Output
("O(N^2*D)", "O(N*D^2*K^2)")
Reasoning
  • Inputs: N=100N = 100 tokens of dimension D=512D = 512, and a 3×33 \times 3 kernel (K=3K = 3) for the comparison.
  • Self-attention: every query is compared with every key, giving an N×N=10,000N \times N = 10{,}000 score matrix. Each score is a dot product of length DD, so that costs 1002⋅512=5,120,000100^2 \cdot 512 = 5{,}120{,}000 multiply-adds; weighting the value vectors by those scores costs the same again, 10,240,00010{,}240{,}000 in total. The constant factor 2 drops, leaving O(N2⋅D)O(N^2 \cdot D).
  • Convolution: at each of the NN positions, each of DD output channels sums over DD input channels times K2K^2 kernel taps: 100⋅5122⋅9=235,929,600100 \cdot 512^2 \cdot 9 = 235{,}929{,}600, i.e. O(N⋅D2⋅K2)O(N \cdot D^2 \cdot K^2).
  • Output: the two answers as strings, O(N^2*D) and O(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 (235,929,600/10,240,000≈23235{,}929{,}600 / 10{,}240{,}000 \approx 23), but attention grows quadratically in NN and overtakes it once 2N2D>ND2K22N^2 D > N D^2 K^2, i.e. N>DK2/2=2304N > D K^2 / 2 = 2304.

Constraints

  • NN (Sequence Length): 1≤N≤1051 \leq N \leq 10^5
  • DD (Embedding Dimension): 1≤D≤10241 \leq D \leq 1024
  • KK (Kernel Size): 1≤K≤101 \leq K \leq 10

Learn this in

More from Advanced Architectures

solution.py

Test results

Sign in to run your code against the test cases.