Table 1 explorer
Section 4 of the paper compares self-attention with the layers it replaced, on three counts: how much work a layer does, how many steps must happen one after another, and how many steps a signal needs to travel between two far-apart words. Set the sizes and watch the counts.
| Layer type | Complexity per layer | Sequential operations | Maximum path length |
|---|---|---|---|
| Self-Attention | O(n²·d) = 51,200 |
O(1) = 1 |
O(1) = 1 |
| Recurrent | O(n·d²) = 2,621,440 |
O(n) = 10 |
O(n) = 10 |
| Convolutional | O(k·n·d²) = 7,864,320 |
O(1) = 1 |
O(log_k(n)) = 3 |
| Self-Attention (restricted) | O(r·n·d) = 81,920 |
O(1) = 1 |
O(n/r) = 1 |
The formulas are those of the paper's Table 1 (section 4), as written there; the values are the formulas without O(...), so they show how the costs grow, not times.
- Self-Attention
- Recurrent
- Convolutional
- Self-Attention (restricted)
How to read the table
n is the number of tokens in the sentence, d the length of each token's vector, k the width of a convolution's window and r how many neighbours a restricted self-attention looks at. O(...) means “grows like”: the table counts how the cost grows, not seconds.
Self-attention compares every token with every other one: n × n pairs, each a dot product of d numbers, so n²·d. A recurrent layer walks the sentence one token at a time, n steps, each multiplying a vector by a d × d matrix, so n·d². When n is smaller than d, which is usual for sentences (our model: about 10 tokens and d = 64; the paper: d = 512), self-attention is cheaper. For very long texts it is not, which is why long contexts cost so much in today's models.
The other two columns are where self-attention wins outright. A recurrent layer must take its n steps one after another, so it cannot use a GPU's parallel power within a sentence; self-attention does all pairs at once. And two words n places apart are one step apart in self-attention, but n steps apart in a recurrent layer, so a signal between them has far to travel and fades.
In the paper (4)
“In terms of computational complexity, self-attention layers are faster than recurrent layers when the sequence length n is smaller than the representation dimensionality d”