seqtoseq.py 16.2 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
25
# -*- coding: utf-8 -*-
#
# This file is part of s4d.
#
# s4d is a python package for speaker diarization.
# Home page: http://www-lium.univ-lemans.fr/s4d/
#
# s4d is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# s4d 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 s4d.  If not, see <http://www.gnu.org/licenses/>.


"""
Copyright 2014-2020 Anthony Larcher
"""

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
26
import logging
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
27
import shutil
Anthony Larcher's avatar
Anthony Larcher committed
28
import torch
29
30
import yaml

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
31
from collections import OrderedDict
32
from sidekit.nnet.sincnet import SincNet
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
33
from torch.utils.data import DataLoader
Anthony Larcher's avatar
Anthony Larcher committed
34

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
35
36
37
from .wavsets import SeqSet
from .wavsets import create_train_val_seqtoseq

Anthony Larcher's avatar
Anthony Larcher committed
38
__license__ = "LGPL"
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
39
__author__ = "Anthony Larcher, Martin Lebourdais, Meysam Shamsi"
Anthony Larcher's avatar
Anthony Larcher committed
40
41
42
43
44
45
__copyright__ = "Copyright 2015-2020 Anthony Larcher"
__maintainer__ = "Anthony Larcher"
__email__ = "anthony.larcher@univ-lemans.fr"
__status__ = "Production"
__docformat__ = 'reS'

Anthony Larcher's avatar
Anthony Larcher committed
46

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
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
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar', best_filename='model_best.pth.tar'):
    """
    :param state:
    :param is_best:
    :param filename:
    :param best_filename:
    :return:
    """
    torch.save(state, filename)
    if is_best:
        shutil.copyfile(filename, best_filename)


def init_weights(m):
    """

    :return:
    """
    if type(m) == torch.nn.Linear:
        torch.nn.init.xavier_uniform_(m.weight)
        m.bias.data.fill_(0.01)


class BLSTM(torch.nn.Module):
    """
    Bi LSTM model used for voice activity detection, speaker turn detection, overlap detection and resegmentation
    """
Anthony Larcher's avatar
Anthony Larcher committed
74
75
    def __init__(self,
                 input_size,
76
                 blstm_sizes):
Anthony Larcher's avatar
Anthony Larcher committed
77
78
79
        """

        :param input_size:
80
        :param blstm_sizes:
Anthony Larcher's avatar
Anthony Larcher committed
81
82
        """
        super(BLSTM, self).__init__()
83
84
        self.input_size = input_size
        self.blstm_sizes = blstm_sizes
Anthony Larcher's avatar
Anthony Larcher committed
85
        self.output_size = blstm_sizes * 2
Anthony Larcher's avatar
Anthony Larcher committed
86

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
87
88
89
90
91
        self.blstm_layers = torch.nn.LSTM(input_size,
                                          blstm_sizes,
                                          bidirectional=True,
                                          batch_first=True,
                                          num_layers=2)
Anthony Larcher's avatar
Anthony Larcher committed
92
93
94
95
96
97
98

    def forward(self, inputs):
        """

        :param inputs:
        :return:
        """
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
99
100
        output, h = self.blstm_layers(inputs)
        return output
Anthony Larcher's avatar
Anthony Larcher committed
101

102
    def output_size(self):
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
103
104
105
106
        """

        :return:
        """
107
108
        return self.output_size

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
109

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
110
class SeqToSeq(torch.nn.Module):
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
111
    """
112
113
114
115
    Model used for voice activity detection or speaker turn detection
    This model can include a pre-processor to input raw waveform,
    a BLSTM module to process the sequence-to-sequence
    and other linear of convolutional layers
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
116
117
    """
    def __init__(self,
118
119
                 model_archi):

Anthony Larcher's avatar
Anthony Larcher committed
120
        super(SeqToSeq, self).__init__()
