File size: 38,289 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
{
    "cells": [
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "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",
                "BRANCH = 'r1.17.0'\n",
                "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]\n",
                "\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "95FHWXOVpUFp",
                "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",
                "! 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": {
                "id": "dzqD2WDFOIN-"
            },
            "outputs": [],
            "source": [
                "from nemo.collections import nlp as nemo_nlp\n",
                "from nemo.utils.exp_manager import exp_manager\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": {
                "id": "daYw_Xll2ZR9"
            },
            "source": [
                "# Task Description\n",
                "**Sentiment Analysis** is the task of detecting the sentiment in text. We model this problem as a simple form of a text classification problem. For example `Gollum's performance is incredible!` has a positive sentiment while `It's neither as romantic nor as thrilling as it should be.` has a negative sentiment.\n",
                "."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "ZnuziSwJ1yEB"
            },
            "source": [
                "# Dataset\n",
                "\n",
                "In this tutorial we going to use [The Stanford Sentiment Treebank (SST-2)](https://nlp.stanford.edu/sentiment/index.html) corpus for sentiment analysis. This version of the dataset contains a collection of sentences with binary labels of positive and negative. It is a standard benchmark for sentence classification and is part of the GLUE Benchmark: https://gluebenchmark.com/tasks. Please download and unzip the SST-2 dataset from GLUE. It should contain three files of train.tsv, dev.tsv, and test.tsv which can be used for training, validation, and test respectively.\n",
                "\n",
                "\n",
                "\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "qzcZ3nb_-SVT"
            },
            "source": [
                "# NeMo Text Classification Data Format\n",
                "\n",
                "[TextClassificationModel](https://github.com/NVIDIA/NeMo/blob/stable/nemo/collections/nlp/models/text_classification/text_classification_model.py) in NeMo supports text classification problems such as sentiment analysis or domain/intent detection for dialogue systems, as long as the data follows the format specified below. \n",
                "\n",
                "TextClassificationModel requires the data to be stored in TAB separated files (.tsv) with two columns of sentence and label. Each line of the data file contains text sequences, where words are separated with spaces and label separated with [TAB], i.e.: \n",
                "\n",
                "```\n",
                "[WORD][SPACE][WORD][SPACE][WORD][TAB][LABEL]\n",
                "```\n",
                "\n",
                "For example:\n",
                "```\n",
                "hide new secretions from the parental units[TAB]0\n",
                "\n",
                "that loves its characters and communicates something rather beautiful about human nature[TAB]1\n",
                "...\n",
                "```\n",
                "\n",
                "\n",
                "If your dataset is stored in another format, you need to convert it to this format to use the TextClassificationModel. "
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "SL58EWkd2ZVb"
            },
            "source": [
                "## Download and Preprocess the Data\n",
                "\n",
                "First, you need to download the zipped file of the SST-2 dataset from the GLUE Benchmark website: https://gluebenchmark.com/tasks, and put it in the current folder. Then the following script would extract it into the data path specified by `DATA_DIR`:"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "n8HZrDmr12_-"
            },
            "outputs": [],
            "source": [
                "DATA_DIR = \"DATA_DIR\"\n",
                "WORK_DIR = \"WORK_DIR\"\n",
                "os.environ['DATA_DIR'] = DATA_DIR\n",
                "\n",
                "os.makedirs(WORK_DIR, exist_ok=True)\n",
                "os.makedirs(DATA_DIR, exist_ok=True)\n",
                "\n",
                "! wget https://dl.fbaipublicfiles.com/glue/data/SST-2.zip\n",
                "! unzip -o SST-2.zip -d {DATA_DIR}"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "U8Ty5_S7Ye8h"
            },
            "source": [
                "Now, the data folder should contain the following files:"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "L8vsyh3JZH26"
            },
            "source": [
                "\n",
                "\n",
                "* train.tsv\n",
                "* dev.tsv\n",
                "* test.tsv\n",
                "\n",
                "\n",
                "The format of `train.tsv` and `dev.tsv` is close to NeMo's format except to have an extra header line at the beginning of the files. We would remove these extra lines. But `test.tsv` has different format and labels are missing for this part of the data.\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "qB0oLE4R9EhJ"
            },
            "outputs": [],
            "source": [
                "! sed 1d {DATA_DIR}/SST-2/train.tsv > {DATA_DIR}/SST-2/train_nemo_format.tsv\n",
                "! sed 1d {DATA_DIR}/SST-2/dev.tsv > {DATA_DIR}/SST-2/dev_nemo_format.tsv\n",
                "! ls -l {DATA_DIR}/SST-2"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "6UDPgadLN6SG"
            },
            "outputs": [],
            "source": [
                "# let's take a look at the data \n",
                "print('Contents (first 5 lines) of train.tsv:')\n",
                "! head -n 5 {DATA_DIR}/SST-2/train_nemo_format.tsv\n",
                "\n",
                "print('\\nContents (first 5 lines) of test.tsv:')\n",
                "! head -n 5 {DATA_DIR}/SST-2/test.tsv"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "daludzzL2Jba"
            },
            "source": [
                "# Model Configuration"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "_whKCxfTMo6Y"
            },
            "source": [
                "Now, let's take a closer look at the model's configuration and learn to train the model from scratch and finetune the pretrained model.\n",
                "\n",
                "Our text classification model uses a pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model (or other BERT-like models) followed by a classification layer on the output of the first token ([CLS]).\n",
                "\n",
                "The model is defined in a config file which declares multiple important sections. The most important ones are:\n",
                "- **model**: All arguments that are related to the Model - language model, tokenizer, head classifier, optimizer, schedulers, and datasets/data loaders.\n",
                "\n",
                "- **trainer**: Any argument to be passed to PyTorch Lightning including number of epochs, number of GPUs, precision level, etc.\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "T1gA8PsJ13MJ"
            },
            "outputs": [],
            "source": [
                "# download the model's configuration file \n",
                "MODEL_CONFIG = \"text_classification_config.yaml\"\n",
                "CONFIG_DIR = WORK_DIR + '/configs/'\n",
                "\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/text_classification/conf/' + MODEL_CONFIG, CONFIG_DIR)\n",
                "    print('Config file downloaded!')\n",
                "else:\n",
                "    print ('config file already exists')\n",
                "config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'\n",
                "print(config_path)\n",
                "config = OmegaConf.load(config_path)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "mX3KmWMvSUQw"
            },
            "source": [
                "## this line will print the entire config of the model\n",
                "print(OmegaConf.to_yaml(config))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "ZCgWzNBkaQLZ"
            },
            "source": [
                "# Model Training From Scratch\n",
                "## Setting up data within the config\n",
                "\n",
                "We first need to set the num_classes in the config file which specifies the number of classes in the dataset. For SST-2, we have just two classes (0-positive and 1-negative). So we set the num_classes to 2. The model supports more than 2 classes too.\n",
                "\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "jFSMiWtlkaC5"
            },
            "outputs": [],
            "source": [
                "config.model.dataset.num_classes=2"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "xCkc7QGikqPh"
            },
            "source": [
                "\n",
                "Among other things, the config file contains dictionaries called dataset, train_ds and validation_ds. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
                "\n",
                "Notice that some config lines, including `model.dataset.classes_num`, have `???` as their value, this means that values for these fields are required to be to be specified by the user. We need to specify and set the `model.train_ds.file_name`, `model.validation_ds.file_name`, and `model.test_ds.file_name` in the config file to the paths of the train, validation, and test files if they exist. We may do it by updating the config file or by setting them from the command line. \n",
                "\n",
                "Let's now set the train and validation paths in the config."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "LQHCJN-ZaoLp"
            },
            "outputs": [],
            "source": [
                "config.model.train_ds.file_path = os.path.join(DATA_DIR, 'SST-2/train_nemo_format.tsv')\n",
                "config.model.validation_ds.file_path = os.path.join(DATA_DIR, 'SST-2/dev_nemo_format.tsv')\n",
                "# Name of the .nemo file where trained model will be saved.\n",
                "config.save_to = 'trained-model.nemo'\n",
                "config.export_to = 'trained-model.onnx'\n",
                "\n",
                "print(\"Train dataloader's config: \\n\")\n",
                "# OmegaConf.to_yaml() is used to create a proper format for printing the train dataloader's config\n",
                "# You may change other params like batch size or the number of samples to be considered (-1 means all the samples)\n",
                "print(OmegaConf.to_yaml(config.model.train_ds))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "nB96-3sTc3yk"
            },
            "source": [
                "## Building the PyTorch Lightning Trainer\n",
                "\n",
                "NeMo models are primarily PyTorch Lightning (PT) modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem.\n",
                "\n",
                "Let's first instantiate a PT Trainer object by using the trainer section of the config."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "1tG4FzZ4Ui60"
            },
            "outputs": [],
            "source": [
                "print(\"Trainer config - \\n\")\n",
                "# OmegaConf.to_yaml() is used to create a proper format for printing the trainer config\n",
                "print(OmegaConf.to_yaml(config.trainer))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "XMVVs0INi5zj"
            },
            "source": [
                "First you need to create a PT trainer with the params stored in the trainer's config. You may set the number of steps for training with max_steps or number of epochs with max_epochs in the trainer's config."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "knF6QeQQdMrH"
            },
            "outputs": [],
            "source": [
                "# lets modify some trainer configs\n",
                "# checks if we have GPU available and uses it\n",
                "config.trainer.accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
                "config.trainer.devices = 1\n",
                "\n",
                "\n",
                "# for mixed precision training, uncomment the lines below (precision should be set to 16 and amp_level to O1):\n",
                "# config.trainer.precision = 16\n",
                "# config.trainer.amp_level = O1\n",
                "\n",
                "# disable distributed training when using Colab to prevent the errors\n",
                "config.trainer.strategy = None\n",
                "\n",
                "# setup max number of steps to reduce training time for demonstration purposes of this tutorial\n",
                "# Training stops when max_step or max_epochs is reached (earliest)\n",
                "config.trainer.max_epochs = 1\n",
                "\n",
                "# instantiates a PT Trainer object by using the trainer section of the config\n",
                "trainer = pl.Trainer(**config.trainer)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "8IlEMdVxdr6p"
            },
            "source": [
                "## Setting up the NeMo Experiment¶\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "6Kl5IdnV3O8y"
            },
            "source": [
                "NeMo has an experiment manager that handles the logging and saving checkpoints for us, so let's setup it. We need the PT trainer and the exp_manager config:"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "8uztqGAmdrYt"
            },
            "outputs": [],
            "source": [
                "# The experiment manager of a trainer object can not be set twice. We repeat the trainer creation code again here to prevent getting error when this cell is executed more than once. \n",
                "trainer = pl.Trainer(**config.trainer)\n",
                "\n",
                "# exp_dir specifies the path to store the the checkpoints and also the logs, it's default is \"./nemo_experiments\"\n",
                "# You may set it by uncommentig the following line\n",
                "# config.exp_manager.exp_dir = 'LOG_CHECKPOINT_DIR'\n",
                "\n",
                "# OmegaConf.to_yaml() is used to create a proper format for printing the trainer config\n",
                "print(OmegaConf.to_yaml(config.exp_manager))\n",
                "\n",
                "exp_dir = exp_manager(trainer, config.exp_manager)\n",
                "\n",
                "# the exp_dir provides a path to the current experiment for easy access\n",
                "print(exp_dir)\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "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 to another model. The default model is `bert-base-uncased`. We support a variety of models including all the models available in HuggingFace, and Megatron."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "Xeuc2i7Y_nP5"
            },
            "outputs": [],
            "source": [
                "# complete list of supported BERT-like models\n",
                "print(nemo_nlp.modules.get_pretrained_lm_models_list())\n",
                "\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "RK2xglXyAUOO"
            },
            "outputs": [],
            "source": [
                "# specify the BERT-like model, you want to use\n",
                "# set the `model.language_modelpretrained_model_name' parameter in the config to the model you want to use\n",
                "config.model.language_model.pretrained_model_name = \"bert-base-uncased\""
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "fzNZNAVRjDD-"
            },
            "source": [
                "Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders will also be prepared for the training and validation.\n",
                "\n",
                "Also, the pretrained BERT model will be automatically downloaded. Note it can take up to a few minutes depending on the size of the chosen BERT model for the first time you create the model. If your dataset is large, it also may take some time to read and process all the datasets. \n",
                "\n",
                "Now we can create the model with the model config and the trainer object like this:"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "NgsGLydWo-6-",
                "scrolled": true
            },
            "outputs": [],
            "source": [
                "model = nemo_nlp.models.TextClassificationModel(cfg=config.model, trainer=trainer)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "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": {
                "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.\")\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "MW_JVIi5z68e"
            },
            "source": [
                "## Training\n",
                "\n",
                "You may start the training by using the trainer.fit() method. The number of steps/epochs of the training are specified already in the config of the trainer and you may update them before creating the trainer."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "hUvnSpyjp0Dh",
                "scrolled": true
            },
            "outputs": [],
            "source": [
                "# start model training\n",
                "trainer.fit(model)\n",
                "model.save_to(config.save_to)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "VPdzJVAgSFaJ"
            },
            "source": [
                "# Evaluation\n",
                "\n",
                "To see how the model performs, we can run evaluate and test the performance of the trained model on a data file. Here we would load the best checkpoint (the one with the lowest validation loss) and create a model (eval_model) from the checkpoint. We would also create a new trainer (eval_trainer) to show how it is done when training is done and you have just the checkpoints. If you want to perform the evaluation in the same script as the training's script, you may still use the same model and trainer you used for training."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "92PB0iTqNnW-"
            },
            "outputs": [],
            "source": [
                "# extract the path of the best checkpoint from the training, you may update it to any checkpoint\n",
                "checkpoint_path = trainer.checkpoint_callback.best_model_path\n",
                "# Create an evaluation model and load the checkpoint\n",
                "eval_model = nemo_nlp.models.TextClassificationModel.load_from_checkpoint(checkpoint_path=checkpoint_path)\n",
                "\n",
                "# create a dataloader config for evaluation, the same data file provided in validation_ds is used here\n",
                "# file_path can get updated with any file\n",
                "eval_config = OmegaConf.create({'file_path': config.model.validation_ds.file_path, 'batch_size': 64, 'shuffle': False, 'num_samples': -1})\n",
                "eval_model.setup_test_data(test_data_config=eval_config)\n",
                "#eval_dataloader = eval_model._create_dataloader_from_config(cfg=eval_config, mode='test')\n",
                "\n",
                "# a new trainer is created to show how to evaluate a checkpoint from an already trained model\n",
                "# create a copy of the trainer config and update it to be used for final evaluation\n",
                "eval_trainer_cfg = config.trainer.copy()\n",
                "eval_trainer_cfg.accelerator = 'gpu' if torch.cuda.is_available() else 'cpu' # it is safer to perform evaluation on single GPU as PT is buggy with the last batch on multi-GPUs\n",
                "eval_trainer_cfg.strategy = None # 'ddp' is buggy with test process in the current PT, it looks like it has been fixed in the latest master\n",
                "eval_trainer = pl.Trainer(**eval_trainer_cfg)\n",
                "\n",
                "eval_trainer.test(model=eval_model, verbose=False) # test_dataloaders=eval_dataloader,\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "Tit5kG4Z5SXu"
            },
            "source": [
                "# Inference\n",
                "\n",
                "You may create a model from a saved checkpoint and use the model.infer() method to perform inference on a list of queries. There is no need of any trainer for inference."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "BKe5Jn4u9xng"
            },
            "outputs": [],
            "source": [
                "# extract the path of the best checkpoint from the training, you may update it to any other checkpoint file\n",
                "checkpoint_path = trainer.checkpoint_callback.best_model_path\n",
                "# Create an evaluation model and load the checkpoint\n",
                "infer_model = nemo_nlp.models.TextClassificationModel.load_from_checkpoint(checkpoint_path=checkpoint_path)\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "y8SFxPJd-hkH"
            },
            "source": [
                "To see how the model performs, let’s get model's predictions for a few examples:"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "id": "DQhsamclRtxJ"
            },
            "outputs": [],
            "source": [
                "# move the model to the desired device for inference\n",
                "# we move the model to \"cuda\" if available otherwise \"cpu\" would be used\n",
                "if torch.cuda.is_available():\n",
                "    infer_model.to(\"cuda\")\n",
                "else:\n",
                "    infer_model.to(\"cpu\")\n",
                "\n",
                "# define the list of queries for inference\n",
                "queries = ['by the end of no such thing the audience , like beatrice , has a watchful affection for the monster .', \n",
                "           'director rob marshall went out gunning to make a great one .', \n",
                "           'uneasy mishmash of styles and genres .']\n",
                "           \n",
                "# max_seq_length=512 is the maximum length BERT supports.       \n",
                "results = infer_model.classifytext(queries=queries, batch_size=3, max_seq_length=512)\n",
                "\n",
                "print('The prediction results of some sample queries with the trained model:')\n",
                "for query, result in zip(queries, results):\n",
                "    print(f'Query : {query}')\n",
                "    print(f'Predicted label: {result}')\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "ref1qSonGNhP"
            },
            "source": [
                "## Training Script\n",
                "\n",
                "If you have NeMo installed locally (eg. cloned from the Github), you can also train the model with `examples/nlp/text_classification/text_classifciation_with_bert.py`. This script contains an example on how to train, evaluate and perform inference with the TextClassificationModel.\n",
                "\n",
                "For example the following would train a model for 50 epochs in 2 GPUs on a classification task with 2 classes:\n",
                "\n",
                "```\n",
                "# python text_classification_with_bert.py \n",
                "        model.dataset.num_classes=2\n",
                "        model.train_ds=PATH_TO_TRAIN_FILE \n",
                "        model.validation_ds=PATH_TO_VAL_FILE  \n",
                "        trainer.max_epochs=50\n",
                "        trainer.devices=2\n",
                "        trainer.accelerator='gpu'\n",
                "```\n",
                "\n",
                "This script would also reload the best checkpoint after the training is done and does evaluation on the dev set. Then perform inference on some sample queries. \n",
                "\n",
                "\n",
                "By default, this script uses `examples/nlp/text_classification/conf/text_classifciation_config.py` config file, and you may update all the params in the config file from the command line. You may also use another config file like this:\n",
                "\n",
                "```\n",
                "# python text_classification_with_bert.py --config-name==PATH_TO_CONFIG_FILE\n",
                "        model.dataset.num_classes=2\n",
                "        model.train_ds=PATH_TO_TRAIN_FILE \n",
                "        model.validation_ds=PATH_TO_VAL_FILE  \n",
                "        trainer.max_epochs=50\n",
                "        trainer.devices=2\n",
                "        trainer.accelerator='gpu'\n",
                "```\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## Deployment\n",
                "\n",
                "You can also deploy a model to an inference engine (like TensorRT or ONNXRuntime) using ONNX exporter.\n",
                "If you don't have one, let's install it:"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "!pip install --upgrade onnxruntime # for gpu, use onnxruntime-gpu\n",
                "# !mkdir -p ort\n",
                "# %cd ort\n",
                "# !git clean -xfd\n",
                "# !git clone --depth 1 --branch v1.8.0 https://github.com/microsoft/onnxruntime.git .\n",
                "# !./build.sh --skip_tests --config Release --build_shared_lib --parallel --use_cuda --cuda_home /usr/local/cuda --cudnn_home /usr/lib/x86_64-linux-gnu --build_wheel\n",
                "# !pip uninstall -y onnxruntime\n",
                "# !pip uninstall -y onnxruntime-gpu\n",
                "# !pip install  --upgrade --force-reinstall ./build/Linux/Release/dist/onnxruntime*.whl\n",
                "# %cd .."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "Then export"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "model.export(config.export_to)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "And run some queries"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "import numpy as np\n",
                "import torch\n",
                "from nemo.utils import logging\n",
                "from nemo.collections.nlp.parts.utils_funcs import tensor2list\n",
                "from nemo.collections.nlp.models.text_classification import TextClassificationModel\n",
                "from nemo.collections.nlp.data.text_classification import TextClassificationDataset\n",
                "\n",
                "import onnxruntime\n",
                "\n",
                "def to_numpy(tensor):\n",
                "    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()\n",
                "\n",
                "def postprocessing(results, labels):\n",
                "    return [labels[str(r)] for r in results]\n",
                "\n",
                "def create_infer_dataloader(model, queries):\n",
                "    batch_size = len(queries)\n",
                "    dataset = TextClassificationDataset(tokenizer=model.tokenizer, queries=queries, max_seq_length=512)\n",
                "    return torch.utils.data.DataLoader(\n",
                "        dataset=dataset,\n",
                "        batch_size=batch_size,\n",
                "        shuffle=False,\n",
                "        num_workers=2,\n",
                "        pin_memory=True,\n",
                "        drop_last=False,\n",
                "        collate_fn=dataset.collate_fn,\n",
                "    )\n",
                "\n",
                "\n",
                "queries = [\"by the end of no such thing the audience , like beatrice , has a watchful affection for the monster .\",\n",
                "\"director rob marshall went out gunning to make a great one .\",\n",
                "\"uneasy mishmash of styles and genres .\",\n",
                "\"I love exotic science fiction / fantasy movies but this one was very unpleasant to watch . Suggestions and images of child abuse , mutilated bodies (live or dead) , other gruesome scenes , plot holes , boring acting made this a regretable experience , The basic idea of entering another person's mind is not even new to the movies or TV (An Outer Limits episode was better at exploring this idea) . i gave it 4 / 10 since some special effects were nice .\"]\n",
                "\n",
                "model.eval()\n",
                "infer_datalayer = create_infer_dataloader(model, queries)\n",
                "\n",
                "ort_session = onnxruntime.InferenceSession(config.export_to)\n",
                "\n",
                "for batch in infer_datalayer:\n",
                "    input_ids, input_type_ids, input_mask, subtokens_mask = batch\n",
                "    ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(input_ids),\n",
                "                  ort_session.get_inputs()[1].name: to_numpy(input_mask),\n",
                "                  ort_session.get_inputs()[2].name: to_numpy(input_type_ids),}\n",
                "    ologits = ort_session.run(None, ort_inputs)\n",
                "    alogits = np.asarray(ologits)\n",
                "    logits = torch.from_numpy(alogits[0])\n",
                "    preds = tensor2list(torch.argmax(logits, dim = -1))\n",
                "    processed_results = postprocessing(preds, {\"0\": \"negative\", \"1\": \"positive\"})\n",
                "\n",
                "    logging.info('The prediction results of some sample queries with the trained model:')\n",
                "    for query, result in zip(queries, processed_results):\n",
                "        logging.info(f'Query : {query}')\n",
                "        logging.info(f'Predicted label: {result}')\n",
                "    break"
            ]
        }
    ],
    "metadata": {
        "accelerator": "GPU",
        "colab": {
            "collapsed_sections": [],
            "name": "Text_Classification_Sentiment_Analysis.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": 4
}