-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCRAFT_fine_tuning_2022
2283 lines (2283 loc) · 143 KB
/
CRAFT_fine_tuning_2022
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
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "CRAFT fine-tuning demo using ConvoKit",
"provenance": [],
"collapsed_sections": [],
"toc_visible": true,
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/RenaGao/2022PairedSpeakingTestData/blob/main/CRAFT_fine_tuning_2022\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t5JqrpJWoNaB"
},
"source": [
"# CRAFT demo (fine-tuning and inference) using ConvoKit\n",
"\n",
"This example notebook shows how to fine-tune a pretrained CRAFT conversational model for the task of forecasting conversational derailment, as shown in the \"Trouble on the Horizon\" paper (note however that due to nondeterminism in the training process, the results will not exactly reproduce the ones shown in the paper; if you need the exact inference results from the paper, see the inference-only version of this notebook)."
]
},
{
"cell_type": "code",
"metadata": {
"id": "tWGZ1Wc0n7BR"
},
"source": [
"# start by installing ConvoKit on the colab VM\n",
"!pip install -q convokit"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "RHkNojY7tzAh",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 74
},
"outputId": "a9d10e05-c6db-401f-a651-20bb60a3c095"
},
"source": [
"# import necessary libraries, including convokit\n",
"import torch\n",
"from torch.jit import script, trace\n",
"import torch.nn as nn\n",
"from torch import optim\n",
"import torch.nn.functional as F\n",
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import nltk\n",
"import requests\n",
"import os\n",
"import sys\n",
"import random\n",
"import unicodedata\n",
"import itertools\n",
"from urllib.request import urlretrieve\n",
"from convokit import download, Corpus\n",
"%matplotlib inline"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"/usr/local/lib/python3.6/dist-packages/sklearn/externals/joblib/__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.\n",
" warnings.warn(msg, category=DeprecationWarning)\n"
],
"name": "stderr"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "6sA5pzI7LRtz"
},
"source": [
"# define globals and constants\n",
"\n",
"MAX_LENGTH = 80 # Maximum sentence length (number of tokens) to consider\n",
"\n",
"# configure model\n",
"hidden_size = 500\n",
"encoder_n_layers = 2\n",
"context_encoder_n_layers = 2\n",
"decoder_n_layers = 2\n",
"dropout = 0.1\n",
"batch_size = 64\n",
"# Configure training/optimization\n",
"clip = 50.0\n",
"teacher_forcing_ratio = 1.0\n",
"learning_rate = 1e-5\n",
"decoder_learning_ratio = 5.0\n",
"print_every = 10\n",
"train_epochs = 30\n",
"\n",
"# Default word tokens\n",
"PAD_token = 0 # Used for padding short sentences\n",
"SOS_token = 1 # Start-of-sentence token\n",
"EOS_token = 2 # End-of-sentence token\n",
"UNK_token = 3 # Unknown word token\n",
"\n",
"# model download paths\n",
"WORD2INDEX_URL = \"http://zissou.infosci.cornell.edu/convokit/models/craft_wikiconv/word2index.json\"\n",
"INDEX2WORD_URL = \"http://zissou.infosci.cornell.edu/convokit/models/craft_wikiconv/index2word.json\"\n",
"MODEL_URL = \"http://zissou.infosci.cornell.edu/convokit/models/craft_wikiconv/craft_pretrained.tar\"\n",
"\n",
"# confidence score threshold for declaring a positive prediction.\n",
"# this value was previously learned on the validation set.\n",
"FORECAST_THRESH = 0.570617"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "L_w8yFiXuCpg"
},
"source": [
"## Part 1: set up data conversion utilities\n",
"\n",
"We begin by setting up some helper functions and classes for converting conversational text data into a torch-friendly Tensor format. Note that these low-level routines are largely taken from the [PyTorch seq2seq chatbot tutorial](https://pytorch.org/tutorials/beginner/chatbot_tutorial.html)."
]
},
{
"cell_type": "code",
"metadata": {
"id": "QM8PeUAduAhq"
},
"source": [
"class Voc:\n",
" \"\"\"A class for representing the vocabulary used by a CRAFT model\"\"\"\n",
"\n",
" def __init__(self, name, word2index=None, index2word=None):\n",
" self.name = name\n",
" self.trimmed = False if not word2index else True # if a precomputed vocab is specified assume the user wants to use it as-is\n",
" self.word2index = word2index if word2index else {\"UNK\": UNK_token}\n",
" self.word2count = {}\n",
" self.index2word = index2word if index2word else {PAD_token: \"PAD\", SOS_token: \"SOS\", EOS_token: \"EOS\", UNK_token: \"UNK\"}\n",
" self.num_words = 4 if not index2word else len(index2word) # Count SOS, EOS, PAD, UNK\n",
"\n",
" def addSentence(self, sentence):\n",
" for word in sentence.split(' '):\n",
" self.addWord(word)\n",
"\n",
" def addWord(self, word):\n",
" if word not in self.word2index:\n",
" self.word2index[word] = self.num_words\n",
" self.word2count[word] = 1\n",
" self.index2word[self.num_words] = word\n",
" self.num_words += 1\n",
" else:\n",
" self.word2count[word] += 1\n",
"\n",
" # Remove words below a certain count threshold\n",
" def trim(self, min_count):\n",
" if self.trimmed:\n",
" return\n",
" self.trimmed = True\n",
"\n",
" keep_words = []\n",
"\n",
" for k, v in self.word2count.items():\n",
" if v >= min_count:\n",
" keep_words.append(k)\n",
"\n",
" print('keep_words {} / {} = {:.4f}'.format(\n",
" len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)\n",
" ))\n",
"\n",
" # Reinitialize dictionaries\n",
" self.word2index = {\"UNK\": UNK_token}\n",
" self.word2count = {}\n",
" self.index2word = {PAD_token: \"PAD\", SOS_token: \"SOS\", EOS_token: \"EOS\", UNK_token: \"UNK\"}\n",
" self.num_words = 4 # Count default tokens\n",
"\n",
" for word in keep_words:\n",
" self.addWord(word)\n",
"\n",
"# Create a Voc object from precomputed data structures\n",
"def loadPrecomputedVoc(corpus_name, word2index_url, index2word_url):\n",
" # load the word-to-index lookup map\n",
" r = requests.get(word2index_url)\n",
" word2index = r.json()\n",
" # load the index-to-word lookup map\n",
" r = requests.get(index2word_url)\n",
" index2word = r.json()\n",
" return Voc(corpus_name, word2index, index2word)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "0SazSyux7KFS"
},
"source": [
"# Helper functions for preprocessing and tokenizing text\n",
"\n",
"# Turn a Unicode string to plain ASCII, thanks to\n",
"# https://stackoverflow.com/a/518232/2809427\n",
"def unicodeToAscii(s):\n",
" return ''.join(\n",
" c for c in unicodedata.normalize('NFD', s)\n",
" if unicodedata.category(c) != 'Mn'\n",
" )\n",
"\n",
"# Tokenize the string using NLTK\n",
"def tokenize(text):\n",
" tokenizer = nltk.tokenize.RegexpTokenizer(pattern=r'\\w+|[^\\w\\s]')\n",
" # simplify the problem space by considering only ASCII data\n",
" cleaned_text = unicodeToAscii(text.lower())\n",
"\n",
" # if the resulting string is empty, nothing else to do\n",
" if not cleaned_text.strip():\n",
" return []\n",
" \n",
" return tokenizer.tokenize(cleaned_text)\n",
"\n",
"# Given a ConvoKit conversation, preprocess each utterance's text by tokenizing and truncating.\n",
"# Returns the processed dialog entry where text has been replaced with a list of\n",
"# tokens, each no longer than MAX_LENGTH - 1 (to leave space for the EOS token)\n",
"def processDialog(voc, dialog):\n",
" processed = []\n",
" for utterance in dialog.iter_utterances():\n",
" # skip the section header, which does not contain conversational content\n",
" if utterance.meta['is_section_header']:\n",
" continue\n",
" tokens = tokenize(utterance.text)\n",
" # replace out-of-vocabulary tokens\n",
" for i in range(len(tokens)):\n",
" if tokens[i] not in voc.word2index:\n",
" tokens[i] = \"UNK\"\n",
" processed.append({\"tokens\": tokens, \"is_attack\": int(utterance.meta['comment_has_personal_attack']), \"id\": utterance.id})\n",
" return processed\n",
"\n",
"# Load context-reply pairs from the Corpus, optionally filtering to only conversations\n",
"# from the specified split (train, val, or test).\n",
"# Each conversation, which has N comments (not including the section header) will\n",
"# get converted into N-1 comment-reply pairs, one pair for each reply \n",
"# (the first comment does not reply to anything).\n",
"# Each comment-reply pair is a tuple consisting of the conversational context\n",
"# (that is, all comments prior to the reply), the reply itself, the label (that\n",
"# is, whether the reply contained a derailment event), and the comment ID of the\n",
"# reply (for later use in re-joining with the ConvoKit corpus).\n",
"# The function returns a list of such pairs.\n",
"def loadPairs(voc, corpus, split=None, last_only=False):\n",
" pairs = []\n",
" for convo in corpus.iter_conversations():\n",
" # consider only conversations in the specified split of the data\n",
" if split is None or convo.meta['split'] == split:\n",
" dialog = processDialog(voc, convo)\n",
" iter_range = range(1, len(dialog)) if not last_only else [len(dialog)-1]\n",
" for idx in iter_range:\n",
" reply = dialog[idx][\"tokens\"][:(MAX_LENGTH-1)]\n",
" label = dialog[idx][\"is_attack\"]\n",
" comment_id = dialog[idx][\"id\"]\n",
" # gather as context all utterances preceding the reply\n",
" context = [u[\"tokens\"][:(MAX_LENGTH-1)] for u in dialog[:idx]]\n",
" pairs.append((context, reply, label, comment_id))\n",
" return pairs"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "zo4Mg7AEK-0Q"
},
"source": [
"# Helper functions for turning dialog and text sequences into tensors, and manipulating those tensors\n",
"\n",
"def indexesFromSentence(voc, sentence):\n",
" return [voc.word2index[word] for word in sentence] + [EOS_token]\n",
"\n",
"def zeroPadding(l, fillvalue=PAD_token):\n",
" return list(itertools.zip_longest(*l, fillvalue=fillvalue))\n",
"\n",
"def binaryMatrix(l, value=PAD_token):\n",
" m = []\n",
" for i, seq in enumerate(l):\n",
" m.append([])\n",
" for token in seq:\n",
" if token == PAD_token:\n",
" m[i].append(0)\n",
" else:\n",
" m[i].append(1)\n",
" return m\n",
"\n",
"# Takes a batch of dialogs (lists of lists of tokens) and converts it into a\n",
"# batch of utterances (lists of tokens) sorted by length, while keeping track of\n",
"# the information needed to reconstruct the original batch of dialogs\n",
"def dialogBatch2UtteranceBatch(dialog_batch):\n",
" utt_tuples = [] # will store tuples of (utterance, original position in batch, original position in dialog)\n",
" for batch_idx in range(len(dialog_batch)):\n",
" dialog = dialog_batch[batch_idx]\n",
" for dialog_idx in range(len(dialog)):\n",
" utterance = dialog[dialog_idx]\n",
" utt_tuples.append((utterance, batch_idx, dialog_idx))\n",
" # sort the utterances in descending order of length, to remain consistent with pytorch padding requirements\n",
" utt_tuples.sort(key=lambda x: len(x[0]), reverse=True)\n",
" # return the utterances, original batch indices, and original dialog indices as separate lists\n",
" utt_batch = [u[0] for u in utt_tuples]\n",
" batch_indices = [u[1] for u in utt_tuples]\n",
" dialog_indices = [u[2] for u in utt_tuples]\n",
" return utt_batch, batch_indices, dialog_indices\n",
"\n",
"# Returns padded input sequence tensor and lengths\n",
"def inputVar(l, voc):\n",
" indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]\n",
" lengths = torch.tensor([len(indexes) for indexes in indexes_batch])\n",
" padList = zeroPadding(indexes_batch)\n",
" padVar = torch.LongTensor(padList)\n",
" return padVar, lengths\n",
"\n",
"# Returns padded target sequence tensor, padding mask, and max target length\n",
"def outputVar(l, voc):\n",
" indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]\n",
" max_target_len = max([len(indexes) for indexes in indexes_batch])\n",
" padList = zeroPadding(indexes_batch)\n",
" mask = binaryMatrix(padList)\n",
" mask = torch.ByteTensor(mask)\n",
" padVar = torch.LongTensor(padList)\n",
" return padVar, mask, max_target_len\n",
"\n",
"# Returns all items for a given batch of pairs\n",
"def batch2TrainData(voc, pair_batch, already_sorted=False):\n",
" if not already_sorted:\n",
" pair_batch.sort(key=lambda x: len(x[0]), reverse=True)\n",
" input_batch, output_batch, label_batch, id_batch = [], [], [], []\n",
" for pair in pair_batch:\n",
" input_batch.append(pair[0])\n",
" output_batch.append(pair[1])\n",
" label_batch.append(pair[2])\n",
" id_batch.append(pair[3])\n",
" dialog_lengths = torch.tensor([len(x) for x in input_batch])\n",
" input_utterances, batch_indices, dialog_indices = dialogBatch2UtteranceBatch(input_batch)\n",
" inp, utt_lengths = inputVar(input_utterances, voc)\n",
" output, mask, max_target_len = outputVar(output_batch, voc)\n",
" label_batch = torch.FloatTensor(label_batch) if label_batch[0] is not None else None\n",
" return inp, dialog_lengths, utt_lengths, batch_indices, dialog_indices, label_batch, id_batch, output, mask, max_target_len\n",
"\n",
"def batchIterator(voc, source_data, batch_size, shuffle=True):\n",
" cur_idx = 0\n",
" if shuffle:\n",
" random.shuffle(source_data)\n",
" while True:\n",
" if cur_idx >= len(source_data):\n",
" cur_idx = 0\n",
" if shuffle:\n",
" random.shuffle(source_data)\n",
" batch = source_data[cur_idx:(cur_idx+batch_size)]\n",
" # the true batch size may be smaller than the given batch size if there is not enough data left\n",
" true_batch_size = len(batch)\n",
" # ensure that the dialogs in this batch are sorted by length, as expected by the padding module\n",
" batch.sort(key=lambda x: len(x[0]), reverse=True)\n",
" # for analysis purposes, get the source dialogs and labels associated with this batch\n",
" batch_dialogs = [x[0] for x in batch]\n",
" batch_labels = [x[2] for x in batch]\n",
" # convert batch to tensors\n",
" batch_tensors = batch2TrainData(voc, batch, already_sorted=True)\n",
" yield (batch_tensors, batch_dialogs, batch_labels, true_batch_size) \n",
" cur_idx += batch_size"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "o_ev-7g-xsGQ"
},
"source": [
"## Part 2: load the data\n",
"\n",
"Now we load the labeled Wikiconv corpus from ConvoKit, and run some transformations to prepare it for use with PyTorch"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Y96SXcp4x1yj",
"outputId": "64557a00-453c-44c0-f334-b5ae83508231",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
}
},
"source": [
"corpus = Corpus(filename=download(\"conversations-gone-awry-corpus\"))"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"Dataset already exists at /root/.convokit/downloads/conversations-gone-awry-corpus\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "fPySt5a4yLId",
"outputId": "18931f88-572d-4c39-e5da-df3eca9c078c",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 72
}
},
"source": [
"# let's check some quick stats to verify that the corpus loaded correctly\n",
"print(len(corpus.get_utterance_ids()))\n",
"print(len(corpus.get_usernames()))\n",
"print(len(corpus.get_conversation_ids()))"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"30021\n",
"8069\n",
"4188\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "eeNfs0A-yosu",
"outputId": "61b9f041-d59f-4f5a-a65b-ce9631c02336",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 74
}
},
"source": [
"# Let's also take a look at some example data to see what kinds of information/metadata are available to us\n",
"print(list(corpus.iter_conversations())[0].__dict__)\n",
"print(list(corpus.iter_utterances())[0])"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"{'_owner': <convokit.model.corpus.Corpus object at 0x7f6424d21358>, '_id': '146743638.12652.12652', '_utterance_ids': ['146743638.12652.12652', '146743638.12667.12652', '146842219.12874.12874', '146860774.13072.13072'], '_usernames': None, '_meta': {'page_title': 'User talk:2005', 'page_id': 1003212, 'pair_id': '143890867.11926.11926', 'conversation_has_personal_attack': False, 'verified': True, 'pair_verified': True, 'annotation_year': '2018', 'split': 'train'}}\n",
"Utterance({'id': '146743638.12652.12652', 'user': User([('name', 'Sirex98')]), 'root': '146743638.12652.12652', 'reply_to': None, 'timestamp': 1185295934.0, 'text': '== [WIKI_LINK: WP:COMMONNAME] ==\\n', 'meta': {'is_section_header': True, 'comment_has_personal_attack': False, 'toxicity': 0}})\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "v3QIoTtbzOfY"
},
"source": [
"Now we can use the utilities defined in Part 1 to convert the ConvoKit conversational data into a tokenized form that can be straightforwardly turned into Tensors later."
]
},
{
"cell_type": "code",
"metadata": {
"id": "WlpbT72FxK8W"
},
"source": [
"# First, we need to build the vocabulary so that we know how to map tokens to tensor indicies.\n",
"# For the sake of replicating the paper results, we will load the pre-computed vocabulary objects used in the paper.\n",
"voc = loadPrecomputedVoc(\"wikiconv\", WORD2INDEX_URL, INDEX2WORD_URL)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "eRSAVrgSxhmD",
"outputId": "a682ac56-5ec9-4a88-fdce-fc9fb08aa104",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 72
}
},
"source": [
"# Inspect the Voc object to make sure it loaded correctly\n",
"print(voc.num_words) # expected vocab size is 50004: it was built using a fixed vocab size of 50k plus 4 spots for special tokens PAD, SOS, EOS, and UNK.\n",
"print(list(voc.word2index.items())[:10])\n",
"print(list(voc.index2word.items())[:10])"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"50004\n",
"[('UNK', 3), ('.', 4), ('the', 5), (\"'\", 6), (',', 7), ('to', 8), ('i', 9), ('of', 10), ('a', 11), ('and', 12)]\n",
"[('0', 'PAD'), ('1', 'SOS'), ('2', 'EOS'), ('3', 'UNK'), ('4', '.'), ('5', 'the'), ('6', \"'\"), ('7', ','), ('8', 'to'), ('9', 'i')]\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "pmaWfn7vyTjy"
},
"source": [
"# Convert the test set data into a list of input/label pairs. Each input will represent the conversation as a list of lists of tokens.\n",
"train_pairs = loadPairs(voc, corpus, \"train\", last_only=True)\n",
"val_pairs = loadPairs(voc, corpus, \"val\", last_only=True)\n",
"test_pairs = loadPairs(voc, corpus, \"test\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "RIiQNvg4zBEi",
"outputId": "11d7b50b-bc00-4080-d4ce-9294b3988194",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 184
}
},
"source": [
"# Validate the conversion by checking data size and some samples\n",
"print(len(train_pairs))\n",
"print(len(val_pairs))\n",
"print(len(test_pairs))\n",
"for p in train_pairs[:5]:\n",
" print(p)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"2508\n",
"840\n",
"4365\n",
"([['i', 'notice', 'that', 'UNK', 'that', 'moved', 'UNK', 'to', 'bill', 'chen', 'citing', 'UNK', ',', 'then', 'you', 'reverted', 'this', 'change', ',', 'bill', 'chen', 'doesn', \"'\", 't', 'commonly', 'go', 'by', 'william', ',', 'his', 'book', 'is', 'even', 'penned', 'as', 'bill', 'chen', '.', 'from', 'what', 'i', 'read', 'in', 'wp', ':', 'commonname', 'UNK', 'seems', 'to', 'be', 'correct', ',', 'examples', 'given', 'are', 'names', 'such', 'as', ':', '*', 'UNK', '(', 'not', 'UNK', ')', '*', 'UNK', '(', 'not', 'UNK', ')', 'i', 'think', 'this', 'revert', 'may', 'have', 'been', 'a'], ['chen', 'was', 'known', 'in', 'the', 'poker', 'world', 'as', '\"', 'william', '\"', 'for', 'years', 'before', 'he', 'became', 'commonly', 'known', 'as', '\"', 'bill', '\"', '.', 'i', 'changed', 'it', 'back', 'because', 'incidences', 'online', 'including', 'usenet', 'are', 'roughly', 'equal', ',', 'nothing', 'at', 'all', 'like', 'bill', 'clinton', 'and', 'william', 'clinton', ',', 'and', 'in', 'equal', 'cases', 'using', 'the', 'real', 'name', 'seems', 'the', 'best', 'choice', '.', '(', 'the', 'UNK', 'page', 'is', 'especially', 'UNK', '.', '.', '.', 'UNK', 'in', 'the', 'page', 'title', ',', 'bill', 'in', 'the', 'page']], ['i', 'see', 'what', 'you', 'saying', 'i', 'just', 'read', 'his', 'UNK', 'profile', ',', 'it', 'struck', 'me', 'when', 'i', 'saw', 'the', 'change', 'because', 'i', 'remember', 'him', 'being', 'called', 'bill', 'when', 'i', 'watched', 'the', 'last', 'season', 'of', 'high', 'stakes', 'poker', ',', 'but', 'you', 'seem', 'to', 'have', 'many', 'more', 'years', 'experience', 'in', 'the', 'poker', '/', 'gambling', 'world', 'then', 'i', 'do', '(', 'i', \"'\", 'm', 'still', 'a', 'bit', 'of', 'a', 'newbie', ')', ',', 'so', 'i', 'wanted', 'to', 'check', 'with', 'you', 'first', '.', 'btw', 'as'], 0, '146860774.13072.13072')\n",
"([['no', 'more', 'than', 'two', 'editors', 'advocated', 'deletion', '.', 'UNK', 'and', 'maybe', 'UNK', '.', 'that', \"'\", 's', 'not', 'a', 'clear', 'consensus', 'for', 'deletion', '.', 'cheers', ','], ['in', 'the', 'future', 'please', 'don', \"'\", 't', 'close', 'afds', 'when', 'you', 'don', \"'\", 't', 'have', 'the', 'courtesy', 'of', 'reading', 'the', 'comments', '.', 'all', 'comments', 'favored', 'deletion', 'except', 'two', '.', 'please', 'don', \"'\", 't', 'be', 'so', 'careless', 'in', 'the', 'future', '.'], ['that', 'simply', 'isn', \"'\", 't', 'true', '.', 'if', 'you', 'read', 'the', 'comments', ',', 'you', \"'\", 'll', 'find', 'it', \"'\", 's', 'actually', '2', 'keep', ',', '4', 'transwiki', ',', '2', 'delete', '(', 'more', 'or', 'less', ')', '.', 'the', \"'\", \"'\", 'comments', \"'\", \"'\", 'favour', 'no', 'consensus', '/', 'transwiki', '.', 'the', '\"', 'votes', '\"', 'favour', 'delete', ',', 'but', 'voting', 'is', 'evil', ',', 'of', 'course', '.', '.', '.'], ['somehow', ',', 'i', 'suspect', 'you', 'may', 'wish', 'to', 'participate', 'in', 'UNK', 'discussion', '.', 'cheers', ',']], ['i', 'assume', 'your', 'deliberate', 'lying', 'has', 'a', 'point', ',', 'but', 'get', 'over', 'it', '.', 'stop', 'bizarrely', 'goin', 'on', 'about', 'UNK', '.', 'that', 'has', 'nothing', 'to', 'do', 'with', 'the', 'afd', '.', 'there', 'was', 'a', 'plain', 'consensus', 'for', 'deleting', 'the', 'article', '.', 'UNK', 'is', 'completely', 'unrelated', '.', 'please', 'don', \"'\", 't', 'be', 'so', 'deliberately', 'obtuse', 'in', 'the', 'future', '.', 'wasting', 'other', 'people', \"'\", 's', 'time', 'is', 'simply', 'rude', '.'], 1, '144065917.12226.12226')\n",
"([['if', 'you', 'have', 'problems', 'with', 'my', 'edits', 'to', 'the', 'UNK', 'page', 'please', 'let', 'me', 'know', ',', 'do', 'not', 'just', 'revert', 'the', 'edits', '.', 'although', 'the', 'UNK', 'article', 'is', 'very', 'accurate', 'the', 'introduction', 'is', 'riddled', 'with', 'errors', ',', 'which', 'i', 'corrected', '.', 'i', 'think', 'it', 'is', 'everyone', \"'\", 's', 'best', 'interests', 'to', 'make', 'wiki', 'pages', 'as', 'accurate', 'as', 'possible', 'and', 'the', 'four', 'wheel', 'drive', 'article', 'is', 'not', 'a', 'UNK', 'example', 'of', 'this', '.', 'i', '.', 'e', '.', 'all', '-', 'wheel'], ['*', 'shrug', '*', 'it', '*', 'is', '*', 'just', 'a', 'marketing', 'term', '.', 'i', 'wish', 'you', 'lot', 'would', 'stop', 'editing', 'it', 'otherwise', '.', 'UNK', '.']], ['although', 'UNK', 'can', 'be', 'considered', 'a', 'form', 'of', 'UNK', 'it', 'is', 'not', 'the', 'same', 'drive', 'train', 'type', 'as', 'part', '-', 'time', 'UNK', '.', 'so', 'i', 'would', 'have', 'to', 'say', 'calling', 'it', 'just', 'a', 'marketing', 'term', 'is', 'a', 'narrow', 'minded', 'and', 'inaccurate', 'statement', '.', 'even', 'though', 'they', 'are', 'similar', 'you', 'can', \"'\", 't', 'just', 'UNK', 'them', 'into', 'the', 'same', 'group', '.', 'if', ',', 'as', 'you', 'say', ',', 'UNK', 'is', 'just', 'a', 'marketing', 'term', 'then', 'taking', 'a', 'turn', 'in', 'a', 'audi'], 0, '127772860.903.903')\n",
"([['please', 'stop', 'removing', 'and', 'altering', 'other', 'editors', \"'\", 'comments', '.', 'what', 'appeared', 'to', 'be', 'valid', 'concern', 'is', 'quickly', 'descending', 'into', 'trolling', ',', 'and', 'if', 'you', 'continue', ',', 'you', 'may', 'be', 'blocked', 'from', 'editing', '.', 'stop', 'it', '.', '-'], ['well', 'please', 'stop', 'posting', 'incorrect', 'information', '.', 'if', 'you', 'were', 'right', 'i', \"'\", 'd', 'agree', 'with', 'you', ',', 'and', 'i', 'am', 'not', 'trolling', '.'], ['UNK', 'is', 'trolling', ',', 'as', 'is', 'removing', 'other', 'people', \"'\", 's', 'comments', '.', 'look', ',', 'wikipedia', 'is', 'built', 'on', 'consensus', ',', 'and', 'consensus', 'has', 'it', 'that', 'we', 'use', 'american', 'style', 'for', 'american', 'subjects', '.', 'end', 'of', 'story', '.', 'any', 'more', 'complaint', 'about', 'trolling', 'about', 'this', 'topic', 'and', 'i', \"'\", 'll', 'report', 'you', 'myself', '.']], ['bullshit', '.', 'i', 'am', 'correcting', 'a', 'simple', 'mistake', '.', 'if', 'i', 'was', 'trolling', 'i', \"'\", 'd', 'be', 'doing', 'damage', 'to', 'the', 'page', ',', 'yet', 'i', 'am', 'not', '.', 'what', 'was', 'written', 'is', 'wrong', ',', 'simple', 'as', 'that', '.', 'all', 'i', 'have', 'done', 'is', 'disagree', 'with', 'what', 'was', 'written', 'and', 'written', 'as', 'such', '.', 'if', 'that', \"'\", 's', 'trolling', 'then', 'you', 'are', 'guilty', 'as', 'well', '.', 'and', 'stop', 'UNK', 'my', 'page', 'dickhead', '.', 'UNK', '.'], 1, '144645449.1479.1479')\n",
"([['please', 'stop', 'including', 'disreputable', 'sources', 'for', 'this', 'article', '.', 'wikipedia', 'policy', 'is', 'quite', 'clear', 'on', 'this', 'matter', 'blogs', 'and', 'other', 'websites', 'which', 'do', 'not', 'employ', 'editorial', 'oversight', 'of', 'authors', \"'\", 'work', 'are', 'not', 'permitted', 'as', 'sources', 'here', '.', 'please', 'stop', 'adding', 'blogs', '.'], ['please', 'stop', 'deleting', 'reputable', 'sources', 'from', 'this', 'article', '.', 'you', 'have', 'deleted', 'joe', 'wilson', \"'\", 's', 'nyt', 'article', 'that', 'is', 'a', 'key', 'factor', 'in', 'this', 'whole', 'controversy', '!', 'among', 'others', '.', 'simply', 'because', 'the', 'article', 'is', 'printed', 'on', 'a', 'different', 'site', 'does', 'not', 'mean', 'it', 'is', 'sourced', 'to', 'a', '\"', 'heinous', 'blog', '\"', '(', 'which', 'the', 'site', 'is', 'not', 'anyway', ')', '.', 'if', 'you', 'find', 'a', 'better', 'place', 'that', 'the', 'article', 'exists', ',', 'put', 'it', 'there', '.', 'or', 'if'], ['the', 'american', 'prospect', 'article', 'should', 'stay', '-', 'american', 'prospect', 'easily', 'meets', 'UNK', '.', 'the', 'cooperative', 'research', 'project', 'link', 'should', 'be', 'nuked', 'and', 'should', 'stay', 'nuked', '-', 'i', 'see', 'no', 'evidence', 'that', 'it', \"'\", 's', 'a', 'reliable', 'source', '.', 'factcheck', '.', 'org', 'is', 'reliable', 'enough', 'that', 'the', 'vice', 'president', 'of', 'the', 'united', 'states', '(', 'incorrectly', ')', 'cited', 'it', 'in', 'his', 'debate', 'as', 'an', 'authoritative', 'source', ';', 'they', 'have', 'a', 'good', 'reputation', ',', 'and', 'their', 'very', \"'\", \"'\", 'purpose', \"'\", \"'\"], ['agreed', 'UNK', 'cooperative', 'research', 'but', 'not', 'the', 'alternet', 'citation', '-', 'they', 'are', 'transcribing', 'an', 'interview', 'on', 'a', 'well', 'known', 'radio', 'show', 'with', 'a', 'well', 'known', 'source', 'with', 'expertise', 'on', 'this', 'topic', 'whose', 'comments', 'are', 'cited', 'in', 'numerous', 'mainstream', 'sources', '.', 'if', 'you', 'have', 'a', 'better', 'source', 'for', 'the', 'transcript', 'that', 'is', 'fine', 'but', 'you', 'cannot', 'just', 'delete', 'it', 'because', 'it', 'is', '\"', 'edited', '\"', '-', 'unless', 'you', 'have', 'evidence', 'that', 'they', 'are', 'making', 'stuff', 'up', ',', 'we', 'must', 'presume'], ['actually', ',', 'especially', 'with', 'alternet', ',', 'we', \"'\", \"'\", 'can', \"'\", 't', \"'\", \"'\", 'assume', 'good', 'faith', ';', 'we', 'need', 'to', 'do', 'exactly', 'the', 'opposite', '.', 'we', 'need', 'to', 'examine', 'sources', 'critically', ',', 'according', 'to', 'the', 'guidelines', 'on', 'UNK', '.', 'were', 'it', 'to', 'be', 'a', 'verbatim', 'copy', ',', 'perhaps', 'we', 'could', 'accept', 'it', 'as', 'a', 'source', '(', \"'\", \"'\", 'perhaps', \"'\", \"'\", 'being', 'absolutely', 'critical', ')', ',', 'but', 'because', 'it', \"'\", 's', 'edited', 'and', 'doesn', \"'\", 't', 'contain', 'information']], ['(', '1', ')', 'please', 'substantiate', 'that', 'the', 'source', 'is', '\"', 'notoriously', 'unreliable', '.', '\"', '(', '2', ')', 'please', 'indicate', 'where', 'it', 'says', 'we', 'should', 'assume', 'bad', 'faith', 'with', 'sources', 'that', 'are', 'transcripts', 'of', 'interviews', '(', 'i', 'know', 'the', 'quote', 'in', 'the', 'article', 'is', 'directly', 'from', 'the', 'interview', 'as', 'i', 'listened', 'to', 'the', 'interview', 'myself', ';', 'i', 'also', 'have', 'looked', 'at', 'the', 'transcript', 'and', 'do', 'not', 'see', 'anything', 'that', 'is', 'different', 'from', 'what', 'i', 'heard', ';', 'but', 'apparently', 'i', 'should'], 0, '67176052.25110.25110')\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ghTVeRFK0CUe"
},
"source": [
"## Part 3: define the model\n",
"\n",
"Next, we need to set up the individual components of the CRAFT framework: the utterance encoder, the context encoder, and the classification head (since we are fine-tuning a pretrained model, we do not need to define the decoder here). Each component will be defined as a PyTorch `nn.Module`."
]
},
{
"cell_type": "code",
"metadata": {
"id": "ZzAgSRKi0p_I"
},
"source": [
"class EncoderRNN(nn.Module):\n",
" \"\"\"This module represents the utterance encoder component of CRAFT, responsible for creating vector representations of utterances\"\"\"\n",
" def __init__(self, hidden_size, embedding, n_layers=1, dropout=0):\n",
" super(EncoderRNN, self).__init__()\n",
" self.n_layers = n_layers\n",
" self.hidden_size = hidden_size\n",
" self.embedding = embedding\n",
"\n",
" # Initialize GRU; the input_size and hidden_size params are both set to 'hidden_size'\n",
" # because our input size is a word embedding with number of features == hidden_size\n",
" self.gru = nn.GRU(hidden_size, hidden_size, n_layers,\n",
" dropout=(0 if n_layers == 1 else dropout), bidirectional=True)\n",
"\n",
" def forward(self, input_seq, input_lengths, hidden=None):\n",
" # Convert word indexes to embeddings\n",
" embedded = self.embedding(input_seq)\n",
" # Pack padded batch of sequences for RNN module\n",
" packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths)\n",
" # Forward pass through GRU\n",
" outputs, hidden = self.gru(packed, hidden)\n",
" # Unpack padding\n",
" outputs, _ = torch.nn.utils.rnn.pad_packed_sequence(outputs)\n",
" # Sum bidirectional GRU outputs\n",
" outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:]\n",
" # Return output and final hidden state\n",
" return outputs, hidden\n",
"\n",
"class ContextEncoderRNN(nn.Module):\n",
" \"\"\"This module represents the context encoder component of CRAFT, responsible for creating an order-sensitive vector representation of conversation context\"\"\"\n",
" def __init__(self, hidden_size, n_layers=1, dropout=0):\n",
" super(ContextEncoderRNN, self).__init__()\n",
" self.n_layers = n_layers\n",
" self.hidden_size = hidden_size\n",
" \n",
" # only unidirectional GRU for context encoding\n",
" self.gru = nn.GRU(hidden_size, hidden_size, n_layers,\n",
" dropout=(0 if n_layers == 1 else dropout), bidirectional=False)\n",
" \n",
" def forward(self, input_seq, input_lengths, hidden=None):\n",
" # Pack padded batch of sequences for RNN module\n",
" packed = torch.nn.utils.rnn.pack_padded_sequence(input_seq, input_lengths)\n",
" # Forward pass through GRU\n",
" outputs, hidden = self.gru(packed, hidden)\n",
" # Unpack padding\n",
" outputs, _ = torch.nn.utils.rnn.pad_packed_sequence(outputs)\n",
" # return output and final hidden state\n",
" return outputs, hidden\n",
"\n",
"class SingleTargetClf(nn.Module):\n",
" \"\"\"This module represents the CRAFT classifier head, which takes the context encoding and uses it to make a forecast\"\"\"\n",
" def __init__(self, hidden_size, dropout=0.1):\n",
" super(SingleTargetClf, self).__init__()\n",
" \n",
" self.hidden_size = hidden_size\n",
" \n",
" # initialize classifier\n",
" self.layer1 = nn.Linear(hidden_size, hidden_size)\n",
" self.layer1_act = nn.LeakyReLU()\n",
" self.layer2 = nn.Linear(hidden_size, hidden_size // 2)\n",
" self.layer2_act = nn.LeakyReLU()\n",
" self.clf = nn.Linear(hidden_size // 2, 1)\n",
" self.dropout = nn.Dropout(p=dropout)\n",
" \n",
" def forward(self, encoder_outputs, encoder_input_lengths):\n",
" # from stackoverflow (https://stackoverflow.com/questions/50856936/taking-the-last-state-from-bilstm-bigru-in-pytorch)\n",
" # First we unsqueeze seqlengths two times so it has the same number of\n",
" # of dimensions as output_forward\n",
" # (batch_size) -> (1, batch_size, 1)\n",
" lengths = encoder_input_lengths.unsqueeze(0).unsqueeze(2)\n",
" # Then we expand it accordingly\n",
" # (1, batch_size, 1) -> (1, batch_size, hidden_size) \n",
" lengths = lengths.expand((1, -1, encoder_outputs.size(2)))\n",
"\n",
" # take only the last state of the encoder for each batch\n",
" last_outputs = torch.gather(encoder_outputs, 0, lengths-1).squeeze()\n",
" # forward pass through hidden layers\n",
" layer1_out = self.layer1_act(self.layer1(self.dropout(last_outputs)))\n",
" layer2_out = self.layer2_act(self.layer2(self.dropout(layer1_out)))\n",
" # compute and return logits\n",
" logits = self.clf(self.dropout(layer2_out)).squeeze()\n",
" return logits\n",
"\n",
"class Predictor(nn.Module):\n",
" \"\"\"This helper module encapsulates the CRAFT pipeline, defining the logic of passing an input through each consecutive sub-module.\"\"\"\n",
" def __init__(self, encoder, context_encoder, classifier):\n",
" super(Predictor, self).__init__()\n",
" self.encoder = encoder\n",
" self.context_encoder = context_encoder\n",
" self.classifier = classifier\n",
" \n",
" def forward(self, input_batch, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, batch_size, max_length):\n",
" # Forward input through encoder model\n",
" _, utt_encoder_hidden = self.encoder(input_batch, utt_lengths)\n",
" \n",
" # Convert utterance encoder final states to batched dialogs for use by context encoder\n",
" context_encoder_input = makeContextEncoderInput(utt_encoder_hidden, dialog_lengths_list, batch_size, batch_indices, dialog_indices)\n",
" \n",
" # Forward pass through context encoder\n",
" context_encoder_outputs, context_encoder_hidden = self.context_encoder(context_encoder_input, dialog_lengths)\n",
" \n",
" # Forward pass through classifier to get prediction logits\n",
" logits = self.classifier(context_encoder_outputs, dialog_lengths)\n",
" \n",
" # Apply sigmoid activation\n",
" predictions = F.sigmoid(logits)\n",
" return predictions\n",
"\n",
"def makeContextEncoderInput(utt_encoder_hidden, dialog_lengths, batch_size, batch_indices, dialog_indices):\n",
" \"\"\"The utterance encoder takes in utterances in combined batches, with no knowledge of which ones go where in which conversation.\n",
" Its output is therefore also unordered. We correct this by using the information computed during tensor conversion to regroup\n",
" the utterance vectors into their proper conversational order.\"\"\"\n",
" # first, sum the forward and backward encoder states\n",
" utt_encoder_summed = utt_encoder_hidden[-2,:,:] + utt_encoder_hidden[-1,:,:]\n",
" # we now have hidden state of shape [utterance_batch_size, hidden_size]\n",
" # split it into a list of [hidden_size,] x utterance_batch_size\n",
" last_states = [t.squeeze() for t in utt_encoder_summed.split(1, dim=0)]\n",
" \n",
" # create a placeholder list of tensors to group the states by source dialog\n",
" states_dialog_batched = [[None for _ in range(dialog_lengths[i])] for i in range(batch_size)]\n",
" \n",
" # group the states by source dialog\n",
" for hidden_state, batch_idx, dialog_idx in zip(last_states, batch_indices, dialog_indices):\n",
" states_dialog_batched[batch_idx][dialog_idx] = hidden_state\n",
" \n",
" # stack each dialog into a tensor of shape [dialog_length, hidden_size]\n",
" states_dialog_batched = [torch.stack(d) for d in states_dialog_batched]\n",
" \n",
" # finally, condense all the dialog tensors into a single zero-padded tensor\n",
" # of shape [max_dialog_length, batch_size, hidden_size]\n",
" return torch.nn.utils.rnn.pad_sequence(states_dialog_batched)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "BjC1hgIWGl7g"
},
"source": [
"## Part 4: define training loop\n",
"\n",
"Now that we have all the model components defined, we need to define the actual training procedure. This will be a fairly standard neural network training loop, iterating over batches of labeled dialogs and computing cross-entropy loss on the predicted label. We will also define evaluation functions so that we can compute accuracy on the validation set after every epoch, allowing us to keep the model with the best validation performance. Note that for the sake of simpler code, validation accuracy is computed in the \"unfair\" manner using a single run of CRAFT over the full context preceding the actual personal attack, rather than the more realistic (and complicated) iterated evaluation that is used for final evaluation of the test set (in practice the two metrics track each other fairly well, making this a reasonable simplification for the sake of easy validation)."
]
},
{
"cell_type": "code",
"metadata": {
"id": "zIAHOvcdHR_h"
},
"source": [
"def train(input_variable, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, labels, # input/output arguments\n",
" encoder, context_encoder, attack_clf, # network arguments\n",
" encoder_optimizer, context_encoder_optimizer, attack_clf_optimizer, # optimization arguments\n",
" batch_size, clip, max_length=MAX_LENGTH): # misc arguments\n",
"\n",
" # Zero gradients\n",
" encoder_optimizer.zero_grad()\n",
" context_encoder_optimizer.zero_grad()\n",
" attack_clf_optimizer.zero_grad()\n",
"\n",
" # Set device options\n",
" input_variable = input_variable.to(device)\n",
" dialog_lengths = dialog_lengths.to(device)\n",
" utt_lengths = utt_lengths.to(device)\n",
" labels = labels.to(device)\n",
"\n",
" # Forward pass through utterance encoder\n",
" _, utt_encoder_hidden = encoder(input_variable, utt_lengths)\n",
" \n",
" # Convert utterance encoder final states to batched dialogs for use by context encoder\n",
" context_encoder_input = makeContextEncoderInput(utt_encoder_hidden, dialog_lengths_list, batch_size, batch_indices, dialog_indices)\n",
" \n",
" # Forward pass through context encoder\n",
" context_encoder_outputs, _ = context_encoder(context_encoder_input, dialog_lengths)\n",
"\n",
" # Forward pass through classifier to get prediction logits\n",
" logits = attack_clf(context_encoder_outputs, dialog_lengths)\n",
" \n",
" # Calculate loss\n",
" loss = F.binary_cross_entropy_with_logits(logits, labels)\n",
"\n",
" # Perform backpropatation\n",
" loss.backward()\n",
"\n",
" # Clip gradients: gradients are modified in place\n",
" _ = torch.nn.utils.clip_grad_norm_(encoder.parameters(), clip)\n",
" _ = torch.nn.utils.clip_grad_norm_(context_encoder.parameters(), clip)\n",
" _ = torch.nn.utils.clip_grad_norm_(attack_clf.parameters(), clip)\n",
"\n",
" # Adjust model weights\n",
" encoder_optimizer.step()\n",
" context_encoder_optimizer.step()\n",
" attack_clf_optimizer.step()\n",
"\n",
" return loss.item()\n",
"\n",
"def evaluateBatch(encoder, context_encoder, predictor, voc, input_batch, dialog_lengths, \n",
" dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, batch_size, device, max_length=MAX_LENGTH):\n",
" # Set device options\n",
" input_batch = input_batch.to(device)\n",
" dialog_lengths = dialog_lengths.to(device)\n",
" utt_lengths = utt_lengths.to(device)\n",
" # Predict future attack using predictor\n",
" scores = predictor(input_batch, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, batch_size, max_length)\n",
" predictions = (scores > 0.5).float()\n",
" return predictions, scores\n",
"\n",
"def validate(dataset, encoder, context_encoder, predictor, voc, batch_size, device):\n",
" # create a batch iterator for the given data\n",
" batch_iterator = batchIterator(voc, dataset, batch_size, shuffle=False)\n",
" # find out how many iterations we will need to cover the whole dataset\n",
" n_iters = len(dataset) // batch_size + int(len(dataset) % batch_size > 0)\n",
" # containers for full prediction results so we can compute accuracy at the end\n",
" all_preds = []\n",
" all_labels = []\n",
" for iteration in range(1, n_iters+1):\n",
" batch, batch_dialogs, _, true_batch_size = next(batch_iterator)\n",
" # Extract fields from batch\n",
" input_variable, dialog_lengths, utt_lengths, batch_indices, dialog_indices, labels, convo_ids, target_variable, mask, max_target_len = batch\n",
" dialog_lengths_list = [len(x) for x in batch_dialogs]\n",
" # run the model\n",
" predictions, scores = evaluateBatch(encoder, context_encoder, predictor, voc, input_variable,\n",
" dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices,\n",
" true_batch_size, device)\n",
" # aggregate results for computing accuracy at the end\n",
" all_preds += [p.item() for p in predictions]\n",
" all_labels += [l.item() for l in labels]\n",
" print(\"Iteration: {}; Percent complete: {:.1f}%\".format(iteration, iteration / n_iters * 100))\n",
"\n",
" # compute and return the accuracy\n",
" return (np.asarray(all_preds) == np.asarray(all_labels)).mean()\n",
"\n",
"def trainIters(voc, pairs, val_pairs, encoder, context_encoder, attack_clf,\n",
" encoder_optimizer, context_encoder_optimizer, attack_clf_optimizer, embedding,\n",
" n_iteration, batch_size, print_every, validate_every, clip):\n",
" \n",
" # create a batch iterator for training data\n",
" batch_iterator = batchIterator(voc, pairs, batch_size)\n",
" \n",
" # Initializations\n",
" print('Initializing ...')\n",
" start_iteration = 1\n",
" print_loss = 0\n",
"\n",
" # Training loop\n",
" print(\"Training...\")\n",
" # keep track of best validation accuracy - only save when we have a model that beats the current best\n",
" best_acc = 0\n",
" for iteration in range(start_iteration, n_iteration + 1):\n",
" training_batch, training_dialogs, _, true_batch_size = next(batch_iterator)\n",
" # Extract fields from batch\n",
" input_variable, dialog_lengths, utt_lengths, batch_indices, dialog_indices, labels, _, target_variable, mask, max_target_len = training_batch\n",
" dialog_lengths_list = [len(x) for x in training_dialogs]\n",
"\n",
" # Run a training iteration with batch\n",
" loss = train(input_variable, dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices, labels, # input/output arguments\n",
" encoder, context_encoder, attack_clf, # network arguments\n",
" encoder_optimizer, context_encoder_optimizer, attack_clf_optimizer, # optimization arguments\n",
" true_batch_size, clip) # misc arguments\n",
" print_loss += loss\n",
" \n",
" # Print progress\n",
" if iteration % print_every == 0:\n",
" print_loss_avg = print_loss / print_every\n",
" print(\"Iteration: {}; Percent complete: {:.1f}%; Average loss: {:.4f}\".format(iteration, iteration / n_iteration * 100, print_loss_avg))\n",
" print_loss = 0\n",
"\n",
" # Evaluate on validation set\n",
" if (iteration % validate_every == 0):\n",
" print(\"Validating!\")\n",
" # put the network components into evaluation mode\n",
" encoder.eval()\n",
" context_encoder.eval()\n",
" attack_clf.eval()\n",
" \n",
" predictor = Predictor(encoder, context_encoder, attack_clf)\n",
" accuracy = validate(val_pairs, encoder, context_encoder, predictor, voc, batch_size, device)\n",
" print(\"Validation set accuracy: {:.2f}%\".format(accuracy * 100))\n",
"\n",
" # keep track of our best model so far\n",
" if accuracy > best_acc:\n",
" print(\"Validation accuracy better than current best; saving model...\")\n",
" best_acc = accuracy\n",
" torch.save({\n",
" 'iteration': iteration,\n",
" 'en': encoder.state_dict(),\n",
" 'ctx': context_encoder.state_dict(),\n",
" 'atk_clf': attack_clf.state_dict(),\n",
" 'en_opt': encoder_optimizer.state_dict(),\n",
" 'ctx_opt': context_encoder_optimizer.state_dict(),\n",
" 'atk_clf_opt': attack_clf_optimizer.state_dict(),\n",
" 'loss': loss,\n",
" 'voc_dict': voc.__dict__,\n",
" 'embedding': embedding.state_dict()\n",
" }, \"finetuned_model.tar\")\n",
" \n",
" # put the network components back into training mode\n",
" encoder.train()\n",
" context_encoder.train()\n",
" attack_clf.train()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "9eG1p_cH5fw9"
},
"source": [
"## Part 5: define the evaluation procedure\n",
"\n",
"We're almost ready to run! The last component we need is some code to evaluate performance on the test set after fine-tuning is completed. This evaluation should use the full iterative procedure described in the paper, replicating how a system might be deployed in practice, without knowledge of where the personal attack occurs"
]
},
{
"cell_type": "code",
"metadata": {
"id": "yZqEcwEJ5bqn"
},
"source": [
"def evaluateDataset(dataset, encoder, context_encoder, predictor, voc, batch_size, device):\n",
" # create a batch iterator for the given data\n",
" batch_iterator = batchIterator(voc, dataset, batch_size, shuffle=False)\n",
" # find out how many iterations we will need to cover the whole dataset\n",
" n_iters = len(dataset) // batch_size + int(len(dataset) % batch_size > 0)\n",
" output_df = {\n",
" \"id\": [],\n",
" \"prediction\": [],\n",
" \"score\": []\n",
" }\n",
" for iteration in range(1, n_iters+1):\n",
" batch, batch_dialogs, _, true_batch_size = next(batch_iterator)\n",
" # Extract fields from batch\n",
" input_variable, dialog_lengths, utt_lengths, batch_indices, dialog_indices, labels, convo_ids, target_variable, mask, max_target_len = batch\n",
" dialog_lengths_list = [len(x) for x in batch_dialogs]\n",
" # run the model\n",
" predictions, scores = evaluateBatch(encoder, context_encoder, predictor, voc, input_variable,\n",
" dialog_lengths, dialog_lengths_list, utt_lengths, batch_indices, dialog_indices,\n",
" true_batch_size, device)\n",
"\n",
" # format the output as a dataframe (which we can later re-join with the corpus)\n",
" for i in range(true_batch_size):\n",
" convo_id = convo_ids[i]\n",
" pred = predictions[i].item()\n",
" score = scores[i].item()\n",
" output_df[\"id\"].append(convo_id)\n",
" output_df[\"prediction\"].append(pred)\n",
" output_df[\"score\"].append(score)\n",
" \n",
" print(\"Iteration: {}; Percent complete: {:.1f}%\".format(iteration, iteration / n_iters * 100))\n",
"\n",
" return pd.DataFrame(output_df).set_index(\"id\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "N0VIv8sbOaB6"
},
"source": [
"## Part 6: build and fine-tune the model\n",
"\n",
"We finally have all the components we need! Now we can instantiate the CRAFT model components, load the pre-trained weights, and run fine-tuning."
]
},
{
"cell_type": "code",
"metadata": {
"id": "4QRinW10Oo_G",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"outputId": "99df8b29-f6cb-4fab-80db-611e73ab3869"
},
"source": [
"# Fix random state (affect native Python code only, does not affect PyTorch and hence does not guarantee reproducibility)\n",
"random.seed(2019)\n",
"\n",
"# Tell torch to use GPU. Note that if you are running this notebook in a non-GPU environment, you can change 'cuda' to 'cpu' to get the code to run.\n",
"device = torch.device('cuda')\n",
"\n",
"print(\"Loading saved parameters...\")\n",
"if not os.path.isfile(\"pretrained_model.tar\"):\n",
" print(\"\\tDownloading pre-trained CRAFT...\")\n",
" urlretrieve(MODEL_URL, \"pretrained_model.tar\")\n",
" print(\"\\t...Done!\")\n",
"checkpoint = torch.load(\"pretrained_model.tar\")\n",
"# If running in a non-GPU environment, you need to tell PyTorch to convert the parameters to CPU tensor format.\n",
"# To do so, replace the previous line with the following:\n",
"#checkpoint = torch.load(\"model.tar\", map_location=torch.device('cpu'))\n",
"encoder_sd = checkpoint['en']\n",
"context_sd = checkpoint['ctx']\n",
"embedding_sd = checkpoint['embedding']\n",