Build the attention mask for shifted window attention

Why it matters Swin Transformer adds this mask to the attention logits in every shifted-window block.

After a cyclic shift, some windows contain pixels that were far apart in the real image. A mask stops those pixels from attending to each other.

Write shifted_window_mask(H, W, ws, shift). Label every pixel of an H x W grid by region: split rows into the three slices [0, H - ws), [H - ws, H - shift) and [H - shift, H), and columns the same way with W; give each of the 9 (row slice, column slice) pairs its own id 0..8 in row-major order. Partition the label grid into ws x ws windows in row-major order (no extra roll: the labels already describe the shifted map). For each window, mask[w, i, j] = 0 if pixels i and j have the same label, else -100. Return a float array of shape (num_windows, ws * ws, ws * ws).

Signaturedef shifted_window_mask(H, W, ws, shift)

Example

shifted_window_mask(4, 4, 2, 1)[0] is all zeros (the top-left window lies in one region), and window 3 (bottom-right) has four different labels, so it is 0 on the diagonal and -100 everywhere else.

Understand the idea

When the feature map is shifted with a cyclic roll, pixels from the bottom edge wrap around to the top and land in the same window as pixels they were never near. Letting them attend to each other would mix unrelated parts of the image. So each pixel gets a label for which region it came from, and attention between different labels is blocked by adding -100 before the softmax. Like a shared table at a wedding where guests from different parties are asked not to talk shop.

Tiny example: a 4 x 4 map, window 2, shift 1. Rows split into [0, 2), [2, 3), [3, 4), and the same for columns. The top-left window lies entirely in region 0, so its mask is all 0. The bottom-right window has one pixel from each of 4 regions, so every off-diagonal pair is -100.

Rule: mask[w, i, j] = 0 if label_i == label_j else -100, added to the attention scores.

Shifted window attention with this mask is the core of Swin and its video and 3D variants.

Shapes and data flow

labels (H,W) -> windows (nW, ws*ws) -> mask (nW, ws*ws, ws*ws)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleshifted_window_mask(4, 4, 2, 1)
  • Sample 2: 6x6 window 3shifted_window_mask(6, 6, 3, 1)[3]