File size: 66,880 Bytes
8340dfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6",
   "metadata": {
    "id": "75b58048-7d14-4fc6-8085-1fc08c81b4a6"
   },
   "source": [
    "# Fine-Tune Whisper For Multilingual ASR with 🤗 Transformers"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a",
   "metadata": {
    "id": "fbfa8ad5-4cdc-4512-9058-836cbbf65e1a"
   },
   "source": [
    "In this Colab, we present a step-by-step guide on how to fine-tune Whisper \n",
    "for any multilingual ASR dataset using Hugging Face 🤗 Transformers. This is a \n",
    "more \"hands-on\" version of the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). \n",
    "For a more in-depth explanation of Whisper, the Common Voice dataset and the theory behind fine-tuning, the reader is advised to refer to the blog post."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e",
   "metadata": {
    "id": "afe0d503-ae4e-4aa7-9af4-dbcba52db41e"
   },
   "source": [
    "## Introduction"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0",
   "metadata": {
    "id": "9ae91ed4-9c3e-4ade-938e-f4c2dcfbfdc0"
   },
   "source": [
    "Whisper is a pre-trained model for automatic speech recognition (ASR) \n",
    "published in [September 2022](https://openai.com/blog/whisper/) by the authors \n",
    "Alec Radford et al. from OpenAI. Unlike many of its predecessors, such as \n",
    "[Wav2Vec 2.0](https://arxiv.org/abs/2006.11477), which are pre-trained \n",
    "on un-labelled audio data, Whisper is pre-trained on a vast quantity of \n",
    "**labelled** audio-transcription data, 680,000 hours to be precise. \n",
    "This is an order of magnitude more data than the un-labelled audio data used \n",
    "to train Wav2Vec 2.0 (60,000 hours). What is more, 117,000 hours of this \n",
    "pre-training data is multilingual ASR data. This results in checkpoints \n",
    "that can be applied to over 96 languages, many of which are considered \n",
    "_low-resource_.\n",
    "\n",
    "When scaled to 680,000 hours of labelled pre-training data, Whisper models \n",
    "demonstrate a strong ability to generalise to many datasets and domains.\n",
    "The pre-trained checkpoints achieve competitive results to state-of-the-art \n",
    "ASR systems, with near 3% word error rate (WER) on the test-clean subset of \n",
    "LibriSpeech ASR and a new state-of-the-art on TED-LIUM with 4.7% WER (_c.f._ \n",
    "Table 8 of the [Whisper paper](https://cdn.openai.com/papers/whisper.pdf)).\n",
    "The extensive multilingual ASR knowledge acquired by Whisper during pre-training \n",
    "can be leveraged for other low-resource languages; through fine-tuning, the \n",
    "pre-trained checkpoints can be adapted for specific datasets and languages \n",
    "to further improve upon these results. We'll show just how Whisper can be fine-tuned \n",
    "for low-resource languages in this Colab."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72",
   "metadata": {
    "id": "e59b91d6-be24-4b5e-bb38-4977ea143a72"
   },
   "source": [
    "<figure>\n",
    "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/whisper_architecture.svg\" alt=\"Trulli\" style=\"width:100%\">\n",
    "<figcaption align = \"center\"><b>Figure 1:</b> Whisper model. The architecture \n",
    "follows the standard Transformer-based encoder-decoder model. A \n",
    "log-Mel spectrogram is input to the encoder. The last encoder \n",
    "hidden states are input to the decoder via cross-attention mechanisms. The \n",
    "decoder autoregressively predicts text tokens, jointly conditional on the \n",
    "encoder hidden states and previously predicted tokens. Figure source: \n",
    "<a href=\"https://openai.com/blog/whisper/\">OpenAI Whisper Blog</a>.</figcaption>\n",
    "</figure>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21b6316e-8a55-4549-a154-66d3da2ab74a",
   "metadata": {
    "id": "21b6316e-8a55-4549-a154-66d3da2ab74a"
   },
   "source": [
    "The Whisper checkpoints come in five configurations of varying model sizes.\n",
    "The smallest four are trained on either English-only or multilingual data.\n",
    "The largest checkpoint is multilingual only. All nine of the pre-trained checkpoints \n",
    "are available on the [Hugging Face Hub](https://huggingface.co/models?search=openai/whisper). The \n",
    "checkpoints are summarised in the following table with links to the models on the Hub:\n",
    "\n",
    "| Size   | Layers | Width | Heads | Parameters | English-only                                         | Multilingual                                      |\n",
    "|--------|--------|-------|-------|------------|------------------------------------------------------|---------------------------------------------------|\n",
    "| tiny   | 4      | 384   | 6     | 39 M       | [✓](https://huggingface.co/openai/whisper-tiny.en)   | [✓](https://huggingface.co/openai/whisper-tiny.)  |\n",
    "| base   | 6      | 512   | 8     | 74 M       | [✓](https://huggingface.co/openai/whisper-base.en)   | [✓](https://huggingface.co/openai/whisper-base)   |\n",
    "| small  | 12     | 768   | 12    | 244 M      | [✓](https://huggingface.co/openai/whisper-small.en)  | [✓](https://huggingface.co/openai/whisper-small)  |\n",
    "| medium | 24     | 1024  | 16    | 769 M      | [✓](https://huggingface.co/openai/whisper-medium.en) | [✓](https://huggingface.co/openai/whisper-medium) |\n",
    "| large  | 32     | 1280  | 20    | 1550 M     | x                                                    | [✓](https://huggingface.co/openai/whisper-large)  |\n",
    "\n",
    "For demonstration purposes, we'll fine-tune the multilingual version of the \n",
    "[`\"small\"`](https://huggingface.co/openai/whisper-small) checkpoint with 244M params (~= 1GB). \n",
    "As for our data, we'll train and evaluate our system on a low-resource language \n",
    "taken from the [Common Voice](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0)\n",
    "dataset. We'll show that with as little as 8 hours of fine-tuning data, we can achieve \n",
    "strong performance in this language."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a",
   "metadata": {
    "id": "3a680dfc-cbba-4f6c-8a1f-e1a5ff3f123a"
   },
   "source": [
    "------------------------------------------------------------------------\n",
    "\n",
    "\\\\({}^1\\\\) The name Whisper follows from the acronym “WSPSR”, which stands for “Web-scale Supervised Pre-training for Speech Recognition”."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0",
   "metadata": {
    "id": "b219c9dd-39b6-4a95-b2a1-3f547a1e7bc0"
   },
   "source": [
    "## Load Dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "674429c5-0ab4-4adf-975b-621bb69eca38",
   "metadata": {
    "id": "674429c5-0ab4-4adf-975b-621bb69eca38"
   },
   "source": [
    "Using 🤗 Datasets, downloading and preparing data is extremely simple. \n",
    "We can download and prepare the Common Voice splits in just one line of code. \n",
    "\n",
    "First, ensure you have accepted the terms of use on the Hugging Face Hub: [mozilla-foundation/common_voice_11_0](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0). Once you have accepted the terms, you will have full access to the dataset and be able to download the data locally.\n",
    "\n",
    "Since Hindi is very low-resource, we'll combine the `train` and `validation` \n",
    "splits to give approximately 8 hours of training data. We'll use the 4 hours \n",
    "of `test` data as our held-out test set:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a2787582-554f-44ce-9f38-4180a5ed6b44",
   "metadata": {
    "id": "a2787582-554f-44ce-9f38-4180a5ed6b44"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.8/site-packages/pandas/core/computation/expressions.py:20: UserWarning: Pandas requires version '2.7.3' or newer of 'numexpr' (version '2.7.1' currently installed).\n",
      "  from pandas.core.computation.check import NUMEXPR_INSTALLED\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "08a4aab5934c4a70997fbe915248035c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading builder script:   0%|          | 0.00/8.30k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "00b3798cd51d453098ecffcb4571cb23",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading readme:   0%|          | 0.00/12.2k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2ff9b05f833c49b192fc2091972bc909",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading extra modules:   0%|          | 0.00/3.44k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d9931e08d3ac4fff87f33d37973f25af",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading extra modules:   0%|          | 0.00/60.9k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading and preparing dataset common_voice_11_0/ar to /home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/ar/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "dc96a42fb8f344b8a895510ad51d6b06",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/12.2k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "44c1404b106646479e9acee7855fc1ef",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data files:   0%|          | 0/5 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d2c52a172caa4cb4a52b771191a023d1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/712M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9479eecdcc8a4b01b5fc654e468594ca",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/300M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8dcc08acff094bed98f7266c28362bad",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/312M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "865c3abe523f4121b8d74d794c555342",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/978M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1ac8e4624c814c6fb576279d4f8b9e5d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/449M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f7cc901827cc4c869cb75a8842128096",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Extracting data files:   0%|          | 0/5 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0aade0c3d91e429889ab5fe5be59c6a9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data files:   0%|          | 0/5 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b1c9858ba88a418eb1bedbd5ecc22210",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/6.90M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "09ef3a9d96b34721bdd6a52c20eb2a07",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/2.52M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "922cd883e3b0407faebc79eb073804dd",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/2.41M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3dda5f54dd9847cea25790a058bf1e6b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/8.44M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8018f9b63d6e49809aea1e80b0953b30",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading data:   0%|          | 0.00/3.78M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6238c505b76340be9daabc88e849c66c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Extracting data files:   0%|          | 0/5 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Generating train split: 0 examples [00:00, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "Reading metadata...: 0it [00:00, ?it/s]\u001b[A\n",
      "Reading metadata...: 6392it [00:00, 63915.18it/s]\u001b[A\n",
      "Reading metadata...: 28043it [00:00, 95151.74it/s]\u001b[A\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Generating validation split: 0 examples [00:00, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "Reading metadata...: 0it [00:00, ?it/s]\u001b[A\u001b[A\n",
      "\n",
      "Reading metadata...: 10438it [00:00, 92085.56it/s][A\u001b[A\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Generating test split: 0 examples [00:00, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "Reading metadata...: 10440it [00:00, 146354.01it/s]\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Generating other split: 0 examples [00:00, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "\n",
      "Reading metadata...: 0it [00:00, ?it/s]\u001b[A\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "\n",
      "Reading metadata...: 9626it [00:00, 96252.06it/s]\u001b[A\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "\n",
      "Reading metadata...: 19252it [00:00, 95765.10it/s]\u001b[A\u001b[A\u001b[A\u001b[A\n",
      "\n",
      "\n",
      "\n",
      "Reading metadata...: 35514it [00:00, 94549.99it/s]\u001b[A\u001b[A\u001b[A\u001b[A\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Generating invalidated split: 0 examples [00:00, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "Reading metadata...: 0it [00:00, ?it/s]\u001b[A\n",
      "Reading metadata...: 14959it [00:00, 104827.82it/s]\u001b[A\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset common_voice_11_0 downloaded and prepared to /home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/ar/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f. Subsequent calls will reuse this data.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Found cached dataset common_voice_11_0 (/home/ubuntu/.cache/huggingface/datasets/mozilla-foundation___common_voice_11_0/ar/11.0.0/f8e47235d9b4e68fa24ed71d63266a02018ccf7194b2a8c9c598a5f3ab304d9f)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DatasetDict({\n",
      "    train: Dataset({\n",
      "        features: ['client_id', 'path', 'audio', 'sentence', 'up_votes', 'down_votes', 'age', 'gender', 'accent', 'locale', 'segment'],\n",
      "        num_rows: 38481\n",
      "    })\n",
      "    test: Dataset({\n",
      "        features: ['client_id', 'path', 'audio', 'sentence', 'up_votes', 'down_votes', 'age', 'gender', 'accent', 'locale', 'segment'],\n",
      "        num_rows: 10440\n",
      "    })\n",
      "})\n"
     ]
    }
   ],
   "source": [
    "from datasets import load_dataset, DatasetDict\n",
    "\n",
    "common_voice = DatasetDict()\n",
    "\n",
    "common_voice[\"train\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"train+validation\", use_auth_token=True)\n",
    "common_voice[\"test\"] = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"ar\", split=\"test\", use_auth_token=True)\n",
    "\n",
    "print(common_voice)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f",
   "metadata": {
    "id": "d5c7c3d6-7197-41e7-a088-49b753c1681f"
   },
   "source": [
    "Most ASR datasets only provide input audio samples (`audio`) and the \n",
    "corresponding transcribed text (`sentence`). Common Voice contains additional \n",
    "metadata information, such as `accent` and `locale`, which we can disregard for ASR.\n",
    "Keeping the notebook as general as possible, we only consider the input audio and\n",
    "transcribed text for fine-tuning, discarding the additional metadata information:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce",
   "metadata": {
    "id": "20ba635d-518c-47ac-97ee-3cad25f1e0ce"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DatasetDict({\n",
      "    train: Dataset({\n",
      "        features: ['audio', 'sentence'],\n",
      "        num_rows: 38481\n",
      "    })\n",
      "    test: Dataset({\n",
      "        features: ['audio', 'sentence'],\n",
      "        num_rows: 10440\n",
      "    })\n",
      "})\n"
     ]
    }
   ],
   "source": [
    "common_voice = common_voice.remove_columns([\"accent\", \"age\", \"client_id\", \"down_votes\", \"gender\", \"locale\", \"path\", \"segment\", \"up_votes\"])\n",
    "\n",
    "print(common_voice)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605",
   "metadata": {
    "id": "2d63b2d2-f68a-4d74-b7f1-5127f6d16605"
   },
   "source": [
    "## Prepare Feature Extractor, Tokenizer and Data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "601c3099-1026-439e-93e2-5635b3ba5a73",
   "metadata": {
    "id": "601c3099-1026-439e-93e2-5635b3ba5a73"
   },
   "source": [
    "The ASR pipeline can be de-composed into three stages: \n",
    "1) A feature extractor which pre-processes the raw audio-inputs\n",
    "2) The model which performs the sequence-to-sequence mapping \n",
    "3) A tokenizer which post-processes the model outputs to text format\n",
    "\n",
    "In 🤗 Transformers, the Whisper model has an associated feature extractor and tokenizer, \n",
    "called [WhisperFeatureExtractor](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperFeatureExtractor)\n",
    "and [WhisperTokenizer](https://huggingface.co/docs/transformers/main/model_doc/whisper#transformers.WhisperTokenizer) \n",
    "respectively.\n",
    "\n",
    "We'll go through details for setting-up the feature extractor and tokenizer one-by-one!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "560332eb-3558-41a1-b500-e83a9f695f84",
   "metadata": {
    "id": "560332eb-3558-41a1-b500-e83a9f695f84"
   },
   "source": [
    "### Load WhisperFeatureExtractor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365",
   "metadata": {
    "id": "32ec8068-0bd7-412d-b662-0edb9d1e7365"
   },
   "source": [
    "The Whisper feature extractor performs two operations:\n",
    "1. Pads / truncates the audio inputs to 30s: any audio inputs shorter than 30s are padded to 30s with silence (zeros), and those longer that 30s are truncated to 30s\n",
    "2. Converts the audio inputs to _log-Mel spectrogram_ input features, a visual representation of the audio and the form of the input expected by the Whisper model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "589d9ec1-d12b-4b64-93f7-04c63997da19",
   "metadata": {
    "id": "589d9ec1-d12b-4b64-93f7-04c63997da19"
   },
   "source": [
    "<figure>\n",
    "<img src=\"https://raw.githubusercontent.com/sanchit-gandhi/notebooks/main/spectrogram.jpg\" alt=\"Trulli\" style=\"width:100%\">\n",
    "<figcaption align = \"center\"><b>Figure 2:</b> Conversion of sampled audio array to log-Mel spectrogram.\n",
    "Left: sampled 1-dimensional audio signal. Right: corresponding log-Mel spectrogram. Figure source:\n",
    "<a href=\"https://ai.googleblog.com/2019/04/specaugment-new-data-augmentation.html\">Google SpecAugment Blog</a>.\n",
    "</figcaption>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa",
   "metadata": {
    "id": "b2ef54d5-b946-4c1d-9fdc-adc5d01b46aa"
   },
   "source": [
    "We'll load the feature extractor from the pre-trained checkpoint with the default values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5",
   "metadata": {
    "id": "bc77d7bb-f9e2-47f5-b663-30f7a4321ce5"
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "bfb191d060994ee6b350780d681959fa",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading:   0%|          | 0.00/185k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from transformers import WhisperFeatureExtractor\n",
    "\n",
    "feature_extractor = WhisperFeatureExtractor.from_pretrained(\"openai/whisper-small\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb",
   "metadata": {
    "id": "93748af7-b917-4ecf-a0c8-7d89077ff9cb"
   },
   "source": [
    "### Load WhisperTokenizer"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bc82609-a9fb-447a-a2af-99597c864029",
   "metadata": {
    "id": "2bc82609-a9fb-447a-a2af-99597c864029"
   },
   "source": [
    "The Whisper model outputs a sequence of _token ids_. The tokenizer maps each of these token ids to their corresponding text string. For Hindi, we can load the pre-trained tokenizer and use it for fine-tuning without any further modifications. We simply have to \n",
    "specify the target language and the task. These arguments inform the \n",
    "tokenizer to prefix the language and task tokens to the start of encoded \n",
    "label sequences:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
   "metadata": {
    "id": "c7b07f9b-ae0e-4f89-98f0-0c50d432eab6",
    "outputId": "5c004b44-86e7-4e00-88be-39e0af5eed69"
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a63122eff18b4afaa38ab99ca70d1a87",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading:   0%|          | 0.00/829 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "63c706936977484e9fe60d086b3fda67",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading:   0%|          | 0.00/1.04M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e24a1bd3e94d4874be2e35621fcf3821",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading:   0%|          | 0.00/494k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "20969c28f0724d23a68f70a538c7a1d4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading:   0%|          | 0.00/52.7k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b4868134dbfe4645a4309467b8503a87",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading:   0%|          | 0.00/2.11k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e4f466a6642249958fcb21cbe614beb6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading:   0%|          | 0.00/2.06k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from transformers import WhisperTokenizer\n",
    "\n",
    "tokenizer = WhisperTokenizer.from_pretrained(\"openai/whisper-small\", language=\"Arabic\", task=\"transcribe\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b",
   "metadata": {
    "id": "d2ef23f3-f4a8-483a-a2dc-080a7496cb1b"
   },
   "source": [
    "### Combine To Create A WhisperProcessor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d",
   "metadata": {
    "id": "5ff67654-5a29-4bb8-a69d-0228946c6f8d"
   },
   "source": [
    "To simplify using the feature extractor and tokenizer, we can _wrap_ \n",
    "both into a single `WhisperProcessor` class. This processor object \n",
    "inherits from the `WhisperFeatureExtractor` and `WhisperProcessor`, \n",
    "and can be used on the audio inputs and model predictions as required. \n",
    "In doing so, we only need to keep track of two objects during training: \n",
    "the `processor` and the `model`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6",
   "metadata": {
    "id": "77d9f0c5-8607-4642-a8ac-c3ab2e223ea6"
   },
   "outputs": [],
   "source": [
    "from transformers import WhisperProcessor\n",
    "\n",
    "processor = WhisperProcessor.from_pretrained(\"openai/whisper-small\", language=\"Arabic\", task=\"transcribe\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c",
   "metadata": {
    "id": "381acd09-0b0f-4d04-9eb3-f028ac0e5f2c"
   },
   "source": [
    "### Prepare Data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f",
   "metadata": {
    "id": "9649bf01-2e8a-45e5-8fca-441c13637b8f"
   },
   "source": [
    "Let's print the first example of the Common Voice dataset to see \n",
    "what form the data is in:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255",
   "metadata": {
    "id": "6e6b0ec5-0c94-4e2c-ae24-c791be1b2255"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'audio': {'path': '/home/ubuntu/.cache/huggingface/datasets/downloads/extracted/d27f3a991789fe1631f955b0f76bf7c7bc2ecb409f7198408b9881a9d31407b7/common_voice_ar_24082672.mp3', 'array': array([-1.6076937e-15, -1.0766865e-13, -5.3649478e-14, ...,\n",
      "        8.6992582e-09,  1.5384171e-07,  1.3540763e-07], dtype=float32), 'sampling_rate': 48000}, 'sentence': 'وما أدراك ما يوم الدين'}\n"
     ]
    }
   ],
   "source": [
    "print(common_voice[\"train\"][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd",
   "metadata": {
    "id": "5a679f05-063d-41b3-9b58-4fc9c6ccf4fd"
   },
   "source": [
    "Since \n",
    "our input audio is sampled at 48kHz, we need to _downsample_ it to \n",
    "16kHz prior to passing it to the Whisper feature extractor, 16kHz being the sampling rate expected by the Whisper model. \n",
    "\n",
    "We'll set the audio inputs to the correct sampling rate using dataset's \n",
    "[`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=cast_column#datasets.DatasetDict.cast_column)\n",
    "method. This operation does not change the audio in-place, \n",
    "but rather signals to `datasets` to resample audio samples _on the fly_ the \n",
    "first time that they are loaded:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f12e2e57-156f-417b-8cfb-69221cc198e8",
   "metadata": {
    "id": "f12e2e57-156f-417b-8cfb-69221cc198e8"
   },
   "outputs": [],
   "source": [
    "from datasets import Audio\n",
    "\n",
    "common_voice = common_voice.cast_column(\"audio\", Audio(sampling_rate=16000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707",
   "metadata": {
    "id": "00382a3e-abec-4cdd-a54c-d1aaa3ea4707"
   },
   "source": [
    "Re-loading the first audio sample in the Common Voice dataset will resample \n",
    "it to the desired sampling rate:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "87122d71-289a-466a-afcf-fa354b18946b",
   "metadata": {
    "id": "87122d71-289a-466a-afcf-fa354b18946b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'audio': {'path': '/home/ubuntu/.cache/huggingface/datasets/downloads/extracted/d27f3a991789fe1631f955b0f76bf7c7bc2ecb409f7198408b9881a9d31407b7/common_voice_ar_24082672.mp3', 'array': array([-3.4152155e-14,  2.7470058e-14,  8.5115027e-14, ...,\n",
      "       -2.4172088e-08, -2.2456084e-07,  4.5994945e-08], dtype=float32), 'sampling_rate': 16000}, 'sentence': 'وما أدراك ما يوم الدين'}\n"
     ]
    }
   ],
   "source": [
    "print(common_voice[\"train\"][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3df7378a-a4c0-45d7-8d07-defbd1062ab6",
   "metadata": {},
   "source": [
    "We'll define our pre-processing strategy. We advise that you **do not** lower-case the transcriptions or remove punctuation unless mixing different datasets. This will enable you to fine-tune Whisper models that can predict punctuation and casing. Later, you will see how we can evaluate the predictions without punctuation or casing, so that the models benefit from the WER improvement obtained by normalising the transcriptions while still predicting fully formatted transcriptions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d041650e-1c48-4439-87b3-5b6f4a514107",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers.models.whisper.english_normalizer import BasicTextNormalizer\n",
    "\n",
    "do_lower_case = False\n",
    "do_remove_punctuation = False\n",
    "\n",
    "normalizer = BasicTextNormalizer()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89e12c2e-2f14-479b-987b-f0c75c881095",
   "metadata": {},
   "source": [
    "Now we can write a function to prepare our data ready for the model:\n",
    "1. We load and resample the audio data by calling `batch[\"audio\"]`. As explained above, 🤗 Datasets performs any necessary resampling operations on the fly.\n",
    "2. We use the feature extractor to compute the log-Mel spectrogram input features from our 1-dimensional audio array.\n",
    "3. We perform any optional pre-processing (lower-case or remove punctuation).\n",
    "4. We encode the transcriptions to label ids through the use of the tokenizer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c085911c-a10a-41ef-8874-306e0503e9bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def prepare_dataset(batch):\n",
    "    # load and (possibly) resample audio data to 16kHz\n",
    "    audio = batch[\"audio\"]\n",
    "\n",
    "    # compute log-Mel input features from input audio array \n",
    "    batch[\"input_features\"] = processor.feature_extractor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"]).input_features[0]\n",
    "    # compute input length of audio sample in seconds\n",
    "    batch[\"input_length\"] = len(audio[\"array\"]) / audio[\"sampling_rate\"]\n",
    "    \n",
    "    # optional pre-processing steps\n",
    "    transcription = batch[\"sentence\"]\n",
    "    if do_lower_case:\n",
    "        transcription = transcription.lower()\n",
    "    if do_remove_punctuation:\n",
    "        transcription = normalizer(transcription).strip()\n",
    "    \n",
    "    # encode target text to label ids\n",
    "    batch[\"labels\"] = processor.tokenizer(transcription).input_ids\n",
    "    return batch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c960965-9fb6-466f-9dbd-c9d43e71d9d0",
   "metadata": {
    "id": "70b319fb-2439-4ef6-a70d-a47bf41c4a13"
   },
   "source": [
    "We can apply the data preparation function to all of our training examples using dataset's `.map` method. The argument `num_proc` specifies how many CPU cores to use. Setting `num_proc` > 1 will enable multiprocessing. If the `.map` method hangs with multiprocessing, set `num_proc=1` and process the dataset sequentially."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b",
   "metadata": {
    "id": "7b73ab39-ffaf-4b9e-86e5-782963c6134b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    "
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "90a67146a43641af8170989fd402f9e5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "#0:   0%|          | 0/19241 [00:00<?, ?ex/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "86b6d97bdfed4f2183435cd3e6b67c44",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "#1:   0%|          | 0/19240 [00:00<?, ?ex/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-11-2bc6187532d2>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mcommon_voice\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcommon_voice\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mprepare_dataset\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mremove_columns\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcommon_voice\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcolumn_names\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"train\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnum_proc\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m~/.local/lib/python3.8/site-packages/datasets/dataset_dict.py\u001b[0m in \u001b[0;36mmap\u001b[0;34m(self, function, with_indices, with_rank, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_names, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, desc)\u001b[0m\n\u001b[1;32m    775\u001b[0m             \u001b[0mcache_file_names\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0mk\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;32mNone\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mk\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    776\u001b[0m         return DatasetDict(\n\u001b[0;32m--> 777\u001b[0;31m             {\n\u001b[0m\u001b[1;32m    778\u001b[0m                 k: dataset.map(\n\u001b[1;32m    779\u001b[0m                     \u001b[0mfunction\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfunction\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/.local/lib/python3.8/site-packages/datasets/dataset_dict.py\u001b[0m in \u001b[0;36m<dictcomp>\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m    776\u001b[0m         return DatasetDict(\n\u001b[1;32m    777\u001b[0m             {\n\u001b[0;32m--> 778\u001b[0;31m                 k: dataset.map(\n\u001b[0m\u001b[1;32m    779\u001b[0m                     \u001b[0mfunction\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mfunction\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    780\u001b[0m                     \u001b[0mwith_indices\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mwith_indices\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/.local/lib/python3.8/site-packages/datasets/arrow_dataset.py\u001b[0m in \u001b[0;36mmap\u001b[0;34m(self, function, with_indices, with_rank, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint, desc)\u001b[0m\n\u001b[1;32m   2816\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   2817\u001b[0m                     \u001b[0;32mfor\u001b[0m \u001b[0mindex\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0masync_result\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mresults\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 2818\u001b[0;31m                         \u001b[0mtransformed_shards\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0masync_result\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   2819\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   2820\u001b[0m             assert (\n",
      "\u001b[0;32m~/.local/lib/python3.8/site-packages/multiprocess/pool.py\u001b[0m in \u001b[0;36mget\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m    763\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    764\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0mget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtimeout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 765\u001b[0;31m         \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwait\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtimeout\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    766\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mready\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    767\u001b[0m             \u001b[0;32mraise\u001b[0m \u001b[0mTimeoutError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/.local/lib/python3.8/site-packages/multiprocess/pool.py\u001b[0m in \u001b[0;36mwait\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m    760\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    761\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0mwait\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtimeout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 762\u001b[0;31m         \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_event\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwait\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtimeout\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    763\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    764\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0mget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtimeout\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/usr/lib/python3.8/threading.py\u001b[0m in \u001b[0;36mwait\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m    556\u001b[0m             \u001b[0msignaled\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_flag\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    557\u001b[0m             \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0msignaled\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 558\u001b[0;31m                 \u001b[0msignaled\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_cond\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwait\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtimeout\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    559\u001b[0m             \u001b[0;32mreturn\u001b[0m \u001b[0msignaled\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    560\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/usr/lib/python3.8/threading.py\u001b[0m in \u001b[0;36mwait\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m    300\u001b[0m         \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m    \u001b[0;31m# restore state no matter what (e.g., KeyboardInterrupt)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    301\u001b[0m             \u001b[0;32mif\u001b[0m \u001b[0mtimeout\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 302\u001b[0;31m                 \u001b[0mwaiter\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0macquire\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    303\u001b[0m                 \u001b[0mgotit\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    304\u001b[0m             \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "common_voice = common_voice.map(prepare_dataset, remove_columns=common_voice.column_names[\"train\"], num_proc=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54ce0fdb-7218-4a4d-b175-383980fec0df",
   "metadata": {},
   "source": [
    "Finally, we filter any training data with audio samples longer than 30s. These samples would otherwise be truncated by the Whisper feature-extractor which could affect the stability of training. We define a function that returns `True` for samples that are less than 30s, and `False` for those that are longer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01cb25ef-4bb0-4325-9461-f59198acadf6",
   "metadata": {},
   "outputs": [],
   "source": [
    "max_input_length = 30.0\n",
    "\n",
    "def is_audio_in_length_range(length):\n",
    "    return length < max_input_length"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30e676a8-7ca8-4850-8c5d-5b2b00d13fba",
   "metadata": {},
   "source": [
    "We apply our filter function to all samples of our training dataset through 🤗 Datasets' `.filter` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "333f7f6e-6053-4d3b-8924-c733c79b82ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "common_voice[\"train\"] = common_voice[\"train\"].filter(\n",
    "    is_audio_in_length_range,\n",
    "    input_columns=[\"input_length\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "263a5a58-0239-4a25-b0df-c625fc9c5810",
   "metadata": {
    "id": "263a5a58-0239-4a25-b0df-c625fc9c5810"
   },
   "source": [
    "## Training and Evaluation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7",
   "metadata": {
    "id": "a693e768-c5a6-453f-89a1-b601dcf7daf7"
   },
   "source": [
    "Now that we've prepared our data, we're ready to dive into the training pipeline. \n",
    "The [🤗 Trainer](https://huggingface.co/transformers/master/main_classes/trainer.html?highlight=trainer)\n",
    "will do much of the heavy lifting for us. All we have to do is:\n",
    "\n",
    "- Define a data collator: the data collator takes our pre-processed data and prepares PyTorch tensors ready for the model.\n",
    "\n",
    "- Evaluation metrics: during evaluation, we want to evaluate the model using the [word error rate (WER)](https://huggingface.co/metrics/wer) metric. We need to define a `compute_metrics` function that handles this computation.\n",
    "\n",
    "- Load a pre-trained checkpoint: we need to load a pre-trained checkpoint and configure it correctly for training.\n",
    "\n",
    "- Define the training configuration: this will be used by the 🤗 Trainer to define the training schedule.\n",
    "\n",
    "Once we've fine-tuned the model, we will evaluate it on the test data to verify that we have correctly trained it \n",
    "to transcribe speech in Hindi."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d230e6d-624c-400a-bbf5-fa660881df25",
   "metadata": {
    "id": "8d230e6d-624c-400a-bbf5-fa660881df25"
   },
   "source": [
    "### Define a Data Collator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04def221-0637-4a69-b242-d3f0c1d0ee78",
   "metadata": {
    "id": "04def221-0637-4a69-b242-d3f0c1d0ee78"
   },
   "source": [
    "The data collator for a sequence-to-sequence speech model is unique in the sense that it \n",
    "treats the `input_features` and `labels` independently: the  `input_features` must be \n",
    "handled by the feature extractor and the `labels` by the tokenizer.\n",
    "\n",
    "The `input_features` are already padded to 30s and converted to a log-Mel spectrogram \n",
    "of fixed dimension by action of the feature extractor, so all we have to do is convert the `input_features`\n",
    "to batched PyTorch tensors. We do this using the feature extractor's `.pad` method with `return_tensors=pt`.\n",
    "\n",
    "The `labels` on the other hand are un-padded. We first pad the sequences\n",
    "to the maximum length in the batch using the tokenizer's `.pad` method. The padding tokens \n",
    "are then replaced by `-100` so that these tokens are **not** taken into account when \n",
    "computing the loss. We then cut the BOS token from the start of the label sequence as we \n",
    "append it later during training.\n",
    "\n",
    "We can leverage the `WhisperProcessor` we defined earlier to perform both the \n",
    "feature extractor and the tokenizer operations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5",
   "metadata": {
    "id": "8326221e-ec13-4731-bb4e-51e5fc1486c5"
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "from dataclasses import dataclass\n",
    "from typing import Any, Dict, List, Union\n",
    "\n",
    "@dataclass\n",
    "class DataCollatorSpeechSeq2SeqWithPadding:\n",
    "    processor: Any\n",
    "\n",
    "    def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n",
    "        # split inputs and labels since they have to be of different lengths and need different padding methods\n",
    "        # first treat the audio inputs by simply returning torch tensors\n",
    "        input_features = [{\"input_features\": feature[\"input_features\"]} for feature in features]\n",
    "        batch = self.processor.feature_extractor.pad(input_features, return_tensors=\"pt\")\n",
    "\n",
    "        # get the tokenized label sequences\n",
    "        label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n",
    "        # pad the labels to max length\n",
    "        labels_batch = self.processor.tokenizer.pad(label_features, return_tensors=\"pt\")\n",
    "\n",
    "        # replace padding with -100 to ignore loss correctly\n",
    "        labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n",
    "\n",
    "        # if bos token is appended in previous tokenization step,\n",
    "        # cut bos token here as it's append later anyways\n",
    "        if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():\n",
    "            labels = labels[:, 1:]\n",
    "\n",
    "        batch[\"labels\"] = labels\n",
    "\n",
    "        return batch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86",
   "metadata": {
    "id": "3cae7dbf-8a50-456e-a3a8-7fd005390f86"
   },
   "source": [
    "Let's initialise the data collator we've just defined:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc834702-c0d3-4a96-b101-7b87be32bf42",
   "metadata": {
    "id": "fc834702-c0d3-4a96-b101-7b87be32bf42"
   },
   "outputs": [],
   "source": [
    "data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698",
   "metadata": {
    "id": "d62bb2ab-750a-45e7-82e9-61d6f4805698"
   },
   "source": [
    "### Evaluation Metrics"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66fee1a7-a44c-461e-b047-c3917221572e",
   "metadata": {
    "id": "66fee1a7-a44c-461e-b047-c3917221572e"
   },
   "source": [
    "We'll use the word error rate (WER) metric, the 'de-facto' metric for assessing \n",
    "ASR systems. For more information, refer to the WER [docs](https://huggingface.co/metrics/wer). We'll load the WER metric from 🤗 Evaluate:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b22b4011-f31f-4b57-b684-c52332f92890",
   "metadata": {
    "id": "b22b4011-f31f-4b57-b684-c52332f92890"
   },
   "outputs": [],
   "source": [
    "import evaluate\n",
    "\n",
    "metric = evaluate.load(\"wer\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508",
   "metadata": {
    "id": "4f32cab6-31f0-4cb9-af4c-40ba0f5fc508"
   },
   "source": [
    "We then simply have to define a function that takes our model \n",
    "predictions and returns the WER metric. This function, called\n",
    "`compute_metrics`, first replaces `-100` with the `pad_token_id`\n",
    "in the `label_ids` (undoing the step we applied in the \n",
    "data collator to ignore padded tokens correctly in the loss).\n",
    "It then decodes the predicted and label ids to strings. Finally,\n",
    "it computes the WER between the predictions and reference labels. \n",
    "Here, we have the option of evaluating with the 'normalised' transcriptions \n",
    "and predictions. We recommend you set this to `True` to benefit from the WER \n",
    "improvement obtained by normalising the transcriptions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52",
   "metadata": {
    "id": "23959a70-22d0-4ffe-9fa1-72b61e75bb52"
   },
   "outputs": [],
   "source": [
    "# evaluate with the 'normalised' WER\n",
    "do_normalize_eval = True\n",
    "\n",
    "def compute_metrics(pred):\n",
    "    pred_ids = pred.predictions\n",
    "    label_ids = pred.label_ids\n",
    "\n",
    "    # replace -100 with the pad_token_id\n",
    "    label_ids[label_ids == -100] = processor.tokenizer.pad_token_id\n",
    "\n",
    "    # we do not want to group tokens when computing the metrics\n",
    "    pred_str = processor.tokenizer.batch_decode(pred_ids, skip_special_tokens=True)\n",
    "    label_str = processor.tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n",
    "\n",
    "    if do_normalize_eval:\n",
    "        pred_str = [normalizer(pred) for pred in pred_str]\n",
    "        label_str = [normalizer(label) for label in label_str]\n",
    "\n",
    "    wer = 100 * metric.compute(predictions=pred_str, references=label_str)\n",
    "\n",
    "    return {\"wer\": wer}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "daf2a825-6d9f-4a23-b145-c37c0039075b",
   "metadata": {
    "id": "daf2a825-6d9f-4a23-b145-c37c0039075b"
   },
   "source": [
    "### Load a Pre-Trained Checkpoint"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "437a97fa-4864-476b-8abc-f28b8166cfa5",
   "metadata": {
    "id": "437a97fa-4864-476b-8abc-f28b8166cfa5"
   },
   "source": [
    "Now let's load the pre-trained Whisper `small` checkpoint. Again, this \n",
    "is trivial through use of 🤗 Transformers!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f",
   "metadata": {
    "id": "5a10cc4b-07ec-4ebd-ac1d-7c601023594f"
   },
   "outputs": [],
   "source": [
    "from transformers import WhisperForConditionalGeneration\n",
    "\n",
    "model = WhisperForConditionalGeneration.from_pretrained(\"openai/whisper-small\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a15ead5f-2277-4a39-937b-585c2497b2df",
   "metadata": {
    "id": "a15ead5f-2277-4a39-937b-585c2497b2df"
   },
   "source": [
    "Override generation arguments - no tokens are forced as decoder outputs (see [`forced_decoder_ids`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.forced_decoder_ids)), no tokens are suppressed during generation (see [`suppress_tokens`](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate.suppress_tokens)). Set `use_cache` to False since we're using gradient checkpointing, and the two are incompatible:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62038ba3-88ed-4fce-84db-338f50dcd04f",
   "metadata": {
    "id": "62038ba3-88ed-4fce-84db-338f50dcd04f"
   },
   "outputs": [],
   "source": [
    "model.config.forced_decoder_ids = None\n",
    "model.config.suppress_tokens = []\n",
    "model.config.use_cache = False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06",
   "metadata": {
    "id": "2178dea4-80ca-47b6-b6ea-ba1915c90c06"
   },
   "source": [
    "### Define the Training Configuration"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c21af1e9-0188-4134-ac82-defc7bdcc436",
   "metadata": {
    "id": "c21af1e9-0188-4134-ac82-defc7bdcc436"
   },
   "source": [
    "In the final step, we define all the parameters related to training. For more detail on the training arguments, refer to the Seq2SeqTrainingArguments [docs](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a",
   "metadata": {
    "id": "0ae3e9af-97b7-4aa0-ae85-20b23b5bcb3a"
   },
   "outputs": [],
   "source": [
    "from transformers import Seq2SeqTrainingArguments\n",
    "\n",
    "training_args = Seq2SeqTrainingArguments(\n",
    "    output_dir=\"./\",\n",
    "    per_device_train_batch_size=64,\n",
    "    gradient_accumulation_steps=1,  # increase by 2x for every 2x decrease in batch size\n",
    "    learning_rate=1e-5,\n",
    "    warmup_steps=500,\n",
    "    max_steps=5000,\n",
    "    gradient_checkpointing=True,\n",
    "    fp16=True,\n",
    "    evaluation_strategy=\"steps\",\n",
    "    per_device_eval_batch_size=8,\n",
    "    predict_with_generate=True,\n",
    "    generation_max_length=225,\n",
    "    save_steps=1000,\n",
    "    eval_steps=1000,\n",
    "    logging_steps=25,\n",
    "    report_to=[\"tensorboard\"],\n",
    "    load_best_model_at_end=True,\n",
    "    metric_for_best_model=\"wer\",\n",
    "    greater_is_better=False,\n",
    "    push_to_hub=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3a944d8-3112-4552-82a0-be25988b3857",
   "metadata": {
    "id": "b3a944d8-3112-4552-82a0-be25988b3857"
   },
   "source": [
    "**Note**: if one does not want to upload the model checkpoints to the Hub, \n",
    "set `push_to_hub=False`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bac29114-d226-4f54-97cf-8718c9f94e1e",
   "metadata": {
    "id": "bac29114-d226-4f54-97cf-8718c9f94e1e"
   },
   "source": [
    "We can forward the training arguments to the 🤗 Trainer along with our model,\n",
    "dataset, data collator and `compute_metrics` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d546d7fe-0543-479a-b708-2ebabec19493",
   "metadata": {
    "id": "d546d7fe-0543-479a-b708-2ebabec19493"
   },
   "outputs": [],
   "source": [
    "from transformers import Seq2SeqTrainer\n",
    "\n",
    "trainer = Seq2SeqTrainer(\n",
    "    args=training_args,\n",
    "    model=model,\n",
    "    train_dataset=common_voice[\"train\"],\n",
    "    eval_dataset=common_voice[\"test\"],\n",
    "    data_collator=data_collator,\n",
    "    compute_metrics=compute_metrics,\n",
    "    tokenizer=processor.feature_extractor,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "uOrRhDGtN5S4",
   "metadata": {
    "id": "uOrRhDGtN5S4"
   },
   "source": [
    "We'll save the processor object once before starting training. Since the processor is not trainable, it won't change over the course of training:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "-2zQwMfEOBJq",
   "metadata": {
    "id": "-2zQwMfEOBJq"
   },
   "outputs": [],
   "source": [
    "processor.save_pretrained(training_args.output_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f404cf9-4345-468c-8196-4bd101d9bd51",
   "metadata": {
    "id": "7f404cf9-4345-468c-8196-4bd101d9bd51"
   },
   "source": [
    "### Training"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112",
   "metadata": {
    "id": "5e8b8d56-5a70-4f68-bd2e-f0752d0bd112"
   },
   "source": [
    "Training will take approximately 5-10 hours depending on your GPU. The peak GPU memory for the given training configuration is approximately 36GB. \n",
    "Depending on your GPU, it is possible that you will encounter a CUDA `\"out-of-memory\"` error when you launch training. \n",
    "In this case, you can reduce the `per_device_train_batch_size` incrementally by factors of 2 \n",
    "and employ [`gradient_accumulation_steps`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.Seq2SeqTrainingArguments.gradient_accumulation_steps)\n",
    "to compensate.\n",
    "\n",
    "To launch training, simply execute:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de",
   "metadata": {
    "id": "ee8b7b8e-1c9a-4d77-9137-1778a629e6de"
   },
   "outputs": [],
   "source": [
    "trainer.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3",
   "metadata": {
    "id": "810ced54-7187-4a06-b2fe-ba6dcca94dc3"
   },
   "source": [
    "We can label our checkpoint with the `whisper-event` tag on push by setting the appropriate key-word arguments (kwargs):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c704f91e-241b-48c9-b8e0-f0da396a9663",
   "metadata": {
    "id": "c704f91e-241b-48c9-b8e0-f0da396a9663"
   },
   "outputs": [],
   "source": [
    "kwargs = {\n",
    "    \"dataset_tags\": \"mozilla-foundation/common_voice_11_0\",\n",
    "    \"dataset\": \"Common Voice 11.0\",  # a 'pretty' name for the training dataset\n",
    "    \"language\": \"hi\",\n",
    "    \"model_name\": \"Whisper Small Hi - Sanchit Gandhi\",  # a 'pretty' name for your model\n",
    "    \"finetuned_from\": \"openai/whisper-small\",\n",
    "    \"tasks\": \"automatic-speech-recognition\",\n",
    "    \"tags\": \"whisper-event\",\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "090d676a-f944-4297-a938-a40eda0b2b68",
   "metadata": {
    "id": "090d676a-f944-4297-a938-a40eda0b2b68"
   },
   "source": [
    "The training results can now be uploaded to the Hub. To do so, execute the `push_to_hub` command and save the preprocessor object we created:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7030622-caf7-4039-939b-6195cdaa2585",
   "metadata": {
    "id": "d7030622-caf7-4039-939b-6195cdaa2585"
   },
   "outputs": [],
   "source": [
    "trainer.push_to_hub(**kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba",
   "metadata": {
    "id": "ca743fbd-602c-48d4-ba8d-a2fe60af64ba"
   },
   "source": [
    "## Closing Remarks"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f737783-2870-4e35-aa11-86a42d7d997a",
   "metadata": {
    "id": "7f737783-2870-4e35-aa11-86a42d7d997a"
   },
   "source": [
    "In this blog, we covered a step-by-step guide on fine-tuning Whisper for multilingual ASR \n",
    "using 🤗 Datasets, Transformers and the Hugging Face Hub. For more details on the Whisper model, the Common Voice dataset and the theory behind fine-tuning, refere to the accompanying [blog post](https://huggingface.co/blog/fine-tune-whisper). If you're interested in fine-tuning other \n",
    "Transformers models, both for English and multilingual ASR, be sure to check out the \n",
    "examples scripts at [examples/pytorch/speech-recognition](https://github.com/huggingface/transformers/tree/main/examples/pytorch/speech-recognition)."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "include_colab_link": true,
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}