Arulkumar03/Fox_Sheep_Detector_Computer_Vision_model
0
1# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved2"""3Implementation of Swin models from :paper:`swin`.4 5This code is adapted from https://github.com/SwinTransformer/Swin-Transformer-Object-Detection/blob/master/mmdet/models/backbones/swin_transformer.py with minimal modifications. # noqa6--------------------------------------------------------7Swin Transformer8Copyright (c) 2021 Microsoft9Licensed under The MIT License [see LICENSE for details]10Written by Ze Liu, Yutong Lin, Yixuan Wei11--------------------------------------------------------12LICENSE: https://github.com/SwinTransformer/Swin-Transformer-Object-Detection/blob/461e003166a8083d0b620beacd4662a2df306bd6/LICENSE13"""14 15import numpy as np16import torch17import torch.nn as nn18import torch.nn.functional as F19import torch.utils.checkpoint as checkpoint20 21from detectron2.modeling.backbone.backbone import Backbone22 23_to_2tuple = nn.modules.utils._ntuple(2)24 25 26class Mlp(nn.Module):27 """Multilayer perceptron."""28 29 def __init__(30 self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.031 ):32 super().__init__()33 out_features = out_features or in_features34 hidden_features = hidden_features or in_features35 self.fc1 = nn.Linear(in_features, hidden_features)36 self.act = act_layer()37 self.fc2 = nn.Linear(hidden_features, out_features)38 self.drop = nn.Dropout(drop)39 40 def forward(self, x):41 x = self.fc1(x)42 x = self.act(x)43 x = self.drop(x)44 x = self.fc2(x)45 x = self.drop(x)46 return x47 48 49def window_partition(x, window_size):50 """51 Args:52 x: (B, H, W, C)53 window_size (int): window size54 Returns:55 windows: (num_windows*B, window_size, window_size, C)56 """57 B, H, W, C = x.shape58 x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)59 windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)60 return windows61 62 63def window_reverse(windows, window_size, H, W):64 """65 Args:66 windows: (num_windows*B, window_size, window_size, C)67 window_size (int): Window size68 H (int): Height of image69 W (int): Width of image70 Returns:71 x: (B, H, W, C)72 """73 B = int(windows.shape[0] / (H * W / window_size / window_size))74 x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)75 x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)76 return x77 78 79class WindowAttention(nn.Module):80 """Window based multi-head self attention (W-MSA) module with relative position bias.81 It supports both of shifted and non-shifted window.82 Args:83 dim (int): Number of input channels.84 window_size (tuple[int]): The height and width of the window.85 num_heads (int): Number of attention heads.86 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value.87 Default: True88 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set89 attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.090 proj_drop (float, optional): Dropout ratio of output. Default: 0.091 """92 93 def __init__(94 self,95 dim,96 window_size,97 num_heads,98 qkv_bias=True,99 qk_scale=None,100 attn_drop=0.0,101 proj_drop=0.0,102 ):103 104 super().__init__()105 self.dim = dim106 self.window_size = window_size # Wh, Ww107 self.num_heads = num_heads108 head_dim = dim // num_heads109 self.scale = qk_scale or head_dim**-0.5110 111 # define a parameter table of relative position bias112 self.relative_position_bias_table = nn.Parameter(113 torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)114 ) # 2*Wh-1 * 2*Ww-1, nH115 116 # get pair-wise relative position index for each token inside the window117 coords_h = torch.arange(self.window_size[0])118 coords_w = torch.arange(self.window_size[1])119 coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww120 coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww121 relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww122 relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2123 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0124 relative_coords[:, :, 1] += self.window_size[1] - 1125 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1126 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww127 self.register_buffer("relative_position_index", relative_position_index)128 129 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)130 self.attn_drop = nn.Dropout(attn_drop)131 self.proj = nn.Linear(dim, dim)132 self.proj_drop = nn.Dropout(proj_drop)133 134 nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02)135 self.softmax = nn.Softmax(dim=-1)136 137 def forward(self, x, mask=None):138 """Forward function.139 Args:140 x: input features with shape of (num_windows*B, N, C)141 mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None142 """143 B_, N, C = x.shape144 qkv = (145 self.qkv(x)146 .reshape(B_, N, 3, self.num_heads, C // self.num_heads)147 .permute(2, 0, 3, 1, 4)148 )149 q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)150 151 q = q * self.scale152 attn = q @ k.transpose(-2, -1)153 154 relative_position_bias = self.relative_position_bias_table[155 self.relative_position_index.view(-1)156 ].view(157 self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1158 ) # Wh*Ww,Wh*Ww,nH159 relative_position_bias = relative_position_bias.permute(160 2, 0, 1161 ).contiguous() # nH, Wh*Ww, Wh*Ww162 attn = attn + relative_position_bias.unsqueeze(0)163 164 if mask is not None:165 nW = mask.shape[0]166 attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)167 attn = attn.view(-1, self.num_heads, N, N)168 attn = self.softmax(attn)169 else:170 attn = self.softmax(attn)171 172 attn = self.attn_drop(attn)173 174 x = (attn @ v).transpose(1, 2).reshape(B_, N, C)175 x = self.proj(x)176 x = self.proj_drop(x)177 return x178 179 180class SwinTransformerBlock(nn.Module):181 """Swin Transformer Block.182 Args:183 dim (int): Number of input channels.184 num_heads (int): Number of attention heads.185 window_size (int): Window size.186 shift_size (int): Shift size for SW-MSA.187 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.188 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True189 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.190 drop (float, optional): Dropout rate. Default: 0.0191 attn_drop (float, optional): Attention dropout rate. Default: 0.0192 drop_path (float, optional): Stochastic depth rate. Default: 0.0193 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU194 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm195 """196 197 def __init__(198 self,199 dim,200 num_heads,201 window_size=7,202 shift_size=0,203 mlp_ratio=4.0,204 qkv_bias=True,205 qk_scale=None,206 drop=0.0,207 attn_drop=0.0,208 drop_path=0.0,209 act_layer=nn.GELU,210 norm_layer=nn.LayerNorm,211 ):212 super().__init__()213 self.dim = dim214 self.num_heads = num_heads215 self.window_size = window_size216 self.shift_size = shift_size217 self.mlp_ratio = mlp_ratio218 assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"219 220 self.norm1 = norm_layer(dim)221 self.attn = WindowAttention(222 dim,223 window_size=_to_2tuple(self.window_size),224 num_heads=num_heads,225 qkv_bias=qkv_bias,226 qk_scale=qk_scale,227 attn_drop=attn_drop,228 proj_drop=drop,229 )230 231 if drop_path > 0.0:232 from timm.models.layers import DropPath233 234 self.drop_path = DropPath(drop_path)235 else:236 self.drop_path = nn.Identity()237 self.norm2 = norm_layer(dim)238 mlp_hidden_dim = int(dim * mlp_ratio)239 self.mlp = Mlp(240 in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop241 )242 243 self.H = None244 self.W = None245 246 def forward(self, x, mask_matrix):247 """Forward function.248 Args:249 x: Input feature, tensor size (B, H*W, C).250 H, W: Spatial resolution of the input feature.251 mask_matrix: Attention mask for cyclic shift.252 """253 B, L, C = x.shape254 H, W = self.H, self.W255 assert L == H * W, "input feature has wrong size"256 257 shortcut = x258 x = self.norm1(x)259 x = x.view(B, H, W, C)260 261 # pad feature maps to multiples of window size262 pad_l = pad_t = 0263 pad_r = (self.window_size - W % self.window_size) % self.window_size264 pad_b = (self.window_size - H % self.window_size) % self.window_size265 x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))266 _, Hp, Wp, _ = x.shape267 268 # cyclic shift269 if self.shift_size > 0:270 shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))271 attn_mask = mask_matrix272 else:273 shifted_x = x274 attn_mask = None275 276 # partition windows277 x_windows = window_partition(278 shifted_x, self.window_size279 ) # nW*B, window_size, window_size, C280 x_windows = x_windows.view(281 -1, self.window_size * self.window_size, C282 ) # nW*B, window_size*window_size, C283 284 # W-MSA/SW-MSA285 attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C286 287 # merge windows288 attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)289 shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C290 291 # reverse cyclic shift292 if self.shift_size > 0:293 x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))294 else:295 x = shifted_x296 297 if pad_r > 0 or pad_b > 0:298 x = x[:, :H, :W, :].contiguous()299 300 x = x.view(B, H * W, C)301 302 # FFN303 x = shortcut + self.drop_path(x)304 x = x + self.drop_path(self.mlp(self.norm2(x)))305 306 return x307 308 309class PatchMerging(nn.Module):310 """Patch Merging Layer311 Args:312 dim (int): Number of input channels.313 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm314 """315 316 def __init__(self, dim, norm_layer=nn.LayerNorm):317 super().__init__()318 self.dim = dim319 self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)320 self.norm = norm_layer(4 * dim)321 322 def forward(self, x, H, W):323 """Forward function.324 Args:325 x: Input feature, tensor size (B, H*W, C).326 H, W: Spatial resolution of the input feature.327 """328 B, L, C = x.shape329 assert L == H * W, "input feature has wrong size"330 331 x = x.view(B, H, W, C)332 333 # padding334 pad_input = (H % 2 == 1) or (W % 2 == 1)335 if pad_input:336 x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))337 338 x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C339 x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C340 x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C341 x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C342 x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C343 x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C344 345 x = self.norm(x)346 x = self.reduction(x)347 348 return x349 350 351class BasicLayer(nn.Module):352 """A basic Swin Transformer layer for one stage.353 Args:354 dim (int): Number of feature channels355 depth (int): Depths of this stage.356 num_heads (int): Number of attention head.357 window_size (int): Local window size. Default: 7.358 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.359 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True360 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.361 drop (float, optional): Dropout rate. Default: 0.0362 attn_drop (float, optional): Attention dropout rate. Default: 0.0363 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0364 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm365 downsample (nn.Module | None, optional): Downsample layer at the end of the layer.366 Default: None367 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.368 """369 370 def __init__(371 self,372 dim,373 depth,374 num_heads,375 window_size=7,376 mlp_ratio=4.0,377 qkv_bias=True,378 qk_scale=None,379 drop=0.0,380 attn_drop=0.0,381 drop_path=0.0,382 norm_layer=nn.LayerNorm,383 downsample=None,384 use_checkpoint=False,385 ):386 super().__init__()387 self.window_size = window_size388 self.shift_size = window_size // 2389 self.depth = depth390 self.use_checkpoint = use_checkpoint391 392 # build blocks393 self.blocks = nn.ModuleList(394 [395 SwinTransformerBlock(396 dim=dim,397 num_heads=num_heads,398 window_size=window_size,399 shift_size=0 if (i % 2 == 0) else window_size // 2,400 mlp_ratio=mlp_ratio,401 qkv_bias=qkv_bias,402 qk_scale=qk_scale,403 drop=drop,404 attn_drop=attn_drop,405 drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,406 norm_layer=norm_layer,407 )408 for i in range(depth)409 ]410 )411 412 # patch merging layer413 if downsample is not None:414 self.downsample = downsample(dim=dim, norm_layer=norm_layer)415 else:416 self.downsample = None417 418 def forward(self, x, H, W):419 """Forward function.420 Args:421 x: Input feature, tensor size (B, H*W, C).422 H, W: Spatial resolution of the input feature.423 """424 425 # calculate attention mask for SW-MSA426 Hp = int(np.ceil(H / self.window_size)) * self.window_size427 Wp = int(np.ceil(W / self.window_size)) * self.window_size428 img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1429 h_slices = (430 slice(0, -self.window_size),431 slice(-self.window_size, -self.shift_size),432 slice(-self.shift_size, None),433 )434 w_slices = (435 slice(0, -self.window_size),436 slice(-self.window_size, -self.shift_size),437 slice(-self.shift_size, None),438 )439 cnt = 0440 for h in h_slices:441 for w in w_slices:442 img_mask[:, h, w, :] = cnt443 cnt += 1444 445 mask_windows = window_partition(446 img_mask, self.window_size447 ) # nW, window_size, window_size, 1448 mask_windows = mask_windows.view(-1, self.window_size * self.window_size)449 attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)450 attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(451 attn_mask == 0, float(0.0)452 )453 454 for blk in self.blocks:455 blk.H, blk.W = H, W456 if self.use_checkpoint:457 x = checkpoint.checkpoint(blk, x, attn_mask)458 else:459 x = blk(x, attn_mask)460 if self.downsample is not None:461 x_down = self.downsample(x, H, W)462 Wh, Ww = (H + 1) // 2, (W + 1) // 2463 return x, H, W, x_down, Wh, Ww464 else:465 return x, H, W, x, H, W466 467 468class PatchEmbed(nn.Module):469 """Image to Patch Embedding470 Args:471 patch_size (int): Patch token size. Default: 4.472 in_chans (int): Number of input image channels. Default: 3.473 embed_dim (int): Number of linear projection output channels. Default: 96.474 norm_layer (nn.Module, optional): Normalization layer. Default: None475 """476 477 def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):478 super().__init__()479 patch_size = _to_2tuple(patch_size)480 self.patch_size = patch_size481 482 self.in_chans = in_chans483 self.embed_dim = embed_dim484 485 self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)486 if norm_layer is not None:487 self.norm = norm_layer(embed_dim)488 else:489 self.norm = None490 491 def forward(self, x):492 """Forward function."""493 # padding494 _, _, H, W = x.size()495 if W % self.patch_size[1] != 0:496 x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))497 if H % self.patch_size[0] != 0:498 x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))499 500 x = self.proj(x) # B C Wh Ww501 if self.norm is not None:502 Wh, Ww = x.size(2), x.size(3)503 x = x.flatten(2).transpose(1, 2)504 x = self.norm(x)505 x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)506 507 return x508 509 510class SwinTransformer(Backbone):511 """Swin Transformer backbone.512 A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted513 Windows` - https://arxiv.org/pdf/2103.14030514 Args:515 pretrain_img_size (int): Input image size for training the pretrained model,516 used in absolute postion embedding. Default 224.517 patch_size (int | tuple(int)): Patch size. Default: 4.518 in_chans (int): Number of input image channels. Default: 3.519 embed_dim (int): Number of linear projection output channels. Default: 96.520 depths (tuple[int]): Depths of each Swin Transformer stage.521 num_heads (tuple[int]): Number of attention head of each stage.522 window_size (int): Window size. Default: 7.523 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.524 qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True525 qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.526 drop_rate (float): Dropout rate.527 attn_drop_rate (float): Attention dropout rate. Default: 0.528 drop_path_rate (float): Stochastic depth rate. Default: 0.2.529 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.530 ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.531 patch_norm (bool): If True, add normalization after patch embedding. Default: True.532 out_indices (Sequence[int]): Output from which stages.533 frozen_stages (int): Stages to be frozen (stop grad and set eval mode).534 -1 means not freezing any parameters.535 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.536 """537 538 def __init__(539 self,540 pretrain_img_size=224,541 patch_size=4,542 in_chans=3,543 embed_dim=96,544 depths=(2, 2, 6, 2),545 num_heads=(3, 6, 12, 24),546 window_size=7,547 mlp_ratio=4.0,548 qkv_bias=True,549 qk_scale=None,550 drop_rate=0.0,551 attn_drop_rate=0.0,552 drop_path_rate=0.2,553 norm_layer=nn.LayerNorm,554 ape=False,555 patch_norm=True,556 out_indices=(0, 1, 2, 3),557 frozen_stages=-1,558 use_checkpoint=False,559 ):560 super().__init__()561 562 self.pretrain_img_size = pretrain_img_size563 self.num_layers = len(depths)564 self.embed_dim = embed_dim565 self.ape = ape566 self.patch_norm = patch_norm567 self.out_indices = out_indices568 self.frozen_stages = frozen_stages569 570 # split image into non-overlapping patches571 self.patch_embed = PatchEmbed(572 patch_size=patch_size,573 in_chans=in_chans,574 embed_dim=embed_dim,575 norm_layer=norm_layer if self.patch_norm else None,576 )577 578 # absolute position embedding579 if self.ape:580 pretrain_img_size = _to_2tuple(pretrain_img_size)581 patch_size = _to_2tuple(patch_size)582 patches_resolution = [583 pretrain_img_size[0] // patch_size[0],584 pretrain_img_size[1] // patch_size[1],585 ]586 587 self.absolute_pos_embed = nn.Parameter(588 torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])589 )590 nn.init.trunc_normal_(self.absolute_pos_embed, std=0.02)591 592 self.pos_drop = nn.Dropout(p=drop_rate)593 594 # stochastic depth595 dpr = [596 x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))597 ] # stochastic depth decay rule598 599 # build layers600 self.layers = nn.ModuleList()601 for i_layer in range(self.num_layers):602 layer = BasicLayer(603 dim=int(embed_dim * 2**i_layer),604 depth=depths[i_layer],605 num_heads=num_heads[i_layer],606 window_size=window_size,607 mlp_ratio=mlp_ratio,608 qkv_bias=qkv_bias,609 qk_scale=qk_scale,610 drop=drop_rate,611 attn_drop=attn_drop_rate,612 drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],613 norm_layer=norm_layer,614 downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,615 use_checkpoint=use_checkpoint,616 )617 self.layers.append(layer)618 619 num_features = [int(embed_dim * 2**i) for i in range(self.num_layers)]620 self.num_features = num_features621 622 # add a norm layer for each output623 for i_layer in out_indices:624 layer = norm_layer(num_features[i_layer])625 layer_name = f"norm{i_layer}"626 self.add_module(layer_name, layer)627 628 self._freeze_stages()629 self._out_features = ["p{}".format(i) for i in self.out_indices]630 self._out_feature_channels = {631 "p{}".format(i): self.embed_dim * 2**i for i in self.out_indices632 }633 self._out_feature_strides = {"p{}".format(i): 2 ** (i + 2) for i in self.out_indices}634 self._size_devisibility = 32635 636 self.apply(self._init_weights)637 638 def _freeze_stages(self):639 if self.frozen_stages >= 0:640 self.patch_embed.eval()641 for param in self.patch_embed.parameters():642 param.requires_grad = False643 644 if self.frozen_stages >= 1 and self.ape:645 self.absolute_pos_embed.requires_grad = False646 647 if self.frozen_stages >= 2:648 self.pos_drop.eval()649 for i in range(0, self.frozen_stages - 1):650 m = self.layers[i]651 m.eval()652 for param in m.parameters():653 param.requires_grad = False654 655 def _init_weights(self, m):656 if isinstance(m, nn.Linear):657 nn.init.trunc_normal_(m.weight, std=0.02)658 if isinstance(m, nn.Linear) and m.bias is not None:659 nn.init.constant_(m.bias, 0)660 elif isinstance(m, nn.LayerNorm):661 nn.init.constant_(m.bias, 0)662 nn.init.constant_(m.weight, 1.0)663 664 @property665 def size_divisibility(self):666 return self._size_divisibility667 668 def forward(self, x):669 """Forward function."""670 x = self.patch_embed(x)671 672 Wh, Ww = x.size(2), x.size(3)673 if self.ape:674 # interpolate the position embedding to the corresponding size675 absolute_pos_embed = F.interpolate(676 self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"677 )678 x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C679 else:680 x = x.flatten(2).transpose(1, 2)681 x = self.pos_drop(x)682 683 outs = {}684 for i in range(self.num_layers):685 layer = self.layers[i]686 x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)687 688 if i in self.out_indices:689 norm_layer = getattr(self, f"norm{i}")690 x_out = norm_layer(x_out)691 692 out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()693 outs["p{}".format(i)] = out694 695 return outs696 