121
122
123
124
125
126

        # Load Yaml configuration
        with open(model_archi, 'r') as fh:
            cfg = yaml.load(fh, Loader=yaml.FullLoader)

        self.loss = cfg["loss"]
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
127
        self.feature_size = None
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

        """
        Prepare Preprocessor
        """
        self.preprocessor = None
        if "preprocessor" in cfg:
            if cfg['preprocessor']["type"] == "sincnet":
                self.preprocessor = SincNet(
                    waveform_normalize=cfg['preprocessor']["waveform_normalize"],
                    sample_rate=cfg['preprocessor']["sample_rate"],
                    min_low_hz=cfg['preprocessor']["min_low_hz"],
                    min_band_hz=cfg['preprocessor']["min_band_hz"],
                    out_channels=cfg['preprocessor']["out_channels"],
                    kernel_size=cfg['preprocessor']["kernel_size"],
                    stride=cfg['preprocessor']["stride"],
                    max_pool=cfg['preprocessor']["max_pool"],
                    instance_normalize=cfg['preprocessor']["instance_normalize"],
                    activation=cfg['preprocessor']["activation"],
                    dropout=cfg['preprocessor']["dropout"]
                )
                self.feature_size = self.preprocessor.dimension

        """
        Prepare sequence to sequence  network
        """
        # Get Feature size
        if self.feature_size is None:
            self.feature_size = cfg["feature_size"]

        input_size = self.feature_size

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
159
160
        self.sequence_to_sequence = BLSTM(input_size=input_size,
                                          blstm_sizes=cfg["sequence_to_sequence"]["blstm_sizes"])
161

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
162
        input_size = self.sequence_to_sequence.output_size
163
164
165
166
167

        """
        Prepare post-processing network
        """
        # Create sequential object for the second part of the network
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
168
        self.post_processing_activation = torch.nn.Tanh()
169
170
171
172
173
174
175
176
177
        post_processing_layers = []
        for k in cfg["post_processing"].keys():

            if k.startswith("lin"):
                post_processing_layers.append((k, torch.nn.Linear(input_size,
                                                                  cfg["post_processing"][k]["output"])))
                input_size = cfg["post_processing"][k]["output"]

            elif k.startswith("activation"):
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
178
                post_processing_layers.append((k, self.post_processing_activation))
179
180
181
182
183
184
185

            elif k.startswith('batch_norm'):
                post_processing_layers.append((k, torch.nn.BatchNorm1d(input_size)))

            elif k.startswith('dropout'):
                post_processing_layers.append((k, torch.nn.Dropout(p=cfg["post_processing"][k])))

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
186
        self.post_processing = torch.nn.Sequential(OrderedDict(post_processing_layers))
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
187
        self.post_processing.apply(init_weights)
Anthony Larcher's avatar
Anthony Larcher committed
188

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
189
190
    def forward(self, inputs):
        """
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
191

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
192
193
194
        :param inputs:
        :return:
        """
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
195
196
        if self.preprocessor is not None:
            x = self.preprocessor(inputs)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
197
        else:
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
198
199
200
            x = inputs
        x = self.sequence_to_sequence(x)
        x = self.post_processing(x)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
201
202
203
        return x


Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
204
205
def seqTrain(dataset_yaml,
             model_yaml,
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
206
207
208
             epochs=100,
             lr=0.0001,
             patience=10,
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
209
             model_name=None,
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
210
211
212
213
             tmp_model_name=None,
             best_model_name=None,
             multi_gpu=True,
             opt='sgd',
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
214
             log_interval=10,
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
             num_thread=10
             ):
    """

    :param data_dir:
    :param mode:
    :param duration:
    :param seg_shift:
    :param filter_type:
    :param collar_duration:
    :param framerate:
    :param epochs:
    :param lr:
    :param loss:
    :param patience:
    :param tmp_model_name:
    :param best_model_name:
    :param multi_gpu:
    :param opt:
    :return:
    """
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    # Start from scratch
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
239
240
241
242
243
244
245
246
    if model_name is None:
       model = SeqToSeq(model_yaml)
    # If we start from an existing model
    else:
        # Load the model
        logging.critical(f"*** Load model from = {model_name}")
        checkpoint = torch.load(model_name)
        model = SeqToSeq(model_yaml)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
247
248
249
250
251
252

    if torch.cuda.device_count() > 1 and multi_gpu:
        print("Let's use", torch.cuda.device_count(), "GPUs!")
        model = torch.nn.DataParallel(model)
    else:
        print("Train on a single GPU")
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
253

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
254
255
    model.to(device)

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
256
257
    with open(dataset_yaml, "r") as fh:
        dataset_params = yaml.load(fh, Loader=yaml.FullLoader)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
