How does self-attention achieve a constant maximum path length between arbitrary tokens in a sequence?

Last updated 22 November 2026

  • In one self-attention layer, each query is scored against all keys at once (softmax(QK^T / sqrt(d_k)) V), so every token has a direct weighted edge to every other token: an O(1) path length.

  • Path length is the number of steps a signal or gradient crosses between positions. RNNs need O(n) and CNNs need O(n/k) or O(log_k n), so long-range dependencies are harder for them to learn.

  • The price is O(n²·d) compute and O(n²) attention memory per layer. A short path makes dependencies learnable but does not guarantee they are learned.

  • https://medium.com/the-software-frontier/revolutionizing-sequence-modeling-with-the-transformer-whats-the-hype-about-part-1-208d46e273c4
  • https://www.ailearning-engineering.com/lessons/attention-is-all-you-need
  • https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/tutorial6/Transformers_and_MHAttention.html
All Transformers interview questions