|
a |
|
b/algorithms/arch/convnext.py |
|
|
1 |
|
|
|
2 |
|
|
|
3 |
import os, sys, time |
|
|
4 |
|
|
|
5 |
import torch |
|
|
6 |
import torch.nn as nn |
|
|
7 |
import torch.nn.functional as F |
|
|
8 |
from timm.models.layers import trunc_normal_, DropPath |
|
|
9 |
from timm.models.registry import register_model |
|
|
10 |
|
|
|
11 |
sys.path.append(os.getcwd()) |
|
|
12 |
import utilities.runUtils as rutl |
|
|
13 |
|
|
|
14 |
##------------------------------------------------------------------------------ |
|
|
15 |
# ConvNext Taken From: https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py |
|
|
16 |
|
|
|
17 |
class Block(nn.Module): |
|
|
18 |
r""" ConvNeXt Block. There are two equivalent implementations: |
|
|
19 |
(1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) |
|
|
20 |
(2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back |
|
|
21 |
We use (2) as we find it slightly faster in PyTorch |
|
|
22 |
|
|
|
23 |
Args: |
|
|
24 |
dim (int): Number of input channels. |
|
|
25 |
drop_path (float): Stochastic depth rate. Default: 0.0 |
|
|
26 |
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. |
|
|
27 |
""" |
|
|
28 |
def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6): |
|
|
29 |
super().__init__() |
|
|
30 |
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv |
|
|
31 |
self.norm = LayerNorm(dim, eps=1e-6) |
|
|
32 |
self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers |
|
|
33 |
self.act = nn.GELU() |
|
|
34 |
self.pwconv2 = nn.Linear(4 * dim, dim) |
|
|
35 |
self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)), |
|
|
36 |
requires_grad=True) if layer_scale_init_value > 0 else None |
|
|
37 |
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() |
|
|
38 |
|
|
|
39 |
def forward(self, x): |
|
|
40 |
input = x |
|
|
41 |
x = self.dwconv(x) |
|
|
42 |
x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) |
|
|
43 |
x = self.norm(x) |
|
|
44 |
x = self.pwconv1(x) |
|
|
45 |
x = self.act(x) |
|
|
46 |
x = self.pwconv2(x) |
|
|
47 |
if self.gamma is not None: |
|
|
48 |
x = self.gamma * x |
|
|
49 |
x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) |
|
|
50 |
|
|
|
51 |
x = input + self.drop_path(x) |
|
|
52 |
return x |
|
|
53 |
|
|
|
54 |
class ConvNeXt(nn.Module): |
|
|
55 |
r""" ConvNeXt |
|
|
56 |
A PyTorch impl of : `A ConvNet for the 2020s` - |
|
|
57 |
https://arxiv.org/pdf/2201.03545.pdf |
|
|
58 |
Args: |
|
|
59 |
in_chans (int): Number of input image channels. Default: 3 |
|
|
60 |
num_classes (int): Number of classes for classification head. Default: 1000 |
|
|
61 |
depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3] |
|
|
62 |
dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768] |
|
|
63 |
drop_path_rate (float): Stochastic depth rate. Default: 0. |
|
|
64 |
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. |
|
|
65 |
head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1. |
|
|
66 |
""" |
|
|
67 |
def __init__(self, in_chans=3, num_classes=1000, |
|
|
68 |
depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], drop_path_rate=0., |
|
|
69 |
layer_scale_init_value=1e-6, head_init_scale=1., |
|
|
70 |
): |
|
|
71 |
super().__init__() |
|
|
72 |
|
|
|
73 |
self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers |
|
|
74 |
stem = nn.Sequential( |
|
|
75 |
nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4), |
|
|
76 |
LayerNorm(dims[0], eps=1e-6, data_format="channels_first") |
|
|
77 |
) |
|
|
78 |
self.downsample_layers.append(stem) |
|
|
79 |
for i in range(3): |
|
|
80 |
downsample_layer = nn.Sequential( |
|
|
81 |
LayerNorm(dims[i], eps=1e-6, data_format="channels_first"), |
|
|
82 |
nn.Conv2d(dims[i], dims[i+1], kernel_size=2, stride=2), |
|
|
83 |
) |
|
|
84 |
self.downsample_layers.append(downsample_layer) |
|
|
85 |
|
|
|
86 |
self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks |
|
|
87 |
dp_rates=[x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] |
|
|
88 |
cur = 0 |
|
|
89 |
for i in range(4): |
|
|
90 |
stage = nn.Sequential( |
|
|
91 |
*[Block(dim=dims[i], drop_path=dp_rates[cur + j], |
|
|
92 |
layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])] |
|
|
93 |
) |
|
|
94 |
self.stages.append(stage) |
|
|
95 |
cur += depths[i] |
|
|
96 |
|
|
|
97 |
self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer |
|
|
98 |
self.head = nn.Linear(dims[-1], num_classes) |
|
|
99 |
|
|
|
100 |
self.apply(self._init_weights) |
|
|
101 |
self.head.weight.data.mul_(head_init_scale) |
|
|
102 |
self.head.bias.data.mul_(head_init_scale) |
|
|
103 |
|
|
|
104 |
def _init_weights(self, m): |
|
|
105 |
if isinstance(m, (nn.Conv2d, nn.Linear)): |
|
|
106 |
trunc_normal_(m.weight, std=.02) |
|
|
107 |
nn.init.constant_(m.bias, 0) |
|
|
108 |
|
|
|
109 |
def forward_features(self, x): |
|
|
110 |
for i in range(4): |
|
|
111 |
x = self.downsample_layers[i](x) |
|
|
112 |
x = self.stages[i](x) |
|
|
113 |
return self.norm(x.mean([-2, -1])) # global average pooling, (N, C, H, W) -> (N, C) |
|
|
114 |
|
|
|
115 |
def forward(self, x): |
|
|
116 |
x = self.forward_features(x) |
|
|
117 |
x = self.head(x) |
|
|
118 |
return x |
|
|
119 |
|
|
|
120 |
class LayerNorm(nn.Module): |
|
|
121 |
r""" LayerNorm that supports two data formats: channels_last (default) or channels_first. |
|
|
122 |
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with |
|
|
123 |
shape (batch_size, height, width, channels) while channels_first corresponds to inputs |
|
|
124 |
with shape (batch_size, channels, height, width). |
|
|
125 |
""" |
|
|
126 |
def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"): |
|
|
127 |
super().__init__() |
|
|
128 |
self.weight = nn.Parameter(torch.ones(normalized_shape)) |
|
|
129 |
self.bias = nn.Parameter(torch.zeros(normalized_shape)) |
|
|
130 |
self.eps = eps |
|
|
131 |
self.data_format = data_format |
|
|
132 |
if self.data_format not in ["channels_last", "channels_first"]: |
|
|
133 |
raise NotImplementedError |
|
|
134 |
self.normalized_shape = (normalized_shape, ) |
|
|
135 |
|
|
|
136 |
def forward(self, x): |
|
|
137 |
if self.data_format == "channels_last": |
|
|
138 |
return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) |
|
|
139 |
elif self.data_format == "channels_first": |
|
|
140 |
u = x.mean(1, keepdim=True) |
|
|
141 |
s = (x - u).pow(2).mean(1, keepdim=True) |
|
|
142 |
x = (x - u) / torch.sqrt(s + self.eps) |
|
|
143 |
x = self.weight[:, None, None] * x + self.bias[:, None, None] |
|
|
144 |
return x |
|
|
145 |
|
|
|
146 |
|
|
|
147 |
model_urls = { |
|
|
148 |
"convnext_tiny_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth", |
|
|
149 |
"convnext_small_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth", |
|
|
150 |
"convnext_base_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth", |
|
|
151 |
"convnext_large_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth", |
|
|
152 |
"convnext_tiny_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_22k_224.pth", |
|
|
153 |
"convnext_small_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_small_22k_224.pth", |
|
|
154 |
"convnext_base_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth", |
|
|
155 |
"convnext_large_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth", |
|
|
156 |
"convnext_xlarge_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth", |
|
|
157 |
} |
|
|
158 |
|
|
|
159 |
@register_model |
|
|
160 |
def convnext_tiny(pretrained=False,in_22k=False, **kwargs): |
|
|
161 |
model = ConvNeXt(depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], **kwargs) |
|
|
162 |
if pretrained: |
|
|
163 |
url = model_urls['convnext_tiny_22k'] if in_22k else model_urls['convnext_tiny_1k'] |
|
|
164 |
checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu", check_hash=True) |
|
|
165 |
model.load_state_dict(checkpoint["model"]) |
|
|
166 |
return model |
|
|
167 |
|
|
|
168 |
@register_model |
|
|
169 |
def convnext_small(pretrained=False,in_22k=False, **kwargs): |
|
|
170 |
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[96, 192, 384, 768], **kwargs) |
|
|
171 |
if pretrained: |
|
|
172 |
url = model_urls['convnext_small_22k'] if in_22k else model_urls['convnext_small_1k'] |
|
|
173 |
checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu") |
|
|
174 |
model.load_state_dict(checkpoint["model"]) |
|
|
175 |
return model |
|
|
176 |
|
|
|
177 |
@register_model |
|
|
178 |
def convnext_base(pretrained=False, in_22k=False, **kwargs): |
|
|
179 |
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[128, 256, 512, 1024], **kwargs) |
|
|
180 |
if pretrained: |
|
|
181 |
url = model_urls['convnext_base_22k'] if in_22k else model_urls['convnext_base_1k'] |
|
|
182 |
checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu") |
|
|
183 |
model.load_state_dict(checkpoint["model"]) |
|
|
184 |
return model |
|
|
185 |
|
|
|
186 |
@register_model |
|
|
187 |
def convnext_large(pretrained=False, in_22k=False, **kwargs): |
|
|
188 |
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[192, 384, 768, 1536], **kwargs) |
|
|
189 |
if pretrained: |
|
|
190 |
url = model_urls['convnext_large_22k'] if in_22k else model_urls['convnext_large_1k'] |
|
|
191 |
checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu") |
|
|
192 |
model.load_state_dict(checkpoint["model"]) |
|
|
193 |
return model |
|
|
194 |
|
|
|
195 |
@register_model |
|
|
196 |
def convnext_xlarge(pretrained=False, in_22k=False, **kwargs): |
|
|
197 |
model = ConvNeXt(depths=[3, 3, 27, 3], dims=[256, 512, 1024, 2048], **kwargs) |
|
|
198 |
if pretrained: |
|
|
199 |
assert in_22k, "only ImageNet-22K pre-trained ConvNeXt-XL is available; please set in_22k=True" |
|
|
200 |
url = model_urls['convnext_xlarge_22k'] |
|
|
201 |
checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu") |
|
|
202 |
model.load_state_dict(checkpoint["model"]) |
|
|
203 |
return model |
|
|
204 |
|
|
|
205 |
|
|
|
206 |
##==================== Task Specific Class====================================== |
|
|
207 |
|
|
|
208 |
class ClassifierNet(nn.Module): |
|
|
209 |
def __init__(self, args): |
|
|
210 |
super().__init__() |
|
|
211 |
rutl.START_SEED() |
|
|
212 |
|
|
|
213 |
self.args = args |
|
|
214 |
|
|
|
215 |
# Feature Extractor |
|
|
216 |
self.backbone, self.feat_outsize = self._load_convnext_backbone() |
|
|
217 |
self.feat_dropout = nn.Dropout(p=self.args.featx_dropout) |
|
|
218 |
|
|
|
219 |
# Classifier |
|
|
220 |
sizes = [self.feat_outsize] + list(args.classifier) |
|
|
221 |
layers = [] |
|
|
222 |
for i in range(len(sizes) - 2): |
|
|
223 |
layers.append(nn.Linear(sizes[i], sizes[i + 1], bias=False)) |
|
|
224 |
layers.append(nn.LayerNorm(sizes[i + 1])) #watchout this is LayerNorm |
|
|
225 |
layers.append(nn.ReLU(inplace=True)) |
|
|
226 |
layers.append(nn.Dropout(p=self.args.clsfy_dropout)) |
|
|
227 |
layers.append(nn.Linear(sizes[-2], sizes[-1], bias=False)) |
|
|
228 |
|
|
|
229 |
self.classifier = nn.Sequential(*layers) |
|
|
230 |
|
|
|
231 |
|
|
|
232 |
def forward(self, x): |
|
|
233 |
x = self.backbone(x) |
|
|
234 |
x = self.feat_dropout(x) |
|
|
235 |
out = self.classifier(x) |
|
|
236 |
|
|
|
237 |
return out |
|
|
238 |
|
|
|
239 |
|
|
|
240 |
def _load_convnext_backbone(self): |
|
|
241 |
|
|
|
242 |
## pretrain setting |
|
|
243 |
pretrain = False; imgnet22k = False |
|
|
244 |
head_default = None |
|
|
245 |
if self.args.featx_pretrain in ["DEFAULT", "IMAGENET-1K"]: |
|
|
246 |
pretrain = True |
|
|
247 |
head_default = 1000 |
|
|
248 |
elif self.args.featx_pretrain == "IMAGENET-22K": |
|
|
249 |
pretrain = True; imgnet22k = True |
|
|
250 |
head_default = 21841 |
|
|
251 |
elif self.args.featx_pretrain not in [None, "NONE", "none"]: |
|
|
252 |
raise ValueError(f"Unknown pretrain weight type requested {self.args.featx_pretrain}" ) |
|
|
253 |
|
|
|
254 |
## Model loading |
|
|
255 |
if self.args.feature_extract == 'convnext-tiny': |
|
|
256 |
backbone = convnext_tiny(pretrained=pretrain, in_22k=imgnet22k, |
|
|
257 |
num_classes = head_default) |
|
|
258 |
outfeat_size = 768 |
|
|
259 |
elif self.args.feature_extract == 'convnext-small': |
|
|
260 |
backbone = convnext_small(pretrained=pretrain, in_22k=imgnet22k, |
|
|
261 |
num_classes = head_default) |
|
|
262 |
outfeat_size = 768 |
|
|
263 |
|
|
|
264 |
elif self.args.feature_extract == 'convnext-base': |
|
|
265 |
backbone = convnext_base(pretrained=pretrain, in_22k=imgnet22k, |
|
|
266 |
num_classes = head_default) |
|
|
267 |
outfeat_size = 1024 |
|
|
268 |
|
|
|
269 |
elif self.args.feature_extract == 'convnext-large': |
|
|
270 |
backbone = convnext_large(pretrained=pretrain, in_22k=imgnet22k, |
|
|
271 |
num_classes = head_default) |
|
|
272 |
outfeat_size = 1536 |
|
|
273 |
|
|
|
274 |
else: |
|
|
275 |
raise ValueError(f"Unknown Model Implementation called in {os.path.basename(__file__)}") |
|
|
276 |
|
|
|
277 |
backbone.head = nn.Identity() #remove fc of default arc |
|
|
278 |
|
|
|
279 |
# pretrain from external file |
|
|
280 |
if os.path.exists(self.args.featx_pretrain): |
|
|
281 |
backbone = self._load_weights_from_file(backbone, |
|
|
282 |
self.args.featx_pretrain ) |
|
|
283 |
print("Loaded:", self.args.featx_pretrain ) |
|
|
284 |
|
|
|
285 |
return backbone, outfeat_size |
|
|
286 |
|
|
|
287 |
|
|
|
288 |
|
|
|
289 |
|
|
|
290 |
|
|
|
291 |
if __name__ == "__main__": |
|
|
292 |
|
|
|
293 |
from torchsummary import summary |
|
|
294 |
|
|
|
295 |
model = convnext_large() |
|
|
296 |
summary(model, (3, 224, 224)) |