File size: 66,743 Bytes
0558aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "11BEbhRng15X"
      },
      "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",
        "\n",
        "NOTE: User is responsible for checking the content of datasets and the applicable licenses and determining if suitable for the intended use.\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell to install dependencies\n",
        "\n",
        "\n",
        "# Install dependencies\n",
        "!pip install wget\n",
        "!apt-get update && apt-get install -y sox libsndfile1 ffmpeg\n",
        "!pip install text-unidecode\n",
        "!pip install omegaconf\n",
        "\n",
        "BRANCH='main'\n",
        "\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@{BRANCH}#egg=nemo_toolkit[asr]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ne4_FHPaoVyq"
      },
      "outputs": [],
      "source": [
        "# import libraries\n",
        "\n",
        "import glob\n",
        "import json\n",
        "import librosa\n",
        "import numpy as np\n",
        "from omegaconf import OmegaConf, open_dict\n",
        "import os\n",
        "import soundfile as sf\n",
        "import subprocess\n",
        "import tarfile\n",
        "import tqdm\n",
        "import wget\n",
        "import re\n",
        "\n",
        "import torch"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y0fqj-DkEU2y"
      },
      "source": [
        "# Introduction to Canary models\n",
        "Canary is a family of multilingual, multitask speech-to-text models based on the attention encoder-decoder (AED) architecture. All Canary models use a FastConformer encoder and Transformer decoder. The current lineup includes `canary-1b-v2`, `canary-1b`, `canary-1b-flash`, and `canary-180m-flash`.\n",
        "\n",
        "`canary-1b-v2` is the latest and most comprehensive model, supporting speech recognition for 25 European languages, as well as translation between English and these languages (En<->X). It introduces new features such as parallel chunking and full timestamp prediction across all supported languages.\n",
        "\n",
        "`canary-1b-flash` (883M parameters) and canary-180m-flash (182M parameters) are optimized for speed and efficiency. These models support speech recognition in English, German, French, and Spanish, as well as translation between English and German/French/Spanish (in both directions). They also offer output with or without punctuation and capitalization (PnC), and support word-level timestamp prediction for all four languages. The canary-1b-flash model achieves faster and more accurate results than `canary-1b` by increasing the encoder size and reducing the decoder size, improving speed while maintaining comparable model capacity.\n",
        "In this tutorial, we will focus primarily on the Canary-1b-v2 model.\n",
        "Refer to the following resources for more details:\n",
        "\n",
        "🤗[canary-1b-v2](https://huggingface.co/nvidia/canary-1b-v2)\n",
        "\n",
        "🤗[canary-1b](https://huggingface.co/nvidia/canary-1b)\n",
        "\n",
        "🤗[canary-1b-flash](https://huggingface.co/nvidia/canary-1b-flash)\n",
        "\n",
        "🤗[canary-180m-flash](https://huggingface.co/nvidia/canary-180m-flash)\n",
        "\n",
        "[Canary-1B paper](https://arxiv.org/abs/2406.19674)\n",
        "\n",
        "[Canary-1B-flash paper](https://arxiv.org/abs/2503.05931)\n",
        "\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8itHPnZO5ATe"
      },
      "source": [
        "## Components of Canary architecture\n",
        "\n",
        "### Model architecture\n",
        "\n",
        "The input audio is converted into 128-dim log-mel features extracted for 25ms window with a stride of 10ms. The spectrogram features are then processed through the encoder. The decoder conditions on the encoder output and decoder prompt to autoregressively generate one token at a time.\n",
        "\n",
        "<img src=\"images/promptformat.png\" width=\"750\" height=\"400\">\n",
        "\n",
        "### Decoder prompt\n",
        "\n",
        "Decoder prompt is the key to attaining multitask capability with Canary models. Decoder prompt is a sequence of special tokens that define the precise task (language output text, punctuations, timestamps, etc.) to be performed on the input audio.\n",
        "As shown in the figure, the decoder takes a sequence of prompt tokens as input before generating output text. The example prompt sequence corresponds to English speech recognition as the language for input audio and output text is set to English. The format of the decoder prompt is defined by `TEMPLATE[\"user\"][\"template\"]` in the [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py).\n",
        "\n",
        "\n",
        "### Tokenizers\n",
        "<img src=\"images/tokenizer.png\" width=\"600\" height=\"400\">\n",
        "\n",
        "\n",
        "For Canary-1b-v2, we use a unified SentencePiece [tokenizer](https://github.com/NVIDIA/NeMo/blob/main/scripts/tokenizers/process_asr_text_tokenizer.py).\n",
        "\n",
        "For all other Canary models, we use the concatenated [tokenizer](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/tokenizers/canary_tokenizer.py), which combines language-specific SentencePiece tokenizers with shared special tokens. Each language uses a vocabulary of 1024 subword tokens, and these per-language vocabularies are concatenated together as shown in the figure below.\n",
        "\n",
        "In addition to language-specific tokens, Canary uses 1152 tokens to represent special tokens. Special tokens include generic tokens such as `<|startoftranscript|>`, `<|endoftext|>`, `<pad>`, as well as many other task-specific tokens.\n",
        "Listed below is a variety of special tokens that the default tokenizer includes. This should give an idea of various tasks that can be supported with the current tokenizer and prompt formatter.\n",
        "\n",
        "* Task-specific tokens; these provide a control for tasks and output characteristics, such as decoding with or without punctuations and capitalizations (`<|pnc|>` or `<|nopnc|>`), timestamp prediction (`<|timestamp|>` or `<|notimestamp|>`), emotion recognition (`<|emo:undefined|>`, `<|emo:neutral|>`, `<|emo:happy|>`, `<|emo:sad|>`, `<|emo:angry|>`).\n",
        "* Language identity tokens; the default `spl_tokens` tokenizer supports 184 language IDs, including an `<|unklang|>` token. Language identity tokens are used to encode `source_lang`, `target_lang` fields in the manifest.\n",
        "* Integer tokens; timestamp prediction uses integer values, between `0` and `899` to denote frame numbers corresponding to word start and word end.\n",
        "* Speaker ID tokens; although current Canary-flash models are not trained for speaker identity, the default tokenizer includes 16 speaker ID tokens, `<|spk0|> ... <|spk15|>`.\n",
        "* Additional tokens; the default tokenizer incldes 30 additional tokens, `<|spltoken0|> ... <|spltoken29|>`, not assigned to any perform any particular function. The user can use one of these to represent a custom behavior."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PJczuX9PKI8O"
      },
      "source": [
        "\n",
        "# Outline\n",
        "\n",
        "The tutorial is divided into four sections.\n",
        "\n",
        "First, we see how to perform inference using Canary models, specifically speech recognition, translation, and timestamp prediction.\n",
        "\n",
        "Then we learn how to train a Canary model in two ways -- from scratch and from an initial checkpoint. We will train a model for English speech recognition.\n",
        "\n",
        "Next, we look deeper into various use cases for Canary model with detailed guidelines on how to use Canary-style training for various tasks.\n",
        "\n",
        "Finally, we share some practitioner's tips from our experience working with Canary models."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FbYgKwsi3zuH"
      },
      "source": [
        "# Download LibriLight data\n",
        "We download LibriLight data so we can run inference on audio samples. We'll later use the small 1 hour split for training a custom Canary model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yyAZeHHxdwo1"
      },
      "outputs": [],
      "source": [
        "def download_and_prepare_librilight_data(data_dir=\"datasets\"):\n",
        "    if not os.path.exists(data_dir):\n",
        "        os.makedirs(data_dir)\n",
        "\n",
        "    libri_data_dir = os.path.join(data_dir, 'LibriLight')\n",
        "    libri_tgz_file = f'{data_dir}/librispeech_finetuning.tgz'\n",
        "\n",
        "    if not os.path.exists(libri_tgz_file):\n",
        "        url = \"https://dl.fbaipublicfiles.com/librilight/data/librispeech_finetuning.tgz\"\n",
        "        libri_path = wget.download(url, data_dir, bar=None)\n",
        "        print(f\"Dataset downloaded at: {libri_path}\")\n",
        "\n",
        "    if not os.path.exists(libri_data_dir):\n",
        "        tar = tarfile.open(libri_tgz_file)\n",
        "        tar.extractall(path=libri_data_dir)\n",
        "\n",
        "    print(f'LibriLight data is ready at {libri_data_dir}')\n",
        "\n",
        "download_and_prepare_librilight_data()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eq2NmXaJBtHv"
      },
      "source": [
        "# Inference with Canary-1b-v2 model\n",
        "\n",
        "We run inference on a sample audio files, both short and long, to demonstrate the various capabilities supported by the released Canary-1b-v2 checkpoints.\n",
        "\n",
        "Canary inference uses the `trancribe` method of `EncDecMultiTaskModel`.\n",
        "The user can control the task and language for the inference using specific arguments to `transcribe`. These arguments control the prompt token sequence passed as an input to the decoder (decoder prompt is discussed in more detail in the next section).\n",
        "\n",
        "See examples below for using `transcribe` to perform various tasks."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "O1SXLoY_4VXi"
      },
      "outputs": [],
      "source": [
        "from pydub import AudioSegment\n",
        "from IPython.display import Audio, display\n",
        "\n",
        "def listen_to_audio(audio_path, offset=0.0, duration=-1):\n",
        "    audio = AudioSegment.from_file(audio_path)\n",
        "    start_ms = int(offset * 1000)\n",
        "    if duration == -1:\n",
        "        end_ms = -1\n",
        "    else:\n",
        "        end_ms = int((offset+duration) * 1000)\n",
        "\n",
        "    segment = audio[start_ms:end_ms]\n",
        "    audio = Audio(segment.export(format='wav').read())\n",
        "    display(audio)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DQnHNwq1NayC"
      },
      "source": [
        "## Load model\n",
        "\n",
        "Load the model of your choice.\n",
        "\n",
        "We use `canary-1b-v2` in these inference examples.\n",
        "\n",
        "If testing a local checkpoint, use the following code snippet in place of the one below:\n",
        "```\n",
        "canary_model = EncDecMultiTaskModel.restore_from(\n",
        "        restore_path=ckpt_path,\n",
        "        map_location=map_location,\n",
        "    )\n",
        "```\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "gQSiM4RI4cSj"
      },
      "outputs": [],
      "source": [
        "from nemo.collections.asr.models import EncDecMultiTaskModel\n",
        "map_location = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
        "canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-1b-v2', map_location=map_location)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ijJeUpYj7DEd"
      },
      "source": [
        "## Speech-to-text recognition\n",
        "\n",
        "Here we pass the `source_lang` (language of audio input) and `target_lang` (language of recognized text) as `en`. Thus, this performs english speech recognition.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9DFBI4Ag7NT3"
      },
      "outputs": [],
      "source": [
        "audio_path = \"datasets/LibriLight/librispeech_finetuning/1h/0/clean/3526/175658/3526-175658-0000.flac\"\n",
        "listen_to_audio(audio_path)\n",
        "\n",
        "# To transcribe in a particular language; this example is for English, but will work for each of 25 supported languages\n",
        "transcript = canary_model.transcribe(\n",
        "  audio=[audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\t# en: English, es: Spanish, fr: French, de: German\n",
        "  target_lang='en',\t# should be same as \"source_lang\" for 'asr'\n",
        ")\n",
        "print(\"\\n\\nEnglish speech recognition:\")\n",
        "print(f'  \\\"{transcript[0].text}\\\"')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LufezWfD4Xj0"
      },
      "source": [
        "## Speech-to-text translation\n",
        "\n",
        "Here we pass the `source_lang` (language of audio input) as `en` and `target_lang` (language of transcription text) as `es`. Thus, this performs English to Spanish speech-to-text translation."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qo_kC4RA7pkR"
      },
      "outputs": [],
      "source": [
        "transcript = canary_model.transcribe(\n",
        "  audio=[audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\t# en: English, es: Spanish, fr: French, de: German\n",
        "  target_lang='es',\t# should be same as \"source_lang\" for 'asr'\n",
        ")\n",
        "print(\"\\n\\nSpeech to text translation form English to Spanish with punctuations and capitalizations:\")\n",
        "print(f'  \\\"{transcript[0].text}\\\"')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Timestamp Generation Workflow\n",
        "\n",
        "Currently timestamps generation for `canary-1b-v2` is done via 3 steps\n",
        "\n",
        "1. The audio is passed through the Canary v2 model, which is an AED (Attention Encoder-Decoder) multi-task model. The output is a token sequence produced by the decoder of the model.\n",
        "\n",
        "2. The same audio is passed through the Multi-lingual Parakeet CTC model. From this model, we obtain the log-probabilities matrix produced by the CTC decoder of the Parakeet model. \n",
        "    This matrix represents the (log) probability of every possible token for each time frame (80ms time windows for the given models).\n",
        "\n",
        "3. Viterbi Decoding: Given the token sequence (from Canary v2) and the log-probability matrix (from multilingual Parakeet CTC), we perform Viterbi Decoding. The goal is to find the most likely sequence of predicted tokens aligned over time frames.\n",
        "\n",
        "<img src=\"images/canary2_timestamps.png\" width=\"1000\" height=\"400\">"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CG2mE4HP7rw0"
      },
      "source": [
        "\n",
        "## Timestamp prediction\n",
        "\n",
        "Timestamp prediction is supported for all langauges and can be performed with timestamp prediction by passing `timestamps=True` argument."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LXsCFuevmfEm"
      },
      "outputs": [],
      "source": [
        "# To recognize with timestamps\n",
        "transcript = canary_model.transcribe(\n",
        "  audio=[audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\t# en: English or other supported language\n",
        "  target_lang='en',\t# should be same as \"source_lang\" for 'asr'\n",
        "  timestamps=True\n",
        ")\n",
        "print(\"\\n\\nEnglish speech to text recognition with timestamp prediction:\\n\")\n",
        "\n",
        "print(f'Predicted output: \\n\"{transcript[0].text}\\\"')\n",
        "\n",
        "print('\\nSegment level timestamps:')\n",
        "for sample in transcript[0].timestamp['segment']:\n",
        "    segment, start, end = sample['segment'], sample['start'], sample['end']\n",
        "    print(f'{segment}')\n",
        "    print(f'Segment start: {start:.2f}s')\n",
        "    print(f'Segment end: {end:.2f}s\\n')\n",
        "\n",
        "print('\\nWord level timestamps:')\n",
        "for sample in transcript[0].timestamp['word']:\n",
        "    word, start, end = sample['word'], sample['start'], sample['end']\n",
        "    print(f'{word:<15}[{start:.2f}s, {end:.2f}s]')\n",
        "    # listen_to_audio(audio_path, offset=start, duration=(end-start)) # uncomment to listen to word segments"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Mo_yDJKGijH8"
      },
      "source": [
        "## Inference with longform input\n",
        "\n",
        "Canary models natively handle inputs up to ~40 seconds. For longer audio, the input is split into 30–40 s chunks (minimizing padding on the final chunk) and processed in parallel.\n",
        "\n",
        "For recordings longer than one hour, processing occurs in consecutive hour‑long segments.\n",
        "\n",
        "Outputs are seamlessly stitched to produce a single, continuous result.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x4JGVDt5AnZz"
      },
      "source": [
        "### Create a longform audio sample\n",
        "\n",
        "\n",
        "As LibriLight does not have a long duration audio, we'll first create one by stitching together all utterances from a story.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nSw6pW3ktC89"
      },
      "outputs": [],
      "source": [
        "# Creating a longform audio sample\n",
        "\n",
        "def get_longform_audio_sample(data_dir=\"datasets\"):\n",
        "    libri_data_dir = os.path.join(data_dir, 'LibriLight')\n",
        "    audio_paths = glob.glob(os.path.join(libri_data_dir, 'librispeech_finetuning/1h/0/clean/3526/175658/3526-175658-*.flac'))\n",
        "    audio_paths.sort() # sort by the utterance IDs\n",
        "    write_path = os.path.join(libri_data_dir, 'longform','-'.join(os.path.basename(audio_paths[0]).split('-')[:2])+'.wav')\n",
        "    os.makedirs(os.path.dirname(write_path), exist_ok=True)\n",
        "    longform_audio_data = []\n",
        "    for audio_path in audio_paths:\n",
        "        data, sr = librosa.load(audio_path, sr=16000)\n",
        "        longform_audio_data.extend(data)\n",
        "    sf.write(write_path, longform_audio_data, sr)\n",
        "    minutes, seconds = divmod(len(longform_audio_data)/sr, 60)\n",
        "    print(f'{int(minutes)} min {int(seconds)} sec audio file saved at {write_path}')\n",
        "    return write_path\n",
        "\n",
        "longform_audio_path = get_longform_audio_sample()\n",
        "listen_to_audio(longform_audio_path)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RhsrobUmAsUe"
      },
      "source": [
        "### Longform inference without timestamps\n",
        "\n",
        "`.transcribe()` will perform inference on the long audio file `datasets/LibriLight/longform/3526-175658.wav`, which is currently just the one file that we created above. Alternatively you can also pass a path to a manifest file. We will discuss manifest creation in the the next section.."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "0zT_Aiw5Ax6U"
      },
      "outputs": [],
      "source": [
        "transcript = canary_model.transcribe(\n",
        "  audio=[longform_audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\n",
        "  target_lang='en',\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SfIXyW6vA1mH"
      },
      "outputs": [],
      "source": [
        "def print_sentences_per_item(items):\n",
        "    for i, item in enumerate(items, 1):\n",
        "        text = item.text if hasattr(item, \"text\") else str(item)\n",
        "        sentences = [s.strip() for s in re.split(r'(?<=[.!?])\\s+', text) if s.strip()]\n",
        "        print(f\"--- Audio {i} ---\")\n",
        "        for s in sentences:\n",
        "            print(s if s[-1] in \".!?\" else s + \".\")\n",
        "        print()\n",
        "print_sentences_per_item(transcript)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rw-OQmQ5AvMh"
      },
      "source": [
        "### Longform inference with timestamps\n",
        "\n",
        "We run the same command as above with `timestamps=True`. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "saSBnOJuA34-"
      },
      "outputs": [],
      "source": [
        "transcript = canary_model.transcribe(\n",
        "  audio=[longform_audio_path],\n",
        "  batch_size=1,\n",
        "  source_lang='en',\n",
        "  target_lang='en',\n",
        "  timestamps=True,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qd0cDiibA633"
      },
      "outputs": [],
      "source": [
        "print('\\nWord level timestamps:')\n",
        "for sample in transcript[0].timestamp['word']:\n",
        "    word, start, end = sample['word'], sample['start'], sample['end']\n",
        "    print(f'{word:<15}[{start:.2f}s, {end:.2f}s]')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6c28bgnN9M8g"
      },
      "source": [
        "# Train a Canary model on custom data\n",
        "\n",
        "Now we will see how to train a Canary model on a custom data. Later we discuss how we can incorporate more languages and tasks.\n",
        "\n",
        "In this example we'll see two ways to train a Canary model on a 1 hour split of the LibriLight data:\n",
        "\n",
        "1. A small, 2-layer encoder, 2-layer decoder, version of the model trained from scratch.\n",
        "\n",
        "2. A 180M model initialized from `canary-180m-flash`.\n",
        "\n",
        "Different components needed for training are passed as an yaml config file to the training script.\n",
        "\n",
        "Next, we'll prepare the following components required to set up the training,\n",
        "\n",
        "```\n",
        "model.train_ds.manifest_filepath=$MANIFEST_PATH \\\n",
        "model.tokenizer.langs.en.dir=\"$LANG_TOKENIZER_DIR\" \\\n",
        "model.tokenizer.langs.spl_tokens.dir=\"$SPL_TOKENIZER_DIR\" \\\n",
        "model.prompt_format=\"canary2\" \\\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash', map_location=map_location)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yXAj7KHP2mW7"
      },
      "source": [
        "## Prepare manifest\n",
        "\n",
        "We'll build manifest from 1 hour split of LibriLight data. The manifest file has a dictionary corresponding to each training sample, something like this:\n",
        "```\n",
        "manifest_sample = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": transcript,\n",
        "    \"target_lang\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"pnc\": \"False\"\n",
        "}\n",
        "```\n",
        "\n",
        "The prepared manifest file will be saved at `datasets/LibriLight/train_manifest.json`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "p29r_HSxcwYe"
      },
      "outputs": [],
      "source": [
        "def build_manifest(data_root, manifest_path):\n",
        "    transcript_list = glob.glob(os.path.join(data_root, 'LibriLight/librispeech_finetuning/1h/**/*.txt'), recursive=True)\n",
        "    tot_duration = 0\n",
        "    with open(manifest_path, 'w') as fout:\n",
        "        pass # make sure a new file is created\n",
        "    for transcript_path in tqdm.tqdm(transcript_list):\n",
        "        with open(transcript_path, 'r') as fin:\n",
        "            wav_dir = os.path.dirname(transcript_path)\n",
        "            with open(manifest_path, 'a') as fout:\n",
        "                for line in fin:\n",
        "                    # Lines look like this:\n",
        "                    # fileID transcript\n",
        "                    file_id = line.strip().split(' ')[0]\n",
        "                    audio_path = os.path.join(wav_dir, f'{file_id}.flac')\n",
        "\n",
        "                    transcript = ' '.join(line.strip().split(' ')[1:]).lower()\n",
        "                    transcript = transcript.strip()\n",
        "\n",
        "                    duration = librosa.core.get_duration(path=audio_path)\n",
        "                    tot_duration += duration\n",
        "                    # Write the metadata to the manifest\n",
        "                    metadata = {\n",
        "                      \"audio_filepath\": audio_path,\n",
        "                      \"duration\": duration,\n",
        "                      \"text\": transcript,\n",
        "                      \"lang\": \"en\",\n",
        "                      \"target_lang\": \"en\",\n",
        "                      \"source_lang\": \"en\",\n",
        "                      \"pnc\": \"False\"\n",
        "                    }\n",
        "                    json.dump(metadata, fout)\n",
        "                    fout.write('\\n')\n",
        "    print(f'\\n{np.round(tot_duration/3600)} hour audio data ready for training')\n",
        "\n",
        "data_dir = \"datasets\"\n",
        "train_manifest = os.path.join(data_dir, 'LibriLight/train_manifest.json')\n",
        "build_manifest(data_dir, train_manifest)\n",
        "print(f\"LibriLight train manifests created at {train_manifest}.\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "czGyTkb_8gKy"
      },
      "source": [
        "## Build tokenizer\n",
        "\n",
        "\n",
        "As described in the introduction, we now build a tokenizer for special tokens and for English text from the training data.\n",
        "\n",
        "**Note** that you do not need to train a new tokenizer if you are initializing from Canary-flash models for a task and language that the default tokenizers already support. At the end of this tutorial we discuss some cases where you'd want to retrain the tokenizer and reinitialize the token embeddings."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BWJu6aat8l_j"
      },
      "source": [
        "### Build tokenizer for special *tokens*\n",
        "\n",
        "The tokenizer will be saved at `tokenizers/spl_tokens`. See `tokenizers/spl_tokens/tokenizer.vocab` for a 1152-unit vocabulary of tokens."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "BRANCH='r2.5.0'\n",
        "def wget_from_nemo(nemo_script_path, local_dir=\"scripts\"):\n",
        "    os.makedirs(local_dir, exist_ok=True)\n",
        "    script_url = f\"https://raw.githubusercontent.com/NVIDIA/NeMo/refs/heads/{BRANCH}/{nemo_script_path}\"\n",
        "    script_path = os.path.basename(nemo_script_path)\n",
        "    if not os.path.exists(f\"{local_dir}/{script_path}\"):\n",
        "        !wget -P {local_dir}/ {script_url}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "MUMjzfht8ffo"
      },
      "outputs": [],
      "source": [
        "wget_from_nemo(\"scripts/speech_recognition/canary/build_canary_2_special_tokenizer.py\")\n",
        "output_dir = \"tokenizers/spl_tokens\"\n",
        "!mkdir -p {output_dir}\n",
        "!python scripts/build_canary_2_special_tokenizer.py {output_dir}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DcfzLk-E9BKO"
      },
      "source": [
        "### Build language-specific tokenizer\n",
        "\n",
        "The tokenizer will be saved at `tokenizers/en_libri1h_1024/tokenizer_spe_bpe_v1024`. See `tokenizer.vocab` for a 1024-unit vocabulary of tokens."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "Brc_4kJpB0_1"
      },
      "outputs": [],
      "source": [
        "wget_from_nemo('scripts/tokenizers/process_asr_text_tokenizer.py')\n",
        "LANG='en'\n",
        "DATA='libri1h'\n",
        "VOCAB_SIZE=1024\n",
        "OUT_DIR = f\"tokenizers/{LANG}_{DATA}_{VOCAB_SIZE}\"\n",
        "manifest_path = os.path.join(data_dir, 'LibriLight', 'train_manifest.json')\n",
        "train_text_path = os.path.join(data_dir, 'LibriLight', 'train_text.lst')\n",
        "with open(manifest_path, \"r\") as f:\n",
        "    data = [json.loads(line.strip()) for line in f.readlines()]\n",
        "with open(train_text_path, \"w\") as f:\n",
        "    for line in data:\n",
        "        f.write(f\"{line['text']}\\n\")\n",
        "\n",
        "!python scripts/process_asr_text_tokenizer.py \\\n",
        "  --data_file={train_text_path} \\\n",
        "  --vocab_size={VOCAB_SIZE} \\\n",
        "  --data_root={OUT_DIR} \\\n",
        "  --tokenizer=\"spe\" \\\n",
        "  --spe_type=bpe \\\n",
        "  --spe_character_coverage=1.0 \\\n",
        "  --no_lower_case \\\n",
        "  --log\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CSPT1tGK6IAL"
      },
      "source": [
        "## Prompt format\n",
        "\n",
        "Canary-flash decoder generates output text conditioned on audio encoder representations and the decoder prompt. As described in the introduction, Canary-Flash models use [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py), and so we set the `prompt_format` accordingly\n",
        "\n",
        "```\n",
        "model.prompt_format=\"canary2\"\n",
        "```\n",
        "\n",
        "For the samples in our training data the decoder prompt will have the following sequence of special tokens,\n",
        "\n",
        "`<|startofcontext|><|startoftranscript|><|emo:undefined|><|en|><|en|><|nopnc|><|noitn|><|notimestamp|><|nodiarize|>`\n",
        "\n",
        "Note that source language and target language are set to `en` for English speech recognition **without** pnc (`<|nopnc|>`), timestamps (`<|notimestamp|>`), emotion recognition (`<|emo:undefined|>`), or diarization (`<|nodiarize|>`)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lwMu74rsGsUa"
      },
      "source": [
        "## Train Canary model from scratch\n",
        "\n",
        "Now we have all the components needed to train. We download a local copy of the training script and the default config. We pass the data and tokenizers we prepared above.\n",
        "\n",
        "The tokenizers are processed as follows with their language IDs as keys.\n",
        "\n",
        "```\n",
        "model:\n",
        "  tokenizer:\n",
        "    langs:\n",
        "      spl_tokens: # special tokens model\n",
        "        dir: \"tokenizers/spl_tokens\"\n",
        "        type: bpe\n",
        "      en: # English tokenizer\n",
        "        dir: \"tokenizers/en_libri1h_1024/tokenizer_spe_bpe_v1024\"\n",
        "        type: bpe\n",
        "```\n",
        "\n",
        "We now train a small Canary model with 2 FastConformer encoder layers and 2 Transformer decoder layers."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GIaZLI4tD8qn"
      },
      "outputs": [],
      "source": [
        "wget_from_nemo('examples/asr/speech_multitask/speech_to_text_aed.py')\n",
        "wget_from_nemo('examples/asr/conf/speech_multitask/fast-conformer_aed.yaml', 'config')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XGnQK_U3_W2d"
      },
      "outputs": [],
      "source": [
        "MANIFEST = os.path.join(\"datasets\", \"LibriLight\", 'train_manifest.json')\n",
        "!HYDRA_FULL_ERROR=1 python scripts/speech_to_text_aed.py \\\n",
        "  --config-path=\"../config\" \\\n",
        "  --config-name=\"fast-conformer_aed.yaml\" \\\n",
        "  name=\"canary-small\" \\\n",
        "  model.prompt_format=\"canary2\" \\\n",
        "  model.train_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.validation_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.test_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.tokenizer.langs.en.dir=\"tokenizers/en_libri1h_1024/tokenizer_spe_bpe_v1024\" \\\n",
        "  model.tokenizer.langs.spl_tokens.dir=\"tokenizers/spl_tokens\" \\\n",
        "  spl_tokens.model_dir=\"tokenizers/spl_tokens\" \\\n",
        "  model.encoder.n_layers=2 \\\n",
        "  model.transf_decoder.config_dict.num_layers=2 \\\n",
        "  exp_manager.exp_dir=\"canary_results\" \\\n",
        "  exp_manager.resume_ignore_no_checkpoint=true \\\n",
        "  trainer.max_steps=10 \\\n",
        "  trainer.log_every_n_steps=1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6F2XDcwwGA7g"
      },
      "source": [
        "## Train Canary model from a Canary flash checkpoint (aka fine-tuning)\n",
        "\n",
        "We will now train a Canary model initialized from the `canary-180m-flash` checkpoint; in effect finetuning the `canary-180m-flash` model. This is the same checkpoint that we used to run sample inference in the previous section.\n",
        "\n",
        "```\n",
        "init_from_pretrained_model: canary-180m-flash\n",
        "```\n",
        "\n",
        "For the sake of simplicity, we will retain the exact same model architecture as `canary-180m-flash`. You can choose to include and exclude certain layers and parameters from the initial checkpoint; we discuss these customizations in the next section."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GXWGI7LyMrd1"
      },
      "source": [
        "### Build config\n",
        "\n",
        "We'll update the base config that we use in the example above and save the new config as `config/canary-180m-flash-finetune`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rD7VXLlnNJD4"
      },
      "outputs": [],
      "source": [
        "# Load canary model if not previously loaded in this notebook instance\n",
        "if 'canary_model' not in locals():\n",
        "    canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash')\n",
        "\n",
        "base_model_cfg = OmegaConf.load(\"config/fast-conformer_aed.yaml\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6Gh1fky8oZ2t"
      },
      "source": [
        "In the training config, we should ensure compatibility with the pre-trained model.\n",
        "\n",
        "1. Set initialization from `canary-180m-flash`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MU1jdmkALyix"
      },
      "outputs": [],
      "source": [
        "base_model_cfg['name'] = 'canary-180m-flash-finetune'\n",
        "base_model_cfg.pop(\"init_from_nemo_model\", None)\n",
        "base_model_cfg['init_from_pretrained_model'] = \"nvidia/canary-180m-flash\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GcDkgzf3MMlk"
      },
      "source": [
        "2. Set path to the tokenizers from the pre-trained model, so as to ensure that the fine-tuning uses a compatible tokenization. The following command reads tokenizers from `canary_model` and saves the files at `canary_flash_tokenizers/{lang}` directories."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8mu5t-Y0GAT5"
      },
      "outputs": [],
      "source": [
        "canary_model.save_tokenizers('./canary_flash_tokenizers/')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "j-Al1IX0NPBG"
      },
      "outputs": [],
      "source": [
        "for lang in os.listdir('canary_flash_tokenizers'):\n",
        "    base_model_cfg['model']['tokenizer']['langs'][lang] = {}\n",
        "    base_model_cfg['model']['tokenizer']['langs'][lang]['dir'] = os.path.join('canary_flash_tokenizers', lang)\n",
        "    base_model_cfg['model']['tokenizer']['langs'][lang]['type'] = 'bpe'\n",
        "base_model_cfg['spl_tokens']['model_dir'] = os.path.join('canary_flash_tokenizers', \"spl_tokens\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-DbxIylkNlIQ"
      },
      "source": [
        "3. Ensure that the prompt format and relevant parameters match."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "I6deg7feN6MZ"
      },
      "outputs": [],
      "source": [
        "base_model_cfg['model']['prompt_format'] = canary_model._cfg['prompt_format']\n",
        "base_model_cfg['model']['prompt_defaults'] = canary_model._cfg['prompt_defaults']"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PS3LRt3jLt7G"
      },
      "source": [
        "4. Ensure that the model architecture matches."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "s4GFt7OGLtZ-"
      },
      "outputs": [],
      "source": [
        "base_model_cfg['model']['model_defaults'] = canary_model._cfg['model_defaults']\n",
        "base_model_cfg['model']['preprocessor'] = canary_model._cfg['preprocessor']\n",
        "base_model_cfg['model']['encoder'] = canary_model._cfg['encoder']\n",
        "base_model_cfg['model']['transf_decoder'] = canary_model._cfg['transf_decoder']\n",
        "base_model_cfg['model']['transf_encoder'] = canary_model._cfg['transf_encoder']"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ItNe8gAmPKki"
      },
      "source": [
        "### Launch training\n",
        "Save config and launch training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_g_vdpioPPEV"
      },
      "outputs": [],
      "source": [
        "cfg = OmegaConf.create(base_model_cfg)\n",
        "with open(\"config/canary-180m-flash-finetune.yaml\", \"w\") as f:\n",
        "    OmegaConf.save(cfg, f)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "t1b7vzJwPfWi"
      },
      "outputs": [],
      "source": [
        "MANIFEST = os.path.join(\"datasets\", \"LibriLight\", 'train_manifest.json')\n",
        "!HYDRA_FULL_ERROR=1 python scripts/speech_to_text_aed.py \\\n",
        "  --config-path=\"../config\" \\\n",
        "  --config-name=\"canary-180m-flash-finetune.yaml\" \\\n",
        "  name=\"canary-180m-flash-finetune\" \\\n",
        "  model.train_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.validation_ds.manifest_filepath={MANIFEST} \\\n",
        "  model.test_ds.manifest_filepath={MANIFEST} \\\n",
        "  exp_manager.exp_dir=\"canary_results\" \\\n",
        "  exp_manager.resume_ignore_no_checkpoint=true \\\n",
        "  trainer.max_steps=10 \\\n",
        "  trainer.log_every_n_steps=1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "J2EPlZHQbnFe"
      },
      "source": [
        "# Guidance for different implementation scenarios\n",
        "\n",
        "You can use the Canary-style training to develop a model for most speech applications. We saw one generic example of training on custom data from scratch on English speech recognition. Here we discuss how to handle several other scenarios.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F-bOiydXbymG"
      },
      "source": [
        "## 1. Speech-to-text recognition and translation\n",
        "\n",
        "When creating the manifest, make sure to pass the appropriate `source_lang` and `target_lang` tokens for each data point.\n",
        "\n",
        "You'll need language-specific tokenizers for each language. You can build the tokenizer as we saw in the previous section.\n",
        "\n",
        "The default `spl_tokens` tokenizer, supports 183 language IDs. If you want to use a language not currently represented, you can rebuild the tokenizer with a new set of `spl_tokens` that includes your language of choice.\n",
        "\n",
        "Finally, in the config add paths to different tokenizers with their language IDs as keys.\n",
        "\n",
        "```\n",
        "model:\n",
        "  tokenizer:\n",
        "    langs:\n",
        "      spl_tokens: # special tokens model\n",
        "        dir: \"tokenizers/spl_tokens\"\n",
        "        type: bpe\n",
        "      en: # English tokenizer (example, replace with whichever language you would like or add tokenizers to add tokenizer for additional languages)\n",
        "        dir: \"tokenizers/spe_bpe_v1024_en\"\n",
        "        type: bpe\n",
        "      de: # German tokenizer (example, replace with whichever language you would like or add tokenizers to add tokenizer for additional languages)\n",
        "        dir: \"tokenizers/spe_bpe_v1024_en\"\n",
        "        type: bpe\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xa1Xg28Mb39_"
      },
      "source": [
        "## 2. Training on a new task: A case of decoding with context\n",
        "\n",
        "This is an example of a capability that is already supported by the current [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py) as well as the tokenizer model.\n",
        "\n",
        "```\n",
        "\"decodercontext\": Modality.Text\n",
        "```\n",
        "\n",
        "During training, you will pass an additional `decodercontext` argument to the samples in the manifest.\n",
        "```\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": transcript,\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"decodercontext\": decoder_context,\n",
        "}\n",
        "```\n",
        "\n",
        "For example, the `decodercontext` can represent past context or certain keywords or topic of the spoken content. The current implementation assumes that `decodercontext` and the output transcript have the same language."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dXVsHDkIb9mS"
      },
      "source": [
        "## 3. Training on a new task: A case of timestamp prediction\n",
        "\n",
        "Canary-Flash models support timestamp prediction. Here, we include how the manifest, prompt formatter, special tokens, and tokenizer functions were modified to add timestamps support for the Canary model.\n",
        "\n",
        "Canary-Flash interleaves word-level timestamps as frame numbers before and after the word. These the frame numbers correspond to the start and end of a word segment. Such \"interleaving\" patterns might be relavant for other tasks as well such as multi-speaker recognition, where you want to interleave speaker ID tokens before appropriate chunks of text tokens spoken by that speaker.\n",
        "\n",
        "Below, we show how a sample in manifest changes with and without timestamps:\n",
        "\n",
        "```\n",
        "# without timestamps\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": \"it's almost beyond conjecture\",\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"timestamp\": \"no\",\n",
        "}\n",
        "```\n",
        "\n",
        "```\n",
        "# with timestamps\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": \"<|3|> it's <|7|> <|8|> almost <|9|> <|14|> beyond <|20|> <|20|> conjecture <|28|>\",\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"timestamp\": \"yes\",\n",
        "}\n",
        "```\n",
        "\n",
        "In order to support this functionality, the [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py) should have the relevant slot value and the default values:\n",
        "\n",
        "```\n",
        "# Should we predict timestamps?\n",
        "\"timestamp\": Modality.TextLiteral(\n",
        "    \"yes\",\n",
        "    \"no\",\n",
        "    \"true\",\n",
        "    \"True\",\n",
        "    \"false\",\n",
        "    \"False\",\n",
        "    \"1\",\n",
        "    \"0\",\n",
        "    \"timestamp\",\n",
        "    \"notimestamp\",\n",
        "    \"<|timestamp|>\",\n",
        "    \"<|notimestamp|>\",\n",
        "),\n",
        "```\n",
        "\n",
        "The default can be set as `<|notimestamp|>`:\n",
        "```\n",
        "optional_slots = {\n",
        "    \"decodercontext\": \"\",\n",
        "    \"emotion\": \"<|emo:undefined|>\",\n",
        "    \"itn\": \"<|noitn|>\",\n",
        "    \"timestamp\": \"<|notimestamp|>\",\n",
        "    \"diarize\": \"<|nodiarize|>\",\n",
        "    \"pnc\": \"<|pnc|>\",  \n",
        "}\n",
        "```\n",
        "\n",
        "Additionally we need tokens to support these additional task-related tokens, `<|timestamp|>`, `<|notimestamp|>`, and integer tokens to encode frame indices.\n",
        "We add 900 integers to the list special tokens along with task-related tokens and rebuild the tokenizer as previously discussed.\n",
        "\n",
        "Now the transcript is a mix of tokens from `spl_tokens` tokenizer (frame indices) and tokens from a language-specific tokenizer.\n",
        "The [canary_tokenizer](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/tokenizers/canary_tokenizer.py) handles this by adding a modified `_text_to_ids` method.\n",
        "\n",
        "\n",
        "```\n",
        "def _text_to_ids_maybe_with_timestamps(self, text_no_eos, lang_id) -> list[int]:\n",
        "    time_pattern = re.compile(r\"<\\|\\d+\\|>\")\n",
        "    time_text = \"\".join(time_pattern.findall(text_no_eos))\n",
        "    has_timestamp = bool(time_text)\n",
        "    if not has_timestamp:\n",
        "        return super().text_to_ids(text_no_eos, lang_id)\n",
        "    else:\n",
        "        text_without_timestamps = time_pattern.sub(\"\", text_no_eos).strip()\n",
        "        return self._text_with_timestamps_to_ids(text_without_timestamps, time_text, lang_id)\n",
        "\n",
        "```\n",
        "\n",
        "Once these changes are in place, you should be able to train the model on data with word-level timestamps."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ejjCj3XfcIpR"
      },
      "source": [
        "## 4. Training on a new task: A case of speech summarization\n",
        "\n",
        "Speech summarization is an example of completely new task, meaning, neither the prompt format nor the default special tokens have an explicit support for this task.\n",
        "\n",
        "You will start with modifying [Canary2PromptFormatter](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/prompts/canary2.py) or even writing your own custom prompt formatter. [This tutorial](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Prompt%20Formatter%20Tutorial.ipynb) has useful references on modifying and building custom prompt formatter.\n",
        "\n",
        "\n",
        "One possible way to modify the existing promp format is to add an optional `\"summarize\"` key whose default value is `false`:\n",
        "```\n",
        "# should we summarize?\n",
        "\"summarize\": Modality.TextLiteral(\n",
        "    \"yes\",\n",
        "    \"no\",\n",
        "    \"true\",\n",
        "    \"True\",\n",
        "    \"false\",\n",
        "    \"False\",\n",
        "    \"1\",\n",
        "    \"0\",\n",
        "    \"<|summarize|>\",\n",
        "    \"<|nosummarize|>\"\n",
        "),\n",
        "```\n",
        "\n",
        "The default can be set as `<|nosummarize|>`:\n",
        "```\n",
        "optional_slots = {\n",
        "    \"decodercontext\": \"\",\n",
        "    \"emotion\": \"<|emo:undefined|>\",\n",
        "    \"itn\": \"<|noitn|>\",\n",
        "    \"timestamp\": \"<|notimestamp|>\",\n",
        "    \"diarize\": \"<|nodiarize|>\",\n",
        "    \"pnc\": \"<|pnc|>\",  \n",
        "    \"summarize\": \"<|nosummarize|>\",\n",
        "}\n",
        "```\n",
        "Then, you'll pass `\"summarize\": true` to the manifest for samples from speech summarization data, where the corresponding `text` will refer to the summary text.\n",
        "\n",
        "```\n",
        "metadata = {\n",
        "    \"audio_filepath\": audio_path,\n",
        "    \"duration\": duration,\n",
        "    \"text\": summary, # note that this is now a text summary and not a transcript\n",
        "    \"target_lane\": \"en\",\n",
        "    \"source_lang\": \"en\",\n",
        "    \"summarize\": \"true\",\n",
        "}\n",
        "```\n",
        "\n",
        "The default list of special tokens does not have `<|summarize|>` and `<|nosummarize|>` in the vocabulary. So you'll want to build a new tokenizer for the new vocabulary of `spl_tokens`.\n",
        "\n",
        "You can selectively retain token embeddings for the matched tokens, or simply reinitialize all token embeddings.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MhTpxSXJE_R6"
      },
      "source": [
        "## 5. Starting from Canary-flash checkpoint\n",
        "\n",
        "For any of the above scenarios, you may choose to intialize the model from one of the public Canary-flash checkpoints. In the previous section we saw a working example of fine-tuning from a Canary-flash checkpoint. Here we see how we can customize the arguments.\n",
        "\n",
        "We use the `include` and `exclude` paramaters to appropriately restore or drop certain weights, in case there is a difference in tokenizer or model architecture.\n",
        "\n",
        "\n",
        "  (i) Initialize all the parameters\n",
        "\n",
        "  ```\n",
        "  init_from_pretrained_model:\n",
        "    model0:\n",
        "      name: \"nvidia/canary-180m-flash\"\n",
        "  ```\n",
        "\n",
        "  (ii) Initialize just the encoder:\n",
        "  ```\n",
        "  init_from_pretrained_model:\n",
        "    model0:\n",
        "      name: \"nvidia/canary-180m-flash\"\n",
        "      include: [\"encoder\"]\n",
        "  ```\n",
        "\n",
        "  (iii) Initialize encoder and decoder but not the token embeddings (relevant for scenarios that use a different tokenizer):\n",
        "  ```\n",
        "  init_from_pretrained_model:\n",
        "    model0:\n",
        "      name: \"nvidia/canary-180m-flash\"\n",
        "      exclude: [\"transf_decoder._embedding.token_embedding\", \"log_softmax.mlp.layer0\"]\n",
        "\n",
        "  ```\n",
        "\n",
        "  (iv) If you wish further customization that cannot be handled with just these arguments, you can modify https://github.com/NVIDIA/NeMo/blob/main/nemo/core/classes/modelPT.py. Specifically, modify the following snippet of code\n",
        "\n",
        "  ```\n",
        "  dict_to_load = {}\n",
        "  for k, v in state_dict.items():\n",
        "      should_add = False\n",
        "      # if any string in include is present, should add\n",
        "      for p in include:\n",
        "          if p in k:\n",
        "              should_add = True\n",
        "              break\n",
        "      # except for if any string from exclude is present\n",
        "      for e in exclude:\n",
        "          if e in k:\n",
        "              excluded_param_names.append(k)\n",
        "              should_add = False\n",
        "              break\n",
        "      if should_add:\n",
        "          dict_to_load[k] = v\n",
        "  ```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uKCijB1ijs6_"
      },
      "source": [
        "# Practitioner's tips"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mWUkwjPfFk_J"
      },
      "source": [
        "## Starting from a pre-trained checkpoint\n",
        "\n",
        "In our experience working with Canary, we noticed that starting from a pre-trained speech encoder, greatly helps convergence. Especially for larger models (1B+ params) initializing from a pretrained encoder may even be required to stabilize the training.\n",
        "\n",
        "Canary-180M-Flash 17-layer fastconformer encoder was initialized from a 17-layer fastconformer encoder of a transducer speech recognition model ([model](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_multilingual_fastconformer_hybrid_large_pc_blend_eu/files), [config](https://github.com/NVIDIA/NeMo/blob/main/examples/asr/conf/fastconformer/fast-conformer_transducer_bpe.yaml#L29)). The 4-layer transformer decoder was initialized from scratch.\n",
        "\n",
        "Canary-1B-Flash has 32-layer fastconformer encoder. The first 24 layers were initialized from a 24-layer fastconfromer encoder of a transducer speech recognition model and the rest were randomly initalized. This 24-layer model was training internally with this [config](https://github.com/NVIDIA/NeMo/blob/main/examples/asr/conf/fastconformer/fast-conformer_transducer_bpe.yaml#L31)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jfFcQv0Pj1Tj"
      },
      "source": [
        "## Training Canary for multiple tasks\n",
        "\n",
        "We have seen that Canary-Flash models support multiple capabilities -- speech recognition in four languages (ASR), speech to text translation (AST)for six language pairs, timestamp (TS) prediction in four languages. Canary-Flash models are also optimized to be robust to background noise (NR) and hallucination (HR).\n",
        "\n",
        "These capabilties were achieved over three stages of training:\n",
        "* **Stage 1**: ASR+AST\n",
        "* **Stage 2**: ASR+AST+HR+NR\n",
        "* **Stage 3**: ASR+AST+HR+NR+TS\n",
        "\n",
        "At each stage, we add new capability to the model and at the same time we continue supervised training for previously learned capabilities. This is essential for the model to learn without forgetting.\n",
        "\n",
        "So, whenever you perform Canary-style training, irrespective of whether or not you start from a Canary-Flash checkpoint, make sure that the training data mix includes supervision for all the capabilities (tasks and languages) that you wish the final model to learn and retain.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tVmcFlA5Ftpu"
      },
      "source": [
        "## Training efficiency with 2-D bucketing and OOMptimizer\n",
        "\n",
        "Canary-Flash training is also optimized for optimal GPU utilization. 2-D bucketing and OOMptimizer are the two key components of for optimal GPU utilization, handled by the config as shown below.\n",
        "```\n",
        "model:\n",
        "  train_ds:\n",
        "    use_bucketing: true\n",
        "    bucket_duration_bins: [[3.79,27],[3.79,65],[4.8,34],[4.8,66],[5.736,39],[5.736,73],[6.42,44],[6.42,79],[7.182,47],[7.182,87],[8.107,52],[8.107,100],[8.78,60],[8.78,111],[9.62,66],[9.62,115],[10.47,71],[10.47,127],[11.14,76],[11.14,139],[11.8,78],[11.8,139],[12.47,82],[12.47,150],[13.02,88],[13.02,160],[13.55,92],[13.55,160],[14.1,94],[14.1,168],[14.64,97],[14.64,169],[15.15,101],[15.15,175],[15.63,102],[15.63,170],[16.09,104],[16.09,180],[16.63,107],[16.63,186],[17.17,109],[17.17,184],[17.71,113],[17.71,206],[18.18,116],[18.18,208],[18.67,119],[18.67,209],[19.13,123],[19.13,210],[19.61,125],[19.61,226],[20.18,126],[20.18,232],[32.467,184],[32.467,321],[36.567,243],[36.567,398],[40.0,272],[40.0,437]]\n",
        "    bucket_batch_size: [334,314,264,248,221,214,196,190,174,169,155,146,142,134,126,123,116,112,106,103,103,95,95,92,92,89,89,86,84,82,80,78,78,76,76,74,74,72,72,68,68,66,66,64,64,62,62,60,60,58,58,56,56,54,33,32,29,28,26,25]\n",
        "```\n",
        "\n",
        "See these parameters for `canary-180m-flash` model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UiAbyTiyTEXt"
      },
      "outputs": [],
      "source": [
        "# Load canary model if not previously loaded in this notebook instance\n",
        "if 'canary_model' not in locals():\n",
        "    canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LP2E0SgvSvI1"
      },
      "outputs": [],
      "source": [
        "print('bucket_duration_bins: \\n', canary_model._cfg['train_ds']['bucket_duration_bins'])\n",
        "print('bucket_batch_size: \\n', canary_model._cfg['train_ds']['bucket_batch_size'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l8DJDwyUS3q4"
      },
      "source": [
        "Simply put, these tools set the optimal batch statistics after considering the distribution of lengths of input audio, lengths of decoder outputs (decoder prompt and tokenized transcript), and model size. Bucketing (`bucket_duration_bins`)ensures that a training batch does not have samples of uneven lengths, as that would lead to wasteful usage of memory by the `<pad>` tokens. OOMptimizer sets batchsizes (`bucket_batch_sizes`) for each bucket ensuring that the training utilizes optimal GPU memory while not running into OOM errors.\n",
        "\n",
        "\n",
        "\n",
        "An alternative, if you don't wish to use bucketing, is to set the batchsize explicitly.\n",
        "```\n",
        "model:\n",
        "  train_ds:\n",
        "    use_bucketing: false\n",
        "    batch_size: 32\n",
        "```\n",
        "\n",
        "Next we add pointers to the script that compute `bucket_duration_bins` and `bucket_batch_sizes`. You will need config for your data, config for your model, and paths to tokenizers.\n",
        "\n",
        "Let's say `$NEMO_DIR` is path to the installed NeMo library.\n",
        "\n",
        "First step is to estimate 2D buckets bins using the data config and tokenizers. It takes as arguments, number of buckets, number of sub-buckets (2D in our case), number of utterances used to estimate the bins, lowest and highest duration in seconds, and arguments related to dataset manifest, tokenizers, and prompt format.\n",
        "\n",
        "```\n",
        "python $NEMO_DIR/scripts/speech_recognition/estimate_duration_bins_2d.py \\\n",
        "    -b 30 \\\n",
        "    -s 2 \\\n",
        "    -n 100000 \\\n",
        "    -l 0.5 -u 40.0 \\\n",
        "    -t $tokenizer_model1 $tokenizer_model2 $tokenizer_model3 \\\n",
        "    -a $lang1 $lang2 $lang3 \\\n",
        "    --lang-field target_lang \\\n",
        "    --text-field answer \\\n",
        "    -f canary2 \\\n",
        "    -p \"[{'role':'user','slots':{'source_lang':'en','target_lang':'en','pnc':'yes','decodercontext':'','emotion':'<|emo:undefined|>','itn':'yes','diarize':'yes','timestamp':'yes'}}]\" \\\n",
        "    $dataset_config\n",
        "```\n",
        "\n",
        "The next step is to obtain `bucket_batch_sizes` using the estimated `bucket_duration_bins` and model config.\n",
        "```\n",
        "BUCKETS=$bucket_duration_bins\n",
        "\n",
        "python $NEMO_DIR/scripts/speech_recognition/oomptimizer.py \\\n",
        "    -m nemo.collections.asr.models.EncDecMultiTaskModel\\\n",
        "    -c $config \\\n",
        "    --no-ddp \\\n",
        "    -b \"$BUCKETS\"\n",
        "\n",
        "```\n",
        "\n",
        "Then you'd update the training config accordingly and launch a training job as shown before.\n",
        "\n",
        "If you are interested to learn more about these tools, we discuss illustrative examples, technical details, and report efficiency gains in [Zelasko et al.](https://arxiv.org/abs/2503.05931).\n",
        "\n",
        "Refer to documentation on [2-D bucketing](https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/asr/datasets.html#d-bucketing) and [OOMptimizer](https://docs.nvidia.com/nemo-framework/user-guide/latest/nemotoolkit/asr/datasets.html#pushing-gpu-utilization-to-the-limits-with-bucketing-and-oomptimizer) for more details."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "75eaOh_LT55a"
      },
      "source": [
        "## Masking loss for prompt tokens\n",
        "\n",
        "The config has `use_loss_mask_for_prompt` parameter which decides whether or not the training objective includes loss for the decoder prompt tokens.\n",
        "\n",
        "We noticed that masking prompt loss tokens led to a better performing `canary-180m-flash` model, where as it did not make any noticeable difference for `canary-1b-flash`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4ArQlMTeUhEO"
      },
      "outputs": [],
      "source": [
        "# Load canary model if not previously loaded in this notebook instance\n",
        "if 'canary_model' not in locals():\n",
        "    canary_model = EncDecMultiTaskModel.from_pretrained('nvidia/canary-180m-flash')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FXMJX8lXU1WP"
      },
      "outputs": [],
      "source": [
        "print('prompt loss masking for canary-180m-flash: \\n', canary_model._cfg['use_loss_mask_for_prompt'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "umo2f6yI4Y--"
      },
      "source": [
        "# Follow-up reading material and tutorials\n",
        "\n",
        "1. [SentencePiece](https://arxiv.org/abs/1808.06226) and [concatenated](https://arxiv.org/abs/2306.08753) tokenizer: To learn more about the tokenization process.\n",
        "\n",
        "\n",
        "2. [Tutorial on prompt formatter](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Prompt%20Formatter%20Tutorial.ipynb): To learn more about prompt formatter.\n",
        "\n",
        "2. [Tutorial on multi-task adapters](https://github.com/NVIDIA/NeMo/blob/main/tutorials/asr/asr_adapters/Multi_Task_Adapters.ipynb): If you wish to explore adaptation of `Canary-flash` checkpoints using adapters."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "ame",
      "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.13.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}