258
259
260
    """
    Create two dataloaders for training and evaluation
    """
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
261
262
    training_set, validation_set = create_train_val_seqtoseq(dataset_yaml)

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
263

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
264
    training_loader = DataLoader(training_set,
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
265
                                 batch_size=dataset_params["batch_size"],
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
266
267
                                 shuffle=True,
                                 drop_last=True,
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
268
                                 pin_memory=True,
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
269
270
                                 num_workers=num_thread)

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
271
272
273
274
275
    validation_loader = DataLoader(validation_set,
                                   batch_size=dataset_params["batch_size"],
                                   drop_last=True,
                                   pin_memory=True,
                                   num_workers=num_thread)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
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

    """
    Set the training options
    """
    if opt == 'sgd':
        _optimizer = torch.optim.SGD
        _options = {'lr': lr, 'momentum': 0.9}
    elif opt == 'adam':
        _optimizer = torch.optim.Adam
        _options = {'lr': lr}
    elif opt == 'rmsprop':
        _optimizer = torch.optim.RMSprop
        _options = {'lr': lr}

    params = [
        {
            'params': [
                param for name, param in model.named_parameters() if 'bn' not in name
            ]
        },
        {
            'params': [
                param for name, param in model.named_parameters() if 'bn' in name
            ],
            'weight_decay': 0
        },
    ]

Anthony Larcher's avatar
Anthony Larcher committed
304
    optimizer = _optimizer([{'params': model.parameters()},], **_options)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
305
306
307
308
309
310

    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', verbose=True)

    best_accuracy = 0.0
    best_accuracy_epoch = 1
    curr_patience = patience
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
311

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
312
313
314
315
316
317
318
319
320
321
322
323
    for epoch in range(1, epochs + 1):
        # Process one epoch and return the current model
        if curr_patience == 0:
            print(f"Stopping at epoch {epoch} for cause of patience")
            break
        model = train_epoch(model,
                            epoch,
                            training_loader,
                            optimizer,
                            log_interval,
                            device=device)

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
324
        # Cross validation here
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
325
326
        accuracy, val_loss = cross_validation(model, validation_loader, device=device)
        logging.critical("*** Cross validation accuracy = {} %".format(accuracy))
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
327
328

        # Decrease learning rate according to the scheduler policy
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
329
330
        scheduler.step(val_loss)
        print(f"Learning rate is {optimizer.param_groups[0]['lr']}")
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
331
332

        # remember best accuracy and save checkpoint
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
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
        is_best = accuracy > best_accuracy
        best_accuracy = max(accuracy, best_accuracy)

        if type(model) is SeqToSeq:
            save_checkpoint({
                'epoch': epoch,
                'model_state_dict': model.state_dict(),
                'optimizer_state_dict': optimizer.state_dict(),
                'accuracy': best_accuracy,
                'scheduler': scheduler
            }, is_best, filename=tmp_model_name + ".pt", best_filename=best_model_name + '.pt')
        else:
            save_checkpoint({
                'epoch': epoch,
                'model_state_dict': model.module.state_dict(),
                'optimizer_state_dict': optimizer.state_dict(),
                'accuracy': best_accuracy,
                'scheduler': scheduler
            }, is_best, filename=tmp_model_name + ".pt", best_filename=best_model_name + '.pt')

        if is_best:
            best_accuracy_epoch = epoch
            curr_patience = patience
        else:
            curr_patience -= 1

    logging.critical(f"Best accuracy {best_accuracy * 100.} obtained at epoch {best_accuracy_epoch}")
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
360
361
362
363
364
365
366
367
368
369
370
371
372
373


def train_epoch(model, epoch, training_loader, optimizer, log_interval, device):
    """

    :param model:
    :param epoch:
    :param training_loader:
    :param optimizer:
    :param log_interval:
    :param device:
    :param clipping:
    :return:
    """
Anthony Larcher's avatar
Anthony Larcher committed
374
    model.to(device)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
375
    model.train()
Anthony Larcher's avatar
Anthony Larcher committed
376
    criterion = torch.nn.CrossEntropyLoss(reduction='mean', weight=torch.FloatTensor([0.1,0.9]).to(device))
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
377

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
378
379
    recall = 0.0
    precision = 0.0
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
380
    accuracy = 0.0
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
381

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
382
383
384
    for batch_idx, (data, target) in enumerate(training_loader):
        target = target.squeeze()
        optimizer.zero_grad()
Anthony Larcher's avatar
Anthony Larcher committed
385
386
387
388
        output = model(data.to(device))
        output = output.permute(1, 2, 0)
        target = target.permute(1, 0)

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
389
        loss = criterion(output, target.to(device))
