File size: 30,684 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
{
    "cells": [
        {
            "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",
                "BRANCH = 'r1.17.0'\n",
                "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "JFWG-jYCfvD7",
                "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": [
                "import json\n",
                "import os\n",
                "\n",
                "from nemo.collections import nlp as nemo_nlp\n",
                "from nemo.utils.exp_manager import exp_manager\n",
                "from nemo.utils import logging\n",
                "from omegaconf import OmegaConf\n",
                "import pandas as pd\n",
                "import pytorch_lightning as pl\n",
                "import torch\n",
                "import wget "
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "daYw_Xll2ZR9"
            },
            "source": [
                "# Task description\n",
                "\n",
                "Intent recognition is the task of classifying the intent of an utterance or document. For example,  for the query:  `What is the weather in Santa Clara tomorrow morning?`, we would like to classify the intent as `weather`. This is a fundamental step that is executed in any task-driven conversational assistant.\n",
                "\n",
                "Typical text classification models, such as the Joint Intent and Slot Classification Model in NeMo, are trained on hundreds or thousands of labeled documents. In this tutorial we demonstrate a different, \"zero shot\" approach that requires no annotated data for the target intents. The zero shot approach uses a model trained on the task of natural language inference (NLI). During training, the model is presented with pairs of sentences consisting of a \"premise\" and a \"hypothesis\", and must classify the relationship between them as entailment (meaning the hypothesis follows logically from the premise), contradiction, or neutral. To use this model for intent prediction, we define a list of candidate labels to represent each of the possible classes in our classification system; for example, the candidate labels might be `request for directions`,  `query about weather`, `request to play music`, etc. We predict the intent of a query by pairing it with each of the candidate labels as a premise-hypothesis pair and using the model to predict the probability of an entailment relationship between them. For example, for the query and candidate labels above, we would run inference for the following pairs:\n",
                "\n",
                "(`What is the weather in Santa Clara tomorrow morning?`, `request for directions`)  \n",
                "(`What is the weather in Santa Clara tomorrow morning?`, `request to play music`)   \n",
                "(`What is the weather in Santa Clara tomorrow morning?`, `query about weather`)\n",
                "\n",
                "In the above example, we would expect a high probability of entailment for the last pair, and low probabilities for the first two pairs. Thus, we would classify the intent of the utterance as `query about weather`. The task can be formulated as single-label classification (only one of the candidate labels can be correct for each query) or multi-label classification (multiple labels can be correct) by setting the parameter multi_label = False or multi_label = True, respectively, during inference.\n",
                "\n",
                "In this tutorial, we demonstrate how to train an NLI model on the MNLI data set and how to use it for zero shot intent recognition."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "# Using an out-of-the-box model"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# this line will download a pre-trained NLI model from NVIDIA's NGC cloud and instantiate it for you\n",
                "\n",
                "pretrained_model = nemo_nlp.models.ZeroShotIntentModel.from_pretrained(\"zeroshotintent_en_bert_base_uncased\")"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "queries = [\n",
                "    \"What is the weather in Santa Clara tomorrow morning?\",\n",
                "    \"I'd like a veggie burger and fries\",\n",
                "    \"Bring me some ice cream when it's sunny\"\n",
                "\n",
                "]\n",
                "\n",
                "candidate_labels = ['Food order', 'Weather query', \"Play music\"]\n",
                "\n",
                "predictions = pretrained_model.predict(queries, candidate_labels, batch_size=4, multi_label=True)\n",
                "\n",
                "print('The prediction results of some sample queries with the trained model:')\n",
                "for query in predictions:\n",
                "    print(json.dumps(query, indent=4))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "In the example above, we set `multi_label=True`, which is also the default setting. This runs a softmax calculation independently for each label over the entailment and contradiction logits. For any given query, the scores for the different labels may add up to more than one.\n",
                "\n",
                "Below, we see what happens if we set `multi_label=False`. In this case, the softmax calculation for each query uses the entailment class logits for all the labels, so the final scores for all classes add up to one."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "predictions = pretrained_model.predict(queries, candidate_labels, batch_size=4, multi_label=False)\n",
                "\n",
                "print('The prediction results of some sample queries with the trained model:')\n",
                "for query in predictions:\n",
                "    print(json.dumps(query, indent=4))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "Under the hood, during inference the candidate labels are not used as is; they're actually used to fill in the blank in a hypothesis template. By default, the hypothesis template is `This example is {}`. So the candidate labels above would actually be presented to the model as `This example is food order`, `This example is weather query`, and `This example is play music`. You can change the hypothesis template with the optional keyword argument `hypothesis_template`, as shown below."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "predictions = pretrained_model.predict(queries, candidate_labels, batch_size=4, multi_label=False,\n",
                "                                      hypothesis_template=\"a person is asking something related to {}\")\n",
                "\n",
                "print('The prediction results of some sample queries with the trained model:')\n",
                "for query in predictions:\n",
                "    print(json.dumps(query, indent=4))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "ZnuziSwJ1yEB"
            },
            "source": [
                "Now, let's take a closer look at the model's configuration and learn to train the model.\n",
                "\n",
                "\n",
                "# Training your own model\n",
                "\n",
                "\n",
                "# Dataset\n",
                "\n",
                "In this tutorial we will train a model on [The Multi-Genre Natural Language Inference Corpus](https://cims.nyu.edu/~sbowman/multinli/multinli_0.9.pdf) (MNLI). This is a crowdsourced collection of sentence pairs with textual entailment annotations. Given a premise sentence followed by a hypothesis sentence, the task is to predict whether the premise entails the hypothesis (entailment), contradicts the hypothesis (contradiction), or neither (neutral). There are two dev sets for this task: the \"matched\" dev set contains examples drawn from the same genres as the training set, and the \"mismatched\" dev set has examples from genres not seen during training. For our purposes, either dev set alone will be sufficient. We will use the \"matched\" dev set here. "
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## Download the dataset"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "--wJ2891aIIE"
            },
            "outputs": [],
            "source": [
                "# you can replace DATA_DIR with your own location\n",
                "DATA_DIR = '.'  "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "wget.download('https://dl.fbaipublicfiles.com/glue/data/MNLI.zip', DATA_DIR)\n",
                "! unzip {DATA_DIR}/MNLI.zip -d {DATA_DIR}"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "qB0oLE4R9EhJ"
            },
            "outputs": [],
            "source": [
                "! ls -l $DATA_DIR/MNLI"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "gMWuU69pbUDe"
            },
            "source": [
                "We will use `train.tsv` as our training set and `dev_matched.tsv` as our validation set."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## Explore the dataset  \n",
                "Let's take a look at some examples from the dev set"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "num_examples = 5\n",
                "df = pd.read_csv(os.path.join(DATA_DIR, \"MNLI\", \"dev_matched.tsv\"), sep=\"\\t\")[:num_examples]\n",
                "for sent1, sent2, label in zip(df['sentence1'].tolist(), df['sentence2'].tolist(), df['gold_label'].tolist()):\n",
                "    print(\"sentence 1: \", sent1)\n",
                "    print(\"sentence 2: \", sent2)\n",
                "    print(\"label: \", label)\n",
                "    print(\"===================\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "_whKCxfTMo6Y"
            },
            "source": [
                "# Training model\n",
                "## Model configuration\n",
                "\n",
                "The model is comprised of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model followed by a Sequence Classifier module.\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, a classifier, optimizer and schedulers, datasets and any other related information\n",
                "\n",
                "- **trainer**: Any argument to be passed to PyTorch Lightning\n",
                "\n",
                "All model and training parameters are defined in the **zero_shot_intent_config.yaml** config file. This file is located in the folder **examples/nlp/zero_shot_intent_recognition/conf/**. It contains 2 main sections:\n",
                "\n",
                "\n",
                "We will download the config file from the repository for the purpose of the tutorial. If you have a version of NeMo installed locally, you can use it from the above folder."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "T1gA8PsJ13MJ"
            },
            "outputs": [],
            "source": [
                "# download the model config file from repository for the purpose of this example\n",
                "WORK_DIR = \".\"  # you can replace WORK_DIR with your own location\n",
                "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/zero_shot_intent_recognition/conf/zero_shot_intent_config.yaml', WORK_DIR)\n",
                "\n",
                "# print content of the config file\n",
                "config_file = os.path.join(WORK_DIR, \"zero_shot_intent_config.yaml\")\n",
                "config = OmegaConf.load(config_file)\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 **dataset**, **train_ds** and **validation_ds**. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
                "\n",
                "To start model training, we need to specify `model.dataset.data_dir`, `model.train_ds.file_name` and `model.validation_ds.file_name`, as we are going to do below.\n",
                "\n",
                "Notice that some config lines, including `model.train_ds.data_dir`, have `???` in place of paths. This means that values for these fields are required to be specified by the user.\n",
                "\n",
                "Let's now add the data paths and output directory for saving predictions to the config."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "LQHCJN-ZaoLp"
            },
            "outputs": [],
            "source": [
                "# you can replace OUTPUT_DIR with your own location; this is where logs and model checkpoints will be saved\n",
                "OUTPUT_DIR = \"nemo_output\"\n",
                "config.exp_manager.exp_dir = OUTPUT_DIR\n",
                "config.model.dataset.data_dir = os.path.join(DATA_DIR, \"MNLI\")\n",
                "config.model.train_ds.file_name = \"train.tsv\"\n",
                "config.model.validation_ds.file_path = \"dev_matched.tsv\""
            ]
        },
        {
            "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",
                "\n",
                "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
                "\n",
                "# for mixed precision training, uncomment the line below (precision should be set to 16 and amp_level to O1):\n",
                "# config.trainer.amp_level = O1\n",
                "\n",
                "# remove distributed training flags\n",
                "config.trainer.strategy = None\n",
                "\n",
                "# setup max number of steps to reduce training time for demonstration purposes of this tutorial\n",
                "config.trainer.max_steps = 128\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": "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 and use [Megatron-LM BERT](https://arxiv.org/abs/1909.08053) or [AlBERT model](https://arxiv.org/abs/1909.11942):"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Xeuc2i7Y_nP5"
            },
            "outputs": [],
            "source": [
                "# get the list of supported BERT-like models, for the complete list of HugginFace models, see https://huggingface.co/models\n",
                "print(nemo_nlp.modules.get_pretrained_lm_models_list(include_external=True))\n",
                "\n",
                "# specify BERT-like model, you want to use, for example, \"megatron-bert-345m-uncased\" or 'bert-base-uncased'\n",
                "PRETRAINED_BERT_MODEL = \"albert-base-v1\""
            ]
        },
        {
            "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"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "fzNZNAVRjDD-"
            },
            "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": "NgsGLydWo-6-"
            },
            "outputs": [],
            "source": [
                "model = nemo_nlp.models.ZeroShotIntentModel(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 model training\n",
                "trainer.fit(model)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## Inference from Examples\n",
                "The next step is to see how the trained model will classify intents. To improve the predictions you may need to train the model for more than 5 epochs.\n",
                "\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# reload the saved model\n",
                "saved_model = os.path.join(exp_dir, \"checkpoints/ZeroShotIntentRecognition.nemo\")\n",
                "eval_model = nemo_nlp.models.ZeroShotIntentModel.restore_from(saved_model)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "queries = [\n",
                "    \"I'd like a veggie burger and fries\",\n",
                "    \"Turn off the lights in the living room\",\n",
                "]\n",
                "\n",
                "candidate_labels = ['Food order', 'Play music', 'Request for directions', 'Change lighting', 'Calendar query']\n",
                "\n",
                "predictions = eval_model.predict(queries, candidate_labels, batch_size=4, multi_label=True)\n",
                "\n",
                "print('The prediction results of some sample queries with the trained model:')\n",
                "for query in predictions:\n",
                "    print(json.dumps(query, indent=4))\n",
                "print(\"Inference finished!\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "As described above in \"Using an out of the box model\", you can set multi_label=False if you want the scores for each query to add up to one. You can also change the hypothesis template used when presenting candidate labels, as shown below."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "predictions = eval_model.predict(queries, candidate_labels, batch_size=4, multi_label=True,\n",
                "                           hypothesis_template=\"related to {}\")\n",
                "\n",
                "print('The prediction results of some sample queries with the trained model:')\n",
                "for query in predictions:\n",
                "    print(json.dumps(query, indent=4))\n",
                "print(\"Inference finished!\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "By default, when an NLI model is trained on MNLI in NeMo, the class indices for entailment and contradiction are 1 and 0, respectively. The `predict` method uses these indices by default. If your NLI model was trained with different class indices for these classes, you can pass the correct indices as keyword arguments to the `predict` method (e.g. `entailment_idx=1`, `contradiction_idx=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 [examples/nlp/zero_shot_intent_recognition/zero_shot_intent_train.py](https://github.com/carolmanderson/NeMo/blob/main/examples/nlp/zero_shot_intent_recognition/zero_shot_intent_train.py).\n",
                "\n",
                "To run training script, use:\n",
                "\n",
                "```\n",
                "python zero_shot_intent_train.py \\\n",
                " model.dataset.data_dir=PATH_TO_DATA_FOLDER\n",
                "```\n",
                " \n",
                " By default, this script uses `examples/nlp/zero_shot_intent_recognition/conf/zero_shot_intent_config.yaml` config file, and you may update all the params inside of this config file or alternatively provide them in the command line.\n"
            ]
        }
    ],
    "metadata": {
        "accelerator": "GPU",
        "colab": {
            "collapsed_sections": [],
            "name": "Zero_Shot_Intent_Recognition.ipynb",
            "private_outputs": true,
            "provenance": []
        },
        "kernelspec": {
            "display_name": "Python [conda env:zeroshot_dev_2]",
            "language": "python",
            "name": "conda-env-zeroshot_dev_2-py"
        },
        "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"
        }
    },
    "nbformat": 4,
    "nbformat_minor": 4
}