-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy patharchitectures.py
320 lines (281 loc) · 12.1 KB
/
architectures.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import torch
import torch.nn as nn
import torch.nn.functional as F
import timm
from modules import *
from kuma_utils.torch.modules import AdaptiveConcatPool2d, GeM, AdaptiveGeM
from kuma_utils.torch.utils import freeze_module
class MultiSpectrogram(nn.Module):
def __init__(self, configs: tuple):
super().__init__()
self.spectrograms = nn.ModuleList()
self.is_wavegram = []
for spec, spec_params in configs:
spectrogram = spec(**spec_params)
is_trainable = spectrogram.__class__.__name__ in \
['WaveNetSpectrogram', 'CNNSpectrogram']
self.is_wavegram.append(is_trainable)
if is_trainable:
freeze_module(spectrogram)
self.spectrograms.append(spectrogram)
def forward(self, s):
bs, ch, w = s.shape
specs = []
for spectrogram, is_trainable in zip(self.spectrograms, self.is_wavegram):
if is_trainable: # Use CNN as spectrogram
specs.append(spectrogram(s))
else:
with torch.cuda.amp.autocast(enabled=False): # MelSpectrogram causes NaN with AMP
spec = spectrogram(s.view(bs * ch, w)) # spec: (batch size * wave channel, freq, time)
_, f, t = spec.shape
spec = spec.view(bs, ch, f, t)
specs.append(spec)
return torch.cat(specs, dim=1)
class SpectroCNN(nn.Module):
def __init__(self,
model_name='efficientnet_b7',
pretrained=False,
num_classes=1,
timm_params={},
custom_preprocess='none',
custom_classifier='none',
custom_attention='none',
spectrogram=None,
spec_params={},
augmentations=None,
augmentations_test=None,
resize_img=None,
upsample='nearest',
mixup='mixup',
norm_spec=False,
return_spec=False):
super().__init__()
if isinstance(spectrogram, nn.Module): # deprecated
self.spectrogram = spectrogram
else:
self.spectrogram = spectrogram(**spec_params)
self.is_cnnspec = self.spectrogram.__class__.__name__ in [
'WaveNetSpectrogram', 'CNNSpectrogram', 'MultiSpectrogram', 'ResNetSpectrogram']
self.cnn = timm.create_model(model_name,
pretrained=pretrained,
num_classes=num_classes,
**timm_params)
self.mixup_mode = 'input'
if custom_classifier != 'none' or custom_attention != 'none':
model_type = self.cnn.__class__.__name__
try:
feature_dim = self.cnn.get_classifier().in_features
self.cnn.reset_classifier(0, '')
except:
raise ValueError(f'Unsupported model type: {model_type}')
if custom_preprocess == 'positional-add':
preprocess = PositionalEncoding(feature_dim=resize_img, mode='add')
elif custom_preprocess == 'positional-cat':
preprocess = PositionalEncoding(feature_dim=resize_img, mode='concat')
else:
preprocess = nn.Identity()
if custom_attention == 'triplet':
attention = TripletAttention()
elif custom_attention == 'mixup':
attention = ManifoldMixup()
self.mixup_mode = 'manifold'
else:
attention = nn.Identity()
if custom_classifier == 'avg':
global_pool = nn.AdaptiveAvgPool2d((1, 1))
elif custom_classifier == 'max':
global_pool = nn.AdaptiveMaxPool2d((1, 1))
elif custom_classifier == 'concat':
global_pool = AdaptiveConcatPool2d()
feature_dim = feature_dim * 2
elif custom_classifier == 'gem':
global_pool = GeM(p=3, eps=1e-4)
elif custom_classifier == 'positional':
global_pool = nn.Sequential(
AdaptiveGeM((1, None), p=3),
PositionalEncoding(),
nn.AdaptiveAvgPool2d((1, 1)))
elif custom_classifier == 'mixup':
global_pool = nn.Sequential(
GeM(p=3, eps=1e-4),
ManifoldMixup())
self.mixup_mode = 'manifold'
else:
raise ValueError(f'Unsupported classifier type: {custom_classifier}')
if model_type[-11:] == 'Transformer' or model_type == 'XCiT': # transformer models
global_pool = nn.Identity()
self.cnn = nn.Sequential(
preprocess,
self.cnn,
attention,
global_pool,
Flatten(),
nn.Linear(feature_dim, 512),
nn.ReLU(inplace=True),
nn.Linear(512, num_classes)
)
self.norm_spec = norm_spec
if self.norm_spec:
self.norm = nn.BatchNorm2d(3)
self.resize_img = resize_img
if isinstance(self.resize_img, int):
self.resize_img = (self.resize_img, self.resize_img)
self.return_spec = return_spec
self.augmentations = augmentations
self.augmentations_test = augmentations_test
self.upsample = upsample
self.mixup = mixup
assert self.mixup in ['mixup', 'cutmix']
def feature_mode(self):
self.cnn[-1] = nn.Identity()
self.cnn[-2] = nn.Identity()
def forward(self, s, lam=None, idx=None): # s: (batch size, wave channel, length of wave)
bs, ch, w = s.shape
if self.is_cnnspec: # Use CNN as spectrogram
spec = self.spectrogram(s)
else:
s = s.view(bs * ch, w)
with torch.cuda.amp.autocast(enabled=False): # MelSpectrogram causes NaN with AMP
spec = self.spectrogram(s) # spec: (batch size * wave channel, freq, time)
_, f, t = spec.shape
spec = spec.view(bs, ch, f, t)
if lam is not None: # in-batch mixup
if self.mixup == 'mixup' and self.mixup_mode == 'input':
spec, lam = mixup(spec, lam, idx)
elif self.mixup == 'cutmix':
spec, lam = cutmix(spec, lam, idx)
if self.training and self.augmentations is not None:
spec = self.augmentations(spec)
if not self.training and self.augmentations_test is not None:
spec = self.augmentations_test(spec)
if self.resize_img is not None:
spec = F.interpolate(spec, size=self.resize_img, mode=self.upsample)
if self.norm_spec:
spec = self.norm(spec)
if self.mixup_mode == 'manifold':
self.cnn[3][1].update(lam, idx)
if self.return_spec and lam is not None:
return self.cnn(spec), spec, lam
elif self.return_spec:
return self.cnn(spec), spec
elif lam is not None:
return self.cnn(spec), lam
else:
return self.cnn(spec)
class MultiInstanceSCNN(nn.Module):
def __init__(self,
model_name='efficientnet_b7',
pretrained=False,
num_classes=1,
timm_params={},
custom_preprocess='none',
custom_classifier='none',
custom_attention='none',
spectrogram=None,
spec_params={},
augmentations=None,
augmentations_test=None,
resize_img=None,
upsample='nearest',
n_patch=2,
return_spec=False):
super().__init__()
if isinstance(spectrogram, nn.Module): # deprecated
self.spectrogram = spectrogram
else:
self.spectrogram = spectrogram(**spec_params)
self.cnn = timm.create_model(model_name,
pretrained=pretrained,
num_classes=num_classes,
**timm_params)
model_type = self.cnn.__class__.__name__
try:
feature_dim = self.cnn.get_classifier().in_features
self.cnn.reset_classifier(0, '')
except:
raise ValueError(f'Unsupported model type: {model_type}')
if custom_preprocess == 'positional-add':
preprocess = PositionalEncoding(feature_dim=resize_img, mode='add')
elif custom_preprocess == 'positional-cat':
preprocess = PositionalEncoding(feature_dim=resize_img, mode='concat')
else:
preprocess = nn.Identity()
if custom_attention == 'triplet':
attention = TripletAttention()
else:
attention = nn.Identity()
if custom_classifier in ['avg', 'none']:
global_pool = nn.AdaptiveAvgPool2d((1, 1))
elif custom_classifier == 'max':
global_pool = nn.AdaptiveMaxPool2d((1, 1))
elif custom_classifier == 'concat':
global_pool = AdaptiveConcatPool2d()
feature_dim = feature_dim * 2
elif custom_classifier == 'gem':
global_pool = GeM(p=3, eps=1e-4)
elif custom_classifier == 'positional':
global_pool = nn.Sequential(
AdaptiveGeM((1, None), p=3),
PositionalEncoding(),
nn.AdaptiveAvgPool2d((1, 1))
)
else:
raise ValueError(f'Unsupported classifier type: {custom_classifier}')
if model_type[-11:] == 'Transformer' or model_type == 'XCiT': # transformer models
global_pool = nn.Identity()
self.cnn = nn.Sequential(
preprocess,
self.cnn,
attention,
global_pool,
Flatten())
self.head = nn.Sequential(
nn.Linear(feature_dim*n_patch, 512),
nn.ReLU(inplace=True),
nn.Linear(512, num_classes)
)
self.resize_img = resize_img
if isinstance(self.resize_img, int):
self.resize_img = (self.resize_img, self.resize_img)
self.return_spec = return_spec
self.augmentations = augmentations
self.augmentations_test = augmentations_test
self.upsample = upsample
self.n_patch = n_patch
@staticmethod
def _make_patches(image: torch.Tensor, n_patch: int): # image: (bs, ch, w, h)
_, _ , h, w = image.shape
stride = (w - h) // (n_patch - 1)
output = []
for i in range(n_patch):
output.append(image[:, :, :, stride*i:stride*i+h])
return torch.stack(output, dim=1)
def feature_mode(self):
self.head[1] = nn.Identity()
self.head[2] = nn.Identity()
def forward(self, s):
bs, ch, w = s.shape
s = s.view(bs * ch, w)
with torch.cuda.amp.autocast(enabled=False): # MelSpectrogram causes NaN with AMP
spec = self.spectrogram(s) # spec: (batch size * wave channel, freq, time)
_, f, t = spec.shape
spec = spec.view(bs, ch, f, t)
if self.training and self.augmentations is not None:
spec = self.augmentations(spec)
if not self.training and self.augmentations_test is not None:
spec = self.augmentations_test(spec)
if self.resize_img is not None:
spec = F.interpolate(spec, size=self.resize_img, mode=self.upsample)
if self.n_patch > 1:
spec = self._make_patches(spec, self.n_patch) # spec: (bs, patch, ch, freq, time)
else:
spec = spec.unsqueeze(1)
_, _, ch, f, t = spec.shape
spec = spec.view(bs * self.n_patch, ch, f, t) # spec: (bs*patch, ch, freq, time)
features = self.cnn(spec) # features: (bs*patch, feature)
features = features.reshape(bs, -1)
output = self.head(features)
if self.return_spec:
return output, spec
else:
return output