Anthony Larcher's avatar
Anthony Larcher committed
390
        loss.backward(retain_graph=True)
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
391
        optimizer.step()
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
392
393
394
395
396

        rc, pr, acc = calc_recall(output.data, target, device)
        recall += rc.item()
        precision += pr.item()
        accuracy += acc.item()
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
397
398
399

        if batch_idx % log_interval == 0:
            batch_size = target.shape[0]
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
            if precision!=0 or recall!=0:
                f_measure = 2 * (precision / ((batch_idx + 1))) * (recall / ((batch_idx+1))) /\
                            ((precision / ((batch_idx + 1) ))+(recall / ((batch_idx + 1))))
                logging.critical(
                        'Train Epoch: {} [{}/{} ({:.0f}%)]  Loss: {:.6f}  Accuracy: {:.3f}  '\
                        'Recall: {:.3f}  Precision: {:.3f}  "\
                        F-Measure: {:.3f}'.format(epoch,
                                                  batch_idx + 1,
                                                  training_loader.__len__(),
                                                  100. * batch_idx / training_loader.__len__(), loss.item(),
                                                  100.0 * accuracy / ((batch_idx + 1)),
                                                  100.0 * recall/ ((batch_idx+1)),
                                                  100.0 * precision / ((batch_idx+1)),
                                                  f_measure)
                )
            else:
                print(f"precision = {precision} and recall = {recall}")

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
418
419
420
421
422
423
424
425
426
427
428
429
430
    return model


def cross_validation(model, validation_loader, device):
    """

    :param model:
    :param validation_loader:
    :param device:
    :return:
    """
    model.eval()

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
431
432
    recall = 0.0
    precision = 0.0
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
433
434
    accuracy = 0.0
    loss = 0.0
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
435

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
436
437
438
439
440
    criterion = torch.nn.CrossEntropyLoss()
    with torch.no_grad():
        for batch_idx, (data, target) in enumerate(validation_loader):
            batch_size = target.shape[0]
            target = target.squeeze()
Anthony Larcher's avatar
VAD    
Anthony Larcher committed
441
442
443
444
445
            output = model(data.to(device))
            output = output.permute(1, 2, 0)
            target = target.permute(1, 0)
            nbpoint = output.shape[0]

Anthony Larcher's avatar
Anthony Larcher committed
446
447
            loss = criterion(output, target.to(device))

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
            rc, pr, acc = calc_recall(output.data, target, device)
            recall += rc.item()
            precision += pr.item()
            accuracy += acc.item()

            batch_size = target.shape[0]
            if precision != 0 or recall != 0:
                f_measure = 2 * (precision / ((batch_idx + 1))) * (recall / ((batch_idx + 1))) / \
                            ((precision / ((batch_idx + 1))) + (recall / ((batch_idx + 1))))
                logging.critical(
                    'Validation: [{}/{} ({:.0f}%)]  Loss: {:.6f}  Accuracy: {:.3f}  ' \
                    'Recall: {:.3f}  Precision: {:.3f}  "\
                    F-Measure: {:.3f}'.format(batch_idx + 1,
                                              validation_loader.__len__(),
                                              100. * batch_idx / validation_loader.__len__(), loss.item(),
                                              100.0 * accuracy / ((batch_idx + 1)),
                                              100.0 * recall / ((batch_idx + 1)),
                                              100.0 * precision / ((batch_idx + 1)),
                                              f_measure)
                )
Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
468

Anthony Larcher's avatar
seq2seq    
Anthony Larcher committed
469

Anthony Larcher's avatar
VAD    
Anthony Larcher committed
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
501
502
503
504
505
def calc_recall(output,target,device):
    """

    :param output:
    :param target:
    :param device:
    :return:
    """
    y_trueb = target.to(device)
    y_predb = output
    rc = 0.0
    pr = 0.0
    acc= 0.0
    for b in range(y_trueb.shape[-1]):
        y_true = y_trueb[:,b]
        y_pred = y_predb[:,:,b]
        assert y_true.ndim == 1
        assert y_pred.ndim == 1 or y_pred.ndim == 2
        if y_pred.ndim == 2:
            y_pred = y_pred.argmax(dim=1)

        tp = (y_true * y_pred).sum().to(torch.float32)
        tn = ((1 - y_true) * (1 - y_pred)).sum().to(torch.float32)
        fp = ((1 - y_true) * y_pred).sum().to(torch.float32)
        fn = (y_true * (1 - y_pred)).sum().to(torch.float32)
        epsilon = 1e-7

        pr+= tp / (tp + fp + epsilon)
        rc+= tp / (tp + fn + epsilon)
        a=(tp+tn)/(tp+fp+tn+fn+epsilon)

        acc+=(tp+tn)/(tp+fp+tn+fn+epsilon)
    rc/=len(y_trueb[0])
    pr/=len(y_trueb[0])
    acc/=len(y_trueb[0])

Anthony Larcher's avatar
Anthony Larcher committed
506
    return rc,pr,acc
Anthony Larcher's avatar
Anthony Larcher committed
507
508
509