res_net.py 18.1 KB
Newer Older
Anthony Larcher's avatar
Anthony Larcher committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# -*- coding: utf-8 -*-
#
# This file is part of SIDEKIT.
#
# SIDEKIT is a python package for speaker verification.
# Home page: http://www-lium.univ-lemans.fr/sidekit/
#
# SIDEKIT is a python package for speaker verification.
# Home page: http://www-lium.univ-lemans.fr/sidekit/
#
# SIDEKIT is free software: you can redistribute it and/or modify
# it under the terms of the GNU LLesser General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# SIDEKIT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with SIDEKIT.  If not, see <http://www.gnu.org/licenses/>.

"""
Anthony Larcher's avatar
v1.3.7    
Anthony Larcher committed
25
Copyright 2014-2021 Anthony Larcher
Anthony Larcher's avatar
Anthony Larcher committed
26
27
28
29
30
31
32
33
"""

import h5py
import logging
import sys
import numpy
import pickle
import torch
Anthony Larcher's avatar
Anthony Larcher committed
34
import torchaudio
Anthony Larcher's avatar
Anthony Larcher committed
35
36
37
38
39
40
41
42
import torch.optim as optim
import torch.multiprocessing as mp
from torchvision import transforms
from collections import OrderedDict
from ..bosaris import IdMap
from ..statserver import StatServer
from torch.utils.data import DataLoader

Anthony Larcher's avatar
Anthony Larcher committed
43

Anthony Larcher's avatar
v1.3.7    
Anthony Larcher committed
44
45
46
47
48
49
50
51
52
__author__ = "Anthony Larcher and Sylvain Meignier"
__copyright__ = "Copyright 2014-2021 Anthony Larcher and Sylvain Meignier"
__license__ = "LGPL"
__maintainer__ = "Anthony Larcher"
__email__ = "anthony.larcher@univ-lemans.fr"
__status__ = "Production"
__docformat__ = 'reStructuredText'


Anthony Larcher's avatar
Anthony Larcher committed
53
class FeatureMapScaling(torch.nn.Module):
Anthony Larcher's avatar
Anthony Larcher committed
54
55
56
57
58
59
60
61
62
63
    """

    """
    def __init__(self, nb_dim, do_add = True, do_mul = True):
        """

        :param nb_dim:
        :param do_add:
        :param do_mul:
        """
Anthony Larcher's avatar
Anthony Larcher committed
64
        super(FeatureMapScaling, self).__init__()
Anthony Larcher's avatar
Anthony Larcher committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        self.fc = torch.nn.Linear(nb_dim, nb_dim)
        self.sig = torch.nn.Sigmoid()
        self.do_add = do_add
        self.do_mul = do_mul

    def forward(self, x):
        """

        :param x:
        :return:
        """
        y = torch.nn.functional.adaptive_avg_pool1d(x, 1).view(x.size(0), -1)
        y = self.sig(self.fc(y)).view(x.size(0), x.size(1), -1)

        if self.do_mul:
            x = x * y

        if self.do_add:
            x = x + y

        return x


