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
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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# Copyright (c) 2022, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest
import torch
from omegaconf import DictConfig

from nemo.collections.asr.models import EncDecDenoiseMaskedTokenPredModel, SpeechEncDecSelfSupervisedModel
from nemo.core.classes.common import typecheck


@pytest.fixture()
def ssl_model():
    preprocessor = {
        'cls': 'nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor',
        'params': dict({'pad_to': 16, 'dither': 0}),
    }

    model_defaults = {'enc_hidden': 32, 'dec_out': 128}

    encoder = {
        'cls': 'nemo.collections.asr.modules.ConvASREncoder',
        'params': {
            'feat_in': 64,
            'activation': 'relu',
            'conv_mask': True,
            'jasper': [
                {
                    'filters': model_defaults['enc_hidden'],
                    'repeat': 1,
                    'kernel': [1],
                    'stride': [1],
                    'dilation': [1],
                    'dropout': 0.0,
                    'residual': False,
                    'separable': True,
                    'se': True,
                    'se_context_size': -1,
                },
                {
                    'filters': model_defaults['enc_hidden'],
                    'repeat': 1,
                    'kernel': [1],
                    'stride': [1],
                    'dilation': [1],
                    'dropout': 0.0,
                    'residual': False,
                    'separable': True,
                    'se': True,
                    'se_context_size': -1,
                },
                {
                    'filters': model_defaults['enc_hidden'],
                    'repeat': 1,
                    'kernel': [1],
                    'stride': [1],
                    'dilation': [1],
                    'dropout': 0.0,
                    'residual': False,
                    'separable': True,
                    'se': True,
                    'se_context_size': -1,
                },
            ],
        },
    }

    spec_augment = {
        '_target_': 'nemo.collections.asr.modules.MaskedPatchAugmentation',
        'freq_masks': 3,
        'freq_width': 20,
        'patch_size': 16,
        'mask_patches': 0.5,
    }

    loss_list_contr_mlm = {
        'contr': {
            'decoder': {
                '_target_': 'nemo.collections.asr.modules.ConvASRDecoderReconstruction',
                'feat_in': model_defaults['enc_hidden'],
                'feat_hidden': 128,
                'feat_out': model_defaults['dec_out'],
                'stride_layers': 0,
                'non_stride_layers': 0,
                'stride_transpose': False,
            },
            'loss': {
                '_target_': 'nemo.collections.asr.losses.ContrastiveLoss',
                'in_dim': 64,
                'proj_dim': model_defaults['dec_out'],
                'combine_time_steps': 1,
                'quantized_targets': True,
                'codebook_size': 64,
                'sample_from_same_utterance_only': True,
                'sample_from_non_masked': False,
                'num_negatives': 3,
            },
        },
        'mlm': {
            'decoder': {
                '_target_': 'nemo.collections.asr.modules.ConvASRDecoder',
                'feat_in': model_defaults['enc_hidden'],
                'num_classes': 4096,
            },
            'loss': {'_target_': 'nemo.collections.asr.losses.MLMLoss', 'combine_time_steps': 1},
            'targets_from_loss': "contr",
        },
    }

    modelConfig_contr_mlm = DictConfig(
        {
            'preprocessor': DictConfig(preprocessor),
            'spec_augment': DictConfig(spec_augment),
            'model_defaults': DictConfig(model_defaults),
            'encoder': DictConfig(encoder),
            'loss_list': DictConfig(loss_list_contr_mlm),
        }
    )
    ssl_model = SpeechEncDecSelfSupervisedModel(cfg=modelConfig_contr_mlm)
    return ssl_model


