Partition a feature map into (shifted) windows for window attention

Why it matters Swin Transformer and many high-resolution ViTs and video models use window attention with this partition.

Swin-style transformers run attention inside small windows. Every other block first shifts the map so information crosses window borders.

Write window_partition(x, ws, shift=0). x is (H, W, C) with H and W divisible by ws. If shift > 0, first cyclically roll x by -shift along both spatial axes (np.roll with shift (-shift, -shift) on axes (0, 1)). Then cut it into non-overlapping ws x ws windows in row-major window order, each flattened in row-major pixel order. Return an array of shape (num_windows, ws * ws, C).

Signaturedef window_partition(x, ws, shift=0)

Example

window_partition(arange(16).reshape(4, 4, 1), 2)[:, :, 0] is [[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]].

Understand the idea

Full self-attention over a big image is too costly, so window attention only lets each pixel talk to the others in its own small square. Then, to stop windows from becoming isolated islands, the next block shifts the grid by half a window, so the new squares straddle the old borders. Like changing seating at each round of a networking event so people meet new neighbours.

Tiny example: a 4 x 4 map with values 0 to 15 and 2 x 2 windows. The top-left window holds 0, 1, 4, 5; the top-right holds 2, 3, 6, 7; and so on. With shift 1, the map is rolled up and left by one, so the first window becomes 5, 6, 9, 10.

Rule: roll by (-s, -s), reshape(H/ws, ws, W/ws, ws, C), transpose(0, 2, 1, 3, 4), reshape(-1, ws*ws, C).

Swin Transformer alternates plain and shifted windows in every stage.

Shapes and data flow

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

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

  • Sample 1: examplewindow_partition(np.arange(16).reshape(4, 4, 1), 2)[:, :, 0]
  • Sample 2: shiftedwindow_partition(np.arange(16).reshape(4, 4, 1), 2, shift=1)[:, :, 0]