File size: 27,544 Bytes
7934b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lJz6FDU1lRzc"
      },
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell.\n",
        "\n",
        "## Install dependencies\n",
        "!pip install wget\n",
        "!apt-get install sox libsndfile1 ffmpeg\n",
        "!pip install text-unidecode\n",
        "!pip install matplotlib>=3.3.2\n",
        "\n",
        "## Install NeMo\n",
        "BRANCH = 'r1.17.0'\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
        "\n",
        "\"\"\"\n",
        "Remember to restart the runtime for the kernel to pick up any upgraded packages (e.g. matplotlib)!\n",
        "Alternatively, you can uncomment the exit() below to crash and restart the kernel, in the case\n",
        "that you want to use the \"Run All Cells\" (or similar) option.\n",
        "\"\"\"\n",
        "# exit()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FGIVHjS1YEPw"
      },
      "source": [
        "# Self-Supervised pre-training for ASR\n",
        "\n",
        "This notebook is a basic tutorial for pre-training a model using the self-supervised approach. With this approach, we use a training objective that does not require our dataset to be labeled, which significantly reduces the difficulty of collecting data for pre-training the model. After pre-training our encoder in this way, we can use it in a CTC or RNNT ASR model.\n",
        "\n",
        "The approach we will use for pre-training our models is represented in the following diagram:\n",
        "\n",
        " ![SSL diagram](https://raw.githubusercontent.com/NVIDIA/NeMo/main/tutorials/asr/images/contrastive_ssl.png)\n",
        "\n",
        "We first mask parts of our input using SpecAugment.  The model is then trained to solve a contrastive task of distinguishing the latent representation of the masked time steps from several sampled distractors. Since our encoders also contain stride blocks which reduce the length of the inputs, in order to obtain target representations we combine several consecutive time steps. They are then passed through a quantizer, which has been found to help with contrastive pre-training."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i5XZWBnTf1pT"
      },
      "source": [
        "# Preparing our data"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "38aYTCTIlRzh"
      },
      "source": [
        "## Downloading dataset\n",
        "\n",
        "In order to demonstrate how to pre-train the model, we will use the AN4 dataset. Note: this is dataset is much smaller than one that we would typically want to use for self-supervised training, however it will suffice for this tutorial. This dataset also contains transcriptions, but they will be ignored for self-supervised pre-training.\n",
        "\n",
        "Before we get started, let's download and prepare the dataset. The utterances are available as `.sph` files, so we will need to convert them to `.wav` for later processing. If you are not using Google Colab, please make sure you have [Sox](http://sox.sourceforge.net/) installed for this step--see the \"Downloads\" section of the linked Sox homepage. (If you are using Google Colab, Sox should have already been installed in the setup cell at the beginning.)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gAhsmi6HlRzh"
      },
      "outputs": [],
      "source": [
        "# This is where the an4/ directory will be placed.\n",
        "# Change this if you don't want the data to be extracted in the current directory.\n",
        "data_dir = '.'"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "Yb4fuUvWlRzk",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "import glob\n",
        "import os\n",
        "import subprocess\n",
        "import tarfile\n",
        "import wget\n",
        "\n",
        "# Download the dataset. This will take a few moments...\n",
        "print(\"******\")\n",
        "if not os.path.exists(data_dir + '/an4_sphere.tar.gz'):\n",
        "    an4_url = 'https://dldata-public.s3.us-east-2.amazonaws.com/an4_sphere.tar.gz'\n",
        "    an4_path = wget.download(an4_url, data_dir)\n",
        "    print(f\"Dataset downloaded at: {an4_path}\")\n",
        "else:\n",
        "    print(\"Tarfile already exists.\")\n",
        "    an4_path = data_dir + '/an4_sphere.tar.gz'\n",
        "\n",
        "if not os.path.exists(data_dir + '/an4/'):\n",
        "    # Untar and convert .sph to .wav (using sox)\n",
        "    tar = tarfile.open(an4_path)\n",
        "    tar.extractall(path=data_dir)\n",
        "\n",
        "    print(\"Converting .sph to .wav...\")\n",
        "    sph_list = glob.glob(data_dir + '/an4/**/*.sph', recursive=True)\n",
        "    for sph_path in sph_list:\n",
        "        wav_path = sph_path[:-4] + '.wav'\n",
        "        cmd = [\"sox\", sph_path, wav_path]\n",
        "        subprocess.run(cmd)\n",
        "print(\"Finished conversion.\\n******\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m_LFeM0elRzm"
      },
      "source": [
        "You should now have a folder called `an4` that contains `etc/an4_train.transcription`, `etc/an4_test.transcription`, audio files in `wav/an4_clstk` and `wav/an4test_clstk`, along with some other files we will not need.\n",
        "\n",
        "Now we can load and take a look at the data. As an example, file `cen2-mgah-b.wav` is a 2.6 second-long audio recording of a man saying the letters \"G L E N N\" one-by-one. To confirm this, we can listen to the file:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_M_bSs3MjQlz"
      },
      "outputs": [],
      "source": [
        "import librosa\n",
        "import IPython.display as ipd\n",
        "\n",
        "# Load and listen to the audio file\n",
        "example_file = data_dir + '/an4/wav/an4_clstk/mgah/cen2-mgah-b.wav'\n",
        "audio, sample_rate = librosa.load(example_file)\n",
        "\n",
        "ipd.Audio(example_file, rate=sample_rate)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RdNyw1b_zgtm"
      },
      "source": [
        "## Creating Data Manifests\n",
        "\n",
        "The first thing we need to do now is to create manifests for our training and evaluation data, which will contain the metadata of our audio files. NeMo data sets take in a standardized manifest format where each line corresponds to one sample of audio, such that the number of lines in a manifest is equal to the number of samples that are represented by that manifest. \n",
        "\n",
        "\n",
        "A line must contain the path to an audio file, and the duration of the audio sample. For labeled datasets it will also contain the corresponding transcript (or path to a transcript file). Even though for self-supervised pre-training the transcript is unnecessary, we will still add it to our manifest, since we will also be using this dataset to demonstrate fine-tuning later on.\n",
        "\n",
        "Here's an example of what one line in a NeMo-compatible manifest might look like:\n",
        "```\n",
        "{\"audio_filepath\": \"path/to/audio.wav\", \"duration\": 3.45, \"text\": \"this is a nemo tutorial\"}\n",
        "```\n",
        "\n",
        "We can build our training and evaluation manifests using `an4/etc/an4_train.transcription` and `an4/etc/an4_test.transcription`, which have lines containing transcripts and their corresponding audio file IDs:\n",
        "```\n",
        "...\n",
        "<s> P I T T S B U R G H </s> (cen5-fash-b)\n",
        "<s> TWO SIX EIGHT FOUR FOUR ONE EIGHT </s> (cen7-fash-b)\n",
        "...\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lVB1sG1GlRzz"
      },
      "outputs": [],
      "source": [
        "# --- Building Manifest Files --- #\n",
        "import json\n",
        "\n",
        "# Function to build a manifest\n",
        "def build_manifest(transcripts_path, manifest_path, wav_path):\n",
        "    with open(transcripts_path, 'r') as fin:\n",
        "        with open(manifest_path, 'w') as fout:\n",
        "            for line in fin:\n",
        "                # Lines look like this:\n",
        "                # <s> transcript </s> (fileID)\n",
        "                transcript = line[: line.find('(')-1].lower()\n",
        "                transcript = transcript.replace('<s>', '').replace('</s>', '')\n",
        "                transcript = transcript.strip()\n",
        "\n",
        "                file_id = line[line.find('(')+1 : -2]  # e.g. \"cen4-fash-b\"\n",
        "                audio_path = os.path.join(\n",
        "                    data_dir, wav_path,\n",
        "                    file_id[file_id.find('-')+1 : file_id.rfind('-')],\n",
        "                    file_id + '.wav')\n",
        "\n",
        "                duration = librosa.core.get_duration(filename=audio_path)\n",
        "\n",
        "                # Write the metadata to the manifest\n",
        "                metadata = {\n",
        "                    \"audio_filepath\": audio_path,\n",
        "                    \"duration\": duration,\n",
        "                    \"text\": transcript\n",
        "                }\n",
        "                json.dump(metadata, fout)\n",
        "                fout.write('\\n')\n",
        "                \n",
        "# Building Manifests\n",
        "print(\"******\")\n",
        "train_transcripts = data_dir + '/an4/etc/an4_train.transcription'\n",
        "train_manifest = data_dir + '/an4/train_manifest.json'\n",
        "if not os.path.isfile(train_manifest):\n",
        "    build_manifest(train_transcripts, train_manifest, 'an4/wav/an4_clstk')\n",
        "    print(\"Training manifest created.\")\n",
        "\n",
        "test_transcripts = data_dir + '/an4/etc/an4_test.transcription'\n",
        "test_manifest = data_dir + '/an4/test_manifest.json'\n",
        "if not os.path.isfile(test_manifest):\n",
        "    build_manifest(test_transcripts, test_manifest, 'an4/wav/an4test_clstk')\n",
        "    print(\"Test manifest created.\")\n",
        "print(\"***Done***\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FLr1aJ-lf4_7"
      },
      "source": [
        "# Self-supervised pre-training"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sT_uewIDk8oA"
      },
      "source": [
        "## Setting up the config\n",
        "\n",
        "First, let's download the default config for ssl pre-training of Citrinet-1024, and the corresponding supervised training config, which we will use for fine-tuning later."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "978wWK7AKIvU"
      },
      "outputs": [],
      "source": [
        "## Grab the configs we'll use in this example\n",
        "!mkdir configs\n",
        "!wget -P configs/ https://raw.githubusercontent.com/NVIDIA/NeMo/main/examples/asr/conf/ssl/citrinet/citrinet_ssl_1024.yaml\n",
        "!wget -P configs/ https://raw.githubusercontent.com/NVIDIA/NeMo/main/examples/asr/conf/citrinet/citrinet_1024.yaml\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RLzjCgmHuJ_j"
      },
      "source": [
        "Since this config is for a very large model, we will modify it to make a much smaller version for the purpose of this tutorial by reducing the number of channels and the number of sub-blocks in each block."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Vmw9WbTPKHHA"
      },
      "outputs": [],
      "source": [
        "from omegaconf import OmegaConf\n",
        "import torch\n",
        "\n",
        "config_path = data_dir + '/configs/citrinet_ssl_1024.yaml'\n",
        "\n",
        "cfg = OmegaConf.load(config_path)\n",
        "\n",
        "cfg.model.model_defaults.filters = 256\n",
        "cfg.model.model_defaults.repeat = 1\n",
        "cfg.model.model_defaults.enc_final = 256\n",
        "\n",
        "cfg.model.train_ds.manifest_filepath = train_manifest\n",
        "cfg.model.train_ds.batch_size = 16\n",
        "\n",
        "cfg.model.validation_ds.manifest_filepath = test_manifest\n",
        "cfg.model.validation_ds.batch_size = 16\n",
        "\n",
        "if torch.cuda.is_available():\n",
        "  cfg.trainer.accelerator = 'gpu'\n",
        "  cfg.trainer.strategy = 'dp'\n",
        "  cfg.trainer.gpus = 1\n",
        "else:\n",
        "  cfg.trainer.accelerator = 'cpu'\n",
        "  cfg.trainer.strategy = None\n",
        "  cfg.trainer.gpus = 0\n",
        "\n",
        "cfg.exp_manager.exp_dir = data_dir + \"/content/exp\"\n",
        "cfg.exp_manager.name = \"pre_trained\"\n",
        "cfg.exp_manager.use_datetime_version = False\n",
        "cfg.exp_manager.create_tensorboard_logger = False\n",
        "cfg.exp_manager.resume_if_exists = True\n",
        "cfg.exp_manager.resume_ignore_no_checkpoint = True\n",
        "cfg.exp_manager.checkpoint_callback_params.save_best_model = True\n",
        "\n",
        "cfg.trainer.check_val_every_n_epoch = 1\n",
        "\n",
        "cfg.model.optim.sched.name = \"CosineAnnealing\"\n",
        "cfg.model.optim.sched.warmup_steps = 1000\n",
        "cfg.model.optim.sched.max_steps = 5000\n",
        "#in practice you will usually want a much larger amount of pre-training steps\n",
        "cfg.model.optim.sched.min_lr = 0\n",
        "cfg.model.optim.lr = 0.015\n",
        "cfg.model.optim.weight_decay = 0\n",
        "del cfg.model.optim.sched.d_model\n",
        "\n",
        "cfg.trainer.max_steps = cfg.model.optim.sched.max_steps\n",
        "\n",
        "cfg.model.spec_augment.patch_size = 16\n",
        "cfg.model.spec_augment.mask_patches = 0.5\n",
        "\n",
        "cfg.model.train_ds.min_duration = 3.2\n",
        "cfg.model.validation_ds.min_duration = 3.2\n",
        "#with patch_size set to 16 and 10 patches, \n",
        "#we need to be able to mask 160 time steps;\n",
        "#at preprocessor stride 0.01 this means we need minimum duration of 1.6 seconds \n",
        "#or more to sample only from masked steps in the same utterance\n",
        "\n",
        "cfg.model.loss_list.contrastive.loss.codebook_size = 32\n",
        "cfg.model.loss_list.mlm.decoder.feat_out = 1024\n",
        "\n",
        "cfg.model.loss_list.contrastive.loss.num_negatives = 40\n",
        "cfg.model.loss_list.contrastive.loss.quantizer_temp_decay = 0.999"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TrfAb1DjWzpL"
      },
      "source": [
        "The following parameters will be used for decoder, loss, and masking:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DTcn93gMXQba"
      },
      "outputs": [],
      "source": [
        "print(OmegaConf.to_yaml(cfg.model.loss_list))\n",
        "print(OmegaConf.to_yaml(cfg.model.spec_augment))"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Note that for this loss the outputs must match the inputs, so since we are using Citrinet architecture with 8x stride, we would need to either set \"combine_time_steps\" to 8, or put additional stride layers in the decoder. By default for Citrinet with 8x stride we use \"combine_time_steps=4\" and \"stride_layers=1\" to match the 8x stride.\n",
        "\n",
        "Since in MaskedPatchAugmentation we set mask_patches to 0.5 and our min_durations are set to 3.2, we are guaranteed to have 1.6 masked second per utterance, or 160 masked steps. Since combine_time_steps is set to 4, this means that 160 / 4 = 40 total negatives can be sampled, so we set num_negatives to 40 (unless you set sample_from_same_utterance_only to false or sample_from_non_masked to true, but this tends to make results worse).\n",
        "\n",
        "In the default configs we assume that min_duration for samples is higher (8 seconds by default), so there we can set patch_size to 48 for a total of 480 masked steps, and use 100 sampled negatives. If the min_duration of samples that you are training on allows, the amount of masked steps as well as negatives can be increased further (masking around 50% of the sample duration tends to work well)."
      ],
      "metadata": {
        "id": "4JnepitBZ3ta"
      }
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yoUIMS7mgrUs"
      },
      "source": [
        "Now we can create the config object."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "l0IqI0Yugqc1"
      },
      "outputs": [],
      "source": [
        "cfg = OmegaConf.to_container(cfg, resolve=True)\n",
        "cfg = OmegaConf.create(cfg)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OxxEwR05XatQ"
      },
      "source": [
        "## Pre-training the model\n",
        "\n",
        "We can now create the model based on our config and start pre-training with pytorch lightning. In NeMo you can use the examples/asr/speech_pretraining/speech_pre_training.py script for this, which contains the following lines:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WbnVpz03Jxto"
      },
      "outputs": [],
      "source": [
        "import pytorch_lightning as pl\n",
        "from omegaconf import OmegaConf\n",
        "\n",
        "from nemo.collections.asr.models.ssl_models import SpeechEncDecSelfSupervisedModel\n",
        "from nemo.core.config import hydra_runner\n",
        "from nemo.utils import logging\n",
        "from nemo.utils.exp_manager import exp_manager\n",
        "\n",
        "trainer = pl.Trainer(**cfg.trainer)\n",
        "exp_manager(trainer, cfg.get(\"exp_manager\", None))\n",
        "asr_model = SpeechEncDecSelfSupervisedModel(cfg=cfg.model, trainer=trainer)\n",
        "\n",
        "trainer.fit(asr_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FylnQvwvKIy9"
      },
      "source": [
        "# Fine-tuning with pre-trained encoder"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RvhsJbsiKNj6"
      },
      "source": [
        "Now that we have pre-trained our encoder, we can fine-tune our model with a supervised objective. Normally the dataset used for pre-training will be large and unlabeled, while the one used for fine-tuning will be a smaller labeled dataset. For the purpose of this tutorial we will just use the same dataset for fine-tuning."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rk7uDmuHAD2e"
      },
      "source": [
        "## Building tokenizer"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9WsIHRVVADZu"
      },
      "outputs": [],
      "source": [
        "!mkdir scripts\n",
        "!wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/tokenizers/process_asr_text_tokenizer.py\n",
        "\n",
        "!python ./scripts/process_asr_text_tokenizer.py \\\n",
        "  --manifest=\"{data_dir}/an4/train_manifest.json\" \\\n",
        "  --data_root=\"{data_dir}/tokenizers/an4/\" \\\n",
        "  --vocab_size=128 \\\n",
        "  --tokenizer=\"spe\" \\\n",
        "  --no_lower_case \\\n",
        "  --spe_type=\"unigram\" \\\n",
        "  --log"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Na0iuLoQMfgj"
      },
      "source": [
        "## Creating config for fine-tuning with CTC objective\n",
        "\n",
        "We will now create a config for a ctc-based model with a matching encoder to the model we pre-trained."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tzF8uOWOoqeO"
      },
      "outputs": [],
      "source": [
        "config_path = data_dir + '/configs/citrinet_1024.yaml'\n",
        "\n",
        "cfg = OmegaConf.load(config_path)\n",
        "\n",
        "cfg.model.model_defaults.filters = 256\n",
        "cfg.model.model_defaults.repeat = 1\n",
        "cfg.model.model_defaults.enc_final = 256\n",
        "\n",
        "cfg.model.spec_augment.freq_masks = 2\n",
        "cfg.model.spec_augment.time_masks = 5\n",
        "\n",
        "cfg.model.train_ds.manifest_filepath = train_manifest\n",
        "cfg.model.train_ds.batch_size = 16\n",
        "\n",
        "cfg.model.validation_ds.manifest_filepath = test_manifest\n",
        "cfg.model.validation_ds.batch_size = 16\n",
        "\n",
        "cfg.model.log_prediction = False\n",
        "\n",
        "if torch.cuda.is_available():\n",
        "  cfg.trainer.accelerator = 'gpu'\n",
        "  cfg.trainer.strategy = 'dp'\n",
        "  cfg.trainer.gpus = 1\n",
        "else:\n",
        "  cfg.trainer.accelerator = 'cpu'\n",
        "  cfg.trainer.strategy = None\n",
        "  cfg.trainer.gpus = 0\n",
        "\n",
        "cfg.model.tokenizer.dir = data_dir + \"/tokenizers/an4/tokenizer_spe_unigram_v128/\"  # note this is a directory, not a path to a vocabulary file\n",
        "cfg.model.tokenizer.type = \"bpe\"\n",
        "\n",
        "cfg.exp_manager.exp_dir = data_dir + \"/content/exp\"\n",
        "cfg.exp_manager.name = \"fine_tuned\"\n",
        "cfg.exp_manager.use_datetime_version = False\n",
        "cfg.exp_manager.create_tensorboard_logger = False\n",
        "cfg.exp_manager.resume_if_exists = True\n",
        "cfg.exp_manager.resume_ignore_no_checkpoint = True\n",
        "cfg.exp_manager.checkpoint_callback_params.save_best_model = True\n",
        "\n",
        "cfg.model.optim.sched.name = \"CosineAnnealing\"\n",
        "cfg.model.optim.sched.warmup_steps = 500\n",
        "cfg.model.optim.sched.max_steps = 2000\n",
        "cfg.model.optim.sched.min_lr = 0\n",
        "cfg.model.optim.lr = 0.015 #if encoder is frozen, lr can be much higher\n",
        "cfg.model.optim.weight_decay = 0\n",
        "\n",
        "cfg.trainer.max_steps = cfg.model.optim.sched.max_steps"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i3-_tFGDNPvZ"
      },
      "source": [
        "In order to load our encoder, we add the following to the config. We need to set init_strict to False, since the decoder for this model will be different, in order to have the correct output for ctc."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3GKv7ERxNPRc"
      },
      "outputs": [],
      "source": [
        "cfg.init_from_nemo_model=data_dir + \"/content/exp/pre_trained/checkpoints/pre_trained.nemo\"\n",
        "cfg.init_strict = False"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MOZmD9sjNgfX"
      },
      "outputs": [],
      "source": [
        "cfg = OmegaConf.to_container(cfg, resolve=True)\n",
        "cfg = OmegaConf.create(cfg)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "InacQMmE8tPZ"
      },
      "source": [
        "## Fine-tuning the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l3eNBs_sNhjE"
      },
      "source": [
        "Initializing our model from config:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IEScq3t_vB6N"
      },
      "outputs": [],
      "source": [
        "from nemo.collections.asr.models.ctc_bpe_models import EncDecCTCModelBPE\n",
        "\n",
        "trainer = pl.Trainer(**cfg.trainer)\n",
        "exp_manager(trainer, cfg.get(\"exp_manager\", None))\n",
        "asr_model = EncDecCTCModelBPE(cfg=cfg.model, trainer=trainer)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uif9DLOQ8d0b"
      },
      "source": [
        "Loading our pre-trained checkpoint:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Jes4vqx4vLRC"
      },
      "outputs": [],
      "source": [
        "asr_model.maybe_init_from_pretrained_checkpoint(cfg)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "We can optionally freeze the encoder and only fine-tune the decoder during training. This can be done to lower the memory and time requirements of fine-tuning, but will likely result in a higher word error rate."
      ],
      "metadata": {
        "id": "S5aVb2F8WuAR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#asr_model.encoder.freeze()"
      ],
      "metadata": {
        "id": "LpF_YQUmXUR8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GdoIbsLn8gNC"
      },
      "source": [
        "Now we can run fine-tuning."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "AACa0T6jJtMQ"
      },
      "outputs": [],
      "source": [
        "trainer.fit(asr_model)"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "Self_Supervised_Pre_Training.ipynb",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.7"
    },
    "pycharm": {
      "stem_cell": {
        "cell_type": "raw",
        "metadata": {
          "collapsed": false
        },
        "source": []
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}