File size: 49,075 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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "collapsed_sections": [
        "dm-qqTdZDUlZ",
        "GGKgsW5gvAuf",
        "0CqpJGR6ecYW"
      ],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pEYsuj0J9pId"
      },
      "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",
        "import os\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",
        "## Grab the config we'll use in this example\n",
        "# !mkdir configs\n",
        "# !wget -P configs/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/conf/contextnet_rnnt/contextnet_rnnt.yaml"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# ASR Domain Adaptation with Adapters\n",
        "\n",
        "Throughout various Automatic Speech Recognition tutorials, you may have noticed that ASR datasets are generally enormous - on the order of hundreds or even thousands of hours of speech. Such a large amount of data imposes significant restrictions on the development of ASR models due to the cost of collection of labeled data (or even unlabeled datasets) and the severe compute cost to train a model on that much data. \n",
        "\n",
        "We further see that when fine-tuning a pre-trained model, we need large datasets and compute to achieve superior results and avoid overfitting to the new dataset. Worse, by training the entire model (or even just the decoder modules), we severely degrade the model's performance on the original dataset.\n",
        "\n",
        "-----\n",
        "\n",
        "In this tutorial, we will showcase **Adapters** : A powerful method to efficiently adapt a pre-trained model to a new dataset (with minimal amounts of data, even just 30 minutes !) with minimal compute resources (on a single GPU, in around 10 minutes of training time).\n"
      ],
      "metadata": {
        "id": "cTV4WLrArmxS"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## What are Adapters?\n",
        "\n",
        "Adapters are a straightforward concept proposed in multiple papers across various domains. For the sake of brevity, we will choose a recent paper [Using Adapters to Overcome Catastrophic Forgetting in End-to-End Automatic Speech Recognition](https://arxiv.org/abs/2203.16082) as a reference for this discussion.\n",
        "\n",
        "Essentially, an **Adapter** is any **trainable module that is added * after * a model has been trained to convergence**. \n",
        "\n",
        "- These additional modules form a residual bridge over the output of each layer they adapt, such that the model's original performance is not lost. \n",
        "- The original parameters of the model are frozen in their entirety - so that we don't lose performance on the original domain.\n",
        "- We train only the new adapter parameters (an insignificant fraction of the total number of parameters). This allows fast experimentation.\n",
        "\n",
        "-----\n",
        "\n",
        "Adapters are a straightforward concept - as shown by the diagram below. At their simplest, they are residual Feedforward layers that compress the input dimension ($D$) to a small bottleneck dimension ($H$), such that $R^D \\text{->} R^H$, compute an activation (such as ReLU), finally mapping $R^H \\text{->} R^D$ with another Feedforward layer. This output is then added to the input via a simple residual connection.\n",
        "\n",
        "<div align=\"center\">\n",
        "  <img src=\"https://mermaid.ink/img/pako:eNptkLFqwzAQhl9F3ORAPDSjA4EUx6RgXEjbycpwWOdG1JaMfEoakrx7ZcfpUKrlxH_fz4d0gcoqggTqxp6qAzoW76k0Ipx1-WI6z3sRxyuRF1GOZ3KisK6d3YG8GFdZ9hRJeLbMDRmqvkRGpDLrTuiUiEWUigBtlyIVqzBnEqZ66I39dcX6iKytKXeUf-wn-286QoFeBMvmu0PTD-EfyXaQpP9JFmP_1XN4S3kfD8W4ue6o18pjc52gYQlzaMm1qFX4msuQSOADtSQhCdfaOupZgjS3QPpOIdNGabYOkhqbnuaAnu3b2VSQsPP0gFKNnw7bibr9AJkZdXU\" height=100% />\n",
        "</div>\n",
        "\n",
        "-----\n",
        "\n",
        "Adapter modules such as this are usually initialized. The initial output of the adapter will always be zeros to prevent degradation of the original model's performance due to the addition of such modules."
      ],
      "metadata": {
        "id": "f-LSGyL4xw9c"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Advantages of Adapters\n",
        "\n",
        "Since adapters are additional parameters added to an already trained network, and due to their construction, they possess multiple beneficial properties.\n",
        "\n",
        "- **Added parameter cost**: They cost an insignificant number of parameters compared to the original model (generally 0.5% - 1% of the initial parameter count).\n",
        "- **Residual bridge**: Adapters are initialized with special care, such that their contribution to the output of each layer they adapt is initially 0. Therefore, after the addition of the adapters, the original model does not lose any accuracy at all (even without training the adapters).\n",
        "- **Fast convergence**: Since the adapters only need to learn to modify the module's output slightly, and each adapter has a trivial parameter cost, they converge rapidly.\n",
        "- **Adapt only the encoder**: Adapters can be used anywhere, but they are most commonly used in just the encoder, keeping the decoder modules frozen. This allows the decoder to be unaffected by costly CTC/RNN-T training, which takes time to converge, and just the adapter modules in the encoder need to be updated.\n",
        "- **Dynamic and flexible adaptation**: Since adapter modules can be added any number of times, a single shared \"core\" model can have multiple adapters that are enabled/disabled dynamically to adapt to numerous scenarios. This potentially offers the case where a single \"core\" model is shared across multiple users, and each user has a small, personal adapter module used for personalization.  "
      ],
      "metadata": {
        "id": "YGn1__-Jv2Bq"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Limitations of Adapters\n",
        "\n",
        "With all those benefits, Adapters have significant drawbacks stemming from how they are currently used.\n",
        "\n",
        "Note that there is ongoing research to overcome such restrictions, which we hope to incorporate eventually.\n",
        "\n",
        "- **Frozen decoder modules**: Since the decoder is frozen to avoid forgetting the past training, it does not learn the semantics of the text from the new domain. This may hamper some models more than others.\n",
        "- **Frozen tokenization/decoding**: A consequence of the frozen decoder is that we cannot change the vocabulary (or tokenizer) of the decoder layer - as this would cause the model to forget its past training entirely. This also means that **adapters cannot be used to train in a different language than the original language**. The text of the new domain must be supported by the original model's tokenizer/decoder.\n",
        "  - **Note**: There is nothing fundamentally wrong with still changing the vocabulary of a model that supports adapters. The benefits of adapters will reduce significantly and require costly training (similar in time and memory to finetuning). The model can no longer recover its performance by disabling all of its adapters.\n",
        "- **Easy to overfit**: Since adapters enable domain adaptation on very small amounts of speech data, it is trivial to rapidly overfit these datasets and significantly degrade performance on the original domain. \n",
        "  - **Note**: This can be overcome with some experimentation, further boosted by the fast experimentation cycle that adapters enable."
      ],
      "metadata": {
        "id": "8d7y1cygv4MP"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Dataset preparation\n",
        "\n",
        "Now that we understand what adapters are and their benefits/drawbacks, we can explore how to set up adapters in NeMo ASR models.\n",
        "\n",
        "-----\n",
        "\n",
        "First, we prepare some datasets that the original model was **not trained on**, making it a new domain to be adapted. \n",
        "\n",
        "In this tutorial, we will be utilizing the `AN4` dataset - also known as the Alphanumeric dataset, which was collected and published by Carnegie Mellon University. We chose this dataset primarily because it is **very small in size** (`<1 hours of training data`), **easy to overfit when training from scratch / fine-tuning by changing the decoder** (`previous tutorials can mostly get around 10-20% WER with fine-tuning without hyperparameter tuning`), and its **text is perfectly supported by the tokenization/decoding scheme of the model**."
      ],
      "metadata": {
        "id": "mtYWTi0irkS6"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "\n",
        "if not os.path.exists(\"scripts/\"):\n",
        "  os.makedirs(\"scripts\")\n",
        "\n",
        "if not os.path.exists(\"scripts/process_an4_data.py\"):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/scripts/dataset_processing/process_an4_data.py"
      ],
      "metadata": {
        "id": "NpKgT6q5-gNk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import wget\n",
        "import tarfile \n",
        "import subprocess \n",
        "import glob\n",
        "\n",
        "data_dir = \"datasets\"\n",
        "\n",
        "if not os.path.exists(data_dir):\n",
        "  os.makedirs(data_dir)\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'  # for the original source, please visit http://www.speech.cs.cmu.edu/databases/an4/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",
        "\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",
        "\n",
        "print(\"Finished conversion.\\n******\")\n",
        "\n",
        "if os.path.exists(f\"{data_dir}/an4\"):\n",
        "  print(\"Preparing AN4 dataset ...\")\n",
        "\n",
        "  an4_path = f\"{data_dir}/\"\n",
        "  !python scripts/process_an4_data.py \\\n",
        "    --data_root=$an4_path\n",
        "\n",
        "print(\"AN4 prepared !\")"
      ],
      "metadata": {
        "id": "0wZZuUDi_gEV"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Manifest filepaths\n",
        "TRAIN_MANIFEST = os.path.join(data_dir, \"an4\", \"train_manifest.json\")\n",
        "TEST_MANIFEST = os.path.join(data_dir, \"an4\", \"test_manifest.json\")"
      ],
      "metadata": {
        "id": "9fiqQeWDAXsH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Prepare the \"base\" model\n",
        "\n",
        "Next, we initialize a small pre-trained model with a relatively small amount of parameters to showcase the efficacy of adapters no matter the original model size.\n",
        "\n",
        "-----\n",
        "\n",
        "Most importantly, we discuss a simple way to enable Adapter specific support to a pre-trained model checkpoint - by modifying the `encoder` config before loading the model."
      ],
      "metadata": {
        "id": "q2nxi5RzAfZ5"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import torch\n",
        "from omegaconf import OmegaConf, open_dict\n",
        "from pytorch_lightning import Trainer\n",
        "\n",
        "import nemo.collections.asr as nemo_asr"
      ],
      "metadata": {
        "id": "F-wt9y5iAali"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "model_name = \"stt_en_conformer_ctc_small\""
      ],
      "metadata": {
        "id": "uVOfU7gsCI5u"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Prepare an Adapter-compatible Encoder\n",
        "\n",
        "The original model was trained without any adapters, and therefore its encoder does not support adapters.\n",
        "\n",
        " To add adapter modules to these models, we perform a few simple steps - \n",
        "\n",
        "- Extract the model config from the \"base\" model.\n",
        "- Update the `encoder` section of the config to a subclass of that model (which does have Adapter support)\n",
        "- Initialize the model with this new config, therefore enabling adapter support."
      ],
      "metadata": {
        "id": "TitUAeq67Hkl"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "- Extract just the config of the model."
      ],
      "metadata": {
        "id": "5V5UY-5c8FDv"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "cfg = nemo_asr.models.ASRModel.from_pretrained(model_name, return_config=True)"
      ],
      "metadata": {
        "id": "RzwLAHVqAqD9"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.core import adapter_mixins\n",
        "\n",
        "# Utility method to check and update the model config\n",
        "def update_model_config_to_support_adapter(model_cfg):\n",
        "    with open_dict(model_cfg):\n",
        "        adapter_metadata = adapter_mixins.get_registered_adapter(model_cfg.encoder._target_)\n",
        "        if adapter_metadata is not None:\n",
        "            model_cfg.encoder._target_ = adapter_metadata.adapter_class_path\n",
        "    \n",
        "    print(\"Updated encoder _target_ model :\", model_cfg.encoder._target_)\n",
        "    return model_cfg"
      ],
      "metadata": {
        "id": "O6xAz38-A_Bh"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "- Update the model config's `encoder` section to support Adapters."
      ],
      "metadata": {
        "id": "TDk2VMXI8OkG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "cfg = update_model_config_to_support_adapter(cfg)"
      ],
      "metadata": {
        "id": "iyp4xUOLBi0v"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "- Finally load the model with the updated config."
      ],
      "metadata": {
        "id": "26NTK00w8VIt"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model = nemo_asr.models.ASRModel.from_pretrained(model_name, override_config_path=cfg)"
      ],
      "metadata": {
        "id": "7r36mkUGBvsy"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Next, we attach a `Trainer` to the model to be appropriately initialized.\n",
        "\n",
        "Note that we select just **300 update steps**, which is approximately just ten epochs over this dataset at batch sizes of 32. You can experiment with different steps to see the effect of overfitting or underfitting.\n",
        "\n",
        "**Recommendation**:\n",
        "\n",
        "You should normally start with 1-5 epochs of adaptation over your entire new domain, and then increase or decrease your number of training steps to trade off a balance in accuracy on general speech."
      ],
      "metadata": {
        "id": "x0C2r7388cRd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
        "max_steps = 300\n",
        "\n",
        "trainer = Trainer(devices=1, accelerator=accelerator, max_steps=max_steps,\n",
        "                  enable_checkpointing=False, logger=False,\n",
        "                  log_every_n_steps=5, check_val_every_n_epoch=3)\n",
        "\n",
        "model.set_trainer(trainer)"
      ],
      "metadata": {
        "id": "sWRUXzjQMWN5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# utility method\n",
        "import json\n",
        "from nemo.collections.asr.parts.utils.manifest_utils import read_manifest\n"
      ],
      "metadata": {
        "id": "tJBriqr3tQV7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## [Optional] Check if the new domain is compatible with the original decoder\n",
        "\n",
        "The following section, while optional, designs a test to ensure that the text of the new domain can be adequately handled by the original decoder/tokenizer of the model. Please open each cell and execute to perform this sanity check.\n",
        "\n",
        "-----\n",
        "\n",
        "If this check fails, the training run might crash, or silently allow the model to learn to produce `⁇` tokens (when using SentencePiece tokenizers)."
      ],
      "metadata": {
        "id": "dm-qqTdZDUlZ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Parse the base character set"
      ],
      "metadata": {
        "id": "UKTiAPV_sdFI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "train_data = read_manifest(TRAIN_MANIFEST)\n",
        "base_sets = [set(list(sample['text'])) for sample in train_data]\n",
        "base_charset = set([])\n",
        "for charset in base_sets:\n",
        "  base_charset.update(charset)\n",
        "base_charset = list(sorted(list(base_charset)))\n",
        "\n",
        "print(\"Base charset :\", base_charset)"
      ],
      "metadata": {
        "id": "WgogR3taD7NA"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Check if there are invalid characters"
      ],
      "metadata": {
        "id": "x-0fzrfPshJj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def check_valid_charset_in_vocab(model, charset):\n",
        "  model_vocab = model.decoder.vocabulary\n",
        "  num_invalid = 0\n",
        "\n",
        "  for char in charset:\n",
        "    if char != ' ' and char not in model_vocab:\n",
        "      print(f\"Character `{char}` does not exist in the base character set of the original model !\")\n",
        "      num_invalid += 1\n",
        "\n",
        "  print(\"Number of invalid tokens :\", num_invalid)"
      ],
      "metadata": {
        "id": "5laUkRf5Eb6l"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "check_valid_charset_in_vocab(model, base_charset)"
      ],
      "metadata": {
        "id": "5rEUqs7AFh5j"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Evaluate original performance on AN4 dev set\n",
        "\n",
        "Now that we possess a model capable of supporting adapters, let us quickly test the performance of the pre-trained model on the AN4 test set without any training or fine-tuning."
      ],
      "metadata": {
        "id": "Sf-2EHznGkI1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "if not os.path.exists('scripts/transcribe_speech.py'):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/transcribe_speech.py\n",
        "\n",
        "if not os.path.exists('scripts/speech_to_text_eval.py'):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/speech_to_text_eval.py"
      ],
      "metadata": {
        "id": "Ak4v4aWjGoQH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# temporarily save current model\n",
        "model.save_to(\"/content/unadapted_model.nemo\")"
      ],
      "metadata": {
        "id": "OVlBKWCiIHw7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "The following evaluation script will properly transcribe the AN4 test set, and score it against its ground truth."
      ],
      "metadata": {
        "id": "r03iDw9k-dAm"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!python scripts/speech_to_text_eval.py \\\n",
        "  model_path=\"/content/unadapted_model.nemo\" \\\n",
        "  dataset_manifest=$TEST_MANIFEST \\\n",
        "  output_filename=\"/content/unadapted_predictions.json\" \\\n",
        "  batch_size=32 \\\n",
        "  use_cer=False"
      ],
      "metadata": {
        "id": "C6YbPt70H0-N"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "------\n",
        "\n",
        "Check the predictions of the current model"
      ],
      "metadata": {
        "id": "2VBQO3w3swu8"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!head -n 5 /content/unadapted_predictions.json"
      ],
      "metadata": {
        "id": "SE8uoRLsJA9F"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Overall, the model does quite well, obtaining roughly 6% Word Error Rate without prior training on this dataset. \n",
        "\n",
        "**Note**: Pre-trained models in NeMo are trained on several thousands of hours of speech, so it is unsurprising why this model is this accurate without any training on this toy dataset. For more realistic cases, we usually observe the range of 10-30% WER for out-of-domain speech."
      ],
      "metadata": {
        "id": "muRBgHHe-n7E"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Setup training and evaluation of the model\n",
        "\n",
        "Now that we have a baseline result, let us set up the data loaders of this model to prepare for training on this dataset.\n",
        "\n",
        "You may note: this step is nearly identical to from scratch training / fine-tuning and skips the tokenizer construction/change vocabulary steps.\n",
        "\n",
        "**Note**: Each model may have special parameters in their data loader. Please refer to the configs of the pre-trained models to determine what additional changes are necessary). Below recommendations are primarily for Conformer CTC and may differ from model to model.\n",
        "\n",
        "You can parse the model config via - `print(OmegaConf.to_yaml(model.cfg))`"
      ],
      "metadata": {
        "id": "b-L3prIzs3CW"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup dataloaders"
      ],
      "metadata": {
        "id": "V2WirN5KJpsD"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "with open_dict(model.cfg):\n",
        "  # Train Dataloader\n",
        "  model.cfg.train_ds.manifest_filepath = TRAIN_MANIFEST\n",
        "  model.cfg.train_ds.batch_size = 32\n",
        "  model.cfg.train_ds.is_tarred = False\n",
        "  model.cfg.train_ds.tarred_audio_filepaths = None\n",
        "\n",
        "  model.cfg.validation_ds.manifest_filepath = TEST_MANIFEST\n",
        "  model.cfg.validation_ds.batch_size = 32\n",
        "\n",
        "model.setup_training_data(model.cfg.train_ds)\n",
        "model.setup_multiple_validation_data(model.cfg.validation_ds)\n",
        "model.setup_multiple_test_data(model.cfg.validation_ds)"
      ],
      "metadata": {
        "id": "F0GIxhyCJmFv"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup Spectrogram Augmentation\n",
        "\n",
        "For this experiment we will continue to use the original spec augmentation config in the base model, however you may find better results by modifying the strength of this augmentation.\n",
        "\n",
        "**Note**: The script inside ASR examples **disables spec augment entirely**. This is done in order to provide a stable default to measure the best possible adaptation case, but may severely degrade the performance on general speech. Please be careful when copying the hyper parameters from the tutorial to the script for large scale experimentatin."
      ],
      "metadata": {
        "id": "T3VuqcGTNuIJ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "with open_dict(model.cfg):\n",
        "  # Spec Augment\n",
        "  model.cfg.spec_augment.freq_masks = model.cfg.spec_augment.freq_masks  # Can be changed\n",
        "  model.cfg.spec_augment.freq_width = model.cfg.spec_augment.freq_width  # Can be changed\n",
        "  model.cfg.spec_augment.time_masks = model.cfg.spec_augment.time_masks  # Can be changed\n",
        "  model.cfg.spec_augment.time_width = model.cfg.spec_augment.time_width  # Can be changed\n",
        "\n",
        "model.spec_augmentation = model.from_config_dict(model.cfg.spec_augment)"
      ],
      "metadata": {
        "id": "T-XFuaA3OlOB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Setup optimizer and scheduler\n",
        "\n",
        "An interesting thing to note for adapters is their rapid convergence speed - they do not require hundreds of thousands of update steps (though that is also possible).\n",
        "\n",
        "For this reason, we have chosen hyperparameter settings that are significantly different from other tutorials - a small learning rate multiplier of 0.1 (for NoamScheduler) and a small warmup phase of just 100 steps (remember, trainer.max_steps is just 300!).\n",
        "\n",
        "Feel free to modify these values to see the effect on adapters' convergence.\n",
        "\n",
        "**Note**: The hyper parameters below correspond to the base model and may not match those applied in the ASR examples! Please note that the script the examples defaults to an **AdamW** optimizer with a **CosineAnnealing** scheduler, where as the config of Conformers is geneally a **AdamW** optimizer with a **NoamAnnealing** scheduler. The *learning rate*, *weight decay* and other hyper parameters may not be exactly the same between the tutorial and the example scripts, so please be careful when transferring the hyper parameters for large scale experiments."
      ],
      "metadata": {
        "id": "xGpdUWl_tGuA"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "if 'optim' in model.cfg:\n",
        "  print(OmegaConf.to_yaml(model.cfg.optim))"
      ],
      "metadata": {
        "id": "UDEIfMTcP6j6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "with open_dict(model.cfg):\n",
        "  model.cfg.optim.lr = 0.1\n",
        "  model.cfg.optim.weight_decay = 0.0\n",
        "  model.cfg.optim.sched.warmup_steps = 100\n",
        "\n",
        "model.setup_optimization(model.cfg.optim);"
      ],
      "metadata": {
        "id": "tp_8FGPcKjMd"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Adapters: Supported Components\n",
        "\n",
        "A NeMo model may have multiple types of adapters that are supported in each of their components. Let us see at a glance what are some of the adapter types supported by the Conformer ASR model.\n",
        "\n",
        "**Note**: Every domain may support their own types of adapters, and use them in different ways. Please refer to the documentation of each domain for information on the adapter support."
      ],
      "metadata": {
        "id": "AGrThAt9Qh0D"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "Let's start with the modules in which the model will support adapters. We can select these adapters with a special syntax to construct \"Module adapters\".\n",
        "\n",
        "**Note**: `''` refers to the \"default\" adapter - usually the `encoder` but it is model dependent. It may also be that no specific modules are provided, in which case only `default` adapters will be available."
      ],
      "metadata": {
        "id": "Wq1JLbNvROcL"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "if hasattr(model, 'adapter_module_names'):\n",
        "  print(model.adapter_module_names)"
      ],
      "metadata": {
        "id": "fRIDhU8RVBwi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "Next, we can try to obtain the accepted types of each of the child modules in the Model."
      ],
      "metadata": {
        "id": "u5BOWWBjfQwN"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "for module in model.children():\n",
        "  if hasattr(module, 'get_accepted_adapter_types'):\n",
        "    types = module.get_accepted_adapter_types()\n",
        "    print(\"Module : \", module.__class__.__name__)\n",
        "\n",
        "    for tp in types:\n",
        "      print(tp)\n",
        "    print()"
      ],
      "metadata": {
        "id": "iNnSp_azQ2u8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "As you can see, a single component of the model may support one or more adapter types (or none at all)! Below, we will experiment with the simple Linear Adapters, but as an excercise, you might try to use other adapter types present here."
      ],
      "metadata": {
        "id": "YXTC4LiSnB2O"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Adapters: Creation and Preparation\n",
        "\n",
        "Now that the data loaders have been prepared, the next step is to add the adapter modules to the model!\n",
        "\n",
        "----\n",
        "\n",
        "We first import a config for a basic `LinearAdapter` most often used in literature. \n",
        "\n",
        "`LinearAdapter` is a simple network comprising LayerNorm, a bottleneck Linear layer, an activation, and an upcast Linear layer (so that input and output channel dim match). We provide some configuration parameters (such as the input dim and the bottleneck dim)."
      ],
      "metadata": {
        "id": "WFCUrYxnGPt3"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.collections.common.parts.adapter_modules import LinearAdapterConfig"
      ],
      "metadata": {
        "id": "oZZr6vSntuyX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#%% [code]\n",
        "#@title Adapter Setup { display-mode: \"form\" }\n",
        "adapter_name = \"AN4\" #@param {type:\"string\"}\n",
        "adapter_dim = 32 #@param {type:\"integer\"}\n",
        "adapter_activation = \"swish\" #@param {type:\"string\"}\n",
        "adapter_norm_position = \"pre\" #@param [\"pre\", \"post\"]"
      ],
      "metadata": {
        "id": "dlj0Yud4MxOi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "adapter_cfg = LinearAdapterConfig(\n",
        "    in_features=model.cfg.encoder.d_model,  # conformer specific model dim. Every layer emits this dim at its output.\n",
        "    dim=adapter_dim,  # the bottleneck dimension of the adapter\n",
        "    activation=adapter_activation,  # activation used in bottleneck block\n",
        "    norm_position=adapter_norm_position,  # whether to use LayerNorm at the beginning or the end of the adapter\n",
        ")\n",
        "print(adapter_cfg)"
      ],
      "metadata": {
        "id": "Uv8WRQkXU3mu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Add a new adapter module\n",
        "\n",
        "Now that our adapter config is ready. Next, we perform a check to see what is the size of the original model and what its size will be after adding the adapter module."
      ],
      "metadata": {
        "id": "pIECyKxit58r"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.summarize()"
      ],
      "metadata": {
        "id": "-MbSTbYiYtnB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Next, we use `add_adapter` to add adapter blocks to the `encoder`.\n",
        "\n",
        "A single line can be used to add adapter modules to every layer of the `encoder` module. We pass it a unique name to identify this adapter and the adapter config (which can be helpful to enable or disable adapters later)."
      ],
      "metadata": {
        "id": "vjYmPbwCC0LZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.add_adapter(name=adapter_name, cfg=adapter_cfg)"
      ],
      "metadata": {
        "id": "El6ewd1GX9V7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "As expected, the number of parameters increased by a marginal amount (roughly 200,000 parameters)."
      ],
      "metadata": {
        "id": "jMsmj1W-DTSd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.summarize()"
      ],
      "metadata": {
        "id": "rIvw0_8iYpHW"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Enable / Disable Adapters\n",
        "\n",
        "Now that we have adapter modules, we can enable or disable them as we require. \n",
        "\n",
        "For this purpose, we utilize the `model.set_enabled_adapters` method - it takes an optional `name` and a boolean value for `enabled`. If a name is not passed, it will set enable/disable all available adapters.\n",
        "\n",
        "**Note**: We recommend training one adapter at a time, disjoint from all other adapters. As such, it simplifies the selection of adapters for each particular domain. To do so - **disable all adapters first, then enable only the newly added adapter**."
      ],
      "metadata": {
        "id": "RH6cXPW2ZHdZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.set_enabled_adapters(enabled=False)  # disable all adapters\n",
        "model.set_enabled_adapters(name=adapter_name, enabled=True)  # enable only the current adapter we want to train"
      ],
      "metadata": {
        "id": "ogUfDkjdZKHu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Training only the adapter(s)\n",
        "\n",
        "Now that we have enabled just the adapter we wish to adapt onto AN4 dataset, we must freeze all the other parameters of the network and train just the adapters.\n",
        "\n",
        "We provide the general utility methods for this purpose - `model.freeze()` and `model.unfreeze_enabled_adapters()`. \n",
        "\n",
        "The second method will look up all the enabled adapters selected in the previous step and enable their gradient calculation so that they can be trained."
      ],
      "metadata": {
        "id": "V87SBzdDY1x1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.freeze()\n",
        "model.unfreeze_enabled_adapters()"
      ],
      "metadata": {
        "id": "RN2YayAoYzaI"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Why are BatchNormalization layers being frozen?\n",
        "\n",
        "A side-note here regarding BatchNormalization - even when the model is frozen, while no gradient updates will occur to the beta and gamma parameters, **the moving averages of each batch norm layer continue to update**!\n",
        "\n",
        "Such updates cause a severe issue when we disable all the adapters - while technically, no parameters of the original model were updated since the moving averages of BatchNormalization were updated. You will have degraded performance on the original domain (even with all adapters disabled !).\n",
        "\n",
        "-----\n",
        "\n",
        "For this reason, `unfreeze_enabled_adapters()` has an argument `freeze_batchnorm=True` as the default. It will find all the batch normalization layers and disable this flag so that it will the encoder layers remain exactly frozen even during adapter finetuning. This allows the original model performance to be recovered.\n",
        "\n"
      ],
      "metadata": {
        "id": "5PriDOuwEbmp"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.summarize()"
      ],
      "metadata": {
        "id": "Lf3pdwQ2Zch5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "Here we see that after the above steps, we will be training just ~ 200,000 parameters out of a 10+ M parameter model."
      ],
      "metadata": {
        "id": "JI6C_TYGGgyZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Prepare NeMo's Experiment manager to handle checkpoint saving and logging for us\n",
        "from nemo.utils import exp_manager\n",
        "\n",
        "# Environment variable generally used for multi-node multi-gpu training.\n",
        "# In notebook environments, this flag is unnecessary and can cause logs of multiple training runs to overwrite each other.\n",
        "os.environ.pop('NEMO_EXPM_VERSION', None)\n",
        "\n",
        "exp_config = exp_manager.ExpManagerConfig(\n",
        "    exp_dir=f'experiments/',\n",
        "    name=f\"ASR-Adapters\",\n",
        "    checkpoint_callback_params=exp_manager.CallbackParams(\n",
        "        monitor=\"val_wer\",\n",
        "        mode=\"min\",\n",
        "        always_save_nemo=True,\n",
        "        save_best_model=True,\n",
        "    ),\n",
        ")\n",
        "\n",
        "exp_config = OmegaConf.structured(exp_config)\n",
        "\n",
        "logdir = exp_manager.exp_manager(trainer, exp_config)"
      ],
      "metadata": {
        "id": "w9ciIw-2bSHq"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Finally, train the adapters\n",
        "trainer.fit(model)"
      ],
      "metadata": {
        "id": "cY2TJod3ZfyE"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "After training, save the final checkpoint to a nemo file to evaluate. We also save just the adapter module itself, as that is much smaller than the size of the full model."
      ],
      "metadata": {
        "id": "A82ylXSZuL1T"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.save_to(\"/content/adapted_model.nemo\")"
      ],
      "metadata": {
        "id": "7tDdE9lZbvhJ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "model.save_adapters('/content/adapter_modules.pt')"
      ],
      "metadata": {
        "id": "L9yO-M-oL3Cy"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Evaluate the adapted model\n",
        "\n",
        "Now that we have finished the adaptation step and saved a trained NeMo file, we can evaluate the accuracy of our adapted model on the test set of AN4."
      ],
      "metadata": {
        "id": "Ak9v58RmdNJT"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Evaluate the adapter-enabled model"
      ],
      "metadata": {
        "id": "r-rjNJAvuZxu"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!python scripts/speech_to_text_eval.py \\\n",
        "  model_path=\"/content/adapted_model.nemo\" \\\n",
        "  dataset_manifest=$TEST_MANIFEST \\\n",
        "  output_filename=\"/content/adapted_predictions.json\" \\\n",
        "  batch_size=32 \\\n",
        "  use_cer=False"
      ],
      "metadata": {
        "id": "_Ps6_45mdJpM"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "-----\n",
        "\n",
        "We could significantly improve the accuracy of this model on the AN4 dataset with a very short training schedule with a small number of parameters. \n",
        "\n",
        "**Note**: Since AN4 is a relatively simple dataset, the gains are very large in this example. We generally observe more modest improvements with such short training schedules on realistic datasets (but gains of this range are easily attainable with more data or precise training schedules to avoid overfitting)."
      ],
      "metadata": {
        "id": "MegsAIcQG5MJ"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Let us compare the adapted model's predictions below - "
      ],
      "metadata": {
        "id": "T6c_p530wMwG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"Original\")\n",
        "!head -n 5 /content/unadapted_predictions.json\n",
        "print(\"Adapted\")\n",
        "!head -n 5 /content/adapted_predictions.json"
      ],
      "metadata": {
        "id": "vlK3PdMhtlv1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Evaluate the adapter-disabled model\n",
        "\n",
        "Now, let us disable the adapters and recover the original performance of the model. We do this as a sanity test, to check that indeed the \"base\" model is still intact, even if adapter training has occurred."
      ],
      "metadata": {
        "id": "CCkH10jqd4q1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.set_enabled_adapters(enabled=False)\n",
        "model.save_to(\"/content/adapter_disabled_model.nemo\")"
      ],
      "metadata": {
        "id": "1R6wHGgRdRKX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "!python scripts/speech_to_text_eval.py \\\n",
        "  model_path=\"/content/adapter_disabled_model.nemo\" \\\n",
        "  dataset_manifest=$TEST_MANIFEST \\\n",
        "  output_filename=\"/content/adapter_disabled_predictions.json\" \\\n",
        "  batch_size=32 \\\n",
        "  use_cer=False"
      ],
      "metadata": {
        "id": "IhGLtRwdeGRf"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# [EXTRA] Check that accuracy can be recovered after adaptation\n",
        "\n",
        "This is a more explicit test than simply checking the WER above - here we do sample by sample check to ensure that predicted text remains the same."
      ],
      "metadata": {
        "id": "GGKgsW5gvAuf"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "original_transcripts = read_manifest('/content/unadapted_predictions.json')\n",
        "adapter_disabled_transcripts = read_manifest('/content/adapter_disabled_predictions.json')\n",
        "\n",
        "for orig, new in zip(original_transcripts, adapter_disabled_transcripts):\n",
        "  match = orig['pred_text'] == new['pred_text']\n",
        "  if not match:\n",
        "    print(\"Sample did not match after disabling adapter !\")\n",
        "    print(\"Original = \", orig['pred_text'])\n",
        "    print(\"Adapters disabled = \", new['pred_text']) \n",
        "    print()"
      ],
      "metadata": {
        "id": "YFKN7QYuvBzP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# [EXTRA] Add as many adapters as needed\n",
        "\n",
        "Now that we have showcased how to utilize adapters for domain adaptation, we can take this further and adapt even more datasets - as many as needed!\n",
        "\n",
        "There is no implicit restriction on how many adapters can be added, as shown below. Still, we do recommend freezing all adapters and training only one at a time to prevent cross-interaction between adapters."
      ],
      "metadata": {
        "id": "0CqpJGR6ecYW"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.add_adapter(name=\"AN4-v2\", cfg=adapter_cfg)"
      ],
      "metadata": {
        "id": "13vZHFFEeK_g"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "model.set_enabled_adapters(enabled=False)\n",
        "model.set_enabled_adapters(name='AN4-v2', enabled=True)\n",
        "\n",
        "model.freeze()\n",
        "model.unfreeze_enabled_adapters()\n",
        "\n",
        "model.summarize()"
      ],
      "metadata": {
        "id": "iOrJ72SUelp6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Further reading\n",
        "\n",
        "For efficient scripts to add, train, and evaluate adapter augmented models, please refer to the [Adapters example section](https://github.com/NVIDIA/NeMo/tree/main/examples/asr/asr_adapters).\n",
        "\n",
        "Please follow the following articles that discuss the use of adapters in ASR - \n",
        "- [Exploiting Adapters for Cross-lingual Low-resource Speech Recognition](https://arxiv.org/abs/2105.11905)\n",
        "- [Efficient Adapter Transfer of Self-Supervised Speech Models for Automatic Speech Recognition](https://arxiv.org/abs/2202.03218)\n"
      ],
      "metadata": {
        "id": "EIli6c_OvKDH"
      }
    }
  ]
}