MCPcopy Create free account
hub / github.com/OpenGVLab/HumanBench / forward

Method forward

PATH/core/models/backbones/vit.py:207–247  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

205 self.proj_drop = nn.Dropout(proj_drop)
206
207 def forward(self, x, H, W):
208 """ Forward function.
209 Args:
210 x: input features with shape of (num_windows*B, N, C)
211 mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
212 """
213 B_, N, C = x.shape
214 x = x.reshape(B_, H, W, C)
215 pad_l = pad_t = 0
216 pad_r = (self.window_size[1] - W % self.window_size[1]) % self.window_size[1]
217 pad_b = (self.window_size[0] - H % self.window_size[0]) % self.window_size[0]
218
219 x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
220 _, Hp, Wp, _ = x.shape
221
222 x = window_partition(x, self.window_size[0]) # nW*B, window_size, window_size, C
223 x = x.view(-1, self.window_size[1] * self.window_size[0], C) # nW*B, window_size*window_size, C
224 B_w = x.shape[0]
225 N_w = x.shape[1]
226 qkv = self.qkv(x).reshape(B_w, N_w, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
227 q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
228
229 attn = ((q * self.scale) @ k.transpose(-2, -1))
230 # attn = calc_rel_pos_spatial(attn, q, self.window_size, self.window_size, self.rel_pos_h, self.rel_pos_w)
231
232 attn = attn.softmax(dim=-1)
233 attn = self.attn_drop(attn)
234
235 x = (attn @ v).transpose(1, 2).reshape(B_w, N_w, C)
236 x = self.proj(x)
237 x = self.proj_drop(x)
238
239 x = x.view(-1, self.window_size[1], self.window_size[0], C)
240 x = window_reverse(x, self.window_size[0], Hp, Wp) # B H' W' C
241
242 if pad_r > 0 or pad_b > 0:
243 x = x[:, :H, :W, :].contiguous()
244
245 x = x.view(B_, H * W, C)
246
247 return x
248
249
250class Block(nn.Module):

Callers

nothing calls this directly

Calls 3

permuteMethod · 0.80
window_partitionFunction · 0.70
window_reverseFunction · 0.70

Tested by

no test coverage detected