S4MUEL commited on
Commit
495bc55
·
verified ·
1 Parent(s): 9f394b5

Upload 3 files

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