Clement commited on
Commit
be0194c
·
verified ·
1 Parent(s): 35e3507

Create birefnet.py

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