Limit attention to a sliding window of recent tokens

Full causal attention lets token i look at every earlier token, so cost grows with the square of the sequence length. Sliding-window attention lets each token look only at itself and the window - 1 tokens before it. Stacked layers still pass information further back.

Write sliding_window_mask(n, window) that returns an n by n boolean NumPy array where mask[i, j] is True when token i may attend to token j: j <= i and i - j < window.

Then write attended_count(n, window): a list with how many positions each token attends to.

Signaturedef sliding_window_mask(n, window)

Understand the idea

Full causal attention lets every token look at all earlier tokens, which gets expensive for long text. Sliding-window attention lets each token see only itself and the window - 1 tokens just before it, like reading with a small torch that lights only the last few words. Information from further back still flows through stacked layers. Token i may attend to token j when j is not in the future (j <= i) and is close enough (i - j < window). Worked example: n = 4, window = 2. Row 0 sees {0}. Row 1 sees {0, 1}. Row 2 sees {1, 2}. Row 3 sees {2, 3}. So the counts are [1, 2, 2, 2]. Using i - j <= window by mistake would let row 3 also see token 1. Rule: mask[i, j] = (j <= i) and (i - j < window); each row has min(i + 1, window) True values. Mistral and several long-context models use sliding-window attention.

Part of the advanced LLM architecture track.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: window 2 on 4 tokenssliding_window_mask(4, 2).astype(int).tolist()
  • Sample 2: window 1 is only yourselfsliding_window_mask(3, 1).astype(int).tolist()
  • Test 3: big window is plain causalbool((sliding_window_mask(5, 99) == np.tril(np.ones((5, 5), dtype=bool))).all())
  • Test 4: countsattended_count(6, 3)