File size: 58,016 Bytes
7934b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Buffered_Transducer_Inference_with_LCS_Merge.ipynb",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "hrnsEZRzgooE"
      },
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell.\n",
        "\n",
        "## Install dependencies\n",
        "!pip install wget\n",
        "!apt-get install sox libsndfile1 ffmpeg\n",
        "!pip install text-unidecode\n",
        "!pip install matplotlib>=3.3.2\n",
        "\n",
        "## Install NeMo\n",
        "BRANCH = 'r1.17.0'\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
        "\n",
        "# Update numba and restart (this is required to update internal numba version of Colab)\n",
        "\n",
        "# In a conda environment, you would use the following command\n",
        "# Update Numba to > 0.54\n",
        "# conda install -c conda-forge numba>=0.54\n",
        "# or\n",
        "# conda update -c conda-forge numba>=0.54\n",
        "\n",
        "# For pip based environments,\n",
        "# Update Numba to > 0.54\n",
        "import os\n",
        "import signal\n",
        "\n",
        "!pip install --upgrade numba\n",
        "\n",
        "# This will kill the kernel, click next cell to import the latest numba\n",
        "os.kill(os.getpid(), signal.SIGKILL)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Buffered Transducer evaluation with Longest Common Subsequence Merge\n",
        "\n",
        "In the [Buffered Transducer Inference](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/asr/Buffered_Transducer_Inference.ipynb) tutorial, we discussed how we could perform Streaming/Buffered inference with Transducer models by using a technique which we term as `\"Middle Token\" selection` from a buffer.\n",
        "\n",
        "In this notebook, we will perform buffered ASR speech recognition and utilize another algorithm to merge buffers during inference. We term this method as the `\"Longest Common Subsequence\" (LCS) Merge` algorithm.\n",
        "\n",
        "While the `Middle Token` algorithm works well in general, it is not a perfect merge algorithm and can make mistakes. We, therefore, compare against the `LCS Merge` algorithm and discuss the merits of both approaches. \n",
        "\n",
        "-----\n",
        "\n",
        "You may use this script [ASR Chunked Streaming Inference](https://github.com/NVIDIA/NeMo/blob/stable/examples/asr/asr_chunked_inference/rnnt/speech_to_text_buffered_infer_rnnt.py) to transcribe long audio files with Transducer models as well as experiment with both merge algorithms. \n"
      ],
      "metadata": {
        "id": "cPuPBSU0ioJO"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "------\n",
        "\n",
        "**Note**: It is highly recommended to review the ``Streaming ASR`` tutorial for a good overview of how streaming/buffered inference works for CTC models and the underlying motivation of streaming ASR itself.\n",
        "\n",
        "------"
      ],
      "metadata": {
        "id": "ylQ3GwvX-n7R"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Prepare the dataset\n",
        "\n",
        "We will reuse the Librispeech dev-clean subset of [Mini Librispeech](https://www.openslr.org/31/). This time, we will not concatenate the audio segments but simply evaluate them in buffered mode over all the audio samples.\n",
        "\n",
        "**Note**: Conformer inference over the entire dev set will take an exorbitant amount of time on the CPU. We recommend the use of GPU for this tutorial."
      ],
      "metadata": {
        "id": "2eDAsjyCi3lc"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Download and prepare Mini Librispeech"
      ],
      "metadata": {
        "id": "fBYvC3lyjM7O"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Prepare dataset and manifest for Libripeech Dev Clean subset.\n",
        "import os\n",
        "\n",
        "if not os.path.exists(\"scripts/get_librispeech_data.py\"):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/stable/scripts/dataset_processing/get_librispeech_data.py\n",
        "\n",
        "# If something goes wrong during data processing, un-comment the following line to delete the cached dataset \n",
        "# !rm -rf datasets/mini-dev-clean\n",
        "!mkdir -p datasets/mini-dev-clean\n",
        "\n",
        "!python scripts/get_librispeech_data.py \\\n",
        "  --data_root \"datasets/mini-dev-clean/\" \\\n",
        "  --data_sets dev_clean_2 \\\n",
        "  --num_workers=10 \\\n",
        "  --log"
      ],
      "metadata": {
        "cellView": "form",
        "id": "LBiTnpz6iket"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "manifest = os.path.join(os.getcwd(), \"datasets/mini-dev-clean/dev_clean_2.json\")\n",
        "print(\"Manifest path :\", manifest)"
      ],
      "metadata": {
        "id": "KHcy1Jbx8d9V"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Prepare the model\n",
        "\n",
        "We will use the same Conformer Transducer model used in the `Buffered Transducer Inference` tutorial, which will provide a fair comparison between the proposed merge algorithms described here."
      ],
      "metadata": {
        "id": "8g61qBwgkHiw"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import torch\n",
        "import nemo.collections.asr as nemo_asr\n",
        "import contextlib\n",
        "import gc\n",
        "\n",
        "# Helper for torch amp autocast\n",
        "if torch.cuda.is_available():\n",
        "    autocast = torch.cuda.amp.autocast\n",
        "else:\n",
        "    @contextlib.contextmanager\n",
        "    def autocast():\n",
        "        print(\"AMP was not available, using FP32!\")\n",
        "        yield\n",
        "\n",
        "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
        "device"
      ],
      "metadata": {
        "id": "j9UHfsR1j-uf"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "pretrained_model_name = \"stt_en_conformer_transducer_large\""
      ],
      "metadata": {
        "id": "CzkoimqKl07U"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Clear up memory\n",
        "torch.cuda.empty_cache()\n",
        "gc.collect()\n",
        "model = nemo_asr.models.EncDecRNNTBPEModel.from_pretrained(pretrained_model_name, map_location=device)\n",
        "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
        "# device = 'cpu'  # You can transcribe even longer samples on the CPU, though it will take much longer !\n",
        "model = model.to(device)\n",
        "model.freeze()"
      ],
      "metadata": {
        "id": "0LjtehkvlvKE"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Longest Common Subsequence Merge\n",
        "\n",
        "Below, we construct the `Longest Common Subsequence Merge` algorithm to merge two consecutive transcript buffers - termed `i-1`th and `i`th buffers. The concept is similar to the work discussed in the paper [Partially Overlapped Inference for Long-Form Speech Recognition](https://ieeexplore.ieee.org/document/9414941) but operates on the notion of subword buffers rather than character tokens.\n",
        "\n",
        "In contrast to the `Middle Token` algorithm, which utilizes certain seconds of both past and future context in order to determine the \"middle tokens\" for that current buffer, the `LCS Merge` algorithm merges only consecutive buffers by selecting the overlap between the end of the `i-1`th buffer and the beginning of the `i`th buffer sub-word tokens, then removing the overlapped tokens from the `i`th buffer.\n",
        "\n",
        "While the idea is simple, since the same text can be represented by a different combination of sub-words, some additional expansion steps must be accounted for to account for imperfect alignment between two buffers."
      ],
      "metadata": {
        "id": "OPZqcbNEnRkI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "### Utility Functions ###\n",
        "def print_alignment(alignment):\n",
        "    \"\"\"\n",
        "    Print an alignment matrix of the shape (m + 1, n + 1)\n",
        "\n",
        "    Args:\n",
        "        alignment: An integer alignment matrix of shape (m + 1, n + 1)\n",
        "    \"\"\"\n",
        "    m = len(alignment)\n",
        "    if m > 0:\n",
        "        n = len(alignment[0])\n",
        "        for i in range(m):\n",
        "            for j in range(n):\n",
        "                if j == 0:\n",
        "                    print(f\"{i:4d} |\", end=\" \")\n",
        "                print(f\"{alignment[i][j]}\", end=\" \")\n",
        "            print()\n",
        "\n",
        "\n",
        "def write_lcs_alignment_to_pickle(alignment, filepath, extras=None):\n",
        "    \"\"\"\n",
        "    Writes out the LCS alignment to a file, along with any extras provided.\n",
        "\n",
        "    Args:\n",
        "        alignment: An alignment matrix of shape [m + 1, n + 1]\n",
        "        filepath: str filepath\n",
        "        extras: Optional dictionary of items to preserve.\n",
        "    \"\"\"\n",
        "    if extras is None:\n",
        "        extras = {}\n",
        "\n",
        "    extras['alignment'] = alignment\n",
        "    torch.save(extras, filepath)"
      ],
      "metadata": {
        "id": "pEPLZyJP_zx2"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Algorithm overview\n",
        "\n",
        "At a high level, the algorithm can be decomposed into the following steps - \n",
        "\n",
        "1. Construct Longest Common Subsequence suffix matrix for initial alignment of text from old and new buffers.\n",
        "2. Detect partial alignment or complete alignment.\n",
        "3. If partial alignment, Loop over LCS suffix matrix to perform a dual objective search: <br>\n",
        "  3.1 Find largest score for LCS at the leftmost target axis: <br>\n",
        "      \n",
        "      This fixed cases where intermediate tokens are an exact match to subsequent buffer getting deleted (causing a larger merge than expected and incurring a high deletion rate). <br>\n",
        "\n",
        "  3.2 Then perform greedy expansion of this suffix: <br>\n",
        "\n",
        "      Perform a loop descending towards the end of the suffix matrix, expanding the search space. <br>\n",
        "      Limit expansion width such that only one additional token can escape per step (prevent extremely far away tokens from the current position from being used for expanded) <br>\n",
        "5. Perform a backward trace of the LCS suffix matrix to find detached sections to know the beginning index of slice and length of slice.\n",
        "6. Finally, check that beginning index of slice < max number of buffer chunks; if true, then slice off new buffer\n",
        " "
      ],
      "metadata": {
        "id": "EwPrhOP2_7D2"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Minimum number of tokens required to assign a LCS merge step, otherwise ignore and\n",
        "# select all i-1 and ith buffer tokens to merge.\n",
        "MIN_MERGE_SUBSEQUENCE_LEN = 1\n",
        "\n",
        "### LCS algorithm ###\n",
        "def longest_common_subsequence_merge(X, Y, filepath=None):\n",
        "    \"\"\"\n",
        "    Longest Common Subsequence merge algorithm for aligning two consecutive buffers.\n",
        "\n",
        "    Base alignment construction algorithm is Longest Common Subsequence (reffered to as LCS hear after)\n",
        "\n",
        "    LCS Merge algorithm looks at two chunks i-1 and i, determines the aligned overlap at the\n",
        "    end of i-1 and beginning of ith chunk, and then clips the subsegment of the ith chunk.\n",
        "\n",
        "    Assumption is that the two chunks are consecutive chunks, and there exists at least small overlap acoustically.\n",
        "\n",
        "    It is a sub-word token merge algorithm, operating on the abstract notion of integer ids representing the subword ids.\n",
        "    It is independent of text or character encoding.\n",
        "\n",
        "    Since the algorithm is merge based, and depends on consecutive buffers, the very first buffer is processed using\n",
        "    the \"middle tokens\" algorithm.\n",
        "\n",
        "    It requires a delay of some number of tokens such that:\n",
        "        lcs_delay = math.floor(((total_buffer_in_secs - chunk_len_in_sec)) / model_stride_in_secs)\n",
        "\n",
        "    Total cost of the model is O(m_{i-1} * n_{i}) where (m, n) represents the number of subword ids of the buffer.\n",
        "\n",
        "    Args:\n",
        "        X: The subset of the previous chunk i-1, sliced such X = X[-(lcs_delay * max_steps_per_timestep):]\n",
        "            Therefore there can be at most lcs_delay * max_steps_per_timestep symbols for X, preserving computation.\n",
        "        Y: The entire current chunk i.\n",
        "        filepath: Optional filepath to save the LCS alignment matrix for later introspection.\n",
        "\n",
        "    Returns:\n",
        "        A tuple containing -\n",
        "            - i: Start index of alignment along the i-1 chunk.\n",
        "            - j: Start index of alignment along the ith chunk.\n",
        "            - slice_len: number of tokens to slice off from the ith chunk.\n",
        "        The LCS alignment matrix itself (shape m + 1, n + 1)\n",
        "    \"\"\"\n",
        "    # LCSuff is the table with zero\n",
        "    # value initially in each cell\n",
        "    m = len(X)\n",
        "    n = len(Y)\n",
        "    LCSuff = [[0 for k in range(n + 1)] for l in range(m + 1)]\n",
        "\n",
        "    # To store the length of\n",
        "    # longest common substring\n",
        "    result = 0\n",
        "    result_idx = [0, 0, 0]  # Contains (i, j, slice_len)\n",
        "\n",
        "    # Following steps to build\n",
        "    # LCSuff[m+1][n+1] in bottom up fashion\n",
        "    for i in range(m + 1):\n",
        "        for j in range(n + 1):\n",
        "            if i == 0 or j == 0:\n",
        "                LCSuff[i][j] = 0\n",
        "            elif X[i - 1] == Y[j - 1]:\n",
        "                LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1\n",
        "\n",
        "                if result <= LCSuff[i][j]:\n",
        "                    result = LCSuff[i][j]\n",
        "                    result_idx = [i, j, result]\n",
        "\n",
        "            else:\n",
        "                LCSuff[i][j] = 0\n",
        "\n",
        "    # Check if perfect alignment was found or not\n",
        "    # Perfect alignment is found if :\n",
        "    # Longest common subsequence extends to the final row of of the old buffer\n",
        "    # This means that there exists a diagonal LCS backtracking to the beginning of the new buffer\n",
        "    i, j = result_idx[0:2]\n",
        "    is_complete_merge = i == m\n",
        "\n",
        "    # Perfect alignment was found, slice eagerly\n",
        "    if is_complete_merge:\n",
        "        length = result_idx[-1]\n",
        "\n",
        "        # In case the LCS was incomplete - missing a few tokens at the beginning\n",
        "        # Perform backtrack to find the origin point of the slice (j) and how many tokens should be sliced\n",
        "        while length >= 0 and i > 0 and j > 0:\n",
        "            # Alignment exists at the required diagonal\n",
        "            if LCSuff[i - 1][j - 1] > 0:\n",
        "                length -= 1\n",
        "                i, j = i - 1, j - 1\n",
        "\n",
        "            else:\n",
        "                # End of longest alignment\n",
        "                i, j, length = i - 1, j - 1, length - 1\n",
        "                break\n",
        "\n",
        "    else:\n",
        "        # Expand hypothesis to catch partial mismatch\n",
        "\n",
        "        # There are 3 steps for partial mismatch in alignment\n",
        "        # 1) Backward search for leftmost LCS\n",
        "        # 2) Greedy expansion of leftmost LCS to the right\n",
        "        # 3) Backtrack final leftmost expanded LCS to find origin point of slice\n",
        "\n",
        "        # (1) Backward search for Leftmost LCS\n",
        "        # This is required for cases where multiple common subsequences exist\n",
        "        # We only need to select the leftmost one - since that corresponds\n",
        "        # to the last potential subsequence that matched with the new buffer.\n",
        "        # If we just chose the LCS (and not the leftmost LCS), then we can potentially\n",
        "        # slice off major sections of text which are repeated between two overlapping buffers.\n",
        "\n",
        "        # backward linear search for leftmost j with longest subsequence\n",
        "        max_j = 0\n",
        "        max_j_idx = n\n",
        "\n",
        "        i_partial = m  # Starting index of i for partial merge\n",
        "        j_partial = -1  # Index holder of j for partial merge\n",
        "        j_skip = 0  # Number of tokens that were skipped along the diagonal\n",
        "        slice_count = 0  # Number of tokens that should be sliced\n",
        "\n",
        "        # Select leftmost LCS\n",
        "        for i_idx in range(m, -1, -1):  # start from last timestep of old buffer\n",
        "            for j_idx in range(0, n + 1):  # start from first token from new buffer\n",
        "                # Select the longest LCSuff, while minimizing the index of j (token index for new buffer)\n",
        "                if LCSuff[i_idx][j_idx] > max_j and j_idx <= max_j_idx:\n",
        "                    max_j = LCSuff[i_idx][j_idx]\n",
        "                    max_j_idx = j_idx\n",
        "\n",
        "                    # Update the starting indices of the partial merge\n",
        "                    i_partial = i_idx\n",
        "                    j_partial = j_idx\n",
        "\n",
        "        # EARLY EXIT (if max subsequence length <= MIN merge length)\n",
        "        # Important case where there is long silence\n",
        "        # The end of one buffer will have many blank tokens, the beginning of new buffer may have many blank tokens\n",
        "        # As such, LCS will potentially be from the region of actual tokens.\n",
        "        # This can be detected as the max length of the suffix in LCS\n",
        "        # If this max length of the leftmost suffix is less than some margin, avoid slicing all together.\n",
        "        if max_j <= MIN_MERGE_SUBSEQUENCE_LEN:\n",
        "            # If the number of partiial tokens to be deleted are less than the minimum,\n",
        "            # dont delete any tokens at all.\n",
        "\n",
        "            i = i_partial\n",
        "            j = 0\n",
        "            result_idx[-1] = 0\n",
        "\n",
        "        else:\n",
        "            # Some valid long partial alignment was found\n",
        "            # (2) Expand this alignment along the diagonal *downwards* towards the end of the old buffer\n",
        "            # such that i_partial = m + 1.\n",
        "            # This is a common case where due to LSTM state or reduced buffer size, the alignment breaks\n",
        "            # in the middle but there are common subsequences between old and new buffers towards the end\n",
        "            # We can expand the current leftmost LCS in a diagonal manner downwards to include such potential\n",
        "            # merge regions.\n",
        "\n",
        "            # Expand current partial subsequence with co-located tokens\n",
        "            i_temp = i_partial + 1  # diagonal next i\n",
        "            j_temp = j_partial + 1  # diagonal next j\n",
        "\n",
        "            j_exp = 0  # number of tokens to expand along the diagonal\n",
        "            j_skip = 0  # how many diagonals didnt have the token. Incremented by 1 for every row i\n",
        "\n",
        "            for i_idx in range(i_temp, m + 1):  # walk from i_partial + 1 => m + 1\n",
        "                j_any_skip = 0  # If the diagonal element at this location is not found, set to 1\n",
        "                # j_any_skip expands the search space one place to the right\n",
        "                # This allows 1 diagonal misalignment per timestep i (and expands the search for the next timestep)\n",
        "\n",
        "                # walk along the diagonal corresponding to i_idx, plus allowing diagonal skips to occur\n",
        "                # diagonal elements may not be aligned due to ASR model predicting\n",
        "                # incorrect token in between correct tokens\n",
        "                for j_idx in range(j_temp, j_temp + j_skip + 1):\n",
        "                    if j_idx < n + 1:\n",
        "                        if LCSuff[i_idx][j_idx] == 0:\n",
        "                            j_any_skip = 1\n",
        "                        else:\n",
        "                            j_exp = 1 + j_skip + j_any_skip\n",
        "\n",
        "                # If the diagonal element existed, dont expand the search space,\n",
        "                # otherwise expand the search space 1 token to the right\n",
        "                j_skip += j_any_skip\n",
        "\n",
        "                # Move one step to the right for the next diagonal j corresponding to i\n",
        "                j_temp += 1\n",
        "\n",
        "            # reset j_skip, augment j_partial with expansions\n",
        "            j_skip = 0\n",
        "            j_partial += j_exp\n",
        "\n",
        "            # (3) Given new leftmost j_partial with expansions, backtrack the partial alignments\n",
        "            # counting how many diagonal skips occured to compute slice length\n",
        "            # as well as starting point of slice.\n",
        "\n",
        "            # Partial backward trace to find start of slice\n",
        "            while i_partial > 0 and j_partial > 0:\n",
        "                if LCSuff[i_partial][j_partial] == 0:\n",
        "                    # diagonal skip occured, move j to left 1 extra time\n",
        "                    j_partial -= 1\n",
        "                    j_skip += 1\n",
        "\n",
        "                if j_partial > 0:\n",
        "                    # If there are more steps to be taken to the left, slice off the current j\n",
        "                    # Then loop for next (i, j) diagonal to the upper left\n",
        "                    slice_count += 1\n",
        "                    i_partial -= 1\n",
        "                    j_partial -= 1\n",
        "\n",
        "            # Recompute total slice length as slice count along diagonal\n",
        "            # plus the number of diagonal skips\n",
        "            i = max(0, i_partial)\n",
        "            j = max(0, j_partial)\n",
        "            result_idx[-1] = slice_count + j_skip\n",
        "\n",
        "    # Set the value of i and j\n",
        "    result_idx[0] = i\n",
        "    result_idx[1] = j\n",
        "\n",
        "    if filepath is not None:\n",
        "        extras = {\n",
        "            \"is_complete_merge\": is_complete_merge,\n",
        "            \"X\": X,\n",
        "            \"Y\": Y,\n",
        "            \"slice_idx\": result_idx,\n",
        "        }\n",
        "        write_lcs_alignment_to_pickle(LCSuff, filepath=filepath, extras=extras)\n",
        "        print(\"Wrote alignemnt to :\", filepath)\n",
        "\n",
        "    return result_idx, LCSuff\n",
        "\n",
        "\n"
      ],
      "metadata": {
        "id": "AOBFADPdoJc8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Merge Overview\n",
        "\n",
        "Now that the LCS suffix matrix has been backtracked to obtain the starting index of the slice and the length of the slice, the merge algorithm has a simple task of simply slicing off a portion of the new buffer.\n",
        "\n",
        "There are a few cases when merging buffers, discussed below : \n",
        "\n",
        "1. If there is no future context provided (i.e., chunk size == buffer size), then there is no need to merge tokens since there is no overlap possible. Then, concatenate all tokens emitted from the previous and current buffers.\n",
        "\n",
        "2. For the first buffer, since there isn't a \"previous buffer\", utilize the `Middle Token` algorithm to select tokens of the first buffer and do not perform LCS merge.\n",
        "\n",
        "3. To reduce the quadratic cost of the LCS suffix matrix computation, we pre-slice a subset of the tokens by the limit of `lcs_delay * max_symbols_per_step`. \n",
        "\n",
        "  > Since $lcs\\_delay = \\frac{total\\_buffer\\_in\\_seconds \\: - \\: chunk\\_size\\_in\\_sec}{model\\_stride\\_in\\_sec}$, it is usually just a small amount such as 10-20 time steps. Overall, this limits the number of tokens in the previous buffer to close to 100 or so tokens, thereby limiting the cost of the LCS suffix matrix.\n",
        "\n",
        "4. Compute the start index and slice length using the computed LCS merge.\n",
        "\n",
        "5. Slice off the new data (`i`th chunk)\n",
        "\n",
        "6. Merge the previous and current subset of the chunk and return the merged buffer."
      ],
      "metadata": {
        "id": "QeCGszfO_5cI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def lcs_alignment_merge_buffer(buffer, data, delay, model, max_steps_per_timestep: int = 5, filepath: str = None):\n",
        "    \"\"\"\n",
        "    Merges the new text from the current frame with the previous text contained in the buffer.\n",
        "\n",
        "    The alignment is based on a Longest Common Subsequence algorithm, with some additional heuristics leveraging\n",
        "    the notion that the chunk size is >= the context window. In case this assumptio is violated, the results of the merge\n",
        "    will be incorrect (or at least obtain worse WER overall).\n",
        "    \"\"\"\n",
        "    # If delay timesteps is 0, that means no future context was used. Simply concatenate the buffer with new data.\n",
        "    if delay < 1:\n",
        "        buffer += data\n",
        "        return buffer\n",
        "\n",
        "    # If buffer is empty, simply concatenate the buffer and data.\n",
        "    if len(buffer) == 0:\n",
        "        buffer += data\n",
        "        return buffer\n",
        "\n",
        "    # Prepare a subset of the buffer that will be LCS Merged with new data\n",
        "    search_size = int(delay * max_steps_per_timestep)\n",
        "    buffer_slice = buffer[-search_size:]\n",
        "\n",
        "    # Perform LCS Merge\n",
        "    lcs_idx, lcs_alignment = longest_common_subsequence_merge(buffer_slice, data, filepath=filepath)\n",
        "\n",
        "    # Slice off new data\n",
        "    # i, j, slice_len = lcs_idx\n",
        "    slice_idx = lcs_idx[1] + lcs_idx[-1]  # slice = j + slice_len\n",
        "    data = data[slice_idx:]\n",
        "\n",
        "    # Concat data to buffer\n",
        "    buffer += data\n",
        "    return buffer"
      ],
      "metadata": {
        "id": "_6r78fEm_48d"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# LCS Merge algorithm as a basis for Buffered ASR\n",
        "\n",
        "Next, let us extend the previous `BatchedFrameASRRNNT` codebase for Buffered Transducer to incorporate the new merge algorithm.\n",
        "\n",
        "We will note that the vast majority of the code remains unchanged - only the `transcribe` function has been changed to utilize the new merge algorithm."
      ],
      "metadata": {
        "id": "Bz31XOhLqu3z"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.collections.asr.parts.utils import streaming_utils\n",
        "from torch.utils.data import DataLoader\n",
        "\n",
        "\n",
        "class LongestCommonSubsequenceBatchedFrameASRRNNT(streaming_utils.BatchedFrameASRRNNT):\n",
        "    \"\"\"\n",
        "    Implements a token alignment algorithm for text alignment instead of middle token alignment.\n",
        "\n",
        "    For more detail, read the docstring of longest_common_subsequence_merge().\n",
        "    \"\"\"\n",
        "\n",
        "    def __init__(self, asr_model, frame_len=1.6, total_buffer=4.0,\n",
        "        batch_size=4, max_steps_per_timestep: int = 5, stateful_decoding: bool = False, \n",
        "        alignment_basepath: str = None,\n",
        "    ):\n",
        "        '''\n",
        "        Args:\n",
        "            asr_model: An RNNT model.\n",
        "            frame_len: frame's duration, seconds.\n",
        "            total_buffer: duration of total audio chunk size, in seconds.\n",
        "            batch_size: Number of independent audio samples to process at each step.\n",
        "            max_steps_per_timestep: Maximum number of tokens (u) to process per acoustic timestep (t).\n",
        "            stateful_decoding: Boolean whether to enable stateful decoding for preservation of state across buffers.\n",
        "            alignment_basepath: Str path to a directory where alignments from LCS will be preserved for later analysis.\n",
        "        '''\n",
        "        super().__init__(asr_model, frame_len, total_buffer, batch_size, max_steps_per_timestep, stateful_decoding)\n",
        "        self.sample_offset = 0\n",
        "        self.lcs_delay = -1\n",
        "        self.alignment_basepath = alignment_basepath\n",
        "\n",
        "    def transcribe(\n",
        "        self, tokens_per_chunk: int, delay: int,\n",
        "    ):\n",
        "        if self.lcs_delay < 0:\n",
        "            raise ValueError(\n",
        "                \"Please set LCS Delay valus as `(buffer_duration - chunk_duration) / model_stride_in_secs`\"\n",
        "            )\n",
        "\n",
        "        self.infer_logits()\n",
        "\n",
        "        self.unmerged = [[] for _ in range(self.batch_size)]\n",
        "        for idx, alignments in enumerate(self.all_alignments):\n",
        "\n",
        "            signal_end_idx = self.frame_bufferer.signal_end_index[idx]\n",
        "            if signal_end_idx is None:\n",
        "                raise ValueError(\"Signal did not end\")\n",
        "\n",
        "            for a_idx, alignment in enumerate(alignments):\n",
        "\n",
        "                # Middle token algorithm for the first chunk\n",
        "                if a_idx == 0:\n",
        "                    alignment = alignment[len(alignment) - 1 - delay :]\n",
        "                    ids, toks = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id)\n",
        "\n",
        "                    if len(ids) > 0:\n",
        "                        self.unmerged[idx] = streaming_utils.inplace_buffer_merge(\n",
        "                            self.unmerged[idx], ids, delay, model=self.asr_model,\n",
        "                        )\n",
        "\n",
        "                else:\n",
        "                    # Use LCS Merge algorithm for remaining chunks\n",
        "                    ids, toks = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id)\n",
        "                    if len(ids) > 0 and a_idx < signal_end_idx:\n",
        "                        \n",
        "                        # Preserve the LCS alignments if a alignment path was provided\n",
        "                        if self.alignment_basepath is not None:\n",
        "                            basepath = self.alignment_basepath\n",
        "                            sample_offset = self.sample_offset + idx\n",
        "                            alignment_offset = a_idx\n",
        "                            path = os.path.join(basepath, str(sample_offset))\n",
        "\n",
        "                            os.makedirs(path, exist_ok=True)\n",
        "                            path = os.path.join(path, \"alignment_\" + str(alignment_offset) + '.pt')\n",
        "\n",
        "                            filepath = path\n",
        "                        else:\n",
        "                            filepath = None \n",
        "\n",
        "                        # Perform LCS merge\n",
        "                        self.unmerged[idx] = lcs_alignment_merge_buffer(\n",
        "                            self.unmerged[idx],\n",
        "                            ids,\n",
        "                            self.lcs_delay,\n",
        "                            model=self.asr_model,\n",
        "                            max_steps_per_timestep=self.max_steps_per_timestep,\n",
        "                            filepath=filepath,\n",
        "                        )\n",
        "\n",
        "        output = []\n",
        "        for idx in range(self.batch_size):\n",
        "            output.append(self.greedy_merge(self.unmerged[idx]))\n",
        "        return output\n"
      ],
      "metadata": {
        "id": "wNgmc68nl1Ri"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Comparing \"Middle Token\" and \"LCS Merge\"\n",
        "\n",
        "While we propose the two algorithms - `Middle Token` and `LCS Merge`, we would recommend using either algorithm in the appropriate circumstances. The `Middle Token` algorithm performs well in general, and its mistakes are often fewer than the `LCS Merge` algorithm but requires future context, which may increase latency by a small amount. There are also cases where `LCS Merge` may select better alignments and result in slightly better scores for some audio samples.\n",
        "\n",
        "In general, we propose these approaches to discuss further and research merge algorithms that show some trade-off between latency and accuracy."
      ],
      "metadata": {
        "id": "0fmD9goyrmEb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Change Decoding Strategy for Buffered Inference\n",
        "# Change Decoding Config\n",
        "from omegaconf import OmegaConf, open_dict\n",
        "\n",
        "decoding_cfg = model.cfg.decoding\n",
        "with open_dict(decoding_cfg):\n",
        "    decoding_cfg.strategy = \"greedy_batch\"\n",
        "    decoding_cfg.preserve_alignments = True  # required to compute the middle token for transducers.\n",
        "    decoding_cfg.fused_batch_size = -1  # temporarily stop fused batch during inference.\n",
        "\n",
        "model.change_decoding_strategy(decoding_cfg)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "FlIGOc_yl4aQ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Helper methods to transcribe audio in buffered mode\n",
        "\n",
        "import tqdm\n",
        "import math\n",
        "\n",
        "def transcribe_buffers(asr_decoder, audio_filepaths, chunk_len_in_secs, buffer_len_in_secs, model_stride):\n",
        "  model.freeze()\n",
        "  model_stride_in_secs = asr_decoder.asr_model.cfg.preprocessor.window_stride * model_stride\n",
        "  tokens_per_chunk = math.ceil(chunk_len_in_secs / model_stride_in_secs)\n",
        "  mid_delay = math.ceil((chunk_len_in_secs + (buffer_len_in_secs - chunk_len_in_secs) / 2) / model_stride_in_secs)\n",
        "  lcs_delay = math.floor(((buffer_len_in_secs - chunk_len_in_secs)) / model_stride_in_secs)\n",
        "\n",
        "  hyps = []\n",
        "  batch_size = asr_decoder.batch_size \n",
        "\n",
        "  with torch.inference_mode():\n",
        "    with torch.cuda.amp.autocast():\n",
        "      batch = []\n",
        "      asr_decoder.sample_offset = 0\n",
        "      asr_decoder.lcs_delay = lcs_delay\n",
        "\n",
        "      for idx in tqdm.tqdm(range(len(audio_filepaths)), desc='Sample:', total=len(audio_filepaths)):\n",
        "          batch.append(audio_filepaths[idx],)\n",
        "\n",
        "          if len(batch) == batch_size:\n",
        "              audio_files = [sample for sample in batch]\n",
        "\n",
        "              asr_decoder.reset()\n",
        "              asr_decoder.read_audio_file(audio_files, mid_delay, model_stride_in_secs)\n",
        "              hyp_list = asr_decoder.transcribe(tokens_per_chunk, mid_delay)\n",
        "              hyps.extend(hyp_list)\n",
        "\n",
        "              batch.clear()\n",
        "              asr_decoder.sample_offset += batch_size\n",
        "\n",
        "      if len(batch) > 0:\n",
        "          asr_decoder.batch_size = len(batch)\n",
        "          asr_decoder.frame_bufferer.batch_size = len(batch)\n",
        "          asr_decoder.reset()\n",
        "\n",
        "          audio_files = [sample for sample in batch]\n",
        "          asr_decoder.read_audio_file(audio_files, mid_delay, model_stride_in_secs)\n",
        "          hyp_list = asr_decoder.transcribe(tokens_per_chunk, mid_delay)\n",
        "          hyps.extend(hyp_list)\n",
        "\n",
        "          batch.clear()\n",
        "          asr_decoder.sample_offset += len(batch)\n",
        "  \n",
        "  print(\"Finished transcribing audio files\")\n",
        "  return hyps"
      ],
      "metadata": {
        "id": "laPBH4eJsiJk",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Select data subset\n",
        "\n",
        "On the GPU, it would take a few minutes to perform inference for the entire dataset, but on the CPU, it would take quite a long time. While the defaults will exist for the whole dataset, if only the CPU is available for some reason, we encourage you to subsample the dataset."
      ],
      "metadata": {
        "id": "csSNtwziubeM"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Manifest helper\n",
        "import json\n",
        "import numpy as np\n",
        "from nemo.collections.asr.parts.utils.manifest_utils import read_manifest\n",
        "\n",
        "\n",
        "def subset_manifest(manifest, num_samples):\n",
        "  rng = np.random.RandomState(seed=0)\n",
        "  num_samples = min(len(manifest), num_samples)\n",
        "\n",
        "  if num_samples < len(manifest):\n",
        "    ids = rng.choice(np.arange(len(manifest)), size=num_samples, replace=False)\n",
        "    ids = ids.tolist()\n",
        "  else:\n",
        "    ids = np.arange(len(manifest)).tolist()\n",
        "\n",
        "  sub_manifest = []\n",
        "  for idx in ids:\n",
        "    sub_manifest.append(manifest[idx])\n",
        "  \n",
        "  print(f\"Prepared subset manifest with {len(sub_manifest)} samples.\")\n",
        "  return sub_manifest"
      ],
      "metadata": {
        "cellView": "form",
        "id": "QoZ0fG8zuf5E"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "manifest_data = read_manifest(manifest)\n",
        "print(f\"Read {len(manifest_data)} samples from manifest {manifest}\")"
      ],
      "metadata": {
        "id": "I8dnQRL6umrO"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "num_samples = len(manifest_data)\n",
        "\n",
        "#########################################################\n",
        "sub_manifest = subset_manifest(manifest_data, num_samples)\n",
        "audio_filepaths = [sample['audio_filepath'] for sample in sub_manifest]\n",
        "ground_texts = [sample['text'] for sample in sub_manifest]"
      ],
      "metadata": {
        "id": "zZOTSFHsuswe"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Buffered Inference arguments\n",
        "\n",
        "Below we detail some critical arguments for buffered transducer inference. Note that the primary difference between streaming and buffered inference would be the chunk length, with larger values contributing to a lower word error rate but higher latency. "
      ],
      "metadata": {
        "id": "GURl8G2Bwlad"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "chunk_len_in_secs: float = 8.0\n",
        "context_len_in_secs: float = 1.0\n",
        "model_stride: int = 4  # 4 for conformers, 8 for contextnet\n",
        "\n",
        "batch_size: int = 64  # Select a low value for CPU such as 4 or 8.\n",
        "lcs_alignments_path = os.path.join(os.getcwd(), \"lcs_alignments\")\n",
        "max_steps_per_timestep: int = model.cfg.decoding.greedy.max_symbols\n",
        "        \n",
        "##########################################################################\n",
        "buffer_len_in_secs = chunk_len_in_secs + 2* context_len_in_secs\n"
      ],
      "metadata": {
        "id": "gF86J9Knwpe_"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Baseline: Middle Token Predictions\n",
        "\n",
        "Now compute the transcriptions over the data subset using the baseline algorithm - `Middle Token`. "
      ],
      "metadata": {
        "id": "C1s93TbcwZNt"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "asr_middle = streaming_utils.BatchedFrameASRRNNT(model, chunk_len_in_secs, buffer_len_in_secs,\n",
        "                                                 batch_size=batch_size, max_steps_per_timestep=max_steps_per_timestep)"
      ],
      "metadata": {
        "id": "PsqjMkeEu4oK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "middle_transcripts = transcribe_buffers(asr_middle, audio_filepaths, chunk_len_in_secs, buffer_len_in_secs, model_stride)"
      ],
      "metadata": {
        "id": "sNQNDjroxWb8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.collections.asr.metrics.wer import word_error_rate\n",
        "\n",
        "wer_middle = word_error_rate(middle_transcripts, ground_texts, use_cer=False)\n",
        "print(\"Middle token algorithm WER :\", wer_middle)"
      ],
      "metadata": {
        "id": "ENGTX70QzcrB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## LCS Merge Predictions\n",
        "\n",
        "Next, let us compute the transcriptions over the data subset using the `LCS Merge` algorithm."
      ],
      "metadata": {
        "id": "Z3hCweGDy12t"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "asr_lcs = LongestCommonSubsequenceBatchedFrameASRRNNT(model, chunk_len_in_secs, buffer_len_in_secs,\n",
        "                                                      batch_size=batch_size, max_steps_per_timestep=max_steps_per_timestep,\n",
        "                                                      alignment_basepath=lcs_alignments_path)"
      ],
      "metadata": {
        "id": "E7DBDeBPx4cJ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "lcs_transcripts = transcribe_buffers(asr_lcs, audio_filepaths, chunk_len_in_secs, buffer_len_in_secs, model_stride)"
      ],
      "metadata": {
        "id": "BQo9TNSyzPfv"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "wer_lcs = word_error_rate(lcs_transcripts, ground_texts, use_cer=False)\n",
        "print(\"LCS algorithm WER :\", wer_lcs)"
      ],
      "metadata": {
        "id": "IXW6I3hDzT6I"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Compare the text predictions from the two merge algorithms\n",
        "\n",
        "Depending on the data subset chosen (or randomly sampled), the WER for this algorithm may be higher or lower than the baseline. Note that if you select all the samples in the dataset, then the WER of this method is slightly higher than the baseline.\n",
        "\n",
        "We will do a more in-depth analysis of the failure cases below."
      ],
      "metadata": {
        "id": "MjGfb1x00egs"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def compare_algorithms(ground_truth, middle_transcripts, lcs_transcripts, use_cer=False):\n",
        "  worse = []\n",
        "  better = []\n",
        "  same = []\n",
        "\n",
        "  for idx, (ground_text, middle_data, lcs_data) in enumerate(zip(ground_truth, middle_transcripts, lcs_transcripts)):\n",
        "      middle_wer = word_error_rate([middle_data], [ground_text], use_cer=use_cer)\n",
        "      lcs_wer = word_error_rate([lcs_data], [ground_text], use_cer=use_cer)\n",
        "\n",
        "      if middle_wer < lcs_wer:\n",
        "          worse.append((idx, ground_text, middle_data, lcs_data))\n",
        "\n",
        "      elif middle_wer > lcs_wer:\n",
        "          better.append((idx, ground_text, middle_data, lcs_data))\n",
        "      \n",
        "      else:\n",
        "          same.append((idx, ground_text, middle_data, lcs_data))\n",
        "  \n",
        "  print(\"Number of samples where both algorithms obtained same WER :\", len(same))\n",
        "  print(\"Number of samples LCS merge was better than middle ground :\", len(better))\n",
        "  print(\"Number of samples LCS merge was worse than middle ground  :\", len(worse))\n",
        "  return same, better, worse"
      ],
      "metadata": {
        "id": "80NvUa1Y0dk7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "both_same, lcs_better, lcs_worse = compare_algorithms(ground_texts, middle_transcripts, lcs_transcripts, use_cer=False)"
      ],
      "metadata": {
        "id": "A-NIFnjo0KB5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# EXTRA: Compare the alignment matrices of LCS\n",
        "\n",
        "Over the entire dataset, there would be some samples where the `LCS Merge` algorithm did better than the `Middle Token` algorithm and vice-versa. Below, we will take a sample-level look at such cases, and since the `LCS Merge` algorithm is an alignment-based technique, we can visualize the alignment itself and determine what cases it failed and the source of the error in the alignment itself.\n"
      ],
      "metadata": {
        "id": "awZNviRC5C-O"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title LCS Alignment helper functions\n",
        "\n",
        "from torch.cuda import stream\n",
        "import torch\n",
        "import glob\n",
        "\n",
        "def try_load_alignments(alignmen_dir, idx):\n",
        "    basepath = os.path.abspath(alignmen_dir)\n",
        "    sample_path = os.path.join(basepath, str(idx))\n",
        "    \n",
        "    files = list(glob.glob(f\"{sample_path}/*.pt\"))\n",
        "    alignments = []\n",
        "    if len(files) > 0:\n",
        "        print(f\"Found {len(files)} alignments\")\n",
        "        for i in range(1, len(files) + 1):\n",
        "            path = os.path.join(sample_path, f\"alignment_{i}.pt\")\n",
        "            alignments.append(torch.load(path))\n",
        "    \n",
        "    return alignments\n",
        "\n",
        "def extract_alignments(alignments):\n",
        "    all_alignments = []\n",
        "    for data in alignments:\n",
        "        all_alignments.append(data['alignment'])\n",
        "    \n",
        "    return all_alignments\n",
        "\n",
        "def find_first_sample_with_alignment(alignment_dir, samples, start_idx: int = 0):\n",
        "    for idx in range(start_idx, len(samples)):\n",
        "        sample = samples[idx]\n",
        "        alignments = try_load_alignments(alignment_dir, sample[0])\n",
        "        if len(alignments) > 0:\n",
        "            return idx\n",
        "\n",
        "def print_alignment(alignment):\n",
        "    m = len(alignment)\n",
        "    if m > 0:\n",
        "        streaming_utils.print_alignment(alignment)\n",
        "\n",
        "def greedy_decode(asr_model, preds):\n",
        "    decoded_prediction = [p for p in preds]\n",
        "    hypothesis = asr_model.tokenizer.ids_to_text(decoded_prediction)\n",
        "    hyp_subwords = asr_model.tokenizer.ids_to_tokens(decoded_prediction)\n",
        "    return hypothesis, hyp_subwords\n",
        "\n",
        "def display_alignment_merge(alignment_path, sample, \n",
        "                            print_xy_token_ids: bool = False,\n",
        "                            print_xy_text: bool = True,\n",
        "                            print_alignments: bool = True,\n",
        "                            max_steps_per_timestep: int = None):\n",
        "\n",
        "  model_stride_in_secs = model.cfg.preprocessor.window_stride * model_stride\n",
        "  lcs_delay = math.floor(((buffer_len_in_secs - chunk_len_in_secs)) / model_stride_in_secs)\n",
        "  if max_steps_per_timestep is None:\n",
        "    max_steps_per_timestep = model.cfg.decoding.greedy.max_symbols\n",
        "\n",
        "  alignments_meta = try_load_alignments(alignment_path, sample[0])\n",
        "  alignments = extract_alignments(alignments_meta)\n",
        "\n",
        "  print(\"Sample Meta Info\")\n",
        "  print()\n",
        "  if print_xy_token_ids:\n",
        "    for idx in range(len(alignments_meta)):\n",
        "      print(\"X\", alignments_meta[idx]['X'])\n",
        "      print(\"Y\", alignments_meta[idx]['Y'])\n",
        "      print()\n",
        "    print()\n",
        "\n",
        "  if print_xy_text:\n",
        "    for idx in range(len(alignments_meta)):\n",
        "      x_text, x_subwords = greedy_decode(model, alignments_meta[idx]['X'])\n",
        "      y_text, y_subwords = greedy_decode(model, alignments_meta[idx]['Y'])\n",
        "      \n",
        "      X = alignments_meta[idx]['X'].copy()\n",
        "      Y = alignments_meta[idx]['Y'].copy()\n",
        "      search_size = int(lcs_delay * max_steps_per_timestep)\n",
        "\n",
        "      result = streaming_utils.lcs_alignment_merge_buffer(X, Y, lcs_delay, model, max_steps_per_timestep)\n",
        "      result, _ = greedy_decode(model, result)\n",
        "\n",
        "      print(\"Alignment step :\", idx)\n",
        "      print(\"Is there perfect alignment match for merge :\", alignments_meta[idx]['is_complete_merge']) \n",
        "      print()\n",
        "      print(\"Ground truth :\", sample[1])\n",
        "      print(\"Merge Result :\", result)\n",
        "      print(\"X text       :\", x_text)\n",
        "      print(\"Y text       :\", y_text)\n",
        "      print(\"Slice index  :\", alignments_meta[idx]['slice_idx'][1:], \"(start index, slice length in subword tokens)\")\n",
        "      print()\n",
        "\n",
        "      if print_alignments:\n",
        "        print_alignment(alignments[idx][-search_size:])\n",
        "        print()\n",
        "      print()\n",
        "    print()\n",
        "\n",
        "        "
      ],
      "metadata": {
        "cellView": "form",
        "id": "SiW4xw424lB1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Worse alignment\n",
        "\n",
        "Let us search for a sample where the `LCS Merge` did worse than the `Middle Token` algorithm. \n",
        "\n",
        "Such cases are necessary to analyze because it is visually apparent where the alignment went wrong. We can determine if there could be an extension to this algorithm to further improve such cases.\n"
      ],
      "metadata": {
        "id": "_DEYtkP46Srw"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "worse_idx = find_first_sample_with_alignment(lcs_alignments_path, lcs_worse, start_idx=0)\n",
        "worse_sample = lcs_worse[worse_idx]\n",
        "\n",
        "print(\"A sample where LCS did worse than Middle Token merge algoritm :\")\n",
        "print(\"The texts are structured as (Ground Truth, Middle Token, LCS Merge)\")\n",
        "worse_sample"
      ],
      "metadata": {
        "id": "rt7c-qoH5a30"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "display_alignment_merge(lcs_alignments_path, worse_sample, print_xy_token_ids=False)"
      ],
      "metadata": {
        "id": "_wBepfcH7kAK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Better alignment\n",
        "\n",
        "Next, let us search for a sample where the `LCS Merge` did better than the `Middle Token` algorithm. \n",
        "\n",
        "Such cases are also essential to analyze because it is visually apparent where the alignment was better. We can determine if we can improve the `Middle Token` algorithm."
      ],
      "metadata": {
        "id": "Z-xHYGIEJXBx"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "better_idx = find_first_sample_with_alignment(lcs_alignments_path, lcs_better, start_idx=0)\n",
        "better_sample = lcs_better[better_idx]\n",
        "\n",
        "print(\"A sample where LCS did better than Middle Token merge algoritm :\")\n",
        "print(\"The texts are structured as (Ground Truth, Middle Token, LCS Merge)\")\n",
        "better_sample"
      ],
      "metadata": {
        "id": "AHBx3QpQE5OX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "display_alignment_merge(lcs_alignments_path, better_sample)"
      ],
      "metadata": {
        "id": "urjYWVGfJhlU"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Final notes\n",
        "\n",
        "Following the [Buffered Transducer Inference](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/asr/Buffered_Transducer_Inference.ipynb) tutorial and designing a token merge algorithm that can be a simple extension to the baseline `Middle Token` algorithm, we see that there are cases where both algorithms have their uses. \n",
        "\n",
        "To expand our research effort on developing more sophisticated streaming / buffered transducer inference methods, we encourage the users to try these algorithms in script format for efficient inference on large datasets - available at [ASR Chunked Streaming Inference](https://github.com/NVIDIA/NeMo/blob/stable/examples/asr/asr_chunked_inference/rnnt/speech_to_text_buffered_infer_rnnt.py).\n"
      ],
      "metadata": {
        "id": "GRFifXuROpzg"
      }
    }
  ]
}