DL0028 Sliding Window Attention

Explain the sliding window attention mechanism in transformer architectures.

Answer

Sliding window attention restricts each token’s attention to a fixed-size local neighborhood instead of the whole sequence: token i attends only to tokens within roughly \pm w/2 positions of itself. This turns the dense n \times n attention matrix into a sparse band around the diagonal, cutting cost from O(n^2) to O(n \cdot w) and making Transformers practical for very long documents, at the price of losing direct long-range links within a single layer.

(1) Local Window: Each token sees itself plus its w nearest neighbors; everything else is masked out before the softmax.
(2) Linear Scaling in n: Cost per token is constant (w keys), so total compute and memory grow linearly with sequence length.
(3) Trade-off: Excellent for local patterns, but global context must be recovered by stacking layers, adding global tokens, or mixing with dilated windows.

Two attention matrices: a fully dense global attention matrix versus a sliding window matrix with attention confined to a band of width five around the diagonal.

Figure 1: Global attention fills the whole n \times n matrix; the sliding window keeps only a diagonal band of width w.

Mathematical Formulation:
A_{ij} = \frac{q_i \cdot k_j}{\sqrt{d_k}} \quad \text{only if } |i - j| \leq \tfrac{w}{2}, \text{ else masked}
\text{Cost: } O(n^2) \;\rightarrow\; O(n \cdot w), \quad w \ll n

Where:

  • w is the window size (e.g., 512 in Longformer); tokens outside the window get -\infty scores before softmax.
  • n is the sequence length; with w fixed, memory and compute scale linearly in n.

How Global Context Survives: Stacking L layers grows the effective receptive field to about L \cdot w tokens, similar to CNNs; Longformer additionally designates a few global tokens (e.g., [CLS], question tokens) that attend to and are attended by everything.

Log-scale plot comparing n-squared full attention cost against n-times-w sliding window cost, with an annotation showing 32 times fewer computations at sequence length 16 thousand.

Figure 2: At n = 16{,}384, full attention needs ~268M score computations versus ~8.4M for a 512-wide window, a 32x saving that grows with n.

Used In: Longformer, BigBird (window + global + random blocks), and many long-document and code models where full O(n^2) attention is infeasible.


Login to view more content


Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *