kezakkezak commited on
Commit
5b260a7
·
verified ·
1 Parent(s): 4c45e75

lama, birefnet

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