Forward function. Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
(self, x, H, W)
| 212 | self.proj = nn.Linear(dim, dim) |
| 213 | |
| 214 | def forward(self, x, H, W): |
| 215 | """ Forward function. |
| 216 | Args: |
| 217 | x: input features with shape of (num_windows*B, N, C) |
| 218 | mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None |
| 219 | """ |
| 220 | B_, N, C = x.shape |
| 221 | x = x.reshape(B_, H, W, C) |
| 222 | pad_l = pad_t = 0 |
| 223 | pad_r = (self.window_size[1] - W % self.window_size[1]) % self.window_size[1] |
| 224 | pad_b = (self.window_size[0] - H % self.window_size[0]) % self.window_size[0] |
| 225 | |
| 226 | x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) |
| 227 | _, Hp, Wp, _ = x.shape |
| 228 | |
| 229 | x = window_partition(x, self.window_size[0]) # nW*B, window_size, window_size, C |
| 230 | x = x.view(-1, self.window_size[1] * self.window_size[0], C) # nW*B, window_size*window_size, C |
| 231 | |
| 232 | B_w = x.shape[0] |
| 233 | N_w = x.shape[1] |
| 234 | qkv = self.qkv(x).reshape(B_w, N_w, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) |
| 235 | q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple) --> (batchsize, heads, len, head_dim) |
| 236 | |
| 237 | attn = ((q * self.scale) @ k.transpose(-2, -1)) |
| 238 | if self.rel_pos_spatial: |
| 239 | raise |
| 240 | |
| 241 | attn = attn.softmax(dim=-1) |
| 242 | _attn_mask = (torch.isinf(attn) + torch.isnan(attn)) |
| 243 | attn = attn.masked_fill(_attn_mask, 0) |
| 244 | |
| 245 | x = (attn @ v).transpose(1, 2).reshape(B_w, N_w, C) |
| 246 | x = self.proj(x) |
| 247 | |
| 248 | x = x.view(-1, self.window_size[1], self.window_size[0], C) |
| 249 | x = window_reverse(x, self.window_size[0], Hp, Wp) # B H' W' C |
| 250 | |
| 251 | if pad_r > 0 or pad_b > 0: |
| 252 | x = x[:, :H, :W, :].contiguous() |
| 253 | |
| 254 | x = x.view(B_, H * W, C) |
| 255 | |
| 256 | return x |
| 257 | |
| 258 | |
| 259 | class Block(nn.Module): |
nothing calls this directly
no test coverage detected