-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstylised_models.py
186 lines (147 loc) · 6.94 KB
/
stylised_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import math
import numpy as np
import torch
import torch.nn as nn
from functools import partial
from timm.models.vision_transformer import VisionTransformer, _cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_
import random
__all__ = [
'deit_tiny_distilled_patch16_224', 'deit_small_distilled_patch16_224',
]
class DistilledVisionTransformer(VisionTransformer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dist_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
num_patches = self.patch_embed.num_patches
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 2, self.embed_dim))
self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if self.num_classes > 0 else nn.Identity()
trunc_normal_(self.dist_token, std=.02)
trunc_normal_(self.pos_embed, std=.02)
self.head_dist.apply(self._init_weights)
def forward_features(self, x):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
B = x.shape[0]
x = self.patch_embed(x)
cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
dist_token = self.dist_token.expand(B, -1, -1)
x = torch.cat((cls_tokens, dist_token, x), dim=1)
x = x + self.pos_embed
x = self.pos_drop(x)
layer_wise_tokens = []
for blk in self.blocks:
x = blk(x)
layer_wise_tokens.append(x)
layer_wise_tokens = [self.norm(x) for x in layer_wise_tokens]
return [(x[:, 0], x[:, 1]) for x in layer_wise_tokens]
def forward(self, x, shape=False):
list_out = self.forward_features(x)
x = [self.head(x) for x, _ in list_out]
x_dist = [self.head_dist(x_dist) for _, x_dist in list_out]
if self.training:
return [(out, out_dist) for out, out_dist in zip(x, x_dist)]
else:
if shape:
return x_dist[-1]
else:
return x[-1]
# during inference, return the average of both classifier predictions
# return [(out + out_dist) / 2 for out, out_dist in zip(x, x_dist)]
class VanillaVisionTransformer(VisionTransformer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward_features(self, x, block_index=None, drop_rate=0):
# taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
# with slight modifications to add the dist_token
B, nc, w, h = x.shape
x = self.patch_embed(x)
# interpolate patch embeddings
dim = x.shape[-1]
w0 = w // self.patch_embed.patch_size[0]
h0 = h // self.patch_embed.patch_size[1]
class_pos_embed = self.pos_embed[:, 0]
N = self.pos_embed.shape[1] - 1
patch_pos_embed = self.pos_embed[:, 1:]
patch_pos_embed = nn.functional.interpolate(
patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),
mode='bicubic',
)
if w0 != patch_pos_embed.shape[-2]:
helper = torch.zeros(h0)[None, None, None, :].repeat(1, dim, w0 - patch_pos_embed.shape[-2], 1).to(x.device)
patch_pos_embed = torch.cat((patch_pos_embed, helper), dim=-2)
if h0 != patch_pos_embed.shape[-1]:
helper = torch.zeros(w0)[None, None, :, None].repeat(1, dim, 1, h0 - patch_pos_embed.shape[-1]).to(x.device)
patch_pos_embed = torch.cat((patch_pos_embed, helper), dim=-1)
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
pos_embed = torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
# interpolate patch embeddings finish
cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
x = torch.cat((cls_tokens, x), dim=1)
x = x + pos_embed
x = self.pos_drop(x)
layer_wise_tokens = []
for idx, blk in enumerate(self.blocks):
if block_index is not None and idx == block_index:
token = x[:, :1, :]
features = x[:, 1:, :]
row = np.random.choice(range(x.shape[1] - 1), size=int(drop_rate*x.shape[1]), replace=False)
features[:, row, :] = 0.0
x = torch.cat((token, features), dim=1)
x = blk(x)
layer_wise_tokens.append(x)
layer_wise_tokens = [self.norm(x) for x in layer_wise_tokens]
return [x[:, 0] for x in layer_wise_tokens], [x for x in layer_wise_tokens]
def forward(self, x, block_index=None, drop_rate=0, patches=False):
list_out, patch_out = self.forward_features(x, block_index, drop_rate)
x = [self.head(x) for x in list_out]
if patches:
return x, patch_out
else:
return x
class NonSpatialVisionTransformer(VisionTransformer):
def __init__(self, *args, **kwargs):
super(NonSpatialVisionTransformer, self).__init__(*args, **kwargs)
self.pos_embed = None
self.pos_drop = None
def forward_features(self, x):
B = x.shape[0]
x = self.patch_embed(x)
cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
x = torch.cat((cls_tokens, x), dim=1)
# x = x + self.pos_embed
# x = self.pos_drop(x)
for blk in self.blocks:
x = blk(x)
x = self.norm(x)
return x[:, 0]
@register_model
def deit_tiny_distilled_patch16_224(pretrained=False, **kwargs):
model = DistilledVisionTransformer(
patch_size=16, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4, qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="https://dl.fbaipublicfiles.com/deit/deit_tiny_distilled_patch16_224-b40b3cf7.pth",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model
@register_model
def deit_small_distilled_patch16_224(pretrained=False, **kwargs):
model = DistilledVisionTransformer(
patch_size=16, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
model.default_cfg = _cfg()
if pretrained:
checkpoint = torch.hub.load_state_dict_from_url(
url="https://dl.fbaipublicfiles.com/deit/deit_small_distilled_patch16_224-649709d9.pth",
map_location="cpu", check_hash=True
)
model.load_state_dict(checkpoint["model"])
return model