tosanoob commited on
Commit
b29fdb3
1 Parent(s): 1b2ce6a

Add definition class

Browse files
uniformer_finetune/__init__.py ADDED
File without changes
uniformer_finetune/uniformer_finetune_config.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class UniformerXXSFinetuneConfig(PretrainedConfig):
4
+ model_type = "uniformer_finetuned"
5
+
6
+ def __init__(
7
+ self,
8
+ pretrained: str = 'uniformer_xxs_400',
9
+ out_class: int = 20,
10
+ **kwargs
11
+ ):
12
+ self.pretrained = pretrained
13
+ self.out_class = out_class
14
+ super().__init__(**kwargs)
15
+
uniformer_finetune/uniformer_finetune_model.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel
2
+ from uniformer_finetune_config import UniformerXXSFinetuneConfig
3
+ from uniformer_xs import UniformerXXSFinetune
4
+
5
+ class UniformerXXSFinetuneModel(PreTrainedModel):
6
+ config_class = UniformerXXSFinetuneConfig
7
+
8
+ def __init__(self, config):
9
+ super().__init__(config)
10
+ self.model = UniformerXXSFinetune(
11
+ out_class=config.out_class
12
+ )
13
+ def forward(self, tensor):
14
+ return self.model.forward(tensor)
uniformer_finetune/uniformer_xs.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # All rights reserved.
2
+ from math import ceil, sqrt
3
+ from collections import OrderedDict
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from functools import partial
8
+ from timm.models.vision_transformer import _cfg
9
+ from timm.models.layers import trunc_normal_, DropPath, to_2tuple
10
+ # from .build import MODEL_REGISTRY
11
+ import os
12
+
13
+ import slowfast.utils.logging as logging
14
+
15
+ logger = logging.get_logger(__name__)
16
+
17
+ model_path = 'path_to_models'
18
+ model_path = {
19
+ 'uniformer_xxs_128_in1k': os.path.join(model_path, 'uniformer_xxs_128_in1k.pth'),
20
+ 'uniformer_xxs_160_in1k': os.path.join(model_path, 'uniformer_xxs_160_in1k.pth'),
21
+ 'uniformer_xxs_192_in1k': os.path.join(model_path, 'uniformer_xxs_192_in1k.pth'),
22
+ 'uniformer_xxs_224_in1k': os.path.join(model_path, 'uniformer_xxs_224_in1k.pth'),
23
+ 'uniformer_xs_192_in1k': os.path.join(model_path, 'uniformer_xs_192_in1k.pth'),
24
+ 'uniformer_xs_224_in1k': os.path.join(model_path, 'uniformer_xs_224_in1k.pth'),
25
+ }
26
+
27
+
28
+ def conv_3xnxn(inp, oup, kernel_size=3, stride=3, groups=1):
29
+ return nn.Conv3d(inp, oup, (3, kernel_size, kernel_size), (2, stride, stride), (1, 0, 0), groups=groups)
30
+
31
+ def conv_1xnxn(inp, oup, kernel_size=3, stride=3, groups=1):
32
+ return nn.Conv3d(inp, oup, (1, kernel_size, kernel_size), (1, stride, stride), (0, 0, 0), groups=groups)
33
+
34
+ def conv_3xnxn_std(inp, oup, kernel_size=3, stride=3, groups=1):
35
+ return nn.Conv3d(inp, oup, (3, kernel_size, kernel_size), (1, stride, stride), (1, 0, 0), groups=groups)
36
+
37
+ def conv_1x1x1(inp, oup, groups=1):
38
+ return nn.Conv3d(inp, oup, (1, 1, 1), (1, 1, 1), (0, 0, 0), groups=groups)
39
+
40
+ def conv_3x3x3(inp, oup, groups=1):
41
+ return nn.Conv3d(inp, oup, (3, 3, 3), (1, 1, 1), (1, 1, 1), groups=groups)
42
+
43
+ def conv_5x5x5(inp, oup, groups=1):
44
+ return nn.Conv3d(inp, oup, (5, 5, 5), (1, 1, 1), (2, 2, 2), groups=groups)
45
+
46
+ def bn_3d(dim):
47
+ return nn.BatchNorm3d(dim)
48
+
49
+
50
+ # code is from https://github.com/YifanXu74/Evo-ViT
51
+ def easy_gather(x, indices):
52
+ # x => B x N x C
53
+ # indices => B x N
54
+ B, N, C = x.shape
55
+ N_new = indices.shape[1]
56
+ offset = torch.arange(B, dtype=torch.long, device=x.device).view(B, 1) * N
57
+ indices = indices + offset
58
+ # only select the informative tokens
59
+ out = x.reshape(B * N, C)[indices.view(-1)].reshape(B, N_new, C)
60
+ return out
61
+
62
+
63
+ # code is from https://github.com/YifanXu74/Evo-ViT
64
+ def merge_tokens(x_drop, score):
65
+ # x_drop => B x N_drop
66
+ # score => B x N_drop
67
+ weight = score / torch.sum(score, dim=1, keepdim=True)
68
+ x_drop = weight.unsqueeze(-1) * x_drop
69
+ return torch.sum(x_drop, dim=1, keepdim=True)
70
+
71
+
72
+ class Mlp(nn.Module):
73
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
74
+ super().__init__()
75
+ out_features = out_features or in_features
76
+ hidden_features = hidden_features or in_features
77
+ self.fc1 = nn.Linear(in_features, hidden_features)
78
+ self.act = act_layer()
79
+ self.fc2 = nn.Linear(hidden_features, out_features)
80
+ self.drop = nn.Dropout(drop)
81
+
82
+ def forward(self, x):
83
+ x = self.fc1(x)
84
+ x = self.act(x)
85
+ x = self.drop(x)
86
+ x = self.fc2(x)
87
+ x = self.drop(x)
88
+ return x
89
+
90
+
91
+ class Attention(nn.Module):
92
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., trade_off=1):
93
+ super().__init__()
94
+ self.num_heads = num_heads
95
+ head_dim = dim // num_heads
96
+ # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
97
+ self.scale = qk_scale or head_dim ** -0.5
98
+
99
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
100
+ self.attn_drop = nn.Dropout(attn_drop)
101
+ self.proj = nn.Linear(dim, dim)
102
+ self.proj_drop = nn.Dropout(proj_drop)
103
+ # updating weight for global score
104
+ self.trade_off = trade_off
105
+
106
+ def forward(self, x, global_attn):
107
+ B, N, C = x.shape
108
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
109
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
110
+
111
+ attn = (q @ k.transpose(-2, -1)) * self.scale
112
+ attn = attn.softmax(dim=-1)
113
+
114
+ # update global score
115
+ tradeoff = self.trade_off
116
+ if isinstance(global_attn, int):
117
+ global_attn = torch.mean(attn[:, :, 0, 1:], dim=1)
118
+ elif global_attn.shape[1] == N - 1:
119
+ # no additional token and no pruning, update all global scores
120
+ cls_attn = torch.mean(attn[:, :, 0, 1:], dim=1)
121
+ global_attn = (1 - tradeoff) * global_attn + tradeoff * cls_attn
122
+ else:
123
+ # only update the informative tokens
124
+ # the first one is class token
125
+ # the last one is rrepresentative token
126
+ cls_attn = torch.mean(attn[:, :, 0, 1:-1], dim=1)
127
+ if self.training:
128
+ temp_attn = (1 - tradeoff) * global_attn[:, :(N - 2)] + tradeoff * cls_attn
129
+ global_attn = torch.cat((temp_attn, global_attn[:, (N - 2):]), dim=1)
130
+ else:
131
+ # no use torch.cat() for fast inference
132
+ global_attn[:, :(N - 2)] = (1 - tradeoff) * global_attn[:, :(N - 2)] + tradeoff * cls_attn
133
+
134
+ attn = self.attn_drop(attn)
135
+
136
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
137
+ x = self.proj(x)
138
+ x = self.proj_drop(x)
139
+ return x, global_attn
140
+
141
+
142
+ class CMlp(nn.Module):
143
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
144
+ super().__init__()
145
+ out_features = out_features or in_features
146
+ hidden_features = hidden_features or in_features
147
+ self.fc1 = conv_1x1x1(in_features, hidden_features)
148
+ self.act = act_layer()
149
+ self.fc2 = conv_1x1x1(hidden_features, out_features)
150
+ self.drop = nn.Dropout(drop)
151
+
152
+ def forward(self, x):
153
+ x = self.fc1(x)
154
+ x = self.act(x)
155
+ x = self.drop(x)
156
+ x = self.fc2(x)
157
+ x = self.drop(x)
158
+ return x
159
+
160
+
161
+ class CBlock(nn.Module):
162
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
163
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
164
+ super().__init__()
165
+ self.pos_embed = conv_3x3x3(dim, dim, groups=dim)
166
+ self.norm1 = bn_3d(dim)
167
+ self.conv1 = conv_1x1x1(dim, dim, 1)
168
+ self.conv2 = conv_1x1x1(dim, dim, 1)
169
+ self.attn = conv_5x5x5(dim, dim, groups=dim)
170
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
171
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
172
+ self.norm2 = bn_3d(dim)
173
+ mlp_hidden_dim = int(dim * mlp_ratio)
174
+ self.mlp = CMlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
175
+
176
+ def forward(self, x):
177
+ x = x + self.pos_embed(x)
178
+ x = x + self.drop_path(self.conv2(self.attn(self.conv1(self.norm1(x)))))
179
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
180
+ return x
181
+
182
+
183
+ class EvoSABlock(nn.Module):
184
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
185
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, prune_ratio=1,
186
+ trade_off=0, downsample=False):
187
+ super().__init__()
188
+ self.pos_embed = conv_3x3x3(dim, dim, groups=dim)
189
+ self.norm1 = norm_layer(dim)
190
+ self.attn = Attention(
191
+ dim,
192
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
193
+ attn_drop=attn_drop, proj_drop=drop, trade_off=trade_off)
194
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
195
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
196
+ self.norm2 = norm_layer(dim)
197
+ mlp_hidden_dim = int(dim * mlp_ratio)
198
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
199
+ self.prune_ratio = prune_ratio
200
+ self.downsample = downsample
201
+ # if downsample:
202
+ self.avgpool = nn.AvgPool3d(kernel_size=(1, 2, 2), stride=(1, 2, 2))
203
+
204
+ def forward(self, cls_token, x, global_attn, token_indices):
205
+ x = x + self.pos_embed(x)
206
+ B, C, T, H, W = x.shape
207
+ x = x.flatten(2).transpose(1, 2)
208
+
209
+ if self.prune_ratio == 1:
210
+ x = torch.cat([cls_token, x], dim=1)
211
+ x , global_attn = self.attn(self.norm1(x), global_attn)
212
+ x = x + self.drop_path(x)
213
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
214
+ cls_token, x = x[:, :1], x[:, 1:]
215
+ x = x.transpose(1, 2).reshape(B, C, T, H, W)
216
+ return cls_token, x, global_attn, token_indices
217
+ else:
218
+ # global global_attn, token_indices
219
+ # calculate the number of informative tokens
220
+ N = x.shape[1]
221
+ N_ = int(N * self.prune_ratio)
222
+ # sort global attention
223
+ indices = torch.argsort(global_attn, dim=1, descending=True)
224
+
225
+ # concatenate x, global attention and token indices => x_ga_ti
226
+ # rearrange the tensor according to new indices
227
+ x_ga_ti = torch.cat((x, global_attn.unsqueeze(-1), token_indices.unsqueeze(-1)), dim=-1)
228
+ x_ga_ti = easy_gather(x_ga_ti, indices)
229
+ x_sorted, global_attn, token_indices = x_ga_ti[:, :, :-2], x_ga_ti[:, :, -2], x_ga_ti[:, :, -1]
230
+
231
+ # informative tokens
232
+ x_info = x_sorted[:, :N_]
233
+ # merge dropped tokens
234
+ x_drop = x_sorted[:, N_:]
235
+ score = global_attn[:, N_:]
236
+ # B x N_drop x C => B x 1 x C
237
+ rep_token = merge_tokens(x_drop, score)
238
+ # concatenate new tokens
239
+ x = torch.cat((cls_token, x_info, rep_token), dim=1)
240
+
241
+ # slow update
242
+ fast_update = 0
243
+ tmp_x, global_attn = self.attn(self.norm1(x), global_attn)
244
+ fast_update = fast_update + tmp_x[:, -1:]
245
+ x = x + self.drop_path(tmp_x)
246
+ tmp_x = self.mlp(self.norm2(x))
247
+ fast_update = fast_update + tmp_x[:, -1:]
248
+ x = x + self.drop_path(tmp_x)
249
+ # fast update
250
+ x_drop = x_drop + fast_update.expand(-1, N - N_, -1)
251
+
252
+ cls_token, x = x[:, :1, :], x[:, 1:-1, :]
253
+ if self.training:
254
+ x_sorted = torch.cat((x, x_drop), dim=1)
255
+ else:
256
+ x_sorted[:, N_:] = x_drop
257
+ x_sorted[:, :N_] = x
258
+
259
+ # recover token
260
+ # scale for normalization
261
+ old_global_scale = torch.sum(global_attn, dim=1, keepdim=True)
262
+ # recover order
263
+ indices = torch.argsort(token_indices, dim=1)
264
+ x_ga_ti = torch.cat((x_sorted, global_attn.unsqueeze(-1), token_indices.unsqueeze(-1)), dim=-1)
265
+ x_ga_ti = easy_gather(x_ga_ti, indices)
266
+ x_patch, global_attn, token_indices = x_ga_ti[:, :, :-2], x_ga_ti[:, :, -2], x_ga_ti[:, :, -1]
267
+ x_patch = x_patch.transpose(1, 2).reshape(B, C, T, H, W)
268
+
269
+ if self.downsample:
270
+ # downsample global attention
271
+ global_attn = global_attn.reshape(B, 1, T, H, W)
272
+ global_attn = self.avgpool(global_attn).view(B, -1)
273
+ # normalize global attention
274
+ new_global_scale = torch.sum(global_attn, dim=1, keepdim=True)
275
+ scale = old_global_scale / new_global_scale
276
+ global_attn = global_attn * scale
277
+
278
+ return cls_token, x_patch, global_attn, token_indices
279
+
280
+
281
+ class SABlock(nn.Module):
282
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
283
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
284
+ super().__init__()
285
+ self.pos_embed = conv_3x3x3(dim, dim, groups=dim)
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)
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
+ def forward(self, x, global_attn):
298
+ x = x + self.pos_embed(x)
299
+ B, C, T, H, W = x.shape
300
+ x = x.flatten(2).transpose(1, 2)
301
+ x , global_attn = self.attn(self.norm1(x),global_attn)
302
+ x = x + self.drop_path(x)
303
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
304
+ x = x.transpose(1, 2).reshape(B, C, T, H, W)
305
+ return x, global_attn
306
+
307
+
308
+ class SplitSABlock(nn.Module):
309
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
310
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
311
+ super().__init__()
312
+ self.pos_embed = conv_3x3x3(dim, dim, groups=dim)
313
+ self.t_norm = norm_layer(dim)
314
+ self.t_attn = Attention(
315
+ dim,
316
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
317
+ attn_drop=attn_drop, proj_drop=drop)
318
+ self.norm1 = norm_layer(dim)
319
+ self.attn = Attention(
320
+ dim,
321
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
322
+ attn_drop=attn_drop, proj_drop=drop)
323
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
324
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
325
+ self.norm2 = norm_layer(dim)
326
+ mlp_hidden_dim = int(dim * mlp_ratio)
327
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
328
+
329
+ def forward(self, x, global_attn):
330
+ x = x + self.pos_embed(x)
331
+ B, C, T, H, W = x.shape
332
+ attn = x.view(B, C, T, H * W).permute(0, 3, 2, 1).contiguous()
333
+ attn = attn.view(B * H * W, T, C)
334
+ attn, global_attn = self.t_attn(self.t_norm(attn),global_attn)
335
+ attn = attn + self.drop_path(attn)
336
+ attn = attn.view(B, H * W, T, C).permute(0, 2, 1, 3).contiguous()
337
+ attn = attn.view(B * T, H * W, C)
338
+ residual = x.view(B, C, T, H * W).permute(0, 2, 3, 1).contiguous()
339
+ residual = residual.view(B * T, H * W, C)
340
+ attn, global_attn = self.attn(self.norm1(attn), global_attn)
341
+ attn = residual + self.drop_path(attn)
342
+ attn = attn.view(B, T * H * W, C)
343
+ out = attn + self.drop_path(self.mlp(self.norm2(attn)))
344
+ out = out.transpose(1, 2).reshape(B, C, T, H, W)
345
+ return out, global_attn
346
+
347
+
348
+ class SpeicalPatchEmbed(nn.Module):
349
+ """ Image to Patch Embedding
350
+ """
351
+ def __init__(self, patch_size=16, in_chans=3, embed_dim=768):
352
+ super().__init__()
353
+ patch_size = to_2tuple(patch_size)
354
+ self.patch_size = patch_size
355
+
356
+ self.proj = nn.Sequential(
357
+ nn.Conv3d(in_chans, embed_dim // 2, kernel_size=(3, 3, 3), stride=(1, 2, 2), padding=(1, 1, 1)),
358
+ nn.BatchNorm3d(embed_dim // 2),
359
+ nn.GELU(),
360
+ nn.Conv3d(embed_dim // 2, embed_dim, kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(1, 1, 1)),
361
+ nn.BatchNorm3d(embed_dim),
362
+ )
363
+
364
+ def forward(self, x):
365
+ B, C, T, H, W = x.shape
366
+ # FIXME look at relaxing size constraints
367
+ # assert H == self.img_size[0] and W == self.img_size[1], \
368
+ # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
369
+ x = self.proj(x)
370
+ B, C, T, H, W = x.shape
371
+ x = x.flatten(2).transpose(1, 2)
372
+ x = x.reshape(B, T, H, W, -1).permute(0, 4, 1, 2, 3).contiguous()
373
+ return x
374
+
375
+
376
+ class PatchEmbed(nn.Module):
377
+ """ Image to Patch Embedding
378
+ """
379
+ def __init__(self, patch_size=16, in_chans=3, embed_dim=768):
380
+ super().__init__()
381
+ patch_size = to_2tuple(patch_size)
382
+ self.patch_size = patch_size
383
+ self.norm = nn.LayerNorm(embed_dim)
384
+ self.proj = conv_1xnxn(in_chans, embed_dim, kernel_size=patch_size[0], stride=patch_size[0])
385
+
386
+ def forward(self, x):
387
+ B, C, T, H, W = x.shape
388
+ # FIXME look at relaxing size constraints
389
+ # assert H == self.img_size[0] and W == self.img_size[1], \
390
+ # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
391
+ x = self.proj(x)
392
+ B, C, T, H, W = x.shape
393
+ x = x.flatten(2).transpose(1, 2)
394
+ x = self.norm(x)
395
+ x = x.reshape(B, T, H, W, -1).permute(0, 4, 1, 2, 3).contiguous()
396
+ return x
397
+
398
+ class Uniformer_light(nn.Module):
399
+ """ Vision Transformer
400
+ A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -
401
+ https://arxiv.org/abs/2010.11929
402
+ """
403
+
404
+ # def __init__(self, cfg):
405
+ # super().__init__()
406
+
407
+ def __init__(self, depth=[3, 5, 9, 3], num_classes=400, img_size=224, in_chans=3, embed_dim=[64, 128, 256, 512],
408
+ head_dim=32, mlp_ratio=3., qkv_bias=True, qk_scale=None, representation_size=None,
409
+ prune_ratio=[[], [], [1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5]],
410
+ trade_off=[[], [], [1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5]],
411
+ drop_rate=0.3, attn_drop_rate=0., drop_path_rate=0., norm_layer=None, split=False, std=False):
412
+ super().__init__()
413
+
414
+ # depth = cfg.UNIFORMER.DEPTH
415
+ # num_classes = cfg.MODEL.NUM_CLASSES
416
+ # in_chans = cfg.DATA.INPUT_CHANNEL_NUM[0]
417
+ # embed_dim = cfg.UNIFORMER.EMBED_DIM
418
+ # head_dim = cfg.UNIFORMER.HEAD_DIM
419
+ # mlp_ratio = cfg.UNIFORMER.MLP_RATIO
420
+ # qkv_bias = cfg.UNIFORMER.QKV_BIAS
421
+ # qk_scale = cfg.UNIFORMER.QKV_SCALE
422
+ # representation_size = cfg.UNIFORMER.REPRESENTATION_SIZE
423
+ # drop_rate = cfg.UNIFORMER.DROPOUT_RATE
424
+ # attn_drop_rate = cfg.UNIFORMER.ATTENTION_DROPOUT_RATE
425
+ # drop_path_rate = cfg.UNIFORMER.DROP_DEPTH_RATE
426
+ # prune_ratio = cfg.UNIFORMER.PRUNE_RATIO
427
+ # trade_off = cfg.UNIFORMER.TRADE_OFF
428
+
429
+ self.num_classes = num_classes
430
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
431
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
432
+
433
+ self.patch_embed1 = SpeicalPatchEmbed(
434
+ patch_size=4, in_chans=in_chans, embed_dim=embed_dim[0])
435
+ self.patch_embed2 = PatchEmbed(
436
+ patch_size=2, in_chans=embed_dim[0], embed_dim=embed_dim[1])
437
+ self.patch_embed3 = PatchEmbed(
438
+ patch_size=2, in_chans=embed_dim[1], embed_dim=embed_dim[2])
439
+ self.patch_embed4 = PatchEmbed(
440
+ patch_size=2, in_chans=embed_dim[2], embed_dim=embed_dim[3])
441
+
442
+ # class token
443
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim[2]))
444
+ self.cls_upsample = nn.Linear(embed_dim[2], embed_dim[3])
445
+
446
+ self.pos_drop = nn.Dropout(p=drop_rate)
447
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depth))] # stochastic depth decay rule
448
+ num_heads = [dim // head_dim for dim in embed_dim]
449
+ self.blocks1 = nn.ModuleList([
450
+ CBlock(
451
+ dim=embed_dim[0], num_heads=num_heads[0], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
452
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
453
+ for i in range(depth[0])])
454
+ self.blocks2 = nn.ModuleList([
455
+ CBlock(
456
+ dim=embed_dim[1], num_heads=num_heads[1], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
457
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i+depth[0]], norm_layer=norm_layer)
458
+ for i in range(depth[1])])
459
+ self.blocks3 = nn.ModuleList([
460
+ EvoSABlock(
461
+ dim=embed_dim[2], num_heads=num_heads[2], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
462
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i+depth[0]+depth[1]], norm_layer=norm_layer,
463
+ prune_ratio=prune_ratio[2][i], trade_off=trade_off[2][i],
464
+ downsample=True if i == depth[2] - 1 else False)
465
+ for i in range(depth[2])])
466
+ self.blocks4 = nn.ModuleList([
467
+ EvoSABlock(
468
+ dim=embed_dim[3], num_heads=num_heads[3], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
469
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i+depth[0]+depth[1]+depth[2]], norm_layer=norm_layer,
470
+ prune_ratio=prune_ratio[3][i], trade_off=trade_off[3][i])
471
+ for i in range(depth[3])])
472
+ self.norm = bn_3d(embed_dim[-1])
473
+ self.norm_cls = nn.LayerNorm(embed_dim[-1])
474
+
475
+ # Representation layer
476
+ if representation_size:
477
+ self.num_features = representation_size
478
+ self.pre_logits = nn.Sequential(OrderedDict([
479
+ ('fc', nn.Linear(embed_dim, representation_size)),
480
+ ('act', nn.Tanh())
481
+ ]))
482
+ else:
483
+ self.pre_logits = nn.Identity()
484
+
485
+ # Classifier head
486
+ self.head = nn.Linear(embed_dim[-1], num_classes) if num_classes > 0 else nn.Identity()
487
+ self.head_cls = nn.Linear(embed_dim[-1], num_classes) if num_classes > 0 else nn.Identity()
488
+
489
+ self.apply(self._init_weights)
490
+
491
+ self.global_attn = None
492
+ self.token_indices = None
493
+
494
+ for name, p in self.named_parameters():
495
+ # fill proj weight with 1 here to improve training dynamics. Otherwise temporal attention inputs
496
+ # are multiplied by 0*0, which is hard for the model to move out of.
497
+ if 't_attn.qkv.weight' in name:
498
+ nn.init.constant_(p, 0)
499
+ if 't_attn.qkv.bias' in name:
500
+ nn.init.constant_(p, 0)
501
+ if 't_attn.proj.weight' in name:
502
+ nn.init.constant_(p, 1)
503
+ if 't_attn.proj.bias' in name:
504
+ nn.init.constant_(p, 0)
505
+
506
+ def _init_weights(self, m):
507
+ if isinstance(m, nn.Linear):
508
+ trunc_normal_(m.weight, std=.02)
509
+ if isinstance(m, nn.Linear) and m.bias is not None:
510
+ nn.init.constant_(m.bias, 0)
511
+ elif isinstance(m, nn.LayerNorm):
512
+ nn.init.constant_(m.bias, 0)
513
+ nn.init.constant_(m.weight, 1.0)
514
+
515
+ @torch.jit.ignore
516
+ def no_weight_decay(self):
517
+ return {'pos_embed', 'cls_token'}
518
+
519
+ def get_classifier(self):
520
+ return self.head
521
+
522
+ def reset_classifier(self, num_classes, global_pool=''):
523
+ self.num_classes = num_classes
524
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
525
+
526
+ def inflate_weight(self, weight_2d, time_dim, center=False):
527
+ if center:
528
+ weight_3d = torch.zeros(*weight_2d.shape)
529
+ weight_3d = weight_3d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
530
+ middle_idx = time_dim // 2
531
+ weight_3d[:, :, middle_idx, :, :] = weight_2d
532
+ else:
533
+ weight_3d = weight_2d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
534
+ weight_3d = weight_3d / time_dim
535
+ return weight_3d
536
+
537
+ def get_pretrained_model(self, cfg):
538
+ if cfg.UNIFORMER.PRETRAIN_NAME:
539
+ checkpoint = torch.load(model_path[cfg.UNIFORMER.PRETRAIN_NAME], map_location='cpu')
540
+
541
+ state_dict_3d = self.state_dict()
542
+ for k in checkpoint.keys():
543
+ if checkpoint[k].shape != state_dict_3d[k].shape:
544
+ if len(state_dict_3d[k].shape) <= 2:
545
+ logger.info(f'Ignore: {k}')
546
+ continue
547
+ logger.info(f'Inflate: {k}, {checkpoint[k].shape} => {state_dict_3d[k].shape}')
548
+ time_dim = state_dict_3d[k].shape[2]
549
+ checkpoint[k] = self.inflate_weight(checkpoint[k], time_dim)
550
+
551
+ if self.num_classes != checkpoint['head.weight'].shape[0]:
552
+ del checkpoint['head.weight']
553
+ del checkpoint['head.bias']
554
+ del checkpoint['head_cls.weight']
555
+ del checkpoint['head_cls.bias']
556
+ return checkpoint
557
+ else:
558
+ return None
559
+
560
+ def forward_features(self, x):
561
+ x = self.patch_embed1(x)
562
+ x = self.pos_drop(x)
563
+ for blk in self.blocks1:
564
+ x = blk(x)
565
+ x = self.patch_embed2(x)
566
+ for blk in self.blocks2:
567
+ x = blk(x)
568
+ x = self.patch_embed3(x)
569
+ # add cls_token in stage3
570
+ cls_token = self.cls_token.expand(x.shape[0], -1, -1)
571
+ # global global_attn, token_indices
572
+ self.global_attn = 0
573
+ self.token_indices = torch.arange(x.shape[2] * x.shape[3] * x.shape[4], dtype=torch.long, device=x.device).unsqueeze(0)
574
+ self.token_indices = self.token_indices.expand(x.shape[0], -1)
575
+ for blk in self.blocks3:
576
+ cls_token, x, self.global_attn, self.token_indices = blk(cls_token, x, self.global_attn, self.token_indices)
577
+ # upsample cls_token before stage4
578
+ cls_token = self.cls_upsample(cls_token)
579
+ x = self.patch_embed4(x)
580
+ # whether reset global attention? Now simple avgpool
581
+ self.token_indices = torch.arange(x.shape[2] * x.shape[3] * x.shape[4], dtype=torch.long, device=x.device).unsqueeze(0)
582
+ self.token_indices = self.token_indices.expand(x.shape[0], -1)
583
+ for blk in self.blocks4:
584
+ cls_token, x, self.global_attn, self.token_indices = blk(cls_token, x, self.global_attn, self.token_indices)
585
+ if self.training:
586
+ # layer normalization for cls_token
587
+ cls_token = self.norm_cls(cls_token)
588
+ x = self.norm(x)
589
+ x = self.pre_logits(x)
590
+ return cls_token, x
591
+
592
+ def forward(self, x):
593
+ # x = x[0]
594
+ cls_token, x = self.forward_features(x)
595
+ x = x.flatten(2).mean(-1)
596
+ # if self.training:
597
+ # x = self.head(x), self.head_cls(cls_token.squeeze(1))
598
+ # else:
599
+ # x = self.head(x)
600
+ x = self.head(x), self.head_cls(cls_token.squeeze(1))
601
+ return x
602
+
603
+ def uniformer_xs():
604
+ return Uniformer_light(
605
+ depth=[3, 5, 9, 3], embed_dim=[64, 128, 256, 512],
606
+ head_dim=32, drop_rate=0.1
607
+ )
608
+
609
+ def uniformer_xxs():
610
+ return Uniformer_light(
611
+ depth=[2, 5, 8, 2], embed_dim=[56, 112, 224, 448],
612
+ head_dim=28, drop_rate=0.05
613
+ )
614
+
615
+ class UniformerXXSFinetune(torch.nn.Module):
616
+
617
+ def __init__(self, out_class=20):
618
+ super(UniformerXXSFinetune, self).__init__()
619
+ self.pretrained = uniformer_xxs()
620
+ self.fc = torch.nn.Linear(400,out_class)
621
+
622
+ def forward(self, x):
623
+ x = self.pretrained(x)[0]
624
+ x = self.fc(x)
625
+ return F.softmax(x,dim=-1)