Muhammed Ömer ERKOÇ commited on
Commit
fb36382
·
1 Parent(s): 37f7a06

Add app.py, requirements.txt, examples and model files 2

Browse files
Files changed (2) hide show
  1. lib/pvt.py +223 -0
  2. lib/pvtv2.py +436 -0
lib/pvt.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from lib.pvtv2 import pvt_v2_b2
5
+ import os
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+
11
+ class BasicConv2d(nn.Module):
12
+ def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1):
13
+ super(BasicConv2d, self).__init__()
14
+
15
+ self.conv = nn.Conv2d(in_planes, out_planes,
16
+ kernel_size=kernel_size, stride=stride,
17
+ padding=padding, dilation=dilation, bias=False)
18
+ self.bn = nn.BatchNorm2d(out_planes)
19
+ self.relu = nn.ReLU(inplace=True)
20
+
21
+ def forward(self, x):
22
+ x = self.conv(x)
23
+ x = self.bn(x)
24
+ return x
25
+
26
+
27
+ class CFM(nn.Module):
28
+ def __init__(self, channel):
29
+ super(CFM, self).__init__()
30
+ self.relu = nn.ReLU(True)
31
+
32
+ self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
33
+ self.conv_upsample1 = BasicConv2d(channel, channel, 3, padding=1)
34
+ self.conv_upsample2 = BasicConv2d(channel, channel, 3, padding=1)
35
+ self.conv_upsample3 = BasicConv2d(channel, channel, 3, padding=1)
36
+ self.conv_upsample4 = BasicConv2d(channel, channel, 3, padding=1)
37
+ self.conv_upsample5 = BasicConv2d(2 * channel, 2 * channel, 3, padding=1)
38
+
39
+ self.conv_concat2 = BasicConv2d(2 * channel, 2 * channel, 3, padding=1)
40
+ self.conv_concat3 = BasicConv2d(3 * channel, 3 * channel, 3, padding=1)
41
+ self.conv4 = BasicConv2d(3 * channel, channel, 3, padding=1)
42
+
43
+ def forward(self, x1, x2, x3):
44
+ x1_1 = x1
45
+ x2_1 = self.conv_upsample1(self.upsample(x1)) * x2
46
+ x3_1 = self.conv_upsample2(self.upsample(self.upsample(x1))) \
47
+ * self.conv_upsample3(self.upsample(x2)) * x3
48
+
49
+ x2_2 = torch.cat((x2_1, self.conv_upsample4(self.upsample(x1_1))), 1)
50
+ x2_2 = self.conv_concat2(x2_2)
51
+
52
+ x3_2 = torch.cat((x3_1, self.conv_upsample5(self.upsample(x2_2))), 1)
53
+ x3_2 = self.conv_concat3(x3_2)
54
+
55
+ x1 = self.conv4(x3_2)
56
+
57
+ return x1
58
+
59
+
60
+
61
+
62
+ class GCN(nn.Module):
63
+ def __init__(self, num_state, num_node, bias=False):
64
+ super(GCN, self).__init__()
65
+ self.conv1 = nn.Conv1d(num_node, num_node, kernel_size=1)
66
+ self.relu = nn.ReLU(inplace=True)
67
+ self.conv2 = nn.Conv1d(num_state, num_state, kernel_size=1, bias=bias)
68
+
69
+ def forward(self, x):
70
+ h = self.conv1(x.permute(0, 2, 1)).permute(0, 2, 1)
71
+ h = h - x
72
+ h = self.relu(self.conv2(h))
73
+ return h
74
+
75
+
76
+ class SAM(nn.Module):
77
+ def __init__(self, num_in=32, plane_mid=16, mids=4, normalize=False):
78
+ super(SAM, self).__init__()
79
+
80
+ self.normalize = normalize
81
+ self.num_s = int(plane_mid)
82
+ self.num_n = (mids) * (mids)
83
+ self.priors = nn.AdaptiveAvgPool2d(output_size=(mids + 2, mids + 2))
84
+
85
+ self.conv_state = nn.Conv2d(num_in, self.num_s, kernel_size=1)
86
+ self.conv_proj = nn.Conv2d(num_in, self.num_s, kernel_size=1)
87
+ self.gcn = GCN(num_state=self.num_s, num_node=self.num_n)
88
+ self.conv_extend = nn.Conv2d(self.num_s, num_in, kernel_size=1, bias=False)
89
+
90
+ def forward(self, x, edge):
91
+ edge = F.upsample(edge, (x.size()[-2], x.size()[-1]))
92
+
93
+ n, c, h, w = x.size()
94
+ edge = torch.nn.functional.softmax(edge, dim=1)[:, 1, :, :].unsqueeze(1)
95
+
96
+ x_state_reshaped = self.conv_state(x).view(n, self.num_s, -1)
97
+ x_proj = self.conv_proj(x)
98
+ x_mask = x_proj * edge
99
+
100
+ x_anchor1 = self.priors(x_mask)
101
+ x_anchor2 = self.priors(x_mask)[:, :, 1:-1, 1:-1].reshape(n, self.num_s, -1)
102
+ x_anchor = self.priors(x_mask)[:, :, 1:-1, 1:-1].reshape(n, self.num_s, -1)
103
+
104
+ x_proj_reshaped = torch.matmul(x_anchor.permute(0, 2, 1), x_proj.reshape(n, self.num_s, -1))
105
+ x_proj_reshaped = torch.nn.functional.softmax(x_proj_reshaped, dim=1)
106
+
107
+ x_rproj_reshaped = x_proj_reshaped
108
+
109
+ x_n_state = torch.matmul(x_state_reshaped, x_proj_reshaped.permute(0, 2, 1))
110
+ if self.normalize:
111
+ x_n_state = x_n_state * (1. / x_state_reshaped.size(2))
112
+ x_n_rel = self.gcn(x_n_state)
113
+
114
+ x_state_reshaped = torch.matmul(x_n_rel, x_rproj_reshaped)
115
+ x_state = x_state_reshaped.view(n, self.num_s, *x.size()[2:])
116
+ out = x + (self.conv_extend(x_state))
117
+
118
+ return out
119
+
120
+
121
+ class ChannelAttention(nn.Module):
122
+ def __init__(self, in_planes, ratio=16):
123
+ super(ChannelAttention, self).__init__()
124
+ self.avg_pool = nn.AdaptiveAvgPool2d(1)
125
+ self.max_pool = nn.AdaptiveMaxPool2d(1)
126
+
127
+ self.fc1 = nn.Conv2d(in_planes, in_planes // 16, 1, bias=False)
128
+ self.relu1 = nn.ReLU()
129
+ self.fc2 = nn.Conv2d(in_planes // 16, in_planes, 1, bias=False)
130
+
131
+ self.sigmoid = nn.Sigmoid()
132
+
133
+ def forward(self, x):
134
+ avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))
135
+ max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))
136
+ out = avg_out + max_out
137
+ return self.sigmoid(out)
138
+
139
+
140
+ class SpatialAttention(nn.Module):
141
+ def __init__(self, kernel_size=7):
142
+ super(SpatialAttention, self).__init__()
143
+
144
+ assert kernel_size in (3, 7), 'kernel size must be 3 or 7'
145
+ padding = 3 if kernel_size == 7 else 1
146
+
147
+ self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)
148
+ self.sigmoid = nn.Sigmoid()
149
+
150
+ def forward(self, x):
151
+ avg_out = torch.mean(x, dim=1, keepdim=True)
152
+ max_out, _ = torch.max(x, dim=1, keepdim=True)
153
+ x = torch.cat([avg_out, max_out], dim=1)
154
+ x = self.conv1(x)
155
+ return self.sigmoid(x)
156
+
157
+
158
+ class PolypPVT(nn.Module):
159
+ def __init__(self, channel=32):
160
+ super(PolypPVT, self).__init__()
161
+
162
+ self.backbone = pvt_v2_b2() # [64, 128, 320, 512]
163
+ path = './pretrained_pth/pvt_v2_b2.pth'
164
+ save_model = torch.load(path)
165
+ model_dict = self.backbone.state_dict()
166
+ state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()}
167
+ model_dict.update(state_dict)
168
+ self.backbone.load_state_dict(model_dict)
169
+
170
+ self.Translayer2_0 = BasicConv2d(64, channel, 1)
171
+ self.Translayer2_1 = BasicConv2d(128, channel, 1)
172
+ self.Translayer3_1 = BasicConv2d(320, channel, 1)
173
+ self.Translayer4_1 = BasicConv2d(512, channel, 1)
174
+
175
+ self.CFM = CFM(channel)
176
+ self.ca = ChannelAttention(64)
177
+ self.sa = SpatialAttention()
178
+ self.SAM = SAM()
179
+
180
+ self.down05 = nn.Upsample(scale_factor=0.5, mode='bilinear', align_corners=True)
181
+ self.out_SAM = nn.Conv2d(channel, 1, 1)
182
+ self.out_CFM = nn.Conv2d(channel, 1, 1)
183
+
184
+
185
+ def forward(self, x):
186
+
187
+ # backbone
188
+ pvt = self.backbone(x)
189
+ x1 = pvt[0]
190
+ x2 = pvt[1]
191
+ x3 = pvt[2]
192
+ x4 = pvt[3]
193
+
194
+ # CIM
195
+ x1 = self.ca(x1) * x1 # channel attention
196
+ cim_feature = self.sa(x1) * x1 # spatial attention
197
+
198
+
199
+ # CFM
200
+ x2_t = self.Translayer2_1(x2)
201
+ x3_t = self.Translayer3_1(x3)
202
+ x4_t = self.Translayer4_1(x4)
203
+ cfm_feature = self.CFM(x4_t, x3_t, x2_t)
204
+
205
+ # SAM
206
+ T2 = self.Translayer2_0(cim_feature)
207
+ T2 = self.down05(T2)
208
+ sam_feature = self.SAM(cfm_feature, T2)
209
+
210
+ prediction1 = self.out_CFM(cfm_feature)
211
+ prediction2 = self.out_SAM(sam_feature)
212
+
213
+ prediction1_8 = F.interpolate(prediction1, scale_factor=8, mode='bilinear')
214
+ prediction2_8 = F.interpolate(prediction2, scale_factor=8, mode='bilinear')
215
+ return prediction1_8, prediction2_8
216
+
217
+
218
+ if __name__ == '__main__':
219
+ model = PolypPVT().cuda()
220
+ input_tensor = torch.randn(1, 3, 352, 352).cuda()
221
+
222
+ prediction1, prediction2 = model(input_tensor)
223
+ print(prediction1.size(), prediction2.size())
lib/pvtv2.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from functools import partial
5
+
6
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
7
+ from timm.models.registry import register_model
8
+ from timm.models.vision_transformer import _cfg
9
+ from timm.models.registry import register_model
10
+
11
+ import math
12
+
13
+
14
+ class Mlp(nn.Module):
15
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
16
+ super().__init__()
17
+ out_features = out_features or in_features
18
+ hidden_features = hidden_features or in_features
19
+ self.fc1 = nn.Linear(in_features, hidden_features)
20
+ self.dwconv = DWConv(hidden_features)
21
+ self.act = act_layer()
22
+ self.fc2 = nn.Linear(hidden_features, out_features)
23
+ self.drop = nn.Dropout(drop)
24
+
25
+ self.apply(self._init_weights)
26
+
27
+ def _init_weights(self, m):
28
+ if isinstance(m, nn.Linear):
29
+ trunc_normal_(m.weight, std=.02)
30
+ if isinstance(m, nn.Linear) and m.bias is not None:
31
+ nn.init.constant_(m.bias, 0)
32
+ elif isinstance(m, nn.LayerNorm):
33
+ nn.init.constant_(m.bias, 0)
34
+ nn.init.constant_(m.weight, 1.0)
35
+ elif isinstance(m, nn.Conv2d):
36
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
37
+ fan_out //= m.groups
38
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
39
+ if m.bias is not None:
40
+ m.bias.data.zero_()
41
+
42
+ def forward(self, x, H, W):
43
+ x = self.fc1(x)
44
+ x = self.dwconv(x, H, W)
45
+ x = self.act(x)
46
+ x = self.drop(x)
47
+ x = self.fc2(x)
48
+ x = self.drop(x)
49
+ return x
50
+
51
+
52
+ class Attention(nn.Module):
53
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
54
+ super().__init__()
55
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
56
+
57
+ self.dim = dim
58
+ self.num_heads = num_heads
59
+ head_dim = dim // num_heads
60
+ self.scale = qk_scale or head_dim ** -0.5
61
+
62
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
63
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
64
+ self.attn_drop = nn.Dropout(attn_drop)
65
+ self.proj = nn.Linear(dim, dim)
66
+ self.proj_drop = nn.Dropout(proj_drop)
67
+
68
+ self.sr_ratio = sr_ratio
69
+ if sr_ratio > 1:
70
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
71
+ self.norm = nn.LayerNorm(dim)
72
+
73
+ self.apply(self._init_weights)
74
+
75
+ def _init_weights(self, m):
76
+ if isinstance(m, nn.Linear):
77
+ trunc_normal_(m.weight, std=.02)
78
+ if isinstance(m, nn.Linear) and m.bias is not None:
79
+ nn.init.constant_(m.bias, 0)
80
+ elif isinstance(m, nn.LayerNorm):
81
+ nn.init.constant_(m.bias, 0)
82
+ nn.init.constant_(m.weight, 1.0)
83
+ elif isinstance(m, nn.Conv2d):
84
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
85
+ fan_out //= m.groups
86
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
87
+ if m.bias is not None:
88
+ m.bias.data.zero_()
89
+
90
+ def forward(self, x, H, W):
91
+ B, N, C = x.shape
92
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
93
+
94
+ if self.sr_ratio > 1:
95
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
96
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
97
+ x_ = self.norm(x_)
98
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
99
+ else:
100
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
101
+ k, v = kv[0], kv[1]
102
+
103
+ attn = (q @ k.transpose(-2, -1)) * self.scale
104
+ attn = attn.softmax(dim=-1)
105
+ attn = self.attn_drop(attn)
106
+
107
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
108
+ x = self.proj(x)
109
+ x = self.proj_drop(x)
110
+
111
+ return x
112
+
113
+
114
+ class Block(nn.Module):
115
+
116
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
117
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
118
+ super().__init__()
119
+ self.norm1 = norm_layer(dim)
120
+ self.attn = Attention(
121
+ dim,
122
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
123
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
124
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
125
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
126
+ self.norm2 = norm_layer(dim)
127
+ mlp_hidden_dim = int(dim * mlp_ratio)
128
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
129
+
130
+ self.apply(self._init_weights)
131
+
132
+ def _init_weights(self, m):
133
+ if isinstance(m, nn.Linear):
134
+ trunc_normal_(m.weight, std=.02)
135
+ if isinstance(m, nn.Linear) and m.bias is not None:
136
+ nn.init.constant_(m.bias, 0)
137
+ elif isinstance(m, nn.LayerNorm):
138
+ nn.init.constant_(m.bias, 0)
139
+ nn.init.constant_(m.weight, 1.0)
140
+ elif isinstance(m, nn.Conv2d):
141
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
142
+ fan_out //= m.groups
143
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
144
+ if m.bias is not None:
145
+ m.bias.data.zero_()
146
+
147
+ def forward(self, x, H, W):
148
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
149
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
150
+
151
+ return x
152
+
153
+
154
+ class OverlapPatchEmbed(nn.Module):
155
+ """ Image to Patch Embedding
156
+ """
157
+
158
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
159
+ super().__init__()
160
+ img_size = to_2tuple(img_size)
161
+ patch_size = to_2tuple(patch_size)
162
+
163
+ self.img_size = img_size
164
+ self.patch_size = patch_size
165
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
166
+ self.num_patches = self.H * self.W
167
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride,
168
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
169
+ self.norm = nn.LayerNorm(embed_dim)
170
+
171
+ self.apply(self._init_weights)
172
+
173
+ def _init_weights(self, m):
174
+ if isinstance(m, nn.Linear):
175
+ trunc_normal_(m.weight, std=.02)
176
+ if isinstance(m, nn.Linear) and m.bias is not None:
177
+ nn.init.constant_(m.bias, 0)
178
+ elif isinstance(m, nn.LayerNorm):
179
+ nn.init.constant_(m.bias, 0)
180
+ nn.init.constant_(m.weight, 1.0)
181
+ elif isinstance(m, nn.Conv2d):
182
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
183
+ fan_out //= m.groups
184
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
185
+ if m.bias is not None:
186
+ m.bias.data.zero_()
187
+
188
+ def forward(self, x):
189
+ x = self.proj(x)
190
+ _, _, H, W = x.shape
191
+ x = x.flatten(2).transpose(1, 2)
192
+ x = self.norm(x)
193
+
194
+ return x, H, W
195
+
196
+
197
+ class PyramidVisionTransformerImpr(nn.Module):
198
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
199
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
200
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
201
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
202
+ super().__init__()
203
+ self.num_classes = num_classes
204
+ self.depths = depths
205
+
206
+ # patch_embed
207
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_chans=in_chans,
208
+ embed_dim=embed_dims[0])
209
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_chans=embed_dims[0],
210
+ embed_dim=embed_dims[1])
211
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_chans=embed_dims[1],
212
+ embed_dim=embed_dims[2])
213
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_chans=embed_dims[2],
214
+ embed_dim=embed_dims[3])
215
+
216
+ # transformer encoder
217
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
218
+ cur = 0
219
+ self.block1 = nn.ModuleList([Block(
220
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
221
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
222
+ sr_ratio=sr_ratios[0])
223
+ for i in range(depths[0])])
224
+ self.norm1 = norm_layer(embed_dims[0])
225
+
226
+ cur += depths[0]
227
+ self.block2 = nn.ModuleList([Block(
228
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
229
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
230
+ sr_ratio=sr_ratios[1])
231
+ for i in range(depths[1])])
232
+ self.norm2 = norm_layer(embed_dims[1])
233
+
234
+ cur += depths[1]
235
+ self.block3 = nn.ModuleList([Block(
236
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
237
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
238
+ sr_ratio=sr_ratios[2])
239
+ for i in range(depths[2])])
240
+ self.norm3 = norm_layer(embed_dims[2])
241
+
242
+ cur += depths[2]
243
+ self.block4 = nn.ModuleList([Block(
244
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
245
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
246
+ sr_ratio=sr_ratios[3])
247
+ for i in range(depths[3])])
248
+ self.norm4 = norm_layer(embed_dims[3])
249
+
250
+ # classification head
251
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
252
+
253
+ self.apply(self._init_weights)
254
+
255
+ def _init_weights(self, m):
256
+ if isinstance(m, nn.Linear):
257
+ trunc_normal_(m.weight, std=.02)
258
+ if isinstance(m, nn.Linear) and m.bias is not None:
259
+ nn.init.constant_(m.bias, 0)
260
+ elif isinstance(m, nn.LayerNorm):
261
+ nn.init.constant_(m.bias, 0)
262
+ nn.init.constant_(m.weight, 1.0)
263
+ elif isinstance(m, nn.Conv2d):
264
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
265
+ fan_out //= m.groups
266
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
267
+ if m.bias is not None:
268
+ m.bias.data.zero_()
269
+
270
+ def init_weights(self, pretrained=None):
271
+ if isinstance(pretrained, str):
272
+ logger = 1
273
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
274
+
275
+ def reset_drop_path(self, drop_path_rate):
276
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
277
+ cur = 0
278
+ for i in range(self.depths[0]):
279
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
280
+
281
+ cur += self.depths[0]
282
+ for i in range(self.depths[1]):
283
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
284
+
285
+ cur += self.depths[1]
286
+ for i in range(self.depths[2]):
287
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
288
+
289
+ cur += self.depths[2]
290
+ for i in range(self.depths[3]):
291
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
292
+
293
+ def freeze_patch_emb(self):
294
+ self.patch_embed1.requires_grad = False
295
+
296
+ @torch.jit.ignore
297
+ def no_weight_decay(self):
298
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
299
+
300
+ def get_classifier(self):
301
+ return self.head
302
+
303
+ def reset_classifier(self, num_classes, global_pool=''):
304
+ self.num_classes = num_classes
305
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
306
+
307
+ # def _get_pos_embed(self, pos_embed, patch_embed, H, W):
308
+ # if H * W == self.patch_embed1.num_patches:
309
+ # return pos_embed
310
+ # else:
311
+ # return F.interpolate(
312
+ # pos_embed.reshape(1, patch_embed.H, patch_embed.W, -1).permute(0, 3, 1, 2),
313
+ # size=(H, W), mode="bilinear").reshape(1, -1, H * W).permute(0, 2, 1)
314
+
315
+ def forward_features(self, x):
316
+ B = x.shape[0]
317
+ outs = []
318
+
319
+ # stage 1
320
+ x, H, W = self.patch_embed1(x)
321
+ for i, blk in enumerate(self.block1):
322
+ x = blk(x, H, W)
323
+ x = self.norm1(x)
324
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
325
+ outs.append(x)
326
+
327
+ # stage 2
328
+ x, H, W = self.patch_embed2(x)
329
+ for i, blk in enumerate(self.block2):
330
+ x = blk(x, H, W)
331
+ x = self.norm2(x)
332
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
333
+ outs.append(x)
334
+
335
+ # stage 3
336
+ x, H, W = self.patch_embed3(x)
337
+ for i, blk in enumerate(self.block3):
338
+ x = blk(x, H, W)
339
+ x = self.norm3(x)
340
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
341
+ outs.append(x)
342
+
343
+ # stage 4
344
+ x, H, W = self.patch_embed4(x)
345
+ for i, blk in enumerate(self.block4):
346
+ x = blk(x, H, W)
347
+ x = self.norm4(x)
348
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
349
+ outs.append(x)
350
+
351
+ return outs
352
+
353
+ # return x.mean(dim=1)
354
+
355
+ def forward(self, x):
356
+ x = self.forward_features(x)
357
+ # x = self.head(x)
358
+
359
+ return x
360
+
361
+
362
+ class DWConv(nn.Module):
363
+ def __init__(self, dim=768):
364
+ super(DWConv, self).__init__()
365
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
366
+
367
+ def forward(self, x, H, W):
368
+ B, N, C = x.shape
369
+ x = x.transpose(1, 2).view(B, C, H, W)
370
+ x = self.dwconv(x)
371
+ x = x.flatten(2).transpose(1, 2)
372
+
373
+ return x
374
+
375
+
376
+ def _conv_filter(state_dict, patch_size=16):
377
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
378
+ out_dict = {}
379
+ for k, v in state_dict.items():
380
+ if 'patch_embed.proj.weight' in k:
381
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
382
+ out_dict[k] = v
383
+
384
+ return out_dict
385
+
386
+
387
+ @register_model
388
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
389
+ def __init__(self, **kwargs):
390
+ super(pvt_v2_b0, self).__init__(
391
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
392
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
393
+ drop_rate=0.0, drop_path_rate=0.1)
394
+
395
+
396
+
397
+ @register_model
398
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
399
+ def __init__(self, **kwargs):
400
+ super(pvt_v2_b1, self).__init__(
401
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
402
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
403
+ drop_rate=0.0, drop_path_rate=0.1)
404
+
405
+ @register_model
406
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
407
+ def __init__(self, **kwargs):
408
+ super(pvt_v2_b2, self).__init__(
409
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
410
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
411
+ drop_rate=0.0, drop_path_rate=0.1)
412
+
413
+ @register_model
414
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
415
+ def __init__(self, **kwargs):
416
+ super(pvt_v2_b3, self).__init__(
417
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
418
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
419
+ drop_rate=0.0, drop_path_rate=0.1)
420
+
421
+ @register_model
422
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
423
+ def __init__(self, **kwargs):
424
+ super(pvt_v2_b4, self).__init__(
425
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
426
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
427
+ drop_rate=0.0, drop_path_rate=0.1)
428
+
429
+
430
+ @register_model
431
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
432
+ def __init__(self, **kwargs):
433
+ super(pvt_v2_b5, self).__init__(
434
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
435
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
436
+ drop_rate=0.0, drop_path_rate=0.1)