Build a local plus global attention mask

Why it matters Long-context encoders use local windows plus global tokens to get near-linear attention cost.

Long-document encoders save compute by letting most tokens attend only to nearby tokens, while a few global tokens (like a classification token) see and are seen by everything.

Write local_global_mask(n, window, global_idx). Return a bool array M of shape (n, n), not causal, where M[i, j] is True if abs(i - j) <= window, or i is a global position, or j is a global position.

Signaturedef local_global_mask(n, window, global_idx)

Example

local_global_mask(4, 1, [0]) is [[True, True, True, True], [True, True, True, False], [True, True, True, True], [True, False, True, True]].

Understand the idea

Full attention compares every token with every other token, which is too slow for very long documents. A local window is like reading with a ruler under the line: each token only looks a few positions left and right. Some tokens, such as a summary token, need the whole picture, so they get global access both ways.

Example: n = 4, window 1, global token 0. Token 1 sees 0, 1, 2 (its band). Token 3 sees 2, 3 from the band, plus token 0 because 0 is global. Token 0 sees everyone. So row 3 is [True, False, True, True].

Rule: M[i, j] = (|i - j| <= w) or (i in G) or (j in G).

The cost becomes about n * (2w + 1) plus n * |G| comparisons instead of n^2. Long-document models such as Longformer and BigBird use this pattern, often with a CLS or question token marked global.

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

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

  • Sample 1: examplelocal_global_mask(4, 1, [0])
  • Sample 2: two globalslocal_global_mask(6, 1, [0, 5])
  • Test 3: no globalslocal_global_mask(5, 2, [])