Andy1621 commited on
Commit
e9e2587
1 Parent(s): 3f41948

Create uniformer.py

Browse files
Files changed (1) hide show
  1. uniformer.py +366 -0
uniformer.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ import torch
3
+ import torch.nn as nn
4
+ from functools import partial
5
+ from timm.models.vision_transformer import _cfg
6
+ from timm.models.registry import register_model
7
+ from timm.models.layers import trunc_normal_, DropPath, to_2tuple
8
+
9
+ layer_scale = False
10
+ init_value = 1e-6
11
+
12
+
13
+ class Mlp(nn.Module):
14
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
15
+ super().__init__()
16
+ out_features = out_features or in_features
17
+ hidden_features = hidden_features or in_features
18
+ self.fc1 = nn.Linear(in_features, hidden_features)
19
+ self.act = act_layer()
20
+ self.fc2 = nn.Linear(hidden_features, out_features)
21
+ self.drop = nn.Dropout(drop)
22
+
23
+ def forward(self, x):
24
+ x = self.fc1(x)
25
+ x = self.act(x)
26
+ x = self.drop(x)
27
+ x = self.fc2(x)
28
+ x = self.drop(x)
29
+ return x
30
+
31
+
32
+ class CMlp(nn.Module):
33
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
34
+ super().__init__()
35
+ out_features = out_features or in_features
36
+ hidden_features = hidden_features or in_features
37
+ self.fc1 = nn.Conv2d(in_features, hidden_features, 1)
38
+ self.act = act_layer()
39
+ self.fc2 = nn.Conv2d(hidden_features, out_features, 1)
40
+ self.drop = nn.Dropout(drop)
41
+
42
+ def forward(self, x):
43
+ x = self.fc1(x)
44
+ x = self.act(x)
45
+ x = self.drop(x)
46
+ x = self.fc2(x)
47
+ x = self.drop(x)
48
+ return x
49
+
50
+
51
+ class Attention(nn.Module):
52
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
53
+ super().__init__()
54
+ self.num_heads = num_heads
55
+ head_dim = dim // num_heads
56
+ # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
57
+ self.scale = qk_scale or head_dim ** -0.5
58
+
59
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
60
+ self.attn_drop = nn.Dropout(attn_drop)
61
+ self.proj = nn.Linear(dim, dim)
62
+ self.proj_drop = nn.Dropout(proj_drop)
63
+
64
+ def forward(self, x):
65
+ B, N, C = x.shape
66
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
67
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
68
+
69
+ attn = (q @ k.transpose(-2, -1)) * self.scale
70
+ attn = attn.softmax(dim=-1)
71
+ attn = self.attn_drop(attn)
72
+
73
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
74
+ x = self.proj(x)
75
+ x = self.proj_drop(x)
76
+ return x
77
+
78
+
79
+ class CBlock(nn.Module):
80
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
81
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
82
+ super().__init__()
83
+ self.pos_embed = nn.Conv2d(dim, dim, 3, padding=1, groups=dim)
84
+ self.norm1 = nn.BatchNorm2d(dim)
85
+ self.conv1 = nn.Conv2d(dim, dim, 1)
86
+ self.conv2 = nn.Conv2d(dim, dim, 1)
87
+ self.attn = nn.Conv2d(dim, dim, 5, padding=2, groups=dim)
88
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
89
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
90
+ self.norm2 = nn.BatchNorm2d(dim)
91
+ mlp_hidden_dim = int(dim * mlp_ratio)
92
+ self.mlp = CMlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
93
+
94
+ def forward(self, x):
95
+ x = x + self.pos_embed(x)
96
+ x = x + self.drop_path(self.conv2(self.attn(self.conv1(self.norm1(x)))))
97
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
98
+ return x
99
+
100
+
101
+ class SABlock(nn.Module):
102
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
103
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
104
+ super().__init__()
105
+ self.pos_embed = nn.Conv2d(dim, dim, 3, padding=1, groups=dim)
106
+ self.norm1 = norm_layer(dim)
107
+ self.attn = Attention(
108
+ dim,
109
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
110
+ attn_drop=attn_drop, proj_drop=drop)
111
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
112
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
113
+ self.norm2 = norm_layer(dim)
114
+ mlp_hidden_dim = int(dim * mlp_ratio)
115
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
116
+ global layer_scale
117
+ self.ls = layer_scale
118
+ if self.ls:
119
+ global init_value
120
+ print(f"Use layer_scale: {layer_scale}, init_values: {init_value}")
121
+ self.gamma_1 = nn.Parameter(init_value * torch.ones((dim)),requires_grad=True)
122
+ self.gamma_2 = nn.Parameter(init_value * torch.ones((dim)),requires_grad=True)
123
+
124
+ def forward(self, x):
125
+ x = x + self.pos_embed(x)
126
+ B, N, H, W = x.shape
127
+ x = x.flatten(2).transpose(1, 2)
128
+ if self.ls:
129
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x)))
130
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
131
+ else:
132
+ x = x + self.drop_path(self.attn(self.norm1(x)))
133
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
134
+ x = x.transpose(1, 2).reshape(B, N, H, W)
135
+ return x
136
+
137
+
138
+ class head_embedding(nn.Module):
139
+ def __init__(self, in_channels, out_channels):
140
+ super(head_embedding, self).__init__()
141
+
142
+ self.proj = nn.Sequential(
143
+ nn.Conv2d(in_channels, out_channels // 2, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
144
+ nn.BatchNorm2d(out_channels // 2),
145
+ nn.GELU(),
146
+ nn.Conv2d(out_channels // 2, out_channels, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
147
+ nn.BatchNorm2d(out_channels),
148
+ )
149
+
150
+ def forward(self, x):
151
+ x = self.proj(x)
152
+ return x
153
+
154
+
155
+ class middle_embedding(nn.Module):
156
+ def __init__(self, in_channels, out_channels):
157
+ super(middle_embedding, self).__init__()
158
+
159
+ self.proj = nn.Sequential(
160
+ nn.Conv2d(in_channels, out_channels, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
161
+ nn.BatchNorm2d(out_channels),
162
+ )
163
+
164
+ def forward(self, x):
165
+ x = self.proj(x)
166
+ return x
167
+
168
+
169
+ class PatchEmbed(nn.Module):
170
+ """ Image to Patch Embedding
171
+ """
172
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
173
+ super().__init__()
174
+ img_size = to_2tuple(img_size)
175
+ patch_size = to_2tuple(patch_size)
176
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
177
+ self.img_size = img_size
178
+ self.patch_size = patch_size
179
+ self.num_patches = num_patches
180
+ self.norm = nn.LayerNorm(embed_dim)
181
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
182
+
183
+ def forward(self, x):
184
+ B, C, H, W = x.shape
185
+ # FIXME look at relaxing size constraints
186
+ # assert H == self.img_size[0] and W == self.img_size[1], \
187
+ # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
188
+ x = self.proj(x)
189
+ B, C, H, W = x.shape
190
+ x = x.flatten(2).transpose(1, 2)
191
+ x = self.norm(x)
192
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
193
+ return x
194
+
195
+
196
+ class UniFormer(nn.Module):
197
+ """ Vision Transformer
198
+ A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -
199
+ https://arxiv.org/abs/2010.11929
200
+ """
201
+ def __init__(self, depth=[3, 4, 8, 3], img_size=224, in_chans=3, num_classes=1000, embed_dim=[64, 128, 320, 512],
202
+ head_dim=64, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None,
203
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=None, conv_stem=False):
204
+ """
205
+ Args:
206
+ depth (list): depth of each stage
207
+ img_size (int, tuple): input image size
208
+ in_chans (int): number of input channels
209
+ num_classes (int): number of classes for classification head
210
+ embed_dim (list): embedding dimension of each stage
211
+ head_dim (int): head dimension
212
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
213
+ qkv_bias (bool): enable bias for qkv if True
214
+ qk_scale (float): override default qk scale of head_dim ** -0.5 if set
215
+ representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
216
+ drop_rate (float): dropout rate
217
+ attn_drop_rate (float): attention dropout rate
218
+ drop_path_rate (float): stochastic depth rate
219
+ norm_layer: (nn.Module): normalization layer
220
+ conv_stem: (bool): whether use overlapped patch stem
221
+ """
222
+ super().__init__()
223
+ self.num_classes = num_classes
224
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
225
+ norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
226
+ if conv_stem:
227
+ self.patch_embed1 = head_embedding(in_channels=in_chans, out_channels=embed_dim[0])
228
+ self.patch_embed2 = middle_embedding(in_channels=embed_dim[0], out_channels=embed_dim[1])
229
+ self.patch_embed3 = middle_embedding(in_channels=embed_dim[1], out_channels=embed_dim[2])
230
+ self.patch_embed4 = middle_embedding(in_channels=embed_dim[2], out_channels=embed_dim[3])
231
+ else:
232
+ self.patch_embed1 = PatchEmbed(
233
+ img_size=img_size, patch_size=4, in_chans=in_chans, embed_dim=embed_dim[0])
234
+ self.patch_embed2 = PatchEmbed(
235
+ img_size=img_size // 4, patch_size=2, in_chans=embed_dim[0], embed_dim=embed_dim[1])
236
+ self.patch_embed3 = PatchEmbed(
237
+ img_size=img_size // 8, patch_size=2, in_chans=embed_dim[1], embed_dim=embed_dim[2])
238
+ self.patch_embed4 = PatchEmbed(
239
+ img_size=img_size // 16, patch_size=2, in_chans=embed_dim[2], embed_dim=embed_dim[3])
240
+
241
+ self.pos_drop = nn.Dropout(p=drop_rate)
242
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depth))] # stochastic depth decay rule
243
+ num_heads = [dim // head_dim for dim in embed_dim]
244
+ self.blocks1 = nn.ModuleList([
245
+ CBlock(
246
+ dim=embed_dim[0], num_heads=num_heads[0], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
247
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
248
+ for i in range(depth[0])])
249
+ self.blocks2 = nn.ModuleList([
250
+ CBlock(
251
+ dim=embed_dim[1], num_heads=num_heads[1], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
252
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i+depth[0]], norm_layer=norm_layer)
253
+ for i in range(depth[1])])
254
+ self.blocks3 = nn.ModuleList([
255
+ SABlock(
256
+ dim=embed_dim[2], num_heads=num_heads[2], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
257
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i+depth[0]+depth[1]], norm_layer=norm_layer)
258
+ for i in range(depth[2])])
259
+ self.blocks4 = nn.ModuleList([
260
+ SABlock(
261
+ dim=embed_dim[3], num_heads=num_heads[3], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
262
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i+depth[0]+depth[1]+depth[2]], norm_layer=norm_layer)
263
+ for i in range(depth[3])])
264
+ self.norm = nn.BatchNorm2d(embed_dim[-1])
265
+
266
+ # Representation layer
267
+ if representation_size:
268
+ self.num_features = representation_size
269
+ self.pre_logits = nn.Sequential(OrderedDict([
270
+ ('fc', nn.Linear(embed_dim, representation_size)),
271
+ ('act', nn.Tanh())
272
+ ]))
273
+ else:
274
+ self.pre_logits = nn.Identity()
275
+
276
+ # Classifier head
277
+ self.head = nn.Linear(embed_dim[-1], num_classes) if num_classes > 0 else nn.Identity()
278
+
279
+ self.apply(self._init_weights)
280
+
281
+ def _init_weights(self, m):
282
+ if isinstance(m, nn.Linear):
283
+ trunc_normal_(m.weight, std=.02)
284
+ if isinstance(m, nn.Linear) and m.bias is not None:
285
+ nn.init.constant_(m.bias, 0)
286
+ elif isinstance(m, nn.LayerNorm):
287
+ nn.init.constant_(m.bias, 0)
288
+ nn.init.constant_(m.weight, 1.0)
289
+
290
+ @torch.jit.ignore
291
+ def no_weight_decay(self):
292
+ return {'pos_embed', 'cls_token'}
293
+
294
+ def get_classifier(self):
295
+ return self.head
296
+
297
+ def reset_classifier(self, num_classes, global_pool=''):
298
+ self.num_classes = num_classes
299
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
300
+
301
+ def forward_features(self, x):
302
+ B = x.shape[0]
303
+ x = self.patch_embed1(x)
304
+ x = self.pos_drop(x)
305
+ for blk in self.blocks1:
306
+ x = blk(x)
307
+ x = self.patch_embed2(x)
308
+ for blk in self.blocks2:
309
+ x = blk(x)
310
+ x = self.patch_embed3(x)
311
+ for blk in self.blocks3:
312
+ x = blk(x)
313
+ x = self.patch_embed4(x)
314
+ for blk in self.blocks4:
315
+ x = blk(x)
316
+ x = self.norm(x)
317
+ x = self.pre_logits(x)
318
+ return x
319
+
320
+ def forward(self, x):
321
+ x = self.forward_features(x)
322
+ x = x.flatten(2).mean(-1)
323
+ x = self.head(x)
324
+ return x
325
+
326
+
327
+ @register_model
328
+ def uniformer_small(pretrained=True, **kwargs):
329
+ model = UniFormer(
330
+ depth=[3, 4, 8, 3],
331
+ embed_dim=[64, 128, 320, 512], head_dim=64, mlp_ratio=4, qkv_bias=True,
332
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
333
+ model.default_cfg = _cfg()
334
+ return model
335
+
336
+
337
+ @register_model
338
+ def uniformer_small_plus(pretrained=True, **kwargs):
339
+ model = UniFormer(
340
+ depth=[3, 5, 9, 3], conv_stem=True,
341
+ embed_dim=[64, 128, 320, 512], head_dim=64, mlp_ratio=4, qkv_bias=True,
342
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
343
+ model.default_cfg = _cfg()
344
+ return model
345
+
346
+
347
+ @register_model
348
+ def uniformer_base(pretrained=True, **kwargs):
349
+ model = UniFormer(
350
+ depth=[5, 8, 20, 7],
351
+ embed_dim=[64, 128, 320, 512], head_dim=64, mlp_ratio=4, qkv_bias=True,
352
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
353
+ model.default_cfg = _cfg()
354
+ return model
355
+
356
+
357
+ @register_model
358
+ def uniformer_base_ls(pretrained=True, **kwargs):
359
+ global layer_scale
360
+ layer_scale = True
361
+ model = UniFormer(
362
+ depth=[5, 8, 20, 7],
363
+ embed_dim=[64, 128, 320, 512], head_dim=64, mlp_ratio=4, qkv_bias=True,
364
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
365
+ model.default_cfg = _cfg()
366
+ return model