mohantesting/remove_background
011
1### config.py2 3import os4import math5from transformers import PretrainedConfig6 7class Config(PretrainedConfig):8 def __init__(self) -> None:9 super().__init__()10 # PATH settings11 self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx12 13 # TASK settings14 self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]15 self.training_set = {16 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],17 'COD': 'TR-COD10K+TR-CAMO',18 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],19 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.20 'P3M-10k': 'TR-P3M-10k',21 }[self.task]22 self.prompt4loc = ['dense', 'sparse'][0]23 24 # Faster-Training settings25 self.load_all = True26 self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.27 # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.28 # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.29 # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.30 self.precisionHigh = True31 32 # MODEL settings33 self.ms_supervision = True34 self.out_ref = self.ms_supervision and True35 self.dec_ipt = True36 self.dec_ipt_split = True37 self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder38 self.mul_scl_ipt = ['', 'add', 'cat'][2]39 self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]40 self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]41 self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]42 43 # TRAINING settings44 self.batch_size = 445 self.IoU_finetune_last_epochs = [46 0,47 {48 'DIS5K': -50,49 'COD': -20,50 'HRSOD': -20,51 'DIS5K+HRSOD+HRS10K': -20,52 'P3M-10k': -20,53 }[self.task]54 ][1] # choose 0 to skip55 self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly56 self.size = 102457 self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader58 59 # Backbone settings60 self.bb = [61 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 262 'swin_v1_t', 'swin_v1_s', # 3, 463 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs464 'pvt_v2_b0', 'pvt_v2_b1', # 7, 865 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs566 ][6]67 self.lateral_channels_in_collection = {68 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],69 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],70 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],71 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],72 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],73 }[self.bb]74 if self.mul_scl_ipt == 'cat':75 self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]76 self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []77 78 # MODEL settings - inactive79 self.lat_blk = ['BasicLatBlk'][0]80 self.dec_channels_inter = ['fixed', 'adap'][0]81 self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]82 self.progressive_ref = self.refine and True83 self.ender = self.progressive_ref and False84 self.scale = self.progressive_ref and 285 self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.86 self.refine_iteration = 187 self.freeze_bb = False88 self.model = [89 'BiRefNet',90 ][0]91 if self.dec_blk == 'HierarAttDecBlk':92 self.batch_size = 2 ** [0, 1, 2, 3, 4][2]93 94 # TRAINING settings - inactive95 self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]96 self.optimizer = ['Adam', 'AdamW'][1]97 self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.98 self.lr_decay_rate = 0.599 # Loss100 self.lambdas_pix_last = {101 # not 0 means opening this loss102 # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30103 'bce': 30 * 1, # high performance104 'iou': 0.5 * 1, # 0 / 255105 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)106 'mse': 150 * 0, # can smooth the saliency map107 'triplet': 3 * 0,108 'reg': 100 * 0,109 'ssim': 10 * 1, # help contours,110 'cnt': 5 * 0, # help contours111 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.112 }113 self.lambdas_cls = {114 'ce': 5.0115 }116 # Adv117 self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training118 self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)119 120 # PATH settings - inactive121 self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')122 self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')123 self.weights = {124 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),125 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),126 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),127 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),128 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),129 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),130 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),131 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),132 }133 134 # Callbacks - inactive135 self.verbose_eval = True136 self.only_S_MAE = False137 self.use_fp16 = False # Bugs. It may cause nan in training.138 self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs139 140 # others141 self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')142 143 self.batch_size_valid = 1144 self.rand_seed = 7145 # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]146 # with open(run_sh_file[0], 'r') as f:147 # lines = f.readlines()148 # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])149 # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])150 # self.val_step = [0, self.save_step][0]151 152 def print_task(self) -> None:153 # Return task for choosing settings in shell scripts.154 print(self.task)155 156 157 158### models/backbones/pvt_v2.py159 160import torch161import torch.nn as nn162from functools import partial163 164from timm.models.layers import DropPath, to_2tuple, trunc_normal_165from timm.models.registry import register_model166 167import math168 169# from config import Config170 171# config = Config()172 173class Mlp(nn.Module):174 def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):175 super().__init__()176 out_features = out_features or in_features177 hidden_features = hidden_features or in_features178 self.fc1 = nn.Linear(in_features, hidden_features)179 self.dwconv = DWConv(hidden_features)180 self.act = act_layer()181 self.fc2 = nn.Linear(hidden_features, out_features)182 self.drop = nn.Dropout(drop)183 184 self.apply(self._init_weights)185 186 def _init_weights(self, m):187 if isinstance(m, nn.Linear):188 trunc_normal_(m.weight, std=.02)189 if isinstance(m, nn.Linear) and m.bias is not None:190 nn.init.constant_(m.bias, 0)191 elif isinstance(m, nn.LayerNorm):192 nn.init.constant_(m.bias, 0)193 nn.init.constant_(m.weight, 1.0)194 elif isinstance(m, nn.Conv2d):195 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels196 fan_out //= m.groups197 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))198 if m.bias is not None:199 m.bias.data.zero_()200 201 def forward(self, x, H, W):202 x = self.fc1(x)203 x = self.dwconv(x, H, W)204 x = self.act(x)205 x = self.drop(x)206 x = self.fc2(x)207 x = self.drop(x)208 return x209 210 211class Attention(nn.Module):212 def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):213 super().__init__()214 assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."215 216 self.dim = dim217 self.num_heads = num_heads218 head_dim = dim // num_heads219 self.scale = qk_scale or head_dim ** -0.5220 221 self.q = nn.Linear(dim, dim, bias=qkv_bias)222 self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)223 self.attn_drop_prob = attn_drop224 self.attn_drop = nn.Dropout(attn_drop)225 self.proj = nn.Linear(dim, dim)226 self.proj_drop = nn.Dropout(proj_drop)227 228 self.sr_ratio = sr_ratio229 if sr_ratio > 1:230 self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)231 self.norm = nn.LayerNorm(dim)232 233 self.apply(self._init_weights)234 235 def _init_weights(self, m):236 if isinstance(m, nn.Linear):237 trunc_normal_(m.weight, std=.02)238 if isinstance(m, nn.Linear) and m.bias is not None:239 nn.init.constant_(m.bias, 0)240 elif isinstance(m, nn.LayerNorm):241 nn.init.constant_(m.bias, 0)242 nn.init.constant_(m.weight, 1.0)243 elif isinstance(m, nn.Conv2d):244 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels245 fan_out //= m.groups246 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))247 if m.bias is not None:248 m.bias.data.zero_()249 250 def forward(self, x, H, W):251 B, N, C = x.shape252 q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)253 254 if self.sr_ratio > 1:255 x_ = x.permute(0, 2, 1).reshape(B, C, H, W)256 x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)257 x_ = self.norm(x_)258 kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)259 else:260 kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)261 k, v = kv[0], kv[1]262 263 if config.SDPA_enabled:264 x = torch.nn.functional.scaled_dot_product_attention(265 q, k, v,266 attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False267 ).transpose(1, 2).reshape(B, N, C)268 else:269 attn = (q @ k.transpose(-2, -1)) * self.scale270 attn = attn.softmax(dim=-1)271 attn = self.attn_drop(attn)272 273 x = (attn @ v).transpose(1, 2).reshape(B, N, C)274 x = self.proj(x)275 x = self.proj_drop(x)276 277 return x278 279 280class Block(nn.Module):281 282 def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,283 drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):284 super().__init__()285 self.norm1 = norm_layer(dim)286 self.attn = Attention(287 dim,288 num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,289 attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)290 # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here291 self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()292 self.norm2 = norm_layer(dim)293 mlp_hidden_dim = int(dim * mlp_ratio)294 self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)295 296 self.apply(self._init_weights)297 298 def _init_weights(self, m):299 if isinstance(m, nn.Linear):300 trunc_normal_(m.weight, std=.02)301 if isinstance(m, nn.Linear) and m.bias is not None:302 nn.init.constant_(m.bias, 0)303 elif isinstance(m, nn.LayerNorm):304 nn.init.constant_(m.bias, 0)305 nn.init.constant_(m.weight, 1.0)306 elif isinstance(m, nn.Conv2d):307 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels308 fan_out //= m.groups309 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))310 if m.bias is not None:311 m.bias.data.zero_()312 313 def forward(self, x, H, W):314 x = x + self.drop_path(self.attn(self.norm1(x), H, W))315 x = x + self.drop_path(self.mlp(self.norm2(x), H, W))316 317 return x318 319 320class OverlapPatchEmbed(nn.Module):321 """ Image to Patch Embedding322 """323 324 def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):325 super().__init__()326 img_size = to_2tuple(img_size)327 patch_size = to_2tuple(patch_size)328 329 self.img_size = img_size330 self.patch_size = patch_size331 self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]332 self.num_patches = self.H * self.W333 self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,334 padding=(patch_size[0] // 2, patch_size[1] // 2))335 self.norm = nn.LayerNorm(embed_dim)336 337 self.apply(self._init_weights)338 339 def _init_weights(self, m):340 if isinstance(m, nn.Linear):341 trunc_normal_(m.weight, std=.02)342 if isinstance(m, nn.Linear) and m.bias is not None:343 nn.init.constant_(m.bias, 0)344 elif isinstance(m, nn.LayerNorm):345 nn.init.constant_(m.bias, 0)346 nn.init.constant_(m.weight, 1.0)347 elif isinstance(m, nn.Conv2d):348 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels349 fan_out //= m.groups350 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))351 if m.bias is not None:352 m.bias.data.zero_()353 354 def forward(self, x):355 x = self.proj(x)356 _, _, H, W = x.shape357 x = x.flatten(2).transpose(1, 2)358 x = self.norm(x)359 360 return x, H, W361 362 363class PyramidVisionTransformerImpr(nn.Module):364 def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],365 num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,366 attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,367 depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):368 super().__init__()369 self.num_classes = num_classes370 self.depths = depths371 372 # patch_embed373 self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,374 embed_dim=embed_dims[0])375 self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],376 embed_dim=embed_dims[1])377 self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],378 embed_dim=embed_dims[2])379 self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],380 embed_dim=embed_dims[3])381 382 # transformer encoder383 dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule384 cur = 0385 self.block1 = nn.ModuleList([Block(386 dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,387 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,388 sr_ratio=sr_ratios[0])389 for i in range(depths[0])])390 self.norm1 = norm_layer(embed_dims[0])391 392 cur += depths[0]393 self.block2 = nn.ModuleList([Block(394 dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,395 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,396 sr_ratio=sr_ratios[1])397 for i in range(depths[1])])398 self.norm2 = norm_layer(embed_dims[1])399 400 cur += depths[1]401 self.block3 = nn.ModuleList([Block(402 dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,403 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,404 sr_ratio=sr_ratios[2])405 for i in range(depths[2])])406 self.norm3 = norm_layer(embed_dims[2])407 408 cur += depths[2]409 self.block4 = nn.ModuleList([Block(410 dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,411 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,412 sr_ratio=sr_ratios[3])413 for i in range(depths[3])])414 self.norm4 = norm_layer(embed_dims[3])415 416 # classification head417 # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()418 419 self.apply(self._init_weights)420 421 def _init_weights(self, m):422 if isinstance(m, nn.Linear):423 trunc_normal_(m.weight, std=.02)424 if isinstance(m, nn.Linear) and m.bias is not None:425 nn.init.constant_(m.bias, 0)426 elif isinstance(m, nn.LayerNorm):427 nn.init.constant_(m.bias, 0)428 nn.init.constant_(m.weight, 1.0)429 elif isinstance(m, nn.Conv2d):430 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels431 fan_out //= m.groups432 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))433 if m.bias is not None:434 m.bias.data.zero_()435 436 def init_weights(self, pretrained=None):437 if isinstance(pretrained, str):438 logger = 1439 #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)440 441 def reset_drop_path(self, drop_path_rate):442 dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]443 cur = 0444 for i in range(self.depths[0]):445 self.block1[i].drop_path.drop_prob = dpr[cur + i]446 447 cur += self.depths[0]448 for i in range(self.depths[1]):449 self.block2[i].drop_path.drop_prob = dpr[cur + i]450 451 cur += self.depths[1]452 for i in range(self.depths[2]):453 self.block3[i].drop_path.drop_prob = dpr[cur + i]454 455 cur += self.depths[2]456 for i in range(self.depths[3]):457 self.block4[i].drop_path.drop_prob = dpr[cur + i]458 459 def freeze_patch_emb(self):460 self.patch_embed1.requires_grad = False461 462 @torch.jit.ignore463 def no_weight_decay(self):464 return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better465 466 def get_classifier(self):467 return self.head468 469 def reset_classifier(self, num_classes, global_pool=''):470 self.num_classes = num_classes471 self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()472 473 def forward_features(self, x):474 B = x.shape[0]475 outs = []476 477 # stage 1478 x, H, W = self.patch_embed1(x)479 for i, blk in enumerate(self.block1):480 x = blk(x, H, W)481 x = self.norm1(x)482 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()483 outs.append(x)484 485 # stage 2486 x, H, W = self.patch_embed2(x)487 for i, blk in enumerate(self.block2):488 x = blk(x, H, W)489 x = self.norm2(x)490 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()491 outs.append(x)492 493 # stage 3494 x, H, W = self.patch_embed3(x)495 for i, blk in enumerate(self.block3):496 x = blk(x, H, W)497 x = self.norm3(x)498 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()499 outs.append(x)500 501 # stage 4502 x, H, W = self.patch_embed4(x)503 for i, blk in enumerate(self.block4):504 x = blk(x, H, W)505 x = self.norm4(x)506 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()507 outs.append(x)508 509 return outs510 511 # return x.mean(dim=1)512 513 def forward(self, x):514 x = self.forward_features(x)515 # x = self.head(x)516 517 return x518 519 520class DWConv(nn.Module):521 def __init__(self, dim=768):522 super(DWConv, self).__init__()523 self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)524 525 def forward(self, x, H, W):526 B, N, C = x.shape527 x = x.transpose(1, 2).view(B, C, H, W).contiguous()528 x = self.dwconv(x)529 x = x.flatten(2).transpose(1, 2)530 531 return x532 533 534def _conv_filter(state_dict, patch_size=16):535 """ convert patch embedding weight from manual patchify + linear proj to conv"""536 out_dict = {}537 for k, v in state_dict.items():538 if 'patch_embed.proj.weight' in k:539 v = v.reshape((v.shape[0], 3, patch_size, patch_size))540 out_dict[k] = v541 542 return out_dict543 544 545## @register_model546class pvt_v2_b0(PyramidVisionTransformerImpr):547 def __init__(self, **kwargs):548 super(pvt_v2_b0, self).__init__(549 patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],550 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],551 drop_rate=0.0, drop_path_rate=0.1)552 553 554 555## @register_model556class pvt_v2_b1(PyramidVisionTransformerImpr):557 def __init__(self, **kwargs):558 super(pvt_v2_b1, self).__init__(559 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],560 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],561 drop_rate=0.0, drop_path_rate=0.1)562 563## @register_model564class pvt_v2_b2(PyramidVisionTransformerImpr):565 def __init__(self, in_channels=3, **kwargs):566 super(pvt_v2_b2, self).__init__(567 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],568 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],569 drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)570 571## @register_model572class pvt_v2_b3(PyramidVisionTransformerImpr):573 def __init__(self, **kwargs):574 super(pvt_v2_b3, self).__init__(575 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],576 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],577 drop_rate=0.0, drop_path_rate=0.1)578 579## @register_model580class pvt_v2_b4(PyramidVisionTransformerImpr):581 def __init__(self, **kwargs):582 super(pvt_v2_b4, self).__init__(583 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],584 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],585 drop_rate=0.0, drop_path_rate=0.1)586 587 588## @register_model589class pvt_v2_b5(PyramidVisionTransformerImpr):590 def __init__(self, **kwargs):591 super(pvt_v2_b5, self).__init__(592 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],593 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],594 drop_rate=0.0, drop_path_rate=0.1)595 596 597 598### models/backbones/swin_v1.py599 600# --------------------------------------------------------601# Swin Transformer602# Copyright (c) 2021 Microsoft603# Licensed under The MIT License [see LICENSE for details]604# Written by Ze Liu, Yutong Lin, Yixuan Wei605# --------------------------------------------------------606 607import torch608import torch.nn as nn609import torch.nn.functional as F610import torch.utils.checkpoint as checkpoint611import numpy as np612from timm.models.layers import DropPath, to_2tuple, trunc_normal_613 614# from config import Config615 616 617# config = Config()618 619class Mlp(nn.Module):620 """ Multilayer perceptron."""621 622 def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):623 super().__init__()624 out_features = out_features or in_features625 hidden_features = hidden_features or in_features626 self.fc1 = nn.Linear(in_features, hidden_features)627 self.act = act_layer()628 self.fc2 = nn.Linear(hidden_features, out_features)629 self.drop = nn.Dropout(drop)630 631 def forward(self, x):632 x = self.fc1(x)633 x = self.act(x)634 x = self.drop(x)635 x = self.fc2(x)636 x = self.drop(x)637 return x638 639 640def window_partition(x, window_size):641 """642 Args:643 x: (B, H, W, C)644 window_size (int): window size645 646 Returns:647 windows: (num_windows*B, window_size, window_size, C)648 """649 B, H, W, C = x.shape650 x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)651 windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)652 return windows653 654 655def window_reverse(windows, window_size, H, W):656 """657 Args:658 windows: (num_windows*B, window_size, window_size, C)659 window_size (int): Window size660 H (int): Height of image661 W (int): Width of image662 663 Returns:664 x: (B, H, W, C)665 """666 B = int(windows.shape[0] / (H * W / window_size / window_size))667 x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)668 x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)669 return x670 671 672class WindowAttention(nn.Module):673 """ Window based multi-head self attention (W-MSA) module with relative position bias.674 It supports both of shifted and non-shifted window.675 676 Args:677 dim (int): Number of input channels.678 window_size (tuple[int]): The height and width of the window.679 num_heads (int): Number of attention heads.680 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True681 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set682 attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0683 proj_drop (float, optional): Dropout ratio of output. Default: 0.0684 """685 686 def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):687 688 super().__init__()689 self.dim = dim690 self.window_size = window_size # Wh, Ww691 self.num_heads = num_heads692 head_dim = dim // num_heads693 self.scale = qk_scale or head_dim ** -0.5694 695 # define a parameter table of relative position bias696 self.relative_position_bias_table = nn.Parameter(697 torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH698 699 # get pair-wise relative position index for each token inside the window700 coords_h = torch.arange(self.window_size[0])701 coords_w = torch.arange(self.window_size[1])702 coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww703 coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww704 relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww705 relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2706 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0707 relative_coords[:, :, 1] += self.window_size[1] - 1708 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1709 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww710 self.register_buffer("relative_position_index", relative_position_index)711 712 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)713 self.attn_drop_prob = attn_drop714 self.attn_drop = nn.Dropout(attn_drop)715 self.proj = nn.Linear(dim, dim)716 self.proj_drop = nn.Dropout(proj_drop)717 718 trunc_normal_(self.relative_position_bias_table, std=.02)719 self.softmax = nn.Softmax(dim=-1)720 721 def forward(self, x, mask=None):722 """ Forward function.723 724 Args:725 x: input features with shape of (num_windows*B, N, C)726 mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None727 """728 B_, N, C = x.shape729 qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)730 q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)731 732 q = q * self.scale733 734 if config.SDPA_enabled:735 x = torch.nn.functional.scaled_dot_product_attention(736 q, k, v,737 attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False738 ).transpose(1, 2).reshape(B_, N, C)739 else:740 attn = (q @ k.transpose(-2, -1))741 742 relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(743 self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH744 relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww745 attn = attn + relative_position_bias.unsqueeze(0)746 747 if mask is not None:748 nW = mask.shape[0]749 attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)750 attn = attn.view(-1, self.num_heads, N, N)751 attn = self.softmax(attn)752 else:753 attn = self.softmax(attn)754 755 attn = self.attn_drop(attn)756 757 x = (attn @ v).transpose(1, 2).reshape(B_, N, C)758 x = self.proj(x)759 x = self.proj_drop(x)760 return x761 762 763class SwinTransformerBlock(nn.Module):764 """ Swin Transformer Block.765 766 Args:767 dim (int): Number of input channels.768 num_heads (int): Number of attention heads.769 window_size (int): Window size.770 shift_size (int): Shift size for SW-MSA.771 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.772 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True773 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.774 drop (float, optional): Dropout rate. Default: 0.0775 attn_drop (float, optional): Attention dropout rate. Default: 0.0776 drop_path (float, optional): Stochastic depth rate. Default: 0.0777 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU778 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm779 """780 781 def __init__(self, dim, num_heads, window_size=7, shift_size=0,782 mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,783 act_layer=nn.GELU, norm_layer=nn.LayerNorm):784 super().__init__()785 self.dim = dim786 self.num_heads = num_heads787 self.window_size = window_size788 self.shift_size = shift_size789 self.mlp_ratio = mlp_ratio790 assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"791 792 self.norm1 = norm_layer(dim)793 self.attn = WindowAttention(794 dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,795 qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)796 797 self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()798 self.norm2 = norm_layer(dim)799 mlp_hidden_dim = int(dim * mlp_ratio)800 self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)801 802 self.H = None803 self.W = None804 805 def forward(self, x, mask_matrix):806 """ Forward function.807 808 Args:809 x: Input feature, tensor size (B, H*W, C).810 H, W: Spatial resolution of the input feature.811 mask_matrix: Attention mask for cyclic shift.812 """813 B, L, C = x.shape814 H, W = self.H, self.W815 assert L == H * W, "input feature has wrong size"816 817 shortcut = x818 x = self.norm1(x)819 x = x.view(B, H, W, C)820 821 # pad feature maps to multiples of window size822 pad_l = pad_t = 0823 pad_r = (self.window_size - W % self.window_size) % self.window_size824 pad_b = (self.window_size - H % self.window_size) % self.window_size825 x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))826 _, Hp, Wp, _ = x.shape827 828 # cyclic shift829 if self.shift_size > 0:830 shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))831 attn_mask = mask_matrix832 else:833 shifted_x = x834 attn_mask = None835 836 # partition windows837 x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C838 x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C839 840 # W-MSA/SW-MSA841 attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C842 843 # merge windows844 attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)845 shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C846 847 # reverse cyclic shift848 if self.shift_size > 0:849 x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))850 else:851 x = shifted_x852 853 if pad_r > 0 or pad_b > 0:854 x = x[:, :H, :W, :].contiguous()855 856 x = x.view(B, H * W, C)857 858 # FFN859 x = shortcut + self.drop_path(x)860 x = x + self.drop_path(self.mlp(self.norm2(x)))861 862 return x863 864 865class PatchMerging(nn.Module):866 """ Patch Merging Layer867 868 Args:869 dim (int): Number of input channels.870 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm871 """872 def __init__(self, dim, norm_layer=nn.LayerNorm):873 super().__init__()874 self.dim = dim875 self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)876 self.norm = norm_layer(4 * dim)877 878 def forward(self, x, H, W):879 """ Forward function.880 881 Args:882 x: Input feature, tensor size (B, H*W, C).883 H, W: Spatial resolution of the input feature.884 """885 B, L, C = x.shape886 assert L == H * W, "input feature has wrong size"887 888 x = x.view(B, H, W, C)889 890 # padding891 pad_input = (H % 2 == 1) or (W % 2 == 1)892 if pad_input:893 x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))894 895 x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C896 x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C897 x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C898 x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C899 x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C900 x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C901 902 x = self.norm(x)903 x = self.reduction(x)904 905 return x906 907 908class BasicLayer(nn.Module):909 """ A basic Swin Transformer layer for one stage.910 911 Args:912 dim (int): Number of feature channels913 depth (int): Depths of this stage.914 num_heads (int): Number of attention head.915 window_size (int): Local window size. Default: 7.916 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.917 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True918 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.919 drop (float, optional): Dropout rate. Default: 0.0920 attn_drop (float, optional): Attention dropout rate. Default: 0.0921 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0922 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm923 downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None924 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.925 """926 927 def __init__(self,928 dim,929 depth,930 num_heads,931 window_size=7,932 mlp_ratio=4.,933 qkv_bias=True,934 qk_scale=None,935 drop=0.,936 attn_drop=0.,937 drop_path=0.,938 norm_layer=nn.LayerNorm,939 downsample=None,940 use_checkpoint=False):941 super().__init__()942 self.window_size = window_size943 self.shift_size = window_size // 2944 self.depth = depth945 self.use_checkpoint = use_checkpoint946 947 # build blocks948 self.blocks = nn.ModuleList([949 SwinTransformerBlock(950 dim=dim,951 num_heads=num_heads,952 window_size=window_size,953 shift_size=0 if (i % 2 == 0) else window_size // 2,954 mlp_ratio=mlp_ratio,955 qkv_bias=qkv_bias,956 qk_scale=qk_scale,957 drop=drop,958 attn_drop=attn_drop,959 drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,960 norm_layer=norm_layer)961 for i in range(depth)])962 963 # patch merging layer964 if downsample is not None:965 self.downsample = downsample(dim=dim, norm_layer=norm_layer)966 else:967 self.downsample = None968 969 def forward(self, x, H, W):970 """ Forward function.971 972 Args:973 x: Input feature, tensor size (B, H*W, C).974 H, W: Spatial resolution of the input feature.975 """976 977 # calculate attention mask for SW-MSA978 Hp = int(np.ceil(H / self.window_size)) * self.window_size979 Wp = int(np.ceil(W / self.window_size)) * self.window_size980 img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1981 h_slices = (slice(0, -self.window_size),982 slice(-self.window_size, -self.shift_size),983 slice(-self.shift_size, None))984 w_slices = (slice(0, -self.window_size),985 slice(-self.window_size, -self.shift_size),986 slice(-self.shift_size, None))987 cnt = 0988 for h in h_slices:989 for w in w_slices:990 img_mask[:, h, w, :] = cnt991 cnt += 1992 993 mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1994 mask_windows = mask_windows.view(-1, self.window_size * self.window_size)995 attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)996 attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)997 998 for blk in self.blocks:999 blk.H, blk.W = H, W1000 if self.use_checkpoint:1001 x = checkpoint.checkpoint(blk, x, attn_mask)1002 else:1003 x = blk(x, attn_mask)1004 if self.downsample is not None:1005 x_down = self.downsample(x, H, W)1006 Wh, Ww = (H + 1) // 2, (W + 1) // 21007 return x, H, W, x_down, Wh, Ww1008 else:1009 return x, H, W, x, H, W1010 1011 1012class PatchEmbed(nn.Module):1013 """ Image to Patch Embedding1014 1015 Args:1016 patch_size (int): Patch token size. Default: 4.1017 in_channels (int): Number of input image channels. Default: 3.1018 embed_dim (int): Number of linear projection output channels. Default: 96.1019 norm_layer (nn.Module, optional): Normalization layer. Default: None1020 """1021 1022 def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):1023 super().__init__()1024 patch_size = to_2tuple(patch_size)1025 self.patch_size = patch_size1026 1027 self.in_channels = in_channels1028 self.embed_dim = embed_dim1029 1030 self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)1031 if norm_layer is not None:1032 self.norm = norm_layer(embed_dim)1033 else:1034 self.norm = None1035 1036 def forward(self, x):1037 """Forward function."""1038 # padding1039 _, _, H, W = x.size()1040 if W % self.patch_size[1] != 0:1041 x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))1042 if H % self.patch_size[0] != 0:1043 x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))1044 1045 x = self.proj(x) # B C Wh Ww1046 if self.norm is not None:1047 Wh, Ww = x.size(2), x.size(3)1048 x = x.flatten(2).transpose(1, 2)1049 x = self.norm(x)1050 x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)1051 1052 return x1053 1054 1055class SwinTransformer(nn.Module):1056 """ Swin Transformer backbone.1057 A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -1058 https://arxiv.org/pdf/2103.140301059 1060 Args:1061 pretrain_img_size (int): Input image size for training the pretrained model,1062 used in absolute postion embedding. Default 224.1063 patch_size (int | tuple(int)): Patch size. Default: 4.1064 in_channels (int): Number of input image channels. Default: 3.1065 embed_dim (int): Number of linear projection output channels. Default: 96.1066 depths (tuple[int]): Depths of each Swin Transformer stage.1067 num_heads (tuple[int]): Number of attention head of each stage.1068 window_size (int): Window size. Default: 7.1069 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.1070 qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True1071 qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.1072 drop_rate (float): Dropout rate.1073 attn_drop_rate (float): Attention dropout rate. Default: 0.1074 drop_path_rate (float): Stochastic depth rate. Default: 0.2.1075 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.1076 ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.1077 patch_norm (bool): If True, add normalization after patch embedding. Default: True.1078 out_indices (Sequence[int]): Output from which stages.1079 frozen_stages (int): Stages to be frozen (stop grad and set eval mode).1080 -1 means not freezing any parameters.1081 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.1082 """1083 1084 def __init__(self,1085 pretrain_img_size=224,1086 patch_size=4,1087 in_channels=3,1088 embed_dim=96,1089 depths=[2, 2, 6, 2],1090 num_heads=[3, 6, 12, 24],1091 window_size=7,1092 mlp_ratio=4.,1093 qkv_bias=True,1094 qk_scale=None,1095 drop_rate=0.,1096 attn_drop_rate=0.,1097 drop_path_rate=0.2,1098 norm_layer=nn.LayerNorm,1099 ape=False,1100 patch_norm=True,1101 out_indices=(0, 1, 2, 3),1102 frozen_stages=-1,1103 use_checkpoint=False):1104 super().__init__()1105 1106 self.pretrain_img_size = pretrain_img_size1107 self.num_layers = len(depths)1108 self.embed_dim = embed_dim1109 self.ape = ape1110 self.patch_norm = patch_norm1111 self.out_indices = out_indices1112 self.frozen_stages = frozen_stages1113 1114 # split image into non-overlapping patches1115 self.patch_embed = PatchEmbed(1116 patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,1117 norm_layer=norm_layer if self.patch_norm else None)1118 1119 # absolute position embedding1120 if self.ape:1121 pretrain_img_size = to_2tuple(pretrain_img_size)1122 patch_size = to_2tuple(patch_size)1123 patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]1124 1125 self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))1126 trunc_normal_(self.absolute_pos_embed, std=.02)1127 1128 self.pos_drop = nn.Dropout(p=drop_rate)1129 1130 # stochastic depth1131 dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule1132 1133 # build layers1134 self.layers = nn.ModuleList()1135 for i_layer in range(self.num_layers):1136 layer = BasicLayer(1137 dim=int(embed_dim * 2 ** i_layer),1138 depth=depths[i_layer],1139 num_heads=num_heads[i_layer],1140 window_size=window_size,1141 mlp_ratio=mlp_ratio,1142 qkv_bias=qkv_bias,1143 qk_scale=qk_scale,1144 drop=drop_rate,1145 attn_drop=attn_drop_rate,1146 drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],1147 norm_layer=norm_layer,1148 downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,1149 use_checkpoint=use_checkpoint)1150 self.layers.append(layer)1151 1152 num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]1153 self.num_features = num_features1154 1155 # add a norm layer for each output1156 for i_layer in out_indices:1157 layer = norm_layer(num_features[i_layer])1158 layer_name = f'norm{i_layer}'1159 self.add_module(layer_name, layer)1160 1161 self._freeze_stages()1162 1163 def _freeze_stages(self):1164 if self.frozen_stages >= 0:1165 self.patch_embed.eval()1166 for param in self.patch_embed.parameters():1167 param.requires_grad = False1168 1169 if self.frozen_stages >= 1 and self.ape:1170 self.absolute_pos_embed.requires_grad = False1171 1172 if self.frozen_stages >= 2:1173 self.pos_drop.eval()1174 for i in range(0, self.frozen_stages - 1):1175 m = self.layers[i]1176 m.eval()1177 for param in m.parameters():1178 param.requires_grad = False1179 1180 1181 def forward(self, x):1182 """Forward function."""1183 x = self.patch_embed(x)1184 1185 Wh, Ww = x.size(2), x.size(3)1186 if self.ape:1187 # interpolate the position embedding to the corresponding size1188 absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')1189 x = (x + absolute_pos_embed) # B Wh*Ww C1190 1191 outs = []#x.contiguous()]1192 x = x.flatten(2).transpose(1, 2)1193 x = self.pos_drop(x)1194 for i in range(self.num_layers):1195 layer = self.layers[i]1196 x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)1197 1198 if i in self.out_indices:1199 norm_layer = getattr(self, f'norm{i}')1200 x_out = norm_layer(x_out)