A Swin Transformer computes self-attention only inside non-overlapping windows, which makes its cost linear in the number of pixels, and alternates with layers whose windows are shifted by pixels so information crosses window borders. The shift is done by cyclically rolling the feature map, which wraps pixels from opposite edges into the same window; an additive attention mask stops those unrelated pixels from attending to each other. Implement the pieces and one complete single-head (shifted-)window attention layer.
Feature maps are (H, W, C) arrays with and multiples of , and for a shifted layer.
window_partition(x, M) returns (nW, M*M, C): windows in row-major order over the grid of windows, and the tokens of each window in row-major order. window_reverse(windows, M, H, W) is its inverse.
shift_mask(H, W, M, s) returns the (nW, M*M, M*M) float mask for a map rolled by toward the top-left, np.roll(x, (-s, -s), axis=(0, 1)).
0:H-M, H-M:H-s and H-s:H, columns into the bands 0:W-M, W-M:W-s and W-s:W, and each of the nine (row band, column band) combinations is one region.[w, i, j] is 0.0 if tokens i and j of window w share a region id and -100.0 otherwise.relative_position_index(M) returns the (M*M, M*M) int array whose entry for query token at (row , column ) of the window and key token at is , an index into a table of learned biases.
window_attention(x, M, s, Wq, Wk, Wv, bias_table)
x by .(C, C)).bias_table[relative_position_index(M)], plus the shift mask when ; softmax over the keys; output softmax times .(H, W, C) result.