Anthony Larcher's avatar
Anthony Larcher committed
88
class ResBlockWFMS(torch.nn.Module):
Anthony Larcher's avatar
Anthony Larcher committed
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
    """

    """
    def __init__(self, nb_filts, first=False):
        """

        :param nb_filts:
        :param first:
        """
        super(ResBlockWFMS, self).__init__()
        self.first = first

        if not self.first:
            self.bn1 = torch.nn.BatchNorm1d(num_features=nb_filts[0])

        self.lrelu = torch.nn.LeakyReLU()
        self.lrelu_keras = torch.nn.LeakyReLU(negative_slope=0.3)

        self.conv1 = torch.nn.Conv1d(in_channels=nb_filts[0],
                                     out_channels=nb_filts[1],
                                     kernel_size=3,
                                     padding=1,
                                     stride=1)

        self.bn2 = torch.nn.BatchNorm1d(num_features=nb_filts[1])

        self.conv2 = torch.nn.Conv1d(in_channels=nb_filts[1],
                                     out_channels=nb_filts[1],
                                     padding=1,
                                     kernel_size=3,
                                     stride=1)

        if nb_filts[0] != nb_filts[1]:
            self.downsample = True
            self.conv_downsample = torch.nn.Conv1d(in_channels=nb_filts[0],
                                                   out_channels=nb_filts[1],
                                                   padding=0,
                                                   kernel_size=1,
                                                   stride=1)
        else:
            self.downsample = False

        self.mp = torch.nn.MaxPool1d(3)

        self.fms = FeatureMapScaling(nb_dim=nb_filts[1],
                                     do_add=True,
                                     do_mul=True
                                     )

    def forward(self, x):
        """

        :param x:
        :return:
        """
        identity = x

        if not self.first:
            out = self.bn1(x)
            out = self.lrelu_keras(out)
        else:
            out = x

        #out = self.conv1(x)
        out = self.conv1(out)   # modif Anthony
        out = self.bn2(out)
        out = self.lrelu_keras(out)
        out = self.conv2(out)

        if self.downsample:
            identity = self.conv_downsample(identity)

        out += identity
        out = self.mp(out)
        out = self.fms(out)

        return out


Anthony Larcher's avatar
Anthony Larcher committed
168
class LayerNorm(torch.nn.Module):
Anthony Larcher's avatar
Anthony Larcher committed
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
    """

    """
    def __init__(self, features, eps=1e-6):
        """

        :param features:
        :param eps:
        """
        super(LayerNorm,self).__init__()
        self.gamma = torch.nn.Parameter(torch.ones(features))
        self.beta = torch.nn.Parameter(torch.zeros(features))
        self.eps = eps

    def forward(self, x):
        """

        :param x:
        :return:
        """
        mean = x.mean(-1, keepdim=True)
        std = x.std(-1, keepdim=True)
        return self.gamma * (x - mean) / (std + self.eps) + self.beta



Anthony Larcher's avatar
Anthony Larcher committed
195
196
197
198
class ResBlock(torch.nn.Module):
    """

    """
Anthony Larcher's avatar
Anthony Larcher committed
199
    def __init__(self, in_channels, out_channels, stride, is_first=False):
Anthony Larcher's avatar
Anthony Larcher committed
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
        """

        :param filter_size:
        :param channel_nb:
        :param is_first: boolean, True if this block ios the first of the model, if not, apply a BatchNorm layer first
        """
        super(ResBlock, self).__init__()
        self.is_first = is_first
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.expansion = self.out_channels // self.in_channels

        self.resample = None
        if not self.in_channels == self.out_channels:
            self.resample = torch.nn.Sequential(
                torch.nn.Conv2d(in_channels=self.in_channels,
                                out_channels=self.out_channels,
                                kernel_size=1),
                torch.nn.BatchNorm2d(self.in_channels * self.expansion),
            )

        if not self.is_first:
            self.batch_norm1 = torch.nn.BatchNorm2d(num_features=self.in_channels)

        self.activation = torch.nn.LeakyReLU()

        self.conv1 = torch.nn.Conv2d(in_channels=self.in_channels,
                                     out_channels=self.out_channels,
                                     kernel_size=(3,3),
Anthony Larcher's avatar
Anthony Larcher committed
229
                                     stride=stride,
Anthony Larcher's avatar
Anthony Larcher committed
230
231
232
233
234
                                     padding=1,
                                     padding_mode='zeros',
                                     dilation=1)
        self.conv2= torch.nn.Conv2d(in_channels=self.out_channels,
                                    out_channels=self.out_channels,
Anthony Larcher's avatar
Anthony Larcher committed
235
                                    stride=stride,
Anthony Larcher's avatar
Anthony Larcher committed
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
                                    kernel_size=(3,3),
                                    padding=1,
                                    padding_mode='zeros',
                                    dilation=1)

        self.batch_norm2 = torch.nn.BatchNorm2d(num_features=self.out_channels)

    def forward(self, x):
        """

        :param x:
        :return:
        """
        identity = x

        if not self.is_first:
            out = self.activation(self.batch_norm1(x))
        else:
            out = x

        out = self.conv1(out)
        out = self.batch_norm2(out)
        out = self.activation(out)

        out = self.conv2(out)
        out = self.batch_norm2(out)

        if not self.expansion == 1:
            identity = self.resample(identity)
        out += identity

        out =  self.activation(out)
        return out