@pytest.fixture()
def denoise_mlm_ssl_model():

    model_defaults = {
        "subsampling_factor": 1,
        'enc_hidden': 32,
        'dec_out': 128,
        "sample_rate": 16000,
        "num_classes": 32,
        "num_books": 1,
        "code_dim": 16,
        "squeeze_single": False,
        "mask_position": "pre_conv",  # position to apply masking, before or after conv subsampling, choices in ['pre_conv', 'post_conv']
    }

    preprocessor = {
        "_target_": "nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor",
        "sample_rate": model_defaults["sample_rate"],
        "normalize": "per_feature",
        "window_size": 0.025,
        "window_stride": 0.01,
        "window": "hann",
        "features": 80,
        "n_fft": 512,
        "log": True,
        "frame_splicing": 1,
        "dither": 0.00001,
        "pad_to": 16,
        "pad_value": 0.0,
    }

    encoder = {
        'cls': 'nemo.collections.asr.modules.ConvASREncoder',
        'params': {
            'feat_in': preprocessor["features"],
            'activation': 'relu',
            'conv_mask': True,
            'jasper': [
                {
                    'filters': model_defaults['enc_hidden'],
                    'repeat': 1,
                    'kernel': [1],
                    'stride': [1],
                    'dilation': [1],
                    'dropout': 0.0,
                    'residual': False,
                    'separable': True,
                    'se': True,
                    'se_context_size': -1,
                },
                {
                    'filters': model_defaults['enc_hidden'],
                    'repeat': 1,
                    'kernel': [1],
                    'stride': [1],
                    'dilation': [1],
                    'dropout': 0.0,
                    'residual': False,
                    'separable': True,
                    'se': True,
                    'se_context_size': -1,
                },
                {
                    'filters': model_defaults['enc_hidden'],
                    'repeat': 1,
                    'kernel': [1],
                    'stride': [1],
                    'dilation': [1],
                    'dropout': 0.0,
                    'residual': False,
                    'separable': True,
                    'se': True,
                    'se_context_size': -1,
                },
            ],
        },
    }

    spec_augment = {
        '_target_': 'nemo.collections.asr.modules.SpectrogramAugmentation',
        'freq_masks': 0,
        'time_masks': 0,
        'freq_width': 16,
        'time_width': 0.05,
    }

    masking = {
        "_target_": "nemo.collections.asr.modules.RandomBlockMasking",
        "block_size": 40,  # for pre_conv masking, 10ms per frame, 400ms per block with block_size=40
        "mask_prob": 0.01,  # for allow_overlap=True, this means the mask prob for each frame; otherwise it means the overall masked proportion
        "feat_in": preprocessor["features"],
        "freeze": True,
        "allow_overlap": True,
    }

    quantizer = {
        "_target_": "nemo.collections.asr.modules.RandomProjectionVectorQuantizer",
        "feat_in": preprocessor["features"],
        "code_dim": model_defaults["code_dim"],
        "num_books": model_defaults["num_books"],
        "num_classes": model_defaults["num_classes"],
        "dist_fn": "l2",  # choices=["l2", "cosine"]
        "freeze": True,
        "squeeze_single": model_defaults["squeeze_single"],
        "combine_time_steps": model_defaults["subsampling_factor"],  # conformer sub-sampling ratio
    }

    decoder = {
        "_target_": "nemo.collections.asr.modules.MultiSoftmaxDecoder",
        "feat_in": model_defaults["enc_hidden"],
        "num_classes": model_defaults["num_classes"],
        "num_decoders": model_defaults["num_books"],
        "squeeze_single": model_defaults["squeeze_single"],
        "use_bias": True,
    }

    loss = {
        "_target_": "nemo.collections.asr.losses.MultiMLMLoss",
        "combine_time_steps": model_defaults[
            "subsampling_factor"
        ],  # conformer sub-sampling ratio for 'pre_conv', 1 for 'post_conv'
        "mask_threshold": 0.8,
        "num_decoders": model_defaults["num_books"],
        "squeeze_single": model_defaults["squeeze_single"],
    }

    optim = {
        "name": "adamw",
        "lr": 5.0,
        # optimizer arguments
        "betas": [0.9, 0.98],
        "weight_decay": 1e-3,
    }

    model_config = DictConfig(
        {
            "preprocessor": DictConfig(preprocessor),
            "spec_augment": DictConfig(spec_augment),
            'model_defaults': DictConfig(model_defaults),
            "masking": DictConfig(masking),
            "quantizer": DictConfig(quantizer),
            "encoder": DictConfig(encoder),
            "decoder": DictConfig(decoder),
            "loss": DictConfig(loss),
            "optim": DictConfig(optim),
        }
    )
    ssl_model = EncDecDenoiseMaskedTokenPredModel(cfg=model_config)
    return ssl_model


