Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of
| 63 | |
| 64 | |
| 65 | class WindowAttention(nn.Module): |
| 66 | """ Window based multi-head self attention (W-MSA) module with relative position bias. |
| 67 | It supports both of shifted and non-shifted window. |
| 68 | |
| 69 | Args: |
| 70 | dim (int): Number of input channels. |
| 71 | window_size (tuple[int]): The height and width of the window. |
| 72 | num_heads (int): Number of attention heads. |
| 73 | qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True |
| 74 | qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set |
| 75 | attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 |
| 76 | proj_drop (float, optional): Dropout ratio of output. Default: 0.0 |
| 77 | """ |
| 78 | |
| 79 | def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.): |
| 80 | |
| 81 | super().__init__() |
| 82 | self.dim = dim |
| 83 | self.window_size = window_size # Wh, Ww |
| 84 | self.num_heads = num_heads |
| 85 | head_dim = dim // num_heads |
| 86 | self.scale = qk_scale or head_dim ** -0.5 |
| 87 | |
| 88 | # define a parameter table of relative position bias |
| 89 | self.relative_position_bias_table = nn.Parameter( |
| 90 | torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH |
| 91 | |
| 92 | # get pair-wise relative position index for each token inside the window |
| 93 | coords_h = torch.arange(self.window_size[0]) |
| 94 | coords_w = torch.arange(self.window_size[1]) |
| 95 | coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww |
| 96 | coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww |
| 97 | relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww |
| 98 | relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 |
| 99 | relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 |
| 100 | relative_coords[:, :, 1] += self.window_size[1] - 1 |
| 101 | relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 |
| 102 | relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww |
| 103 | self.register_buffer("relative_position_index", relative_position_index) |
| 104 | |
| 105 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) |
| 106 | self.attn_drop = nn.Dropout(attn_drop) |
| 107 | self.proj = nn.Linear(dim, dim) |
| 108 | self.proj_drop = nn.Dropout(proj_drop) |
| 109 | |
| 110 | trunc_normal_(self.relative_position_bias_table, std=.02) |
| 111 | self.softmax = nn.Softmax(dim=-1) |
| 112 | |
| 113 | def forward(self, x, mask=None): |
| 114 | """ Forward function. |
| 115 | |
| 116 | Args: |
| 117 | x: input features with shape of (num_windows*B, N, C) |
| 118 | mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None |
| 119 | """ |
| 120 | B_, N, C = x.shape |
| 121 | qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) |
| 122 | q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) |