File size: 52,820 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
{
    "cells": [
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "BRANCH = 'r1.17.0'"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "o_0K1lsW1dj9"
            },
            "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",
                "\"\"\"\n",
                "# If you're using Google Colab and not running locally, run this cell\n",
                "\n",
                "# install NeMo\n",
                "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "uglDB-pVh__t",
                "pycharm": {
                    "name": "#%%\n"
                }
            },
            "outputs": [],
            "source": [
                "# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:\n",
                "# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'\n",
                "\n",
                "! pip install ipywidgets\n",
                "! jupyter nbextension enable --py widgetsnbextension\n",
                "\n",
                "# Please restart the kernel after running this cell"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "dzqD2WDFOIN-"
            },
            "outputs": [],
            "source": [
                "from nemo.utils.exp_manager import exp_manager\n",
                "from nemo.collections import nlp as nemo_nlp\n",
                "\n",
                "import os\n",
                "import wget \n",
                "import torch\n",
                "import pytorch_lightning as pl\n",
                "from omegaconf import OmegaConf"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "daYw_Xll2ZR9"
            },
            "source": [
                "# Task Description\n",
                "Automatic Speech Recognition (ASR) systems typically generate text with no punctuation and capitalization of the words. \n",
                "This tutorial explains how to implement a model in NeMo that will predict punctuation and capitalization for each word in a sentence to make ASR output more readable and to boost performance of the named entity recognition, machine translation or text-to-speech models. \n",
                "We'll show how to train a model for this task using a pre-trained BERT model. \n",
                "For every word in our training dataset we’re going to predict:\n",
                "\n",
                "- punctuation mark that should follow the word and\n",
                "- whether the word should be capitalized"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "ZnuziSwJ1yEB"
            },
            "source": [
                "# Dataset\n",
                "This model can work with any dataset as long as it follows the format specified below. \n",
                "The training and evaluation data is divided into *2 files: text.txt and labels.txt*. \n",
                "Each line of the **text.txt** file contains text sequences, where words are separated with spaces: [WORD] [SPACE] [WORD] [SPACE] [WORD], for example:"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "TXFORGBv2Jqu"
            },
            "source": [
                "\n",
                "\n",
                "```\n",
                "when is the next flight to new york\n",
                "the next flight is ...\n",
                "...\n",
                "```\n",
                "\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "Y7ci55rM2QH8"
            },
            "source": [
                "The **labels.txt** file contains corresponding labels for each word in text.txt, the labels are separated with spaces. Each label in labels.txt file consists of 2 symbols:\n",
                "\n",
                "- the first symbol of the label indicates what punctuation mark should follow the word (where O means no punctuation needed);\n",
                "- the second symbol determines if a word needs to be capitalized or not (where U indicates that the word should be upper cased, and O - no capitalization needed.)\n",
                "\n",
                "In this tutorial, we are considering only commas, periods, and question marks the rest punctuation marks were removed. To use more punctuation marks, update the dataset to include desired labels, no changes to the model needed. \n",
                "\n",
                "Each line of the **labels.txt** should follow the format: \n",
                "[LABEL] [SPACE] [LABEL] [SPACE] [LABEL] (for labels.txt). \n",
                "For example, labels for the above text.txt file should be:"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "-94C1-864EW1"
            },
            "source": [
                "\n",
                "\n",
                "```\n",
                "OU OO OO OO OO OO OU ?U\n",
                "OU OO OO OO ...\n",
                "...\n",
                "```\n",
                "\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "VsEmwIPO4L4V"
            },
            "source": [
                "The complete list of all possible labels for this task used in this tutorial is: `OO, ,O, .O, ?O, OU, ,U, .U, ?U.`"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "SL58EWkd2ZVb"
            },
            "source": [
                "## Download and preprocess the data¶"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "THi6s1Qx2G1k"
            },
            "source": [
                "In this notebook we are going to use a subset of English examples from the [Tatoeba collection of sentences](https://tatoeba.org/eng) this script will download and preprocess the Tatoeba data [NeMo/examples/nlp/token_classification/get_tatoeba_data.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/data/get_tatoeba_data.py). Note, for further experiments with the model, set NUM_SAMPLES=-1 and consider including other datasets to improve model performance. \n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "n8HZrDmr12_-"
            },
            "outputs": [],
            "source": [
                "DATA_DIR = 'PATH_TO_A_DIRECTORY_WHERE_DATA_FROM_THIS_TUTORIAL_IS_STORED'\n",
                "WORK_DIR = 'PATH_TO_A_DIRECTORY_WHERE_SCRIPTS_FOR_THIS_TUTORIAL_ARE_SAVED'\n",
                "MODEL_CONFIG = \"punctuation_capitalization_config.yaml\"\n",
                "\n",
                "# model parameters\n",
                "TOKENS_IN_BATCH = 1024\n",
                "MAX_SEQ_LENGTH = 64\n",
                "LEARNING_RATE = 0.00002\n",
                "NUM_SAMPLES = 10000"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "UOeeeCGqI-9c"
            },
            "outputs": [],
          "source": [
            "## download get_tatoeba_data.py script to download and preprocess the Tatoeba data\n",
            "os.makedirs(WORK_DIR, exist_ok=True)\n",
            "if not os.path.exists(f\"{WORK_DIR}/get_tatoeba_data.py\"):\n",
            "    print('Downloading get_tatoeba_data.py...')\n",
            "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/data/get_tatoeba_data.py', WORK_DIR)\n",
            "else:\n",
            "    print ('get_tatoeba_data.py already exists')"
      ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "H0ulD2TL13DR"
            },
            "outputs": [],
            "source": [
                "# download and preprocess the data\n",
                "# --clean_dir flag deletes raw Tataoeba data, remove the flag to avoid multiple data downloads if you want to experiment with the dataset size\n",
                "! python $WORK_DIR/get_tatoeba_data.py --data_dir $DATA_DIR --num_sample $NUM_SAMPLES --clean_dir"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "pctMm2vsPlPT"
            },
            "source": [
                "after execution of the above cell, your data folder will contain the following 4 files needed for training (raw Tatoeba data could be present if `--clean_dir` was not used):\n",
                "- labels_dev.txt\n",
                "- labels_train.txt\n",
                "- text_dev.txt\n",
                "- text_train.txt\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "KKwxXXezPvXF"
            },
            "outputs": [],
            "source": [
                "! ls -l $DATA_DIR"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "6UDPgadLN6SG"
            },
            "outputs": [],
            "source": [
                "# let's take a look at the data \n",
                "print('Text:')\n",
                "! head -n 5 $DATA_DIR/text_train.txt\n",
                "\n",
                "print('\\nLabels:')\n",
                "! head -n 5 $DATA_DIR/labels_train.txt"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
            "As you see, `get_tatoeba_data.py` script provides not only downloads Tatoeba but also creates labels. If you wish to preprocess your own data, use [examples/nlp/token_classification/data/prepare_data_for_punctuation_capitalization.py](https://github.com/NVIDIA/NeMo/blob/main/examples/nlp/token_classification/data/prepare_data_for_punctuation_capitalization.py) script:\n",
            "\n",
            "```\n",
            "NEMO_ROOT = \"<Path_to_NeMo>\"\n",
            "!python $NEMO_ROOT/examples/nlp/token_classification/data/prepare_data_for_punctuation_capitalization.py \\\n",
            "    --source_file $DATA_DIR/text_train.txt \\\n",
            "    --output_dir $DATA_DIR/my_train_preprocessed\n",
            "```"
          ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "!ls $DATA_DIR/my_train_preprocessed -l"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "# Tarred dataset\n",
                "\n",
                "If your dataset is too large to be stored in memory, you can use tarred dataset. A tarred dataset is a collection of tarred files which contain batches ready for passing into a model.\n",
                "\n",
                "All tar files will contain identical number of batches, so if number of batches in the dataset is not evenly divisible by parameter `--num_batches_per_tar_file` value, then up to `--num_batches_per_tar_file - 1` batches may be lost."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# Number of lines in text and labels files\n",
                "!wc -l $DATA_DIR/text_train.txt\n",
                "!wc -l $DATA_DIR/labels_train.txt"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
          "source": [
            "## download script to prepare tarred dataset\n",
            "os.makedirs(WORK_DIR, exist_ok=True)\n",
            "if not os.path.exists(f\"{WORK_DIR}/create_punctuation_capitalization_tarred_dataset.py\"):\n",
            "    print('Downloading create_punctuation_capitalization_tarred_dataset.py...')\n",
            "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/data/create_punctuation_capitalization_tarred_dataset.py', WORK_DIR)\n",
            "else:\n",
            "    print (\"create_punctuation_capitalization_tarred_dataset.py script already exists\")\n",
            "\n",
            "!python $WORK_DIR/create_punctuation_capitalization_tarred_dataset.py \\\n",
            "    --text $DATA_DIR/text_train.txt \\\n",
            "    --labels $DATA_DIR/labels_train.txt \\\n",
            "    --output_dir $DATA_DIR/train_tarred \\\n",
            "    --num_batches_per_tarfile 5 \\\n",
            "    --tokens_in_batch 1024 \\\n",
            "    --lines_per_dataset_fragment 4000 \\\n",
            "    --tokenizer_name bert-base-uncased \\\n",
            "    --n_jobs 2"
          ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "!ls $DATA_DIR/train_tarred -l"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "!ls $DATA_DIR/train_tarred/*.tar | wc -l  # number of tar files"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "!ls $DATA_DIR/train_tarred/ | grep -v '.tar'  # all not tar files"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "If you wish to use tarred dataset, then you need to \n",
                "- pass metadata JSON file in config parameter `model.train_ds.tar_metadata_file`,\n",
                "- set `model.train_ds.use_tarred_dataset=true`."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "daludzzL2Jba"
            },
            "source": [
                "# Model Configuration"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "_whKCxfTMo6Y"
            },
            "source": [
                "In the Punctuation and Capitalization Model, we are jointly training two token-level classifiers on top of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model: \n",
                "- one classifier to predict punctuation and\n",
                "- the other one - capitalization.\n",
                "\n",
                "The model is defined in a config file which declares multiple important sections. They are:\n",
                "- **model**: All arguments that are related to the Model - language model, token classifiers, optimizer and schedulers, dataset and any other related information\n",
                "\n",
                "- **trainer**: Any argument to be passed to PyTorch Lightning\n",
                "\n",
                "See [docs](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/main/nlp/punctuation_and_capitalization.html#training-punctuation-and-capitalization-model) for full config description."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "T1gA8PsJ13MJ"
            },
            "outputs": [],
            "source": [
                "# download the model's configuration file \n",
                "config_dir = WORK_DIR + '/configs/'\n",
                "os.makedirs(config_dir, exist_ok=True)\n",
                "if not os.path.exists(config_dir + MODEL_CONFIG):\n",
                "    print('Downloading config file...')\n",
                "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG, config_dir)\n",
                "else:\n",
                "    print ('config file already exists')"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "mX3KmWMvSUQw"
            },
            "outputs": [],
            "source": [
                "# this line will print the entire config of the model\n",
                "config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'\n",
                "print(config_path)\n",
                "config = OmegaConf.load(config_path)\n",
                "print(OmegaConf.to_yaml(config))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "ZCgWzNBkaQLZ"
            },
            "source": [
                "# Setting up Data within the config\n",
                "\n",
                "Among other things, the config file contains dictionaries called `common_dataset_parameters`, `train_ds` and `validation_ds`. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
                "\n",
                "Specify paths directories with train and dev datasets in parameters `train_ds.ds_item` and `validation_ds.ds_item`.\n",
                "\n",
                "I you want to use multiple datasets for evaluation, specify paths to the directory(ies) with evaluation file(s) in the following way:\n",
                "\n",
                "`model.validation_ds.ds_item=[PATH_TO_DEV1,PATH_TO_DEV2]` (Note no space between the paths and square brackets).\n",
                "\n",
                "Also notice that some configs, including `model.train_ds.ds_item`, have `???` in place of values, this values are required to be specified by the user.\n",
                "\n",
                "Let's now add the data directory path to the config."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "LQHCJN-ZaoLp"
            },
            "outputs": [],
            "source": [
                "# in this tutorial train and dev data is located in the same folder\n",
                "config.model.train_ds.ds_item = DATA_DIR\n",
                "config.model.validation_ds.ds_item=DATA_DIR\n",
                "del config.model.test_ds  # We do not have test data, only train and dev"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "nB96-3sTc3yk"
            },
            "source": [
                "# Building the PyTorch Lightning Trainer\n",
                "\n",
                "NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem!\n",
                "\n",
                "Let's first instantiate a Trainer object!"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "1tG4FzZ4Ui60"
            },
            "outputs": [],
            "source": [
                "print(\"Trainer config - \\n\")\n",
                "print(OmegaConf.to_yaml(config.trainer))"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "knF6QeQQdMrH"
            },
            "outputs": [],
            "source": [
                "# lets modify some trainer configs\n",
                "# checks if we have GPU available and uses it\n",
                "accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
                "config.trainer.devices = 1\n",
                "config.trainer.accelerator = accelerator\n",
                "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
                "\n",
                "# For mixed precision training, use precision=16 and amp_level=O1\n",
                "\n",
                "# Reduces maximum number of epochs to 1 for a quick training\n",
                "config.trainer.max_epochs = 1\n",
                "\n",
                "# Remove distributed training flags\n",
                "config.trainer.strategy = None\n",
                "\n",
                "trainer = pl.Trainer(**config.trainer)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "8IlEMdVxdr6p"
            },
            "source": [
                "# Setting up a NeMo Experiment¶\n",
                "\n",
                "NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it!"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "8uztqGAmdrYt"
            },
            "outputs": [],
            "source": [
                "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
                "\n",
                "# the exp_dir provides a path to the current experiment for easy access\n",
                "exp_dir = str(exp_dir)\n",
                "exp_dir"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "6FI_nQsJo_11"
            },
            "source": [
                "# Model Training"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "8tjLhUvL_o7_"
            },
            "source": [
                "Before initializing the model, we might want to modify some of the model configs. For example, we might want to modify the pretrained BERT model."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Xeuc2i7Y_nP5"
            },
            "outputs": [],
            "source": [
                "# complete list of supported BERT-like models\n",
                "print(nemo_nlp.modules.get_pretrained_lm_models_list())\n",
                "\n",
                "PRETRAINED_BERT_MODEL = \"bert-base-uncased\""
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "RK2xglXyAUOO"
            },
            "outputs": [],
            "source": [
                "# add the specified above model parameters to the config\n",
                "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL\n",
                "config.model.train_ds.tokens_in_batch = TOKENS_IN_BATCH\n",
                "config.model.validation_ds.tokens_in_batch = TOKENS_IN_BATCH\n",
                "config.model.optim.lr = LEARNING_RATE\n",
                "config.model.train_ds.num_samples = NUM_SAMPLES\n",
                "config.model.validation_ds.num_samples = NUM_SAMPLES\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "gYKcziSsiAAd"
            },
            "source": [
                "Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders we'll be prepared for training and evaluation.\n",
                "Also, the pretrained BERT model will be downloaded, note it can take up to a few minutes depending on the size of the chosen BERT model."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Yk2hJssviAAe",
                "pycharm": {
                    "name": "#%%\n"
                },
                "scrolled": false
            },
            "outputs": [],
            "source": [
                "# initialize the model\n",
                "# during this stage, the dataset and data loaders we'll be prepared for training and evaluation\n",
                "model = nemo_nlp.models.PunctuationCapitalizationModel(cfg=config.model, trainer=trainer)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "kQ592Tx4pzyB"
            },
            "source": [
                "## Monitoring training progress\n",
                "Optionally, you can create a Tensorboard visualization to monitor training progress."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "mTJr16_pp0aS"
            },
            "outputs": [],
            "source": [
                "try:\n",
                "  from google import colab\n",
                "  COLAB_ENV = True\n",
                "except (ImportError, ModuleNotFoundError):\n",
                "  COLAB_ENV = False\n",
                "\n",
                "# Load the TensorBoard notebook extension\n",
                "if COLAB_ENV:\n",
                "  %load_ext tensorboard\n",
                "  %tensorboard --logdir {exp_dir}\n",
                "else:\n",
                "  print(\"To use tensorboard, please use this notebook in a Google Colab environment.\")"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "hUvnSpyjp0Dh"
            },
            "outputs": [],
            "source": [
                "# start the training\n",
                "trainer.fit(model)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "# Training using tarred dataset"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "config = OmegaConf.load(config_path)\n",
                "config.model.train_ds.ds_item = f'{DATA_DIR}/train_tarred'\n",
                "config.model.train_ds.use_tarred_dataset = True\n",
                "# Only metadata file name is required if `use_tarred_dataset=true`.\n",
                "config.model.train_ds.tar_metadata_file = 'metadata.punctuation_capitalization.tokens1024.max_seq_length512.bert-base-uncased.json'\n",
                "config.model.validation_ds.ds_item = DATA_DIR\n",
                "del config.model.test_ds  # We do not have test data, only train and dev\n",
                "\n",
                "# Trainer\n",
                "accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
                "config.trainer.devices = 1\n",
                "config.trainer.accelerator = accelerator\n",
                "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
                "config.trainer.max_epochs = 1\n",
                "config.trainer.strategy = None\n",
                "\n",
                "# Exp manager\n",
                "config.exp_manager.explicit_log_dir = 'tarred_experiment'\n",
                "\n",
                "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL\n",
                "config.model.validation_ds.tokens_in_batch = TOKENS_IN_BATCH\n",
                "config.model.optim.lr = LEARNING_RATE\n",
                "config.model.validation_ds.num_samples = NUM_SAMPLES"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "trainer = pl.Trainer(**config.trainer)\n",
                "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
                "model = nemo_nlp.models.PunctuationCapitalizationModel(cfg=config.model, trainer=trainer)\n",
                "trainer.fit(model)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "VPdzJVAgSFaJ"
            },
            "source": [
                "# Inference using a pretrained model\n",
                "\n",
                "To see how the model performs, let’s run inference on a few examples."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "DQhsamclRtxJ"
            },
            "outputs": [],
            "source": [
                "print(f\"Available_models: {nemo_nlp.models.PunctuationCapitalizationModel.get_available_model_names()}\\n\")\n",
                "\n",
                "pretrained_model = nemo_nlp.models.PunctuationCapitalizationModel.from_pretrained(\"punctuation_en_distilbert\")\n",
                "# define the list of queiries for inference\n",
                "queries = [\n",
                "        'we bought four shirts and one mug from the nvidia gear store in santa clara',\n",
                "        'what can i do for you today',\n",
                "        'how are you',\n",
                "        'how is the weather in',\n",
                "    ]\n",
                "inference_results = pretrained_model.add_punctuation_capitalization(queries)\n",
                "print()\n",
                "\n",
                "for query, result in zip(queries, inference_results):\n",
                "    print(f'Query   : {query}')\n",
                "    print(f'Combined: {result.strip()}\\n')"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "Inference for large amounts of text can be performed by a script [examples/nlp/token_classification/punctuate_capitalize_infer.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/punctuate_capitalize_infer.py)\n",
                "\n",
                "```\n",
                "python punctuate_capitalize_infer.py \\\n",
                "    --input_manifest <PATH/TO/INPUT/MANIFEST> \\\n",
                "    --output_manifest <PATH/TO/OUTPUT/MANIFEST> \\\n",
                "    --pretrained_name punctuation_en_bert \\\n",
                "    --max_seq_length 64 \\\n",
                "    --margin 16 \\\n",
                "    --step 8\n",
                "```\n",
                "\n",
                "`<PATH/TO/INPUT/MANIFEST>` is a path to NeMo [ASR manifest](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/asr/datasets.html) which contains text in which you need to restore punctuation and capitalization. If manifest contains `'pred_text'` key, then `'pred_text'` elements will be processed. Otherwise, punctuation and capitalization will be restored in `'text'` elements.\n",
                "\n",
                "`<PATH/TO/OUTPUT/MANIFEST>` is a path to NeMo ASR manifest into which result will be saved. The text with restored\n",
                "punctuation and capitalization is saved into `'pred_text'` elements if `'pred_text'` key is present in\n",
                "input manifest. Otherwise result will be saved into `'text'` elements.\n",
                "\n",
                "Alternatively you can pass text for restoring punctuation and capitalization as plain text. See help for parameters `--input_text` and `--output_text` of the script\n",
                "[punctuate_capitalize_infer.py](https://github.com/NVIDIA/NeMo/blob/stable/examples/nlp/token_classification/punctuate_capitalize_infer.py).\n",
                "\n",
                "The script `examples/nlp/token_classification/punctuate_capitalize_infer.py` can restore punctuation and capitalization in a text of arbitrary length. Long sequences are split into segments\n",
                "`--max_seq_length - 2` tokens each. Each segment starts and ends with `[CLS]` and `[SEP]`\n",
                "tokens correspondingly. Every segment is offset to the previous one by `--step` tokens. For example, if\n",
                "every character is a token, `--max_seq_length=5`, `--step=2`, then text `\"hello\"` will be split into\n",
                "segments `[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]`.\n",
                "\n",
                "If segments overlap, then predicted probabilities for a token present in several segments are multiplied before selecting the best candidate.\n",
                "\n",
                "Splitting leads to pour performance of a model near edges of segments. Use parameter `--margin` to discard `--margin`\n",
                "probabilities predicted for `--margin` tokens near segment edges. For example, if every character is a token, `--max_seq_length=5`, `--step=1`, `--margin=1`, then text `\"hello\"` will be split into segments `[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'e', 'l', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]`. Before calculating actual predictions, probabilities for tokens marked by asterisk are removed: `[['[CLS]', 'h', 'e', 'l'*, '[SEP]'*], ['[CLS]'*, 'e'*, 'l', 'l'*, '[SEP]'*], ['[CLS]'*, 'l'*, 'l', 'o', '[SEP]']]`.\n",
                "\n",
                "You may use parameters `max_seq_length`, `step`, and `margin` in `add_punctuation_capitalization` method.\n",
                "\n",
                "The text in the following example is from IWSLT 2019 test dataset."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "inference_results = pretrained_model.add_punctuation_capitalization(\n",
                "    [\n",
                "        \"each of these songs represents a scene a movement in some cases a sonic revolution that completely altered the \"\n",
                "        \"course of popular music they're all also calling cards almost for those cities songs totally linked with their \"\n",
                "        \"city's identity and might be why you probably consider them to be music cities now the magical mythical thing \"\n",
                "        \"the thing we kind of all love about stories like these is that those cities weren't doing anything in particular \"\n",
                "        \"to make those moments happen there's no formula for capturing lightning in a bottle a formula didn't give us \"\n",
                "        \"grunge music or introduce tupock to dr dray and there's definitely no blueprint for how to open your record \"\n",
                "        \"business in a south memphis neighborhood that turns out is home to booker t jones william bell and albert king \"\n",
                "        \"so this is just something that happens and right when the stars perfectly align great music just happens and \"\n",
                "        \"in the meantime new york and nashville can churn out the hits that come through our radios define our \"\n",
                "        \"generations and soundtrack our weddings and our funerals and everything in between i don't know about you but \"\n",
                "        \"the very idea of that is just deadly boring to me there are musicians all around you making powerful important \"\n",
                "        \"music and thanks to the internet and it's limitless possibilities for creators to create music and fans to \"\n",
                "        \"discover that music those zyite guy songs don't have to be handed down to us from some conference room full of \"\n",
                "        \"songwriters in a corporate high rise but also and more importantly we can't decide that it's just something that \"\n",
                "        \"happens because music is about so much more than hits those big iconic moments that change everything it's more \"\n",
                "        \"than just entertainment for so many of us music is truly a way to navigate life a means of self expression sure \"\n",
                "        \"but it also helps us find ourrselfel worse and figure out who we are it connects us with other people as almost \"\n",
                "        \"nothing else can across language barriers across social and cultural and economic divides music makes us smarter \"\n",
                "        \"and healthier and happier music is necessary what if you lived in a city that believed that that said we're not \"\n",
                "        \"waiting for that hit song to define us we're a music city because music is necessary by seeing music as \"\n",
                "        \"necessary a city can build two things 1st an ecosystem to support the development of professional musicians \"\n",
                "        \"and music business and 2nd a receptive and engaged audience to sustain them and those are the two critical \"\n",
                "        \"elements of a music city a city whose leaders recognize the importance of music for our development as \"\n",
                "        \"individuals our connection as a community and our viability as a vibrant place to live see smart cities music \"\n",
                "        \"cities know that thriving night lifef a creative class culture is what attracts young talented people to cities \"\n",
                "        \"it's what brings that lightning and no we can't predict the next egg that will hatch but we can create a city \"\n",
                "        \"that acts like an incubator to do that 1st we got to know what we've got that means identifying and quantifying \"\n",
                "        \"our assets we need to know them backward and forward from who and what and where they are to what their impact \"\n",
                "        \"is on the economy let's count our recording studios and our record labels our historic landmarks and our \"\n",
                "        \"hardcore punk clubs we should count monthly free jazz nights and weekly folk jams music schools artist \"\n",
                "        \"development instrument shops every lay than every luther music museums open once a open year round and music \"\n",
                "        \"festivals open just one weekend year now ideally through this process we'll create an actual asset map \"\n",
                "        \"dropping a pin for each one allowing us to see exactly what we've got and where organic momentum is already \"\n",
                "        \"happening because it's not enough to paint in broad strokes here when it comes to specific support for music \"\n",
                "        \"locally and a broad understanding of a music brand nationally you've got to have the receipts next we'll need \"\n",
                "        \"to identify our challenges now it's important to knowe that for the most part this won't be just the opposite \"\n",
                "        \"of step one we won't gain a whole lot by simply thinking about what's missing from our map instead we need to \"\n",
                "        \"approach this more holistically there are lots of music venues on our map awesome but are they struggling do \"\n",
                "        \"we have a venue ladder which just means can an artist starting out at a coffee house open mike see a clear path \"\n",
                "        \"for how they'll grow from that 25 seat room to a hundred seat room and so on or are we expecting them to go from \"\n",
                "        \"a coffee house to a colossum maybe our challenges lie in city infrastructure public transportation affordable \"\n",
                "        \"housing maybe like in london where the number of music venues went from 400 in 2010 to 100 in 2015 we need to \"\n",
                "        \"think about protections against gentrification the mayor of london in december of last year actually added \"\n",
                "        \"something called the agent of change principle to the city's comprehensive plan the name says it all if a real \"\n",
                "        \"estate developer wants to build condos next to an existing music venue the developer is the agent of change they \"\n",
                "        \"have to take the necessary steps for noise mitigation next and this is a very big one we need leadership and we \"\n",
                "        \"need a strategy now we know there's a lot of magic in this mix a lot of right people right place right time and \"\n",
                "        \"that will never stop being an important element of the way music is made the way some of the best most enduring \"\n",
                "        \"music is made but there cannot be a leadership vacuum in 2018 surriving music cities don't often happen and \"\n",
                "        \"don't have to happen accidentally we need elected officials who recognize the power of music and elevate the \"\n",
                "        \"voices of creatives and they're ready to put a strategy in place in music cities from berlin to paris to bogata \"\n",
                "        \"music advisory councils ensure that musicians have a seat at the table they're volunteer councils and they work \"\n",
                "        \"directly with a designated advocate inside of city hall or even the chamber of commerce the strongest strategies \"\n",
                "        \"will build music community supports like this one inward while also exporting music outward they go hand in hand \"\n",
                "        \"when we look inward we create that place that musicians want to live and when we look outward we build \"\n",
                "        \"opportunities for them to advance their career while also driving attention back to our city and leveraging music \"\n",
                "        \"as a talent attraction tool and here's something else that will help with that we've got to figure out who we are \"\n",
                "        \"now when i say austin you probably think live music capital and why because in 1991 leadership in austin saw \"\n",
                "        \"something percolating with an existing asset and they chose to own it by recognizing that momentum naming it and \"\n",
                "        \"claiming it they inevitably caused more live music venues to open existing spaces to add live music to their \"\n",
                "        \"repertoire and they created a swell of civic buy in around the idea which meant that it wasn't just a slogan in \"\n",
                "        \"some tourism pamphlet was something that locals really started to believe and take pride in now generally \"\n",
                "        \"speaking what austin created is just an assets based narrative and when we think back to step one we know that \"\n",
                "        \"every city will not tick every box many cities won't have recording studios like memphis or a songwriter and \"\n",
                "        \"publishing scene like nashville and that's not a deal breaker we simply have to find the momentum happening in \"\n",
                "        \"our city what are our unique assets in comparison to no other place so if all of that sounds like something \"\n",
                "        \"you'd like to happen where you live here are three things you can do to move the needle 1st you can use your \"\n",
                "        \"feet your ears and your dollars show up be that receptive and engaged audience that is so necessary for a music \"\n",
                "        \"city to thrive pay a cover charge buy a record discover new music and please take your friends two you can use \"\n",
                "        \"your voice buy in to the assets based narrative talk about and celebrate what your city has and three you can \"\n",
                "        \"use your vote seek out leadership that doesn't just pay lip service to your city's music but recognizes its \"\n",
                "        \"power and is prepared to put a strategy in place to elevate it grow it and build collaboration no there really \"\n",
                "        \"is no telling what city could be defined by a certain scene or a certain song in the next decade but as much \"\n",
                "        \"as we absolutely cannot predict that what we absolutely can predict is what happens when we treat music as \"\n",
                "        \"necessary and we work to build a music city and that is a place where i want to live thank you\"\n",
                "    ],\n",
                "    max_seq_length=128,\n",
                "    step=8,\n",
                "    margin=16,\n",
                "    batch_size=32,\n",
                ")\n",
                "print(inference_results[0])"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "ref1qSonGNhP"
            },
            "source": [
                "## Training Script\n",
                "\n",
                "If you have NeMo installed locally, you can also train the model with [nlp/token_classification/punctuation_capitalization_train_evaluate.py](https://github.com/NVIDIA/NeMo/blob/main/examples/nlp/token_classification/punctuation_capitalization_train_evaluate.py).\n",
                "\n",
                "To run training script, use:\n",
                "\n",
                "`python punctuation_capitalization_train_evaluate.py model.train_ds.ds_item=PATH_TO_TRAIN_DATA_DIR`\n",
                "\n",
                "Set NUM_SAMPLES=-1 and consider including other datasets to improve the performance of the model.\n",
                "\n",
                "# Finetuning model with your data\n",
                "\n",
                "When we were training the model from scratch, the datasets were prepared for training during the model initialization. When we are using a pretrained Punctuation and Capitalization model, before training, we need to setup training and evaluation data."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "4X1BahRlkaNf"
            },
            "outputs": [],
            "source": [
                "# let's reload our pretrained model\n",
                "pretrained_model = nemo_nlp.models.PunctuationCapitalizationModel.from_pretrained('punctuation_en_distilbert')\n",
                "\n",
                "# setup train and validation Pytorch DataLoaders\n",
                "pretrained_model.update_config_after_restoring_from_checkpoint(\n",
                "    train_ds={\n",
                "        'ds_item': DATA_DIR,\n",
                "        'text_file': 'text_train.txt',\n",
                "        'labels_file': 'labels_train.txt',\n",
                "        'tokens_in_batch': 1024,\n",
                "    },\n",
                "    validation_ds={\n",
                "        'ds_item': DATA_DIR,\n",
                "        'text_file': 'text_dev.txt',\n",
                "        'labels_file': 'labels_dev.txt',\n",
                "        'tokens_in_batch': 1024,\n",
                "    },\n",
                ")\n",
                "\n",
                "# and now we can create a PyTorch Lightning trainer and call `fit` again\n",
                "# for this tutorial we are setting fast_dev_run to True, and the trainer will run 1 training batch and 1 validation batch\n",
                "# for actual model training, disable the flag\n",
                "fast_dev_run = True\n",
                "trainer = pl.Trainer(devices=1, accelerator='gpu', fast_dev_run=fast_dev_run)\n",
                "pretrained_model.set_trainer(trainer)\n",
                "pretrained_model.setup_training_data()\n",
                "pretrained_model.setup_validation_data()\n",
                "trainer.fit(pretrained_model)"
            ]
        }
    ],
    "metadata": {
        "accelerator": "GPU",
        "colab": {
            "collapsed_sections": [
                "daYw_Xll2ZR9"
            ],
            "name": "Punctuation_and_Capitalization.ipynb",
            "private_outputs": true,
            "provenance": []
        },
        "kernelspec": {
            "display_name": "Python 3 (ipykernel)",
            "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.12"
        },
        "pycharm": {
            "stem_cell": {
                "cell_type": "raw",
                "metadata": {
                    "collapsed": false
                },
                "source": []
            }
        }
    },
    "nbformat": 4,
    "nbformat_minor": 1
}