birefnet.py
90.0 KB · 2251 lines · python Raw
1 ### config.py
2
3 import os
4 import math
5 from transformers import PretrainedConfig
6
7
8 class Config(PretrainedConfig):
9 def __init__(self) -> None:
10 # Compatible with the latest version of transformers.
11 # Error source: https://github.com/huggingface/transformers/commit/9568b506ed511c76ab4d0c6ed591c7fce8e048a5
12 # Previous solution in the users' end: https://github.com/ZhengPeng7/BiRefNet/issues/189#issuecomment-2716688688
13 super().__init__()
14
15 # PATH settings
16 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/xx
17
18 # TASK settings
19 self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
20 self.training_set = {
21 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
22 'COD': 'TR-COD10K+TR-CAMO',
23 '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],
24 '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.
25 'P3M-10k': 'TR-P3M-10k',
26 }[self.task]
27 self.prompt4loc = ['dense', 'sparse'][0]
28
29 # Faster-Training settings
30 self.load_all = True
31 self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
32 # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
33 # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
34 # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
35 self.precisionHigh = True
36
37 # MODEL settings
38 self.ms_supervision = True
39 self.out_ref = self.ms_supervision and True
40 self.dec_ipt = True
41 self.dec_ipt_split = True
42 self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
43 self.mul_scl_ipt = ['', 'add', 'cat'][2]
44 self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
45 self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
46 self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
47
48 # TRAINING settings
49 self.batch_size = 4
50 self.IoU_finetune_last_epochs = [
51 0,
52 {
53 'DIS5K': -50,
54 'COD': -20,
55 'HRSOD': -20,
56 'DIS5K+HRSOD+HRS10K': -20,
57 'P3M-10k': -20,
58 }[self.task]
59 ][1] # choose 0 to skip
60 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 linearly
61 self.size = 1024
62 self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
63
64 # Backbone settings
65 self.bb = [
66 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
67 'swin_v1_t', 'swin_v1_s', # 3, 4
68 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
69 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
70 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
71 ][3]
72 self.lateral_channels_in_collection = {
73 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
74 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
75 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
76 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
77 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
78 }[self.bb]
79 if self.mul_scl_ipt == 'cat':
80 self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
81 self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
82
83 # MODEL settings - inactive
84 self.lat_blk = ['BasicLatBlk'][0]
85 self.dec_channels_inter = ['fixed', 'adap'][0]
86 self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
87 self.progressive_ref = self.refine and True
88 self.ender = self.progressive_ref and False
89 self.scale = self.progressive_ref and 2
90 self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
91 self.refine_iteration = 1
92 self.freeze_bb = False
93 self.model = [
94 'BiRefNet',
95 ][0]
96 if self.dec_blk == 'HierarAttDecBlk':
97 self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
98
99 # TRAINING settings - inactive
100 self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
101 self.optimizer = ['Adam', 'AdamW'][1]
102 self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
103 self.lr_decay_rate = 0.5
104 # Loss
105 self.lambdas_pix_last = {
106 # not 0 means opening this loss
107 # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
108 'bce': 30 * 1, # high performance
109 'iou': 0.5 * 1, # 0 / 255
110 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
111 'mse': 150 * 0, # can smooth the saliency map
112 'triplet': 3 * 0,
113 'reg': 100 * 0,
114 'ssim': 10 * 1, # help contours,
115 'cnt': 5 * 0, # help contours
116 '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.
117 }
118 self.lambdas_cls = {
119 'ce': 5.0
120 }
121 # Adv
122 self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
123 self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
124
125 # PATH settings - inactive
126 self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
127 self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
128 self.weights = {
129 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
130 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
131 '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]),
132 '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]),
133 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
134 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
135 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
136 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
137 }
138
139 # Callbacks - inactive
140 self.verbose_eval = True
141 self.only_S_MAE = False
142 self.use_fp16 = False # Bugs. It may cause nan in training.
143 self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
144
145 # others
146 self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
147
148 self.batch_size_valid = 1
149 self.rand_seed = 7
150 # 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]
151 # with open(run_sh_file[0], 'r') as f:
152 # lines = f.readlines()
153 # 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])
154 # 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])
155 # self.val_step = [0, self.save_step][0]
156
157 def print_task(self) -> None:
158 # Return task for choosing settings in shell scripts.
159 print(self.task)
160
161
162
163 ### models/backbones/pvt_v2.py
164
165 import torch
166 import torch.nn as nn
167 from functools import partial
168
169 from timm.layers import DropPath, to_2tuple, trunc_normal_
170
171
172 import math
173
174 # from config import Config
175
176 # config = Config()
177
178 class Mlp(nn.Module):
179 def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
180 super().__init__()
181 out_features = out_features or in_features
182 hidden_features = hidden_features or in_features
183 self.fc1 = nn.Linear(in_features, hidden_features)
184 self.dwconv = DWConv(hidden_features)
185 self.act = act_layer()
186 self.fc2 = nn.Linear(hidden_features, out_features)
187 self.drop = nn.Dropout(drop)
188
189 self.apply(self._init_weights)
190
191 def _init_weights(self, m):
192 if isinstance(m, nn.Linear):
193 trunc_normal_(m.weight, std=.02)
194 if isinstance(m, nn.Linear) and m.bias is not None:
195 nn.init.constant_(m.bias, 0)
196 elif isinstance(m, nn.LayerNorm):
197 nn.init.constant_(m.bias, 0)
198 nn.init.constant_(m.weight, 1.0)
199 elif isinstance(m, nn.Conv2d):
200 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
201 fan_out //= m.groups
202 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
203 if m.bias is not None:
204 m.bias.data.zero_()
205
206 def forward(self, x, H, W):
207 x = self.fc1(x)
208 x = self.dwconv(x, H, W)
209 x = self.act(x)
210 x = self.drop(x)
211 x = self.fc2(x)
212 x = self.drop(x)
213 return x
214
215
216 class Attention(nn.Module):
217 def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
218 super().__init__()
219 assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
220
221 self.dim = dim
222 self.num_heads = num_heads
223 head_dim = dim // num_heads
224 self.scale = qk_scale or head_dim ** -0.5
225
226 self.q = nn.Linear(dim, dim, bias=qkv_bias)
227 self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
228 self.attn_drop_prob = attn_drop
229 self.attn_drop = nn.Dropout(attn_drop)
230 self.proj = nn.Linear(dim, dim)
231 self.proj_drop = nn.Dropout(proj_drop)
232
233 self.sr_ratio = sr_ratio
234 if sr_ratio > 1:
235 self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
236 self.norm = nn.LayerNorm(dim)
237
238 self.apply(self._init_weights)
239
240 def _init_weights(self, m):
241 if isinstance(m, nn.Linear):
242 trunc_normal_(m.weight, std=.02)
243 if isinstance(m, nn.Linear) and m.bias is not None:
244 nn.init.constant_(m.bias, 0)
245 elif isinstance(m, nn.LayerNorm):
246 nn.init.constant_(m.bias, 0)
247 nn.init.constant_(m.weight, 1.0)
248 elif isinstance(m, nn.Conv2d):
249 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
250 fan_out //= m.groups
251 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
252 if m.bias is not None:
253 m.bias.data.zero_()
254
255 def forward(self, x, H, W):
256 B, N, C = x.shape
257 q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
258
259 if self.sr_ratio > 1:
260 x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
261 x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
262 x_ = self.norm(x_)
263 kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
264 else:
265 kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
266 k, v = kv[0], kv[1]
267
268 if config.SDPA_enabled:
269 x = torch.nn.functional.scaled_dot_product_attention(
270 q, k, v,
271 attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
272 ).transpose(1, 2).reshape(B, N, C)
273 else:
274 attn = (q @ k.transpose(-2, -1)) * self.scale
275 attn = attn.softmax(dim=-1)
276 attn = self.attn_drop(attn)
277
278 x = (attn @ v).transpose(1, 2).reshape(B, N, C)
279 x = self.proj(x)
280 x = self.proj_drop(x)
281
282 return x
283
284
285 class Block(nn.Module):
286
287 def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
288 drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
289 super().__init__()
290 self.norm1 = norm_layer(dim)
291 self.attn = Attention(
292 dim,
293 num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
294 attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
295 # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
296 self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
297 self.norm2 = norm_layer(dim)
298 mlp_hidden_dim = int(dim * mlp_ratio)
299 self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
300
301 self.apply(self._init_weights)
302
303 def _init_weights(self, m):
304 if isinstance(m, nn.Linear):
305 trunc_normal_(m.weight, std=.02)
306 if isinstance(m, nn.Linear) and m.bias is not None:
307 nn.init.constant_(m.bias, 0)
308 elif isinstance(m, nn.LayerNorm):
309 nn.init.constant_(m.bias, 0)
310 nn.init.constant_(m.weight, 1.0)
311 elif isinstance(m, nn.Conv2d):
312 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
313 fan_out //= m.groups
314 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
315 if m.bias is not None:
316 m.bias.data.zero_()
317
318 def forward(self, x, H, W):
319 x = x + self.drop_path(self.attn(self.norm1(x), H, W))
320 x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
321
322 return x
323
324
325 class OverlapPatchEmbed(nn.Module):
326 """ Image to Patch Embedding
327 """
328
329 def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
330 super().__init__()
331 img_size = to_2tuple(img_size)
332 patch_size = to_2tuple(patch_size)
333
334 self.img_size = img_size
335 self.patch_size = patch_size
336 self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
337 self.num_patches = self.H * self.W
338 self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
339 padding=(patch_size[0] // 2, patch_size[1] // 2))
340 self.norm = nn.LayerNorm(embed_dim)
341
342 self.apply(self._init_weights)
343
344 def _init_weights(self, m):
345 if isinstance(m, nn.Linear):
346 trunc_normal_(m.weight, std=.02)
347 if isinstance(m, nn.Linear) and m.bias is not None:
348 nn.init.constant_(m.bias, 0)
349 elif isinstance(m, nn.LayerNorm):
350 nn.init.constant_(m.bias, 0)
351 nn.init.constant_(m.weight, 1.0)
352 elif isinstance(m, nn.Conv2d):
353 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
354 fan_out //= m.groups
355 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
356 if m.bias is not None:
357 m.bias.data.zero_()
358
359 def forward(self, x):
360 x = self.proj(x)
361 _, _, H, W = x.shape
362 x = x.flatten(2).transpose(1, 2)
363 x = self.norm(x)
364
365 return x, H, W
366
367
368 class PyramidVisionTransformerImpr(nn.Module):
369 def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
370 num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
371 attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
372 depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
373 super().__init__()
374 self.num_classes = num_classes
375 self.depths = depths
376
377 # patch_embed
378 self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
379 embed_dim=embed_dims[0])
380 self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
381 embed_dim=embed_dims[1])
382 self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
383 embed_dim=embed_dims[2])
384 self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
385 embed_dim=embed_dims[3])
386
387 # transformer encoder
388 dpr = np.linspace(0, drop_path_rate, sum(depths)).tolist() # stochastic depth decay rule
389 cur = 0
390 self.block1 = nn.ModuleList([Block(
391 dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
392 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
393 sr_ratio=sr_ratios[0])
394 for i in range(depths[0])])
395 self.norm1 = norm_layer(embed_dims[0])
396
397 cur += depths[0]
398 self.block2 = nn.ModuleList([Block(
399 dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
400 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
401 sr_ratio=sr_ratios[1])
402 for i in range(depths[1])])
403 self.norm2 = norm_layer(embed_dims[1])
404
405 cur += depths[1]
406 self.block3 = nn.ModuleList([Block(
407 dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
408 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
409 sr_ratio=sr_ratios[2])
410 for i in range(depths[2])])
411 self.norm3 = norm_layer(embed_dims[2])
412
413 cur += depths[2]
414 self.block4 = nn.ModuleList([Block(
415 dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
416 drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
417 sr_ratio=sr_ratios[3])
418 for i in range(depths[3])])
419 self.norm4 = norm_layer(embed_dims[3])
420
421 # classification head
422 # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
423
424 self.apply(self._init_weights)
425
426 def _init_weights(self, m):
427 if isinstance(m, nn.Linear):
428 trunc_normal_(m.weight, std=.02)
429 if isinstance(m, nn.Linear) and m.bias is not None:
430 nn.init.constant_(m.bias, 0)
431 elif isinstance(m, nn.LayerNorm):
432 nn.init.constant_(m.bias, 0)
433 nn.init.constant_(m.weight, 1.0)
434 elif isinstance(m, nn.Conv2d):
435 fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
436 fan_out //= m.groups
437 m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
438 if m.bias is not None:
439 m.bias.data.zero_()
440
441 def init_weights(self, pretrained=None):
442 if isinstance(pretrained, str):
443 logger = 1
444 #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
445
446 def reset_drop_path(self, drop_path_rate):
447 dpr = np.linspace(0, drop_path_rate, sum(self.depths)).tolist()
448 cur = 0
449 for i in range(self.depths[0]):
450 self.block1[i].drop_path.drop_prob = dpr[cur + i]
451
452 cur += self.depths[0]
453 for i in range(self.depths[1]):
454 self.block2[i].drop_path.drop_prob = dpr[cur + i]
455
456 cur += self.depths[1]
457 for i in range(self.depths[2]):
458 self.block3[i].drop_path.drop_prob = dpr[cur + i]
459
460 cur += self.depths[2]
461 for i in range(self.depths[3]):
462 self.block4[i].drop_path.drop_prob = dpr[cur + i]
463
464 def freeze_patch_emb(self):
465 self.patch_embed1.requires_grad = False
466
467 @torch.jit.ignore
468 def no_weight_decay(self):
469 return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
470
471 def get_classifier(self):
472 return self.head
473
474 def reset_classifier(self, num_classes, global_pool=''):
475 self.num_classes = num_classes
476 self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
477
478 def forward_features(self, x):
479 B = x.shape[0]
480 outs = []
481
482 # stage 1
483 x, H, W = self.patch_embed1(x)
484 for i, blk in enumerate(self.block1):
485 x = blk(x, H, W)
486 x = self.norm1(x)
487 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
488 outs.append(x)
489
490 # stage 2
491 x, H, W = self.patch_embed2(x)
492 for i, blk in enumerate(self.block2):
493 x = blk(x, H, W)
494 x = self.norm2(x)
495 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
496 outs.append(x)
497
498 # stage 3
499 x, H, W = self.patch_embed3(x)
500 for i, blk in enumerate(self.block3):
501 x = blk(x, H, W)
502 x = self.norm3(x)
503 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
504 outs.append(x)
505
506 # stage 4
507 x, H, W = self.patch_embed4(x)
508 for i, blk in enumerate(self.block4):
509 x = blk(x, H, W)
510 x = self.norm4(x)
511 x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
512 outs.append(x)
513
514 return outs
515
516 # return x.mean(dim=1)
517
518 def forward(self, x):
519 x = self.forward_features(x)
520 # x = self.head(x)
521
522 return x
523
524
525 class DWConv(nn.Module):
526 def __init__(self, dim=768):
527 super(DWConv, self).__init__()
528 self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
529
530 def forward(self, x, H, W):
531 B, N, C = x.shape
532 x = x.transpose(1, 2).view(B, C, H, W).contiguous()
533 x = self.dwconv(x)
534 x = x.flatten(2).transpose(1, 2)
535
536 return x
537
538
539 def _conv_filter(state_dict, patch_size=16):
540 """ convert patch embedding weight from manual patchify + linear proj to conv"""
541 out_dict = {}
542 for k, v in state_dict.items():
543 if 'patch_embed.proj.weight' in k:
544 v = v.reshape((v.shape[0], 3, patch_size, patch_size))
545 out_dict[k] = v
546
547 return out_dict
548
549
550 class pvt_v2_b0(PyramidVisionTransformerImpr):
551 def __init__(self, **kwargs):
552 super(pvt_v2_b0, self).__init__(
553 patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
554 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
555 drop_rate=0.0, drop_path_rate=0.1)
556
557
558
559 class pvt_v2_b1(PyramidVisionTransformerImpr):
560 def __init__(self, **kwargs):
561 super(pvt_v2_b1, self).__init__(
562 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
563 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
564 drop_rate=0.0, drop_path_rate=0.1)
565
566 class pvt_v2_b2(PyramidVisionTransformerImpr):
567 def __init__(self, in_channels=3, **kwargs):
568 super(pvt_v2_b2, self).__init__(
569 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
570 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
571 drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
572
573 class pvt_v2_b3(PyramidVisionTransformerImpr):
574 def __init__(self, **kwargs):
575 super(pvt_v2_b3, self).__init__(
576 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
577 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
578 drop_rate=0.0, drop_path_rate=0.1)
579
580 class 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 class pvt_v2_b5(PyramidVisionTransformerImpr):
589 def __init__(self, **kwargs):
590 super(pvt_v2_b5, self).__init__(
591 patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
592 qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
593 drop_rate=0.0, drop_path_rate=0.1)
594
595
596
597 ### models/backbones/swin_v1.py
598
599 # --------------------------------------------------------
600 # Swin Transformer
601 # Copyright (c) 2021 Microsoft
602 # Licensed under The MIT License [see LICENSE for details]
603 # Written by Ze Liu, Yutong Lin, Yixuan Wei
604 # --------------------------------------------------------
605
606 import torch
607 import torch.nn as nn
608 import torch.nn.functional as F
609 import torch.utils.checkpoint as checkpoint
610 import numpy as np
611 from timm.layers import DropPath, to_2tuple, trunc_normal_
612
613 # from config import Config
614
615
616 # config = Config()
617
618
619 class 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_features
625 hidden_features = hidden_features or in_features
626 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 x
638
639
640 def window_partition(x, window_size):
641 """
642 Args:
643 x: (B, H, W, C)
644 window_size (int): window size
645
646 Returns:
647 windows: (num_windows*B, window_size, window_size, C)
648 """
649 B, H, W, C = x.shape
650 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 windows
653
654
655 def 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 size
660 H (int): Height of image
661 W (int): Width of image
662
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 x
670
671
672 class 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: True
681 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
682 attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
683 proj_drop (float, optional): Dropout ratio of output. Default: 0.0
684 """
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 = dim
690 self.window_size = window_size # Wh, Ww
691 self.num_heads = num_heads
692 head_dim = dim // num_heads
693 self.scale = qk_scale or head_dim ** -0.5
694
695 # define a parameter table of relative position bias
696 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, nH
698
699 # get pair-wise relative position index for each token inside the window
700 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, Ww
703 coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
704 relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
705 relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
706 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
707 relative_coords[:, :, 1] += self.window_size[1] - 1
708 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
709 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
710 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_drop
714 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 None
727 """
728 B_, N, C = x.shape
729 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.scale
733
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=False
738 ).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
744 ) # Wh*Ww, Wh*Ww, nH
745 relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
746 attn = attn + relative_position_bias.unsqueeze(0)
747
748 if mask is not None:
749 nW = mask.shape[0]
750 attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
751 attn = attn.view(-1, self.num_heads, N, N)
752 attn = self.softmax(attn)
753 else:
754 attn = self.softmax(attn)
755
756 attn = self.attn_drop(attn)
757
758 x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
759 x = self.proj(x)
760 x = self.proj_drop(x)
761 return x
762
763
764 class SwinTransformerBlock(nn.Module):
765 """ Swin Transformer Block.
766
767 Args:
768 dim (int): Number of input channels.
769 num_heads (int): Number of attention heads.
770 window_size (int): Window size.
771 shift_size (int): Shift size for SW-MSA.
772 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
773 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
774 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
775 drop (float, optional): Dropout rate. Default: 0.0
776 attn_drop (float, optional): Attention dropout rate. Default: 0.0
777 drop_path (float, optional): Stochastic depth rate. Default: 0.0
778 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
779 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
780 """
781
782 def __init__(self, dim, num_heads, window_size=7, shift_size=0,
783 mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
784 act_layer=nn.GELU, norm_layer=nn.LayerNorm):
785 super().__init__()
786 self.dim = dim
787 self.num_heads = num_heads
788 self.window_size = window_size
789 self.shift_size = shift_size
790 self.mlp_ratio = mlp_ratio
791 assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
792
793 self.norm1 = norm_layer(dim)
794 self.attn = WindowAttention(
795 dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
796 qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
797
798 self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
799 self.norm2 = norm_layer(dim)
800 mlp_hidden_dim = int(dim * mlp_ratio)
801 self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
802
803 self.H = None
804 self.W = None
805
806 def forward(self, x, mask_matrix):
807 """ Forward function.
808
809 Args:
810 x: Input feature, tensor size (B, H*W, C).
811 H, W: Spatial resolution of the input feature.
812 mask_matrix: Attention mask for cyclic shift.
813 """
814 B, L, C = x.shape
815 H, W = self.H, self.W
816 assert L == H * W, "input feature has wrong size"
817
818 shortcut = x
819 x = self.norm1(x)
820 x = x.view(B, H, W, C)
821
822 # pad feature maps to multiples of window size
823 pad_l = pad_t = 0
824 pad_r = (self.window_size - W % self.window_size) % self.window_size
825 pad_b = (self.window_size - H % self.window_size) % self.window_size
826 x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
827 _, Hp, Wp, _ = x.shape
828
829 # cyclic shift
830 if self.shift_size > 0:
831 shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
832 attn_mask = mask_matrix
833 else:
834 shifted_x = x
835 attn_mask = None
836
837 # partition windows
838 x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
839 x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
840
841 # W-MSA/SW-MSA
842 attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
843
844 # merge windows
845 attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
846 shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
847
848 # reverse cyclic shift
849 if self.shift_size > 0:
850 x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
851 else:
852 x = shifted_x
853
854 if pad_r > 0 or pad_b > 0:
855 x = x[:, :H, :W, :].contiguous()
856
857 x = x.view(B, H * W, C)
858
859 # FFN
860 x = shortcut + self.drop_path(x)
861 x = x + self.drop_path(self.mlp(self.norm2(x)))
862
863 return x
864
865
866 class PatchMerging(nn.Module):
867 """ Patch Merging Layer
868
869 Args:
870 dim (int): Number of input channels.
871 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
872 """
873 def __init__(self, dim, norm_layer=nn.LayerNorm):
874 super().__init__()
875 self.dim = dim
876 self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
877 self.norm = norm_layer(4 * dim)
878
879 def forward(self, x, H, W):
880 """ Forward function.
881
882 Args:
883 x: Input feature, tensor size (B, H*W, C).
884 H, W: Spatial resolution of the input feature.
885 """
886 B, L, C = x.shape
887 assert L == H * W, "input feature has wrong size"
888
889 x = x.view(B, H, W, C)
890
891 # padding
892 pad_input = (H % 2 == 1) or (W % 2 == 1)
893 if pad_input:
894 x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
895
896 x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
897 x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
898 x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
899 x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
900 x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
901 x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
902
903 x = self.norm(x)
904 x = self.reduction(x)
905
906 return x
907
908
909 class BasicLayer(nn.Module):
910 """ A basic Swin Transformer layer for one stage.
911
912 Args:
913 dim (int): Number of feature channels
914 depth (int): Depths of this stage.
915 num_heads (int): Number of attention head.
916 window_size (int): Local window size. Default: 7.
917 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
918 qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
919 qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
920 drop (float, optional): Dropout rate. Default: 0.0
921 attn_drop (float, optional): Attention dropout rate. Default: 0.0
922 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
923 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
924 downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
925 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
926 """
927
928 def __init__(self,
929 dim,
930 depth,
931 num_heads,
932 window_size=7,
933 mlp_ratio=4.,
934 qkv_bias=True,
935 qk_scale=None,
936 drop=0.,
937 attn_drop=0.,
938 drop_path=0.,
939 norm_layer=nn.LayerNorm,
940 downsample=None,
941 use_checkpoint=False):
942 super().__init__()
943 self.window_size = window_size
944 self.shift_size = window_size // 2
945 self.depth = depth
946 self.use_checkpoint = use_checkpoint
947
948 # build blocks
949 self.blocks = nn.ModuleList([
950 SwinTransformerBlock(
951 dim=dim,
952 num_heads=num_heads,
953 window_size=window_size,
954 shift_size=0 if (i % 2 == 0) else window_size // 2,
955 mlp_ratio=mlp_ratio,
956 qkv_bias=qkv_bias,
957 qk_scale=qk_scale,
958 drop=drop,
959 attn_drop=attn_drop,
960 drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
961 norm_layer=norm_layer)
962 for i in range(depth)])
963
964 # patch merging layer
965 if downsample is not None:
966 self.downsample = downsample(dim=dim, norm_layer=norm_layer)
967 else:
968 self.downsample = None
969
970 def forward(self, x, H, W):
971 """ Forward function.
972
973 Args:
974 x: Input feature, tensor size (B, H*W, C).
975 H, W: Spatial resolution of the input feature.
976 """
977
978 # calculate attention mask for SW-MSA
979 # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5.
980 Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
981 Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
982 img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
983 h_slices = (slice(0, -self.window_size),
984 slice(-self.window_size, -self.shift_size),
985 slice(-self.shift_size, None))
986 w_slices = (slice(0, -self.window_size),
987 slice(-self.window_size, -self.shift_size),
988 slice(-self.shift_size, None))
989 cnt = 0
990 for h in h_slices:
991 for w in w_slices:
992 img_mask[:, h, w, :] = cnt
993 cnt += 1
994
995 mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
996 mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
997 attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
998 attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
999
1000 for blk in self.blocks:
1001 blk.H, blk.W = H, W
1002 if self.use_checkpoint:
1003 x = checkpoint.checkpoint(blk, x, attn_mask)
1004 else:
1005 x = blk(x, attn_mask)
1006 if self.downsample is not None:
1007 x_down = self.downsample(x, H, W)
1008 Wh, Ww = (H + 1) // 2, (W + 1) // 2
1009 return x, H, W, x_down, Wh, Ww
1010 else:
1011 return x, H, W, x, H, W
1012
1013
1014 class PatchEmbed(nn.Module):
1015 """ Image to Patch Embedding
1016
1017 Args:
1018 patch_size (int): Patch token size. Default: 4.
1019 in_channels (int): Number of input image channels. Default: 3.
1020 embed_dim (int): Number of linear projection output channels. Default: 96.
1021 norm_layer (nn.Module, optional): Normalization layer. Default: None
1022 """
1023
1024 def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1025 super().__init__()
1026 patch_size = to_2tuple(patch_size)
1027 self.patch_size = patch_size
1028
1029 self.in_channels = in_channels
1030 self.embed_dim = embed_dim
1031
1032 self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1033 if norm_layer is not None:
1034 self.norm = norm_layer(embed_dim)
1035 else:
1036 self.norm = None
1037
1038 def forward(self, x):
1039 """Forward function."""
1040 # padding
1041 _, _, H, W = x.size()
1042 if W % self.patch_size[1] != 0:
1043 x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1044 if H % self.patch_size[0] != 0:
1045 x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1046
1047 x = self.proj(x) # B C Wh Ww
1048 if self.norm is not None:
1049 Wh, Ww = x.size(2), x.size(3)
1050 x = x.flatten(2).transpose(1, 2)
1051 x = self.norm(x)
1052 x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1053
1054 return x
1055
1056
1057 class SwinTransformer(nn.Module):
1058 """ Swin Transformer backbone.
1059 A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1060 https://arxiv.org/pdf/2103.14030
1061
1062 Args:
1063 pretrain_img_size (int): Input image size for training the pretrained model,
1064 used in absolute postion embedding. Default 224.
1065 patch_size (int | tuple(int)): Patch size. Default: 4.
1066 in_channels (int): Number of input image channels. Default: 3.
1067 embed_dim (int): Number of linear projection output channels. Default: 96.
1068 depths (tuple[int]): Depths of each Swin Transformer stage.
1069 num_heads (tuple[int]): Number of attention head of each stage.
1070 window_size (int): Window size. Default: 7.
1071 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1072 qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1073 qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1074 drop_rate (float): Dropout rate.
1075 attn_drop_rate (float): Attention dropout rate. Default: 0.
1076 drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1077 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1078 ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1079 patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1080 out_indices (Sequence[int]): Output from which stages.
1081 frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1082 -1 means not freezing any parameters.
1083 use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1084 """
1085
1086 def __init__(self,
1087 pretrain_img_size=224,
1088 patch_size=4,
1089 in_channels=3,
1090 embed_dim=96,
1091 depths=[2, 2, 6, 2],
1092 num_heads=[3, 6, 12, 24],
1093 window_size=7,
1094 mlp_ratio=4.,
1095 qkv_bias=True,
1096 qk_scale=None,
1097 drop_rate=0.,
1098 attn_drop_rate=0.,
1099 drop_path_rate=0.2,
1100 norm_layer=nn.LayerNorm,
1101 ape=False,
1102 patch_norm=True,
1103 out_indices=(0, 1, 2, 3),
1104 frozen_stages=-1,
1105 use_checkpoint=False):
1106 super().__init__()
1107
1108 self.pretrain_img_size = pretrain_img_size
1109 self.num_layers = len(depths)
1110 self.embed_dim = embed_dim
1111 self.ape = ape
1112 self.patch_norm = patch_norm
1113 self.out_indices = out_indices
1114 self.frozen_stages = frozen_stages
1115
1116 # split image into non-overlapping patches
1117 self.patch_embed = PatchEmbed(
1118 patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1119 norm_layer=norm_layer if self.patch_norm else None)
1120
1121 # absolute position embedding
1122 if self.ape:
1123 pretrain_img_size = to_2tuple(pretrain_img_size)
1124 patch_size = to_2tuple(patch_size)
1125 patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1126
1127 self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1128 trunc_normal_(self.absolute_pos_embed, std=.02)
1129
1130 self.pos_drop = nn.Dropout(p=drop_rate)
1131
1132 # stochastic depth
1133 dpr = np.linspace(0, drop_path_rate, sum(depths)).tolist() # stochastic depth decay rule
1134
1135 # build layers
1136 self.layers = nn.ModuleList()
1137 for i_layer in range(self.num_layers):
1138 layer = BasicLayer(
1139 dim=int(embed_dim * 2 ** i_layer),
1140 depth=depths[i_layer],
1141 num_heads=num_heads[i_layer],
1142 window_size=window_size,
1143 mlp_ratio=mlp_ratio,
1144 qkv_bias=qkv_bias,
1145 qk_scale=qk_scale,
1146 drop=drop_rate,
1147 attn_drop=attn_drop_rate,
1148 drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1149 norm_layer=norm_layer,
1150 downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1151 use_checkpoint=use_checkpoint)
1152 self.layers.append(layer)
1153
1154 num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1155 self.num_features = num_features
1156
1157 # add a norm layer for each output
1158 for i_layer in out_indices:
1159 layer = norm_layer(num_features[i_layer])
1160 layer_name = f'norm{i_layer}'
1161 self.add_module(layer_name, layer)
1162
1163 self._freeze_stages()
1164
1165 def _freeze_stages(self):
1166 if self.frozen_stages >= 0:
1167 self.patch_embed.eval()
1168 for param in self.patch_embed.parameters():
1169 param.requires_grad = False
1170
1171 if self.frozen_stages >= 1 and self.ape:
1172 self.absolute_pos_embed.requires_grad = False
1173
1174 if self.frozen_stages >= 2:
1175 self.pos_drop.eval()
1176 for i in range(0, self.frozen_stages - 1):
1177 m = self.layers[i]
1178 m.eval()
1179 for param in m.parameters():
1180 param.requires_grad = False
1181
1182
1183 def forward(self, x):
1184 """Forward function."""
1185 x = self.patch_embed(x)
1186
1187 Wh, Ww = x.size(2), x.size(3)
1188 if self.ape:
1189 # interpolate the position embedding to the corresponding size
1190 absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1191 x = (x + absolute_pos_embed) # B Wh*Ww C
1192
1193 outs = []#x.contiguous()]
1194 x = x.flatten(2).transpose(1, 2)
1195 x = self.pos_drop(x)
1196 for i in range(self.num_layers):
1197 layer = self.layers[i]
1198 x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1199
1200 if i in self.out_indices:
1201 norm_layer = getattr(self, f'norm{i}')
1202 x_out = norm_layer(x_out)
1203
1204 out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1205 outs.append(out)
1206
1207 return tuple(outs)
1208
1209 def train(self, mode=True):
1210 """Convert the model into training mode while keep layers freezed."""
1211 super(SwinTransformer, self).train(mode)
1212 self._freeze_stages()
1213
1214 def swin_v1_t():
1215 model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1216 return model
1217
1218 def swin_v1_s():
1219 model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1220 return model
1221
1222 def swin_v1_b():
1223 model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1224 return model
1225
1226 def swin_v1_l():
1227 model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1228 return model
1229
1230
1231
1232 ### models/modules/deform_conv.py
1233
1234 import torch
1235 import torch.nn as nn
1236 from torchvision.ops import deform_conv2d
1237
1238
1239 class DeformableConv2d(nn.Module):
1240 def __init__(self,
1241 in_channels,
1242 out_channels,
1243 kernel_size=3,
1244 stride=1,
1245 padding=1,
1246 bias=False):
1247
1248 super(DeformableConv2d, self).__init__()
1249
1250 assert type(kernel_size) == tuple or type(kernel_size) == int
1251
1252 kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1253 self.stride = stride if type(stride) == tuple else (stride, stride)
1254 self.padding = padding
1255
1256 self.offset_conv = nn.Conv2d(in_channels,
1257 2 * kernel_size[0] * kernel_size[1],
1258 kernel_size=kernel_size,
1259 stride=stride,
1260 padding=self.padding,
1261 bias=True)
1262
1263 nn.init.constant_(self.offset_conv.weight, 0.)
1264 nn.init.constant_(self.offset_conv.bias, 0.)
1265
1266 self.modulator_conv = nn.Conv2d(in_channels,
1267 1 * kernel_size[0] * kernel_size[1],
1268 kernel_size=kernel_size,
1269 stride=stride,
1270 padding=self.padding,
1271 bias=True)
1272
1273 nn.init.constant_(self.modulator_conv.weight, 0.)
1274 nn.init.constant_(self.modulator_conv.bias, 0.)
1275
1276 self.regular_conv = nn.Conv2d(in_channels,
1277 out_channels=out_channels,
1278 kernel_size=kernel_size,
1279 stride=stride,
1280 padding=self.padding,
1281 bias=bias)
1282
1283 def forward(self, x):
1284 #h, w = x.shape[2:]
1285 #max_offset = max(h, w)/4.
1286
1287 offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1288 modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1289
1290 x = deform_conv2d(
1291 input=x,
1292 offset=offset,
1293 weight=self.regular_conv.weight,
1294 bias=self.regular_conv.bias,
1295 padding=self.padding,
1296 mask=modulator,
1297 stride=self.stride,
1298 )
1299 return x
1300
1301
1302
1303
1304 ### utils.py
1305
1306 import torch.nn as nn
1307
1308
1309 def build_act_layer(act_layer):
1310 if act_layer == 'ReLU':
1311 return nn.ReLU(inplace=True)
1312 elif act_layer == 'SiLU':
1313 return nn.SiLU(inplace=True)
1314 elif act_layer == 'GELU':
1315 return nn.GELU()
1316
1317 raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1318
1319
1320 def build_norm_layer(dim,
1321 norm_layer,
1322 in_format='channels_last',
1323 out_format='channels_last',
1324 eps=1e-6):
1325 layers = []
1326 if norm_layer == 'BN':
1327 if in_format == 'channels_last':
1328 layers.append(to_channels_first())
1329 layers.append(nn.BatchNorm2d(dim))
1330 if out_format == 'channels_last':
1331 layers.append(to_channels_last())
1332 elif norm_layer == 'LN':
1333 if in_format == 'channels_first':
1334 layers.append(to_channels_last())
1335 layers.append(nn.LayerNorm(dim, eps=eps))
1336 if out_format == 'channels_first':
1337 layers.append(to_channels_first())
1338 else:
1339 raise NotImplementedError(
1340 f'build_norm_layer does not support {norm_layer}')
1341 return nn.Sequential(*layers)
1342
1343
1344 class to_channels_first(nn.Module):
1345
1346 def __init__(self):
1347 super().__init__()
1348
1349 def forward(self, x):
1350 return x.permute(0, 3, 1, 2)
1351
1352
1353 class to_channels_last(nn.Module):
1354
1355 def __init__(self):
1356 super().__init__()
1357
1358 def forward(self, x):
1359 return x.permute(0, 2, 3, 1)
1360
1361
1362
1363 ### dataset.py
1364
1365 _class_labels_TR_sorted = (
1366 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1367 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1368 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1369 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1370 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1371 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1372 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1373 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1374 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1375 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1376 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1377 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1378 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1379 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1380 )
1381 class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1382
1383
1384 ### models/backbones/build_backbones.py
1385
1386 import torch
1387 import torch.nn as nn
1388 from collections import OrderedDict
1389 from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1390 # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1391 # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1392 # from config import Config
1393
1394
1395 config = Config()
1396
1397 def build_backbone(bb_name, pretrained=True, params_settings=''):
1398 if bb_name == 'vgg16':
1399 bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1400 bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1401 elif bb_name == 'vgg16bn':
1402 bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1403 bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1404 elif bb_name == 'resnet50':
1405 bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1406 bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1407 else:
1408 bb = eval('{}({})'.format(bb_name, params_settings))
1409 if pretrained:
1410 bb = load_weights(bb, bb_name)
1411 return bb
1412
1413 def load_weights(model, model_name):
1414 save_model = torch.load(config.weights[model_name], map_location='cpu')
1415 model_dict = model.state_dict()
1416 state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1417 # to ignore the weights with mismatched size when I modify the backbone itself.
1418 if not state_dict:
1419 save_model_keys = list(save_model.keys())
1420 sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1421 state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1422 if not state_dict or not sub_item:
1423 print('Weights are not successully loaded. Check the state dict of weights file.')
1424 return None
1425 else:
1426 print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1427 model_dict.update(state_dict)
1428 model.load_state_dict(model_dict)
1429 return model
1430
1431
1432
1433 ### models/modules/decoder_blocks.py
1434
1435 import torch
1436 import torch.nn as nn
1437 # from models.aspp import ASPP, ASPPDeformable
1438 # from config import Config
1439
1440
1441 # config = Config()
1442
1443
1444 class BasicDecBlk(nn.Module):
1445 def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1446 super(BasicDecBlk, self).__init__()
1447 inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1448 self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1449 self.relu_in = nn.ReLU(inplace=True)
1450 if config.dec_att == 'ASPP':
1451 self.dec_att = ASPP(in_channels=inter_channels)
1452 elif config.dec_att == 'ASPPDeformable':
1453 self.dec_att = ASPPDeformable(in_channels=inter_channels)
1454 self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1455 self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1456 self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1457
1458 def forward(self, x):
1459 x = self.conv_in(x)
1460 x = self.bn_in(x)
1461 x = self.relu_in(x)
1462 if hasattr(self, 'dec_att'):
1463 x = self.dec_att(x)
1464 x = self.conv_out(x)
1465 x = self.bn_out(x)
1466 return x
1467
1468
1469 class ResBlk(nn.Module):
1470 def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1471 super(ResBlk, self).__init__()
1472 if out_channels is None:
1473 out_channels = in_channels
1474 inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1475
1476 self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1477 self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1478 self.relu_in = nn.ReLU(inplace=True)
1479
1480 if config.dec_att == 'ASPP':
1481 self.dec_att = ASPP(in_channels=inter_channels)
1482 elif config.dec_att == 'ASPPDeformable':
1483 self.dec_att = ASPPDeformable(in_channels=inter_channels)
1484
1485 self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1486 self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1487
1488 self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1489
1490 def forward(self, x):
1491 _x = self.conv_resi(x)
1492 x = self.conv_in(x)
1493 x = self.bn_in(x)
1494 x = self.relu_in(x)
1495 if hasattr(self, 'dec_att'):
1496 x = self.dec_att(x)
1497 x = self.conv_out(x)
1498 x = self.bn_out(x)
1499 return x + _x
1500
1501
1502
1503 ### models/modules/lateral_blocks.py
1504
1505 import numpy as np
1506 import torch
1507 import torch.nn as nn
1508 import torch.nn.functional as F
1509 from functools import partial
1510
1511 # from config import Config
1512
1513
1514 # config = Config()
1515
1516
1517 class BasicLatBlk(nn.Module):
1518 def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1519 super(BasicLatBlk, self).__init__()
1520 inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1521 self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1522
1523 def forward(self, x):
1524 x = self.conv(x)
1525 return x
1526
1527
1528
1529 ### models/modules/aspp.py
1530
1531 import torch
1532 import torch.nn as nn
1533 import torch.nn.functional as F
1534 # from models.deform_conv import DeformableConv2d
1535 # from config import Config
1536
1537
1538 # config = Config()
1539
1540
1541 class _ASPPModule(nn.Module):
1542 def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1543 super(_ASPPModule, self).__init__()
1544 self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1545 stride=1, padding=padding, dilation=dilation, bias=False)
1546 self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1547 self.relu = nn.ReLU(inplace=True)
1548
1549 def forward(self, x):
1550 x = self.atrous_conv(x)
1551 x = self.bn(x)
1552
1553 return self.relu(x)
1554
1555
1556 class ASPP(nn.Module):
1557 def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1558 super(ASPP, self).__init__()
1559 self.down_scale = 1
1560 if out_channels is None:
1561 out_channels = in_channels
1562 self.in_channelster = 256 // self.down_scale
1563 if output_stride == 16:
1564 dilations = [1, 6, 12, 18]
1565 elif output_stride == 8:
1566 dilations = [1, 12, 24, 36]
1567 else:
1568 raise NotImplementedError
1569
1570 self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1571 self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1572 self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1573 self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1574
1575 self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1576 nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1577 nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1578 nn.ReLU(inplace=True))
1579 self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1580 self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1581 self.relu = nn.ReLU(inplace=True)
1582 self.dropout = nn.Dropout(0.5)
1583
1584 def forward(self, x):
1585 x1 = self.aspp1(x)
1586 x2 = self.aspp2(x)
1587 x3 = self.aspp3(x)
1588 x4 = self.aspp4(x)
1589 x5 = self.global_avg_pool(x)
1590 x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1591 x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1592
1593 x = self.conv1(x)
1594 x = self.bn1(x)
1595 x = self.relu(x)
1596
1597 return self.dropout(x)
1598
1599
1600 ##################### Deformable
1601 class _ASPPModuleDeformable(nn.Module):
1602 def __init__(self, in_channels, planes, kernel_size, padding):
1603 super(_ASPPModuleDeformable, self).__init__()
1604 self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1605 stride=1, padding=padding, bias=False)
1606 self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1607 self.relu = nn.ReLU(inplace=True)
1608
1609 def forward(self, x):
1610 x = self.atrous_conv(x)
1611 x = self.bn(x)
1612
1613 return self.relu(x)
1614
1615
1616 class ASPPDeformable(nn.Module):
1617 def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1618 super(ASPPDeformable, self).__init__()
1619 self.down_scale = 1
1620 if out_channels is None:
1621 out_channels = in_channels
1622 self.in_channelster = 256 // self.down_scale
1623
1624 self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1625 self.aspp_deforms = nn.ModuleList([
1626 _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1627 ])
1628
1629 self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1630 nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1631 nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1632 nn.ReLU(inplace=True))
1633 self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1634 self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1635 self.relu = nn.ReLU(inplace=True)
1636 self.dropout = nn.Dropout(0.5)
1637
1638 def forward(self, x):
1639 x1 = self.aspp1(x)
1640 x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1641 x5 = self.global_avg_pool(x)
1642 x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1643 x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1644
1645 x = self.conv1(x)
1646 x = self.bn1(x)
1647 x = self.relu(x)
1648
1649 return self.dropout(x)
1650
1651
1652
1653 ### models/refinement/refiner.py
1654
1655 import torch
1656 import torch.nn as nn
1657 from collections import OrderedDict
1658 import torch
1659 import torch.nn as nn
1660 import torch.nn.functional as F
1661 from torchvision.models import vgg16, vgg16_bn
1662 from torchvision.models import resnet50
1663
1664 # from config import Config
1665 # from dataset import class_labels_TR_sorted
1666 # from models.build_backbone import build_backbone
1667 # from models.decoder_blocks import BasicDecBlk
1668 # from models.lateral_blocks import BasicLatBlk
1669 # from models.ing import *
1670 # from models.stem_layer import StemLayer
1671
1672
1673 class RefinerPVTInChannels4(nn.Module):
1674 def __init__(self, in_channels=3+1):
1675 super(RefinerPVTInChannels4, self).__init__()
1676 self.config = Config()
1677 self.epoch = 1
1678 self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1679
1680 lateral_channels_in_collection = {
1681 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1682 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1683 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1684 }
1685 channels = lateral_channels_in_collection[self.config.bb]
1686 self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1687
1688 self.decoder = Decoder(channels)
1689
1690 if 0:
1691 for key, value in self.named_parameters():
1692 if 'bb.' in key:
1693 value.requires_grad = False
1694
1695 def forward(self, x):
1696 if isinstance(x, list):
1697 x = torch.cat(x, dim=1)
1698 ########## Encoder ##########
1699 if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1700 x1 = self.bb.conv1(x)
1701 x2 = self.bb.conv2(x1)
1702 x3 = self.bb.conv3(x2)
1703 x4 = self.bb.conv4(x3)
1704 else:
1705 x1, x2, x3, x4 = self.bb(x)
1706
1707 x4 = self.squeeze_module(x4)
1708
1709 ########## Decoder ##########
1710
1711 features = [x, x1, x2, x3, x4]
1712 scaled_preds = self.decoder(features)
1713
1714 return scaled_preds
1715
1716
1717 class Refiner(nn.Module):
1718 def __init__(self, in_channels=3+1):
1719 super(Refiner, self).__init__()
1720 self.config = Config()
1721 self.epoch = 1
1722 self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1723 self.bb = build_backbone(self.config.bb)
1724
1725 lateral_channels_in_collection = {
1726 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1727 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1728 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1729 }
1730 channels = lateral_channels_in_collection[self.config.bb]
1731 self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1732
1733 self.decoder = Decoder(channels)
1734
1735 if 0:
1736 for key, value in self.named_parameters():
1737 if 'bb.' in key:
1738 value.requires_grad = False
1739
1740 def forward(self, x):
1741 if isinstance(x, list):
1742 x = torch.cat(x, dim=1)
1743 x = self.stem_layer(x)
1744 ########## Encoder ##########
1745 if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1746 x1 = self.bb.conv1(x)
1747 x2 = self.bb.conv2(x1)
1748 x3 = self.bb.conv3(x2)
1749 x4 = self.bb.conv4(x3)
1750 else:
1751 x1, x2, x3, x4 = self.bb(x)
1752
1753 x4 = self.squeeze_module(x4)
1754
1755 ########## Decoder ##########
1756
1757 features = [x, x1, x2, x3, x4]
1758 scaled_preds = self.decoder(features)
1759
1760 return scaled_preds
1761
1762
1763 class Decoder(nn.Module):
1764 def __init__(self, channels):
1765 super(Decoder, self).__init__()
1766 self.config = Config()
1767 DecoderBlock = eval('BasicDecBlk')
1768 LateralBlock = eval('BasicLatBlk')
1769
1770 self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1771 self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1772 self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1773 self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1774
1775 self.lateral_block4 = LateralBlock(channels[1], channels[1])
1776 self.lateral_block3 = LateralBlock(channels[2], channels[2])
1777 self.lateral_block2 = LateralBlock(channels[3], channels[3])
1778
1779 if self.config.ms_supervision:
1780 self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1781 self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1782 self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1783 self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1784
1785 def forward(self, features):
1786 x, x1, x2, x3, x4 = features
1787 outs = []
1788 p4 = self.decoder_block4(x4)
1789 _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1790 _p3 = _p4 + self.lateral_block4(x3)
1791
1792 p3 = self.decoder_block3(_p3)
1793 _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1794 _p2 = _p3 + self.lateral_block3(x2)
1795
1796 p2 = self.decoder_block2(_p2)
1797 _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1798 _p1 = _p2 + self.lateral_block2(x1)
1799
1800 _p1 = self.decoder_block1(_p1)
1801 _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1802 p1_out = self.conv_out1(_p1)
1803
1804 if self.config.ms_supervision:
1805 outs.append(self.conv_ms_spvn_4(p4))
1806 outs.append(self.conv_ms_spvn_3(p3))
1807 outs.append(self.conv_ms_spvn_2(p2))
1808 outs.append(p1_out)
1809 return outs
1810
1811
1812 class RefUNet(nn.Module):
1813 # Refinement
1814 def __init__(self, in_channels=3+1):
1815 super(RefUNet, self).__init__()
1816 self.encoder_1 = nn.Sequential(
1817 nn.Conv2d(in_channels, 64, 3, 1, 1),
1818 nn.Conv2d(64, 64, 3, 1, 1),
1819 nn.BatchNorm2d(64),
1820 nn.ReLU(inplace=True)
1821 )
1822
1823 self.encoder_2 = nn.Sequential(
1824 nn.MaxPool2d(2, 2, ceil_mode=True),
1825 nn.Conv2d(64, 64, 3, 1, 1),
1826 nn.BatchNorm2d(64),
1827 nn.ReLU(inplace=True)
1828 )
1829
1830 self.encoder_3 = nn.Sequential(
1831 nn.MaxPool2d(2, 2, ceil_mode=True),
1832 nn.Conv2d(64, 64, 3, 1, 1),
1833 nn.BatchNorm2d(64),
1834 nn.ReLU(inplace=True)
1835 )
1836
1837 self.encoder_4 = nn.Sequential(
1838 nn.MaxPool2d(2, 2, ceil_mode=True),
1839 nn.Conv2d(64, 64, 3, 1, 1),
1840 nn.BatchNorm2d(64),
1841 nn.ReLU(inplace=True)
1842 )
1843
1844 self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1845 #####
1846 self.decoder_5 = nn.Sequential(
1847 nn.Conv2d(64, 64, 3, 1, 1),
1848 nn.BatchNorm2d(64),
1849 nn.ReLU(inplace=True)
1850 )
1851 #####
1852 self.decoder_4 = nn.Sequential(
1853 nn.Conv2d(128, 64, 3, 1, 1),
1854 nn.BatchNorm2d(64),
1855 nn.ReLU(inplace=True)
1856 )
1857
1858 self.decoder_3 = nn.Sequential(
1859 nn.Conv2d(128, 64, 3, 1, 1),
1860 nn.BatchNorm2d(64),
1861 nn.ReLU(inplace=True)
1862 )
1863
1864 self.decoder_2 = nn.Sequential(
1865 nn.Conv2d(128, 64, 3, 1, 1),
1866 nn.BatchNorm2d(64),
1867 nn.ReLU(inplace=True)
1868 )
1869
1870 self.decoder_1 = nn.Sequential(
1871 nn.Conv2d(128, 64, 3, 1, 1),
1872 nn.BatchNorm2d(64),
1873 nn.ReLU(inplace=True)
1874 )
1875
1876 self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1877
1878 self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1879
1880 def forward(self, x):
1881 outs = []
1882 if isinstance(x, list):
1883 x = torch.cat(x, dim=1)
1884 hx = x
1885
1886 hx1 = self.encoder_1(hx)
1887 hx2 = self.encoder_2(hx1)
1888 hx3 = self.encoder_3(hx2)
1889 hx4 = self.encoder_4(hx3)
1890
1891 hx = self.decoder_5(self.pool4(hx4))
1892 hx = torch.cat((self.upscore2(hx), hx4), 1)
1893
1894 d4 = self.decoder_4(hx)
1895 hx = torch.cat((self.upscore2(d4), hx3), 1)
1896
1897 d3 = self.decoder_3(hx)
1898 hx = torch.cat((self.upscore2(d3), hx2), 1)
1899
1900 d2 = self.decoder_2(hx)
1901 hx = torch.cat((self.upscore2(d2), hx1), 1)
1902
1903 d1 = self.decoder_1(hx)
1904
1905 x = self.conv_d0(d1)
1906 outs.append(x)
1907 return outs
1908
1909
1910
1911 ### models/stem_layer.py
1912
1913 import torch.nn as nn
1914 # from utils import build_act_layer, build_norm_layer
1915
1916
1917 class StemLayer(nn.Module):
1918 r""" Stem layer of InternImage
1919 Args:
1920 in_channels (int): number of input channels
1921 out_channels (int): number of output channels
1922 act_layer (str): activation layer
1923 norm_layer (str): normalization layer
1924 """
1925
1926 def __init__(self,
1927 in_channels=3+1,
1928 inter_channels=48,
1929 out_channels=96,
1930 act_layer='GELU',
1931 norm_layer='BN'):
1932 super().__init__()
1933 self.conv1 = nn.Conv2d(in_channels,
1934 inter_channels,
1935 kernel_size=3,
1936 stride=1,
1937 padding=1)
1938 self.norm1 = build_norm_layer(
1939 inter_channels, norm_layer, 'channels_first', 'channels_first'
1940 )
1941 self.act = build_act_layer(act_layer)
1942 self.conv2 = nn.Conv2d(inter_channels,
1943 out_channels,
1944 kernel_size=3,
1945 stride=1,
1946 padding=1)
1947 self.norm2 = build_norm_layer(
1948 out_channels, norm_layer, 'channels_first', 'channels_first'
1949 )
1950
1951 def forward(self, x):
1952 x = self.conv1(x)
1953 x = self.norm1(x)
1954 x = self.act(x)
1955 x = self.conv2(x)
1956 x = self.norm2(x)
1957 return x
1958
1959
1960 ### models/birefnet.py
1961
1962 import torch
1963 import torch.nn as nn
1964 import torch.nn.functional as F
1965 from kornia.filters import laplacian
1966 from transformers import PreTrainedModel
1967 from einops import rearrange
1968
1969 # from config import Config
1970 # from dataset import class_labels_TR_sorted
1971 # from models.build_backbone import build_backbone
1972 # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1973 # from models.lateral_blocks import BasicLatBlk
1974 # from models.aspp import ASPP, ASPPDeformable
1975 # from models.ing import *
1976 # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1977 # from models.stem_layer import StemLayer
1978 from .BiRefNet_config import BiRefNetConfig
1979
1980
1981 def image2patches(image, grid_h=2, grid_w=2, patch_ref=None, transformation='b c (hg h) (wg w) -> (b hg wg) c h w'):
1982 if patch_ref is not None:
1983 grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1]
1984 patches = rearrange(image, transformation, hg=grid_h, wg=grid_w)
1985 return patches
1986
1987 def patches2image(patches, grid_h=2, grid_w=2, patch_ref=None, transformation='(b hg wg) c h w -> b c (hg h) (wg w)'):
1988 if patch_ref is not None:
1989 grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1]
1990 image = rearrange(patches, transformation, hg=grid_h, wg=grid_w)
1991 return image
1992
1993 class BiRefNet(
1994 PreTrainedModel
1995 ):
1996 config_class = BiRefNetConfig
1997 def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1998 super(BiRefNet, self).__init__(config)
1999 bb_pretrained = config.bb_pretrained
2000 self.config = Config()
2001 self.epoch = 1
2002 self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
2003
2004 channels = self.config.lateral_channels_in_collection
2005
2006 if self.config.auxiliary_classification:
2007 self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
2008 self.cls_head = nn.Sequential(
2009 nn.Linear(channels[0], len(class_labels_TR_sorted))
2010 )
2011
2012 if self.config.squeeze_block:
2013 self.squeeze_module = nn.Sequential(*[
2014 eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
2015 for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2016 ])
2017
2018 self.decoder = Decoder(channels)
2019
2020 if self.config.ender:
2021 self.dec_end = nn.Sequential(
2022 nn.Conv2d(1, 16, 3, 1, 1),
2023 nn.Conv2d(16, 1, 3, 1, 1),
2024 nn.ReLU(inplace=True),
2025 )
2026
2027 # refine patch-level segmentation
2028 if self.config.refine:
2029 if self.config.refine == 'itself':
2030 self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2031 else:
2032 self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2033
2034 if self.config.freeze_bb:
2035 # Freeze the backbone...
2036 print(self.named_parameters())
2037 for key, value in self.named_parameters():
2038 if 'bb.' in key and 'refiner.' not in key:
2039 value.requires_grad = False
2040
2041 self.post_init()
2042
2043 def forward_enc(self, x):
2044 if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2045 x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2046 else:
2047 x1, x2, x3, x4 = self.bb(x)
2048 if self.config.mul_scl_ipt == 'cat':
2049 B, C, H, W = x.shape
2050 x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2051 x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2052 x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2053 x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2054 x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2055 elif self.config.mul_scl_ipt == 'add':
2056 B, C, H, W = x.shape
2057 x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2058 x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2059 x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2060 x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2061 x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2062 class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2063 if self.config.cxt:
2064 x4 = torch.cat(
2065 (
2066 *[
2067 F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2068 F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2069 F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2070 ][-len(self.config.cxt):],
2071 x4
2072 ),
2073 dim=1
2074 )
2075 return (x1, x2, x3, x4), class_preds
2076
2077 def forward_ori(self, x):
2078 ########## Encoder ##########
2079 (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2080 if self.config.squeeze_block:
2081 x4 = self.squeeze_module(x4)
2082 ########## Decoder ##########
2083 features = [x, x1, x2, x3, x4]
2084 if self.training and self.config.out_ref:
2085 features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2086 scaled_preds = self.decoder(features)
2087 return scaled_preds, class_preds
2088
2089 def forward(self, x):
2090 scaled_preds, class_preds = self.forward_ori(x)
2091 class_preds_lst = [class_preds]
2092 return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2093
2094
2095 class Decoder(nn.Module):
2096 def __init__(self, channels):
2097 super(Decoder, self).__init__()
2098 self.config = Config()
2099 DecoderBlock = eval(self.config.dec_blk)
2100 LateralBlock = eval(self.config.lat_blk)
2101
2102 if self.config.dec_ipt:
2103 self.split = self.config.dec_ipt_split
2104 N_dec_ipt = 64
2105 DBlock = SimpleConvs
2106 ic = 64
2107 ipt_cha_opt = 1
2108 self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2109 self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2110 self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2111 self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2112 self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2113 else:
2114 self.split = None
2115
2116 self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2117 self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2118 self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2119 self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2120 self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2121
2122 self.lateral_block4 = LateralBlock(channels[1], channels[1])
2123 self.lateral_block3 = LateralBlock(channels[2], channels[2])
2124 self.lateral_block2 = LateralBlock(channels[3], channels[3])
2125
2126 if self.config.ms_supervision:
2127 self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2128 self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2129 self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2130
2131 if self.config.out_ref:
2132 _N = 16
2133 self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2134 self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2135 self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2136
2137 self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2138 self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2139 self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2140
2141 self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2142 self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2143 self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2144
2145 def forward(self, features):
2146 if self.training and self.config.out_ref:
2147 outs_gdt_pred = []
2148 outs_gdt_label = []
2149 x, x1, x2, x3, x4, gdt_gt = features
2150 else:
2151 x, x1, x2, x3, x4 = features
2152 outs = []
2153
2154 if self.config.dec_ipt:
2155 patches_batch = image2patches(x, patch_ref=x4, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2156 x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2157 p4 = self.decoder_block4(x4)
2158 m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None
2159 if self.config.out_ref:
2160 p4_gdt = self.gdt_convs_4(p4)
2161 if self.training:
2162 # >> GT:
2163 m4_dia = m4
2164 gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2165 outs_gdt_label.append(gdt_label_main_4)
2166 # >> Pred:
2167 gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2168 outs_gdt_pred.append(gdt_pred_4)
2169 gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2170 # >> Finally:
2171 p4 = p4 * gdt_attn_4
2172 _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2173 _p3 = _p4 + self.lateral_block4(x3)
2174
2175 if self.config.dec_ipt:
2176 patches_batch = image2patches(x, patch_ref=_p3, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2177 _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2178 p3 = self.decoder_block3(_p3)
2179 m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None
2180 if self.config.out_ref:
2181 p3_gdt = self.gdt_convs_3(p3)
2182 if self.training:
2183 # >> GT:
2184 # m3 --dilation--> m3_dia
2185 # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2186 m3_dia = m3
2187 gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2188 outs_gdt_label.append(gdt_label_main_3)
2189 # >> Pred:
2190 # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2191 # F_3^G --sigmoid--> A_3^G
2192 gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2193 outs_gdt_pred.append(gdt_pred_3)
2194 gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2195 # >> Finally:
2196 # p3 = p3 * A_3^G
2197 p3 = p3 * gdt_attn_3
2198 _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2199 _p2 = _p3 + self.lateral_block3(x2)
2200
2201 if self.config.dec_ipt:
2202 patches_batch = image2patches(x, patch_ref=_p2, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2203 _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2204 p2 = self.decoder_block2(_p2)
2205 m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None
2206 if self.config.out_ref:
2207 p2_gdt = self.gdt_convs_2(p2)
2208 if self.training:
2209 # >> GT:
2210 m2_dia = m2
2211 gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2212 outs_gdt_label.append(gdt_label_main_2)
2213 # >> Pred:
2214 gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2215 outs_gdt_pred.append(gdt_pred_2)
2216 gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2217 # >> Finally:
2218 p2 = p2 * gdt_attn_2
2219 _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2220 _p1 = _p2 + self.lateral_block2(x1)
2221
2222 if self.config.dec_ipt:
2223 patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2224 _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2225 _p1 = self.decoder_block1(_p1)
2226 _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2227
2228 if self.config.dec_ipt:
2229 patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2230 _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2231 p1_out = self.conv_out1(_p1)
2232
2233 if self.config.ms_supervision and self.training:
2234 outs.append(m4)
2235 outs.append(m3)
2236 outs.append(m2)
2237 outs.append(p1_out)
2238 return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2239
2240
2241 class SimpleConvs(nn.Module):
2242 def __init__(
2243 self, in_channels: int, out_channels: int, inter_channels=64
2244 ) -> None:
2245 super().__init__()
2246 self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2247 self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2248
2249 def forward(self, x):
2250 return self.conv_out(self.conv1(x))
2251