class TestSSLModel:
    @pytest.mark.unit
    def test_constructor(self, ssl_model):
        confdict = ssl_model.to_config_dict()
        instance2 = SpeechEncDecSelfSupervisedModel.from_config_dict(confdict)
        assert isinstance(instance2, SpeechEncDecSelfSupervisedModel)

    @pytest.mark.unit
    def test_contr_nonquant(self, ssl_model):
        modelConfig_contr_nonquant = ssl_model.to_config_dict()

        loss_list_contr_nonquant = dict(modelConfig_contr_nonquant['loss_list'])
        del loss_list_contr_nonquant['mlm']

        loss_list_contr_nonquant['contr']['loss']['quantized_targets'] = False

        modelConfig_contr_nonquant['loss_list'] = DictConfig(loss_list_contr_nonquant)

        ssl_model = SpeechEncDecSelfSupervisedModel(cfg=modelConfig_contr_nonquant)

        input_signal = torch.randn(size=(4, 64000))
        length = torch.randint(low=48000, high=64000, size=[4])

        with torch.no_grad():
            spectrograms, spec_masks, encoded, encoded_len = ssl_model.forward(
                input_signal=input_signal, input_signal_length=length
            )

            loss_value, loss_val_dict = ssl_model.decoder_loss_step(spectrograms, spec_masks, encoded, encoded_len)

        assert len(loss_val_dict) == 1

    @pytest.mark.unit
    def test_contr_mlm(self, ssl_model):

        input_signal = torch.randn(size=(4, 64000))
        length = torch.randint(low=48000, high=64000, size=[4])

        with torch.no_grad():
            spectrograms, spec_masks, encoded, encoded_len = ssl_model.forward(
                input_signal=input_signal, input_signal_length=length
            )

        loss_value, loss_val_dict = ssl_model.decoder_loss_step(spectrograms, spec_masks, encoded, encoded_len)

        assert len(loss_val_dict) == 2

    @pytest.mark.unit
    def test_contr_mlm_multi(self, ssl_model):
        modelConfig_contr_mlm_multi = ssl_model.to_config_dict()

        model_defaults = modelConfig_contr_mlm_multi['model_defaults']

        loss_list_contr_mlm_multi = dict(modelConfig_contr_mlm_multi['loss_list'])
        loss_list_contr_mlm_multi['mlm_2'] = {
            'decoder': {
                '_target_': 'nemo.collections.asr.modules.ConvASRDecoder',
                'feat_in': model_defaults['enc_hidden'],
                'num_classes': 4096,
            },
            'loss': {'_target_': 'nemo.collections.asr.losses.MLMLoss', 'combine_time_steps': 1},
            'output_from_layer': "encoder.0",
            'targets_from_loss': "contr",
        }
        loss_list_contr_mlm_multi['mlm_3'] = {
            'decoder': {
                '_target_': 'nemo.collections.asr.modules.ConvASRDecoder',
                'feat_in': model_defaults['enc_hidden'],
                'num_classes': 4096,
            },
            'loss': {'_target_': 'nemo.collections.asr.losses.MLMLoss', 'combine_time_steps': 1},
            'output_from_layer': "encoder.1",
            'targets_from_loss': "contr",
        }
        modelConfig_contr_mlm_multi['loss_list'] = DictConfig(loss_list_contr_mlm_multi)

        ssl_model = SpeechEncDecSelfSupervisedModel(cfg=modelConfig_contr_mlm_multi)

        input_signal = torch.randn(size=(4, 64000))
        length = torch.randint(low=48000, high=64000, size=[4])

        with torch.no_grad():
            spectrograms, spec_masks, encoded, encoded_len = ssl_model.forward(
                input_signal=input_signal, input_signal_length=length
            )

            loss_value, loss_val_dict = ssl_model.decoder_loss_step(spectrograms, spec_masks, encoded, encoded_len)

        assert len(loss_val_dict) == 4


class TestDenoiseMLMSSLModel:
    @pytest.mark.unit
    def test_forward(self, denoise_mlm_ssl_model):
        input_signal = torch.randn(size=(4, 64000))
        input_length = torch.randint(low=48000, high=64000, size=[4])
        noise = 0.1 * torch.ones_like(input_signal)
        noisy_input_signal = input_signal + noise
        noisy_input_length = input_length
        with torch.no_grad():
            with typecheck.disable_checks():
                log_probs, encoded_len, masks, tokens = denoise_mlm_ssl_model.forward(
                    input_signal=input_signal,
                    input_signal_length=input_length,
                    noisy_input_signal=noisy_input_signal,
                    noisy_input_signal_length=noisy_input_length,
                )

        assert log_probs.size(0) == 4
        assert log_probs.size(2) == denoise_mlm_ssl_model.cfg.model_defaults.num_classes
        assert encoded_len.size(0) == 4
        assert masks.size(0) == 4
        assert tokens.size(0) == 4
        assert masks.sum() == 0.0  # no mask should be applied to the input by default

    @pytest.mark.unit
    def test_forward_masked(self, denoise_mlm_ssl_model: EncDecDenoiseMaskedTokenPredModel):
        input_signal = torch.randn(size=(4, 64000))
        input_length = torch.randint(low=48000, high=64000, size=[4])
        noise = 0.1 * torch.ones_like(input_signal)
        noisy_input_signal = input_signal + noise
        noisy_input_length = input_length

        with torch.no_grad():
            with typecheck.disable_checks():
                log_probs, encoded_len, masks, tokens = denoise_mlm_ssl_model.forward(
                    input_signal=input_signal,
                    input_signal_length=input_length,
                    noisy_input_signal=noisy_input_signal,
                    noisy_input_signal_length=noisy_input_length,
                    apply_mask=True,
                )

        loss_value = denoise_mlm_ssl_model.loss(
            masks=masks, decoder_outputs=log_probs, targets=tokens, decoder_lengths=encoded_len
        )

        assert log_probs.size(0) == 4
        assert log_probs.size(2) == denoise_mlm_ssl_model.cfg.model_defaults.num_classes
        assert encoded_len.size(0) == 4
        assert masks.size(0) == 4
        assert tokens.size(0) == 4
        assert masks.sum() > 0.0  # mask should be applied to the input
        assert not torch.isnan(loss_value)