Skip to content

← Attention Variants step 4 of 14

Medium Research

Sliding Window Attention

Sliding-window attention limits each query to nearby keys. This exercise uses a two-sided window: position i can attend to itself and up to window_size positions on either side. It can use later positions, so this is not a causal mask.

The window is a radius

Let w = window_size. Keep key j when abs(i - j) <= w, clipping the range to the sequence boundaries. There are at most 2 * w + 1 allowed keys, and fewer near either end.

For a three-position sequence with w = 1:

Query position Allowed key positions
0 0, 1
1 0, 1, 2
2 1, 2

If queries and keys are zero and the values are [[10], [20], [30]], all allowed scores are equal. The outputs are the local means [[15], [20], [25]]. With w = 0, only the diagonal is allowed and the output equals V. With w >= seq_len - 1, all keys are allowed.

Compute attention within each window

Calculate scores = (Q @ K.T) / sqrt(d_k). Mask scores outside each window with negative infinity before applying a stable softmax along the last axis. Multiply the resulting weights by V.

Softmax must normalize over only the allowed keys. Every row includes its own position, so it has at least one allowed score. Assume the unmasked dot products are finite. A fixed finite penalty such as -1e9 is not an exact substitute for negative infinity when excluded scores can be very large.

A local attention pattern can support implementations that compute only nearby pairs. This exercise's dense score-and-mask approach still constructs a square matrix; the mask alone does not reduce its quadratic storage. It implements the local pattern, not a complete Longformer model with additional global attention or specialized kernels.

Inputs

Implement sliding_window_attention(Q, K, V, window_size).

  • Q, K and V: floating-point tensors of shape (seq_len, d_k). Both dimensions are positive.
  • window_size: a nonnegative integer radius, which may exceed the sequence length.

Inputs use compatible dtypes and, in PyTorch, the same device. Allocate any mask on that device. No batching, padding mask or dropout is required.

Output

Return a tensor of shape (seq_len, d_k) containing the weighted value vectors. Leave all input tensors unchanged.