Anthony Larcher's avatar
Anthony Larcher committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class SELayer(torch.nn.Module):
    def __init__(self, channel, reduction=16):
        super(SELayer, self).__init__()
        self.avg_pool = torch.nn.AdaptiveAvgPool2d(1)
        self.fc = torch.nn.Sequential(
            torch.nn.Linear(channel, channel // reduction, bias=False),
            torch.nn.ReLU(inplace=True),
            torch.nn.Linear(channel // reduction, channel, bias=False),
            torch.nn.Sigmoid()
        )

    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x).view(b, c)
        y = self.fc(y).view(b, c, 1, 1)
        return x * y.expand_as(x)


Anthony Larcher's avatar
Anthony Larcher committed
289
class BasicBlock(torch.nn.Module):
Anthony Larcher's avatar
Anthony Larcher committed
290
291
292
    """

    """
Anthony Larcher's avatar
Anthony Larcher committed
293
294
295
296
297
298
299
300
301
302
303
    expansion = 1

    def __init__(self, in_planes, planes, stride=1):
        super(BasicBlock, self).__init__()
        self.conv1 = torch.nn.Conv2d(
            in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = torch.nn.BatchNorm2d(planes)
        self.conv2 = torch.nn.Conv2d(planes, planes, kernel_size=3,
                               stride=1, padding=1, bias=False)
        self.bn2 = torch.nn.BatchNorm2d(planes)

Anthony Larcher's avatar
Anthony Larcher committed
304
305
        self.se = SELayer(planes)

Anthony Larcher's avatar
Anthony Larcher committed
306
307
308
309
310
311
312
313
314
        self.shortcut = torch.nn.Sequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = torch.nn.Sequential(
                torch.nn.Conv2d(in_planes, self.expansion*planes,
                          kernel_size=1, stride=stride, bias=False),
                torch.nn.BatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
315
        out = torch.nn.functional.relu(self.bn1(self.conv1(x)))
Anthony Larcher's avatar
Anthony Larcher committed
316
        out = self.bn2(self.conv2(out))
Anthony Larcher's avatar
Anthony Larcher committed
317
        out = self.se(out)
Anthony Larcher's avatar
Anthony Larcher committed
318
        out += self.shortcut(x)
319
        out = torch.nn.functional.relu(out)
Anthony Larcher's avatar
Anthony Larcher committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
        return out


class Bottleneck(torch.nn.Module):
    expansion = 4

    def __init__(self, in_planes, planes, stride=1):
        super(Bottleneck, self).__init__()
        self.conv1 = torch.nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
        self.bn1 = torch.nn.BatchNorm2d(planes)
        self.conv2 = torch.nn.Conv2d(planes, planes, kernel_size=3,
                               stride=stride, padding=1, bias=False)
        self.bn2 = torch.nn.BatchNorm2d(planes)
        self.conv3 = torch.nn.Conv2d(planes, self.expansion *
                               planes, kernel_size=1, bias=False)
        self.bn3 = torch.nn.BatchNorm2d(self.expansion*planes)

        self.shortcut = torch.nn.Sequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = torch.nn.Sequential(
                torch.nn.Conv2d(in_planes, self.expansion*planes,
                          kernel_size=1, stride=stride, bias=False),
                torch.nn.BatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
        out = torch.nn.functional.relu(self.bn1(self.conv1(x)))
        out = torch.nn.functional.relu(self.bn2(self.conv2(out)))
        out = self.bn3(self.conv3(out))
        out += self.shortcut(x)
        out = torch.nn.functional.relu(out)
        return out


class ResNet(torch.nn.Module):
    def __init__(self, block, num_blocks, speaker_number=10):
        super(ResNet, self).__init__()
        self.in_planes = 128
        self.speaker_number = speaker_number

Anthony Larcher's avatar
Anthony Larcher committed
360
361
362
363
364
365
366
        # Feature extraction
        n_fft = 2048
        win_length = None
        hop_length = 512
        n_mels = 80
        n_mfcc = 80

Anthony Larcher's avatar
debug    
Anthony Larcher committed
367
        self.MFCC = torchaudio.transforms.MFCC(
Anthony Larcher's avatar
Anthony Larcher committed
368
369
370
            sample_rate=16000,
            n_mfcc=n_mfcc, melkwargs={'n_fft': n_fft, 'n_mels': n_mels, 'hop_length': hop_length})

Anthony Larcher's avatar
debug    
Anthony Larcher committed
371
372
        self.CMVN = torch.nn.InstanceNorm1d(80)

Anthony Larcher's avatar
Anthony Larcher committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
        self.conv1 = torch.nn.Conv2d(1, 128, kernel_size=3,
                               stride=1, padding=1, bias=False)
        self.bn1 = torch.nn.BatchNorm2d(128)

        #  With block = [3, 1, 3, 1, 5, 1, 2]
        self.layer1 = self._make_layer(block, 128, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 128, num_blocks[2], stride=1)
        self.layer4 = self._make_layer(block, 256, num_blocks[3], stride=2)
        self.layer5 = self._make_layer(block, 256, num_blocks[4], stride=1)
        self.layer6 = self._make_layer(block, 256, num_blocks[5], stride=2)
        self.layer7 = self._make_layer(block, 256, num_blocks[5], stride=1)
        self.stat_pooling = MeanStdPooling()
        self.before_embedding = torch.nn.Linear(5120, 256)

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return torch.nn.Sequential(*layers)

    def forward(self, x):
Anthony Larcher's avatar
debug    
Anthony Larcher committed
397
        out = self.MFCC(x)
Anthony Larcher's avatar
debug    
Anthony Larcher committed
398
399
        out = self.CMVN(out)
        out = out.unsqueeze(1)
Anthony Larcher's avatar
Anthony Larcher committed
400
        out = torch.nn.functional.relu(self.bn1(self.conv1(out)))
Anthony Larcher's avatar
Anthony Larcher committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = self.layer5(out)
        out = self.layer6(out)
        out = self.layer7(out)
        out = torch.flatten(out, start_dim=1, end_dim=2)
        out = self.stat_pooling(out)
        out = self.before_embedding(out)
        return out


class PreResNet34(torch.nn.Module):
    """
    Networks that contains only the ResNet part until pooling, with NO classification layers
    """
    def __init__(self, block=BasicBlock, num_blocks=[3, 1, 3, 1, 5, 1, 2], speaker_number=10):
        super(PreResNet34, self).__init__()
        self.in_planes = 128
Anthony Larcher's avatar
debug    
Anthony Larcher committed
421

Anthony Larcher's avatar
Anthony Larcher committed
422
        self.speaker_number = speaker_number
Anthony Larcher's avatar
Anthony Larcher committed
423
424
        self.conv1 = torch.nn.Conv2d(1, 128, kernel_size=3,
                               stride=1, padding=1, bias=False)
Anthony Larcher's avatar
debug    
Anthony Larcher committed
425

Anthony Larcher's avatar
Anthony Larcher committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
        self.bn1 = torch.nn.BatchNorm2d(128)

        #  With block = [3, 1, 3, 1, 5, 1, 2]
        self.layer1 = self._make_layer(block, 128, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 128, num_blocks[2], stride=1)
        self.layer4 = self._make_layer(block, 256, num_blocks[3], stride=2)
        self.layer5 = self._make_layer(block, 256, num_blocks[4], stride=1)
        self.layer6 = self._make_layer(block, 256, num_blocks[5], stride=2)
        self.layer7 = self._make_layer(block, 256, num_blocks[5], stride=1)


    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return torch.nn.Sequential(*layers)

    def forward(self, x):
Anthony Larcher's avatar
debug    
Anthony Larcher committed
447
        out = x.unsqueeze(1)
Anthony Larcher's avatar
debug    
Anthony Larcher committed
448
        out = torch.nn.functional.relu(self.bn1(self.conv1(out)))
Anthony Larcher's avatar
Anthony Larcher committed
449
450
451
452
453
454
455
456
457
458
459
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = self.layer5(out)
        out = self.layer6(out)
        out = self.layer7(out)
        out = torch.flatten(out, start_dim=1, end_dim=2)
        return out


Anthony Larcher's avatar
Anthony Larcher committed
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
class PreHalfResNet34(torch.nn.Module):
    """
    Networks that contains only the ResNet part until pooling, with NO classification layers
    """
    def __init__(self, block=BasicBlock, num_blocks=[3, 4, 6, 3], speaker_number=10):
        super(PreHalfResNet34, self).__init__()
        self.in_planes = 32
        self.speaker_number = speaker_number

        self.conv1 = torch.nn.Conv2d(1, 32, kernel_size=3,
                               stride=(1, 1), padding=1, bias=False)
        self.bn1 = torch.nn.BatchNorm2d(32)

        #  With block = [3, 4, 6, 3]
        self.layer1 = self._make_layer(block, 32, num_blocks[0], stride=(1, 1))
        self.layer2 = self._make_layer(block, 64, num_blocks[1], stride=(2, 2))
        self.layer3 = self._make_layer(block, 128, num_blocks[2], stride=(2, 2))
        self.layer4 = self._make_layer(block, 256, num_blocks[3], stride=(2, 2))


    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return torch.nn.Sequential(*layers)

    def forward(self, x):
        out = x.unsqueeze(1)
        out = out.contiguous(memory_format=torch.channels_last)
        out = torch.nn.functional.relu(self.bn1(self.conv1(out)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = out.contiguous(memory_format=torch.contiguous_format)
        out = torch.flatten(out, start_dim=1, end_dim=2)
        return out


Anthony Larcher's avatar
Anthony Larcher committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
class PreFastResNet34(torch.nn.Module):
    """
    Networks that contains only the ResNet part until pooling, with NO classification layers
    """
    def __init__(self, block=BasicBlock, num_blocks=[3, 4, 6, 3], speaker_number=10):
        super(PreFastResNet34, self).__init__()
        self.in_planes = 16
        self.speaker_number = speaker_number

        self.conv1 = torch.nn.Conv2d(1, 16, kernel_size=7,
                               stride=(2, 1), padding=3, bias=False)
        self.bn1 = torch.nn.BatchNorm2d(16)

        #  With block = [3, 4, 6, 3]
        self.layer1 = self._make_layer(block, 16, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 32, num_blocks[1], stride=(2, 2))
        self.layer3 = self._make_layer(block, 64, num_blocks[2], stride=(2, 2))
        self.layer4 = self._make_layer(block, 128, num_blocks[3], stride=(1, 1))


    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return torch.nn.Sequential(*layers)

    def forward(self, x):
Anthony Larcher's avatar
debug    
Anthony Larcher committed
530
        out = x.unsqueeze(1)
Anthony Larcher's avatar
Anthony Larcher committed
531
        out = out.contiguous(memory_format=torch.channels_last)
Anthony Larcher's avatar
Anthony Larcher committed
532
533
534
535
536
        out = torch.nn.functional.relu(self.bn1(self.conv1(out)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
Anthony Larcher's avatar
Anthony Larcher committed
537
        out = out.contiguous(memory_format=torch.contiguous_format)
Anthony Larcher's avatar
Anthony Larcher committed
538
539
540
        out = torch.flatten(out, start_dim=1, end_dim=2)
        return out

Anthony Larcher's avatar
Anthony Larcher committed
541
542
543
544

def ResNet34():
    return ResNet(BasicBlock, [3, 1, 3, 1, 5, 1, 2])