File size: 42,746 Bytes
f4355cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fd69392",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Tutorial url\n",
    "# https://medium.com/data-and-beyond/complete-guide-to-building-bert-model-from-sratch-3e6562228891"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7bc1129e",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: transformers in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (4.24.0)\n",
      "Collecting datasets\n",
      "  Downloading datasets-2.13.1-py3-none-any.whl (486 kB)\n",
      "     ------------------------------------- 486.2/486.2 kB 10.1 MB/s eta 0:00:00\n",
      "Requirement already satisfied: tokenizers in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (0.11.4)\n",
      "Requirement already satisfied: packaging>=20.0 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (22.0)\n",
      "Requirement already satisfied: tqdm>=4.27 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (4.64.1)\n",
      "Requirement already satisfied: numpy>=1.17 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (1.23.5)\n",
      "Requirement already satisfied: huggingface-hub<1.0,>=0.10.0 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (0.10.1)\n",
      "Requirement already satisfied: pyyaml>=5.1 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (6.0)\n",
      "Requirement already satisfied: requests in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (2.28.1)\n",
      "Requirement already satisfied: filelock in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (3.9.0)\n",
      "Requirement already satisfied: regex!=2019.12.17 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from transformers) (2022.7.9)\n",
      "Collecting huggingface-hub<1.0,>=0.10.0\n",
      "  Downloading huggingface_hub-0.16.2-py3-none-any.whl (268 kB)\n",
      "     ------------------------------------- 268.5/268.5 kB 16.1 MB/s eta 0:00:00\n",
      "Requirement already satisfied: pandas in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from datasets) (1.5.3)\n",
      "Collecting aiohttp\n",
      "  Downloading aiohttp-3.8.4-cp310-cp310-win_amd64.whl (319 kB)\n",
      "     ---------------------------------------- 319.8/319.8 kB ? eta 0:00:00\n",
      "Requirement already satisfied: fsspec[http]>=2021.11.1 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from datasets) (2022.11.0)\n",
      "Collecting xxhash\n",
      "  Downloading xxhash-3.2.0-cp310-cp310-win_amd64.whl (30 kB)\n",
      "Collecting pyarrow>=8.0.0\n",
      "  Downloading pyarrow-12.0.1-cp310-cp310-win_amd64.whl (21.5 MB)\n",
      "     --------------------------------------- 21.5/21.5 MB 26.1 MB/s eta 0:00:00\n",
      "Collecting multiprocess\n",
      "  Downloading multiprocess-0.70.14-py310-none-any.whl (134 kB)\n",
      "     -------------------------------------- 134.3/134.3 kB 8.3 MB/s eta 0:00:00\n",
      "Requirement already satisfied: dill<0.3.7,>=0.3.0 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from datasets) (0.3.6)\n",
      "Requirement already satisfied: charset-normalizer<4.0,>=2.0 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from aiohttp->datasets) (2.0.4)\n",
      "Collecting yarl<2.0,>=1.0\n",
      "  Downloading yarl-1.9.2-cp310-cp310-win_amd64.whl (61 kB)\n",
      "     ---------------------------------------- 61.0/61.0 kB ? eta 0:00:00\n",
      "Collecting aiosignal>=1.1.2\n",
      "  Downloading aiosignal-1.3.1-py3-none-any.whl (7.6 kB)\n",
      "Collecting frozenlist>=1.1.1\n",
      "  Downloading frozenlist-1.3.3-cp310-cp310-win_amd64.whl (33 kB)\n",
      "Collecting async-timeout<5.0,>=4.0.0a3\n",
      "  Downloading async_timeout-4.0.2-py3-none-any.whl (5.8 kB)\n",
      "Collecting multidict<7.0,>=4.5\n",
      "  Downloading multidict-6.0.4-cp310-cp310-win_amd64.whl (28 kB)\n",
      "Requirement already satisfied: attrs>=17.3.0 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from aiohttp->datasets) (22.1.0)\n",
      "Requirement already satisfied: typing-extensions>=3.7.4.3 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from huggingface-hub<1.0,>=0.10.0->transformers) (4.4.0)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from requests->transformers) (3.4)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from requests->transformers) (1.26.14)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from requests->transformers) (2022.12.7)\n",
      "Requirement already satisfied: colorama in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from tqdm>=4.27->transformers) (0.4.6)\n",
      "Requirement already satisfied: python-dateutil>=2.8.1 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from pandas->datasets) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from pandas->datasets) (2022.7)\n",
      "Requirement already satisfied: six>=1.5 in c:\\users\\yozhan\\appdata\\local\\anaconda3\\lib\\site-packages (from python-dateutil>=2.8.1->pandas->datasets) (1.16.0)\n",
      "Installing collected packages: xxhash, pyarrow, multiprocess, multidict, frozenlist, async-timeout, yarl, huggingface-hub, aiosignal, aiohttp, datasets\n",
      "  Attempting uninstall: huggingface-hub\n",
      "    Found existing installation: huggingface-hub 0.10.1\n",
      "    Uninstalling huggingface-hub-0.10.1:\n",
      "      Successfully uninstalled huggingface-hub-0.10.1\n",
      "Successfully installed aiohttp-3.8.4 aiosignal-1.3.1 async-timeout-4.0.2 datasets-2.13.1 frozenlist-1.3.3 huggingface-hub-0.16.2 multidict-6.0.4 multiprocess-0.70.14 pyarrow-12.0.1 xxhash-3.2.0 yarl-1.9.2\n"
     ]
    }
   ],
   "source": [
    "!pip install transformers datasets tokenizers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c23bad9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.chdir(r\"C:\\Users\\yozhan\\cryptocurrency\\tutorial\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d6d279f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "import torch\n",
    "import re\n",
    "import random\n",
    "import transformers, datasets\n",
    "from tokenizers import BertWordPieceTokenizer\n",
    "from transformers import BertTokenizer\n",
    "import tqdm\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "import itertools\n",
    "import math\n",
    "import torch.nn.functional as F\n",
    "import numpy as np\n",
    "from torch.optim import Adam\n",
    "\n",
    "MAX_LEN = 64"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "af0bf9cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "### loading all data into memory\n",
    "corpus_movie_conv = r'.\\cornell_movie-dialogs_corpus\\movie_conversations.txt'\n",
    "corpus_movie_lines = '.\\cornell_movie-dialogs_corpus\\movie_lines.txt'\n",
    "with open(corpus_movie_conv, 'r', encoding='iso-8859-1') as c:\n",
    "    conv = c.readlines()\n",
    "with open(corpus_movie_lines, 'r', encoding='iso-8859-1') as l:\n",
    "    lines = l.readlines()\n",
    "\n",
    "### splitting text using special lines\n",
    "lines_dic = {}\n",
    "for line in lines:\n",
    "    objects = line.split(\" +++$+++ \")\n",
    "    lines_dic[objects[0]] = objects[-1]\n",
    "\n",
    "### generate question answer pairs\n",
    "pairs = []\n",
    "for con in conv:\n",
    "    \n",
    "    # get a list of sentence ids\n",
    "    ids = eval(con.split(\" +++$+++ \")[-1])\n",
    "    for i in range(len(ids)):\n",
    "        qa_pairs = []\n",
    "        \n",
    "        # if this is the last id\n",
    "        if i == len(ids) - 1:\n",
    "            break\n",
    "\n",
    "        first = lines_dic[ids[i]].strip()  \n",
    "        second = lines_dic[ids[i+1]].strip() \n",
    "\n",
    "        qa_pairs.append(' '.join(first.split()[:MAX_LEN]))\n",
    "        qa_pairs.append(' '.join(second.split()[:MAX_LEN]))\n",
    "        pairs.append(qa_pairs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c9f5a78d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Can we make this quick? Roxanne Korrine and Andrew Barrett are having an incredibly horrendous public break- up on the quad. Again.', \"Well, I thought we'd start with pronunciation, if that's okay with you.\"]\n"
     ]
    }
   ],
   "source": [
    "print(pairs[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "28b4a8b9",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 221616/221616 [00:00<00:00, 1154039.87it/s]\n",
      "C:\\Users\\yozhan\\AppData\\Local\\anaconda3\\lib\\site-packages\\transformers\\tokenization_utils_base.py:1679: FutureWarning: Calling BertTokenizer.from_pretrained() with the path to a single file or url is deprecated and won't be possible anymore in v5. Use a model identifier or the path to a directory instead.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "os.mkdir('./data')\n",
    "text_data = []\n",
    "file_count = 0\n",
    "\n",
    "for sample in tqdm.tqdm([x[0] for x in pairs]):\n",
    "    text_data.append(sample)\n",
    "\n",
    "    # once we hit the 10K mark, save to file\n",
    "    if len(text_data) == 10000:\n",
    "        with open(f'./data/text_{file_count}.txt', 'w', encoding='utf-8') as fp:\n",
    "            fp.write('\\n'.join(text_data))\n",
    "        text_data = []\n",
    "        file_count += 1\n",
    "\n",
    "paths = [str(x) for x in Path('./data').glob('**/*.txt')]\n",
    "\n",
    "### training own tokenizer\n",
    "tokenizer = BertWordPieceTokenizer(\n",
    "    clean_text=True,\n",
    "    handle_chinese_chars=False,\n",
    "    strip_accents=False,\n",
    "    lowercase=True\n",
    ")\n",
    "\n",
    "tokenizer.train( \n",
    "    files=paths,\n",
    "    vocab_size=30_000, \n",
    "    min_frequency=5,\n",
    "    limit_alphabet=1000, \n",
    "    wordpieces_prefix='##',\n",
    "    special_tokens=['[PAD]', '[CLS]', '[SEP]', '[MASK]', '[UNK]']\n",
    "    )\n",
    "\n",
    "os.mkdir('./bert-it-1')\n",
    "tokenizer.save_model('./bert-it-1', 'bert-it')\n",
    "tokenizer = BertTokenizer.from_pretrained('./bert-it-1/bert-it-vocab.txt', local_files_only=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "30e775ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BERTDataset(Dataset):\n",
    "    def __init__(self, data_pair, tokenizer, seq_len=64):\n",
    "\n",
    "        self.tokenizer = tokenizer\n",
    "        self.seq_len = seq_len\n",
    "        self.corpus_lines = len(data_pair)\n",
    "        self.lines = data_pair\n",
    "\n",
    "    def __len__(self):\n",
    "        return self.corpus_lines\n",
    "\n",
    "    def __getitem__(self, item):\n",
    "\n",
    "        # Step 1: get random sentence pair, either negative or positive (saved as is_next_label)\n",
    "        t1, t2, is_next_label = self.get_sent(item)\n",
    "\n",
    "        # Step 2: replace random words in sentence with mask / random words\n",
    "        t1_random, t1_label = self.random_word(t1)\n",
    "        t2_random, t2_label = self.random_word(t2)\n",
    "\n",
    "        # Step 3: Adding CLS and SEP tokens to the start and end of sentences\n",
    "         # Adding PAD token for labels\n",
    "        t1 = [self.tokenizer.vocab['[CLS]']] + t1_random + [self.tokenizer.vocab['[SEP]']]\n",
    "        t2 = t2_random + [self.tokenizer.vocab['[SEP]']]\n",
    "        t1_label = [self.tokenizer.vocab['[PAD]']] + t1_label + [self.tokenizer.vocab['[PAD]']]\n",
    "        t2_label = t2_label + [self.tokenizer.vocab['[PAD]']]\n",
    "\n",
    "        # Step 4: combine sentence 1 and 2 as one input\n",
    "        # adding PAD tokens to make the sentence same length as seq_len\n",
    "        segment_label = ([1 for _ in range(len(t1))] + [2 for _ in range(len(t2))])[:self.seq_len]\n",
    "        bert_input = (t1 + t2)[:self.seq_len]\n",
    "        bert_label = (t1_label + t2_label)[:self.seq_len]\n",
    "        padding = [self.tokenizer.vocab['[PAD]'] for _ in range(self.seq_len - len(bert_input))]\n",
    "        bert_input.extend(padding), bert_label.extend(padding), segment_label.extend(padding)\n",
    "\n",
    "        output = {\"bert_input\": bert_input,\n",
    "                  \"bert_label\": bert_label,\n",
    "                  \"segment_label\": segment_label,\n",
    "                  \"is_next\": is_next_label}\n",
    "\n",
    "        return {key: torch.tensor(value) for key, value in output.items()}\n",
    "\n",
    "    def random_word(self, sentence):\n",
    "        tokens = sentence.split()\n",
    "        output_label = []\n",
    "        output = []\n",
    "\n",
    "        # 15% of the tokens would be replaced\n",
    "        for i, token in enumerate(tokens):\n",
    "            prob = random.random()\n",
    "\n",
    "            # remove cls and sep token\n",
    "            token_id = self.tokenizer(token)['input_ids'][1:-1]\n",
    "\n",
    "            if prob < 0.15:\n",
    "                prob /= 0.15\n",
    "\n",
    "                # 80% chance change token to mask token\n",
    "                if prob < 0.8:\n",
    "                    for i in range(len(token_id)):\n",
    "                        output.append(self.tokenizer.vocab['[MASK]'])\n",
    "\n",
    "                # 10% chance change token to random token\n",
    "                elif prob < 0.9:\n",
    "                    for i in range(len(token_id)):\n",
    "                        output.append(random.randrange(len(self.tokenizer.vocab)))\n",
    "\n",
    "                # 10% chance change token to current token\n",
    "                else:\n",
    "                    output.append(token_id)\n",
    "\n",
    "                output_label.append(token_id)\n",
    "\n",
    "            else:\n",
    "                output.append(token_id)\n",
    "                for i in range(len(token_id)):\n",
    "                    output_label.append(0)\n",
    "\n",
    "        # flattening\n",
    "        output = list(itertools.chain(*[[x] if not isinstance(x, list) else x for x in output]))\n",
    "        output_label = list(itertools.chain(*[[x] if not isinstance(x, list) else x for x in output_label]))\n",
    "        assert len(output) == len(output_label)\n",
    "        return output, output_label\n",
    "\n",
    "    def get_sent(self, index):\n",
    "        '''return random sentence pair'''\n",
    "        t1, t2 = self.get_corpus_line(index)\n",
    "\n",
    "        # negative or positive pair, for next sentence prediction\n",
    "        if random.random() > 0.5:\n",
    "            return t1, t2, 1\n",
    "        else:\n",
    "            return t1, self.get_random_line(), 0\n",
    "\n",
    "    def get_corpus_line(self, item):\n",
    "        '''return sentence pair'''\n",
    "        return self.lines[item][0], self.lines[item][1]\n",
    "\n",
    "    def get_random_line(self):\n",
    "        '''return random single sentence'''\n",
    "        return self.lines[random.randrange(len(self.lines))][1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "b0d9f35c",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = BERTDataset(\n",
    "   pairs, seq_len=MAX_LEN, tokenizer=tokenizer)\n",
    "train_loader = DataLoader(\n",
    "   train_data, batch_size=32, shuffle=True, pin_memory=True)\n",
    "sample_data = next(iter(train_loader))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "ad60cf79",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'bert_input': tensor([   1,  182,   11,   58,  162,  874,   34,    2,    6, 3232,  108,  512,\n",
      "          17,    6,    2,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
      "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
      "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
      "           0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,\n",
      "           0,    0,    0,    0]), 'bert_label': tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 'segment_label': tensor([1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
      "        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 'is_next': tensor(1)}\n"
     ]
    }
   ],
   "source": [
    "print(train_data[random.randrange(len(train_data))])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "bd70e96e",
   "metadata": {},
   "outputs": [],
   "source": [
    "class PositionalEmbedding(torch.nn.Module):\n",
    "\n",
    "    def __init__(self, d_model, max_len=128):\n",
    "        super().__init__()\n",
    "\n",
    "        # Compute the positional encodings once in log space.\n",
    "        pe = torch.zeros(max_len, d_model).float()\n",
    "        pe.require_grad = False\n",
    "\n",
    "        for pos in range(max_len):   \n",
    "            # for each dimension of the each position\n",
    "            for i in range(0, d_model, 2):   \n",
    "                pe[pos, i] = math.sin(pos / (10000 ** ((2 * i)/d_model)))\n",
    "                pe[pos, i + 1] = math.cos(pos / (10000 ** ((2 * (i + 1))/d_model)))\n",
    "\n",
    "        # include the batch size\n",
    "        self.pe = pe.unsqueeze(0)   \n",
    "        # self.register_buffer('pe', pe)\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.pe\n",
    "\n",
    "class BERTEmbedding(torch.nn.Module):\n",
    "    \"\"\"\n",
    "    BERT Embedding which is consisted with under features\n",
    "        1. TokenEmbedding : normal embedding matrix\n",
    "        2. PositionalEmbedding : adding positional information using sin, cos\n",
    "        2. SegmentEmbedding : adding sentence segment info, (sent_A:1, sent_B:2)\n",
    "        sum of all these features are output of BERTEmbedding\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, vocab_size, embed_size, seq_len=64, dropout=0.1):\n",
    "        \"\"\"\n",
    "        :param vocab_size: total vocab size\n",
    "        :param embed_size: embedding size of token embedding\n",
    "        :param dropout: dropout rate\n",
    "        \"\"\"\n",
    "\n",
    "        super().__init__()\n",
    "        self.embed_size = embed_size\n",
    "        # (m, seq_len) --> (m, seq_len, embed_size)\n",
    "        # padding_idx is not updated during training, remains as fixed pad (0)\n",
    "        self.token = torch.nn.Embedding(vocab_size, embed_size, padding_idx=0)\n",
    "        self.segment = torch.nn.Embedding(3, embed_size, padding_idx=0)\n",
    "        self.position = PositionalEmbedding(d_model=embed_size, max_len=seq_len)\n",
    "        self.dropout = torch.nn.Dropout(p=dropout)\n",
    "       \n",
    "    def forward(self, sequence, segment_label):\n",
    "        x = self.token(sequence) + self.position(sequence) + self.segment(segment_label)\n",
    "        return self.dropout(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "baa5caa0",
   "metadata": {},
   "outputs": [],
   "source": [
    "### attention layers\n",
    "class MultiHeadedAttention(torch.nn.Module):\n",
    "    \n",
    "    def __init__(self, heads, d_model, dropout=0.1):\n",
    "        super(MultiHeadedAttention, self).__init__()\n",
    "        \n",
    "        assert d_model % heads == 0\n",
    "        self.d_k = d_model // heads\n",
    "        self.heads = heads\n",
    "        self.dropout = torch.nn.Dropout(dropout)\n",
    "\n",
    "        self.query = torch.nn.Linear(d_model, d_model)\n",
    "        self.key = torch.nn.Linear(d_model, d_model)\n",
    "        self.value = torch.nn.Linear(d_model, d_model)\n",
    "        self.output_linear = torch.nn.Linear(d_model, d_model)\n",
    "        \n",
    "    def forward(self, query, key, value, mask):\n",
    "        \"\"\"\n",
    "        query, key, value of shape: (batch_size, max_len, d_model)\n",
    "        mask of shape: (batch_size, 1, 1, max_words)\n",
    "        \"\"\"\n",
    "        # (batch_size, max_len, d_model)\n",
    "        query = self.query(query)\n",
    "        key = self.key(key)        \n",
    "        value = self.value(value)   \n",
    "        \n",
    "        # (batch_size, max_len, d_model) --> (batch_size, max_len, h, d_k) --> (batch_size, h, max_len, d_k)\n",
    "        query = query.view(query.shape[0], -1, self.heads, self.d_k).permute(0, 2, 1, 3)   \n",
    "        key = key.view(key.shape[0], -1, self.heads, self.d_k).permute(0, 2, 1, 3)  \n",
    "        value = value.view(value.shape[0], -1, self.heads, self.d_k).permute(0, 2, 1, 3)  \n",
    "        \n",
    "        # (batch_size, h, max_len, d_k) matmul (batch_size, h, d_k, max_len) --> (batch_size, h, max_len, max_len)\n",
    "        scores = torch.matmul(query, key.permute(0, 1, 3, 2)) / math.sqrt(query.size(-1))\n",
    "\n",
    "        # fill 0 mask with super small number so it wont affect the softmax weight\n",
    "        # (batch_size, h, max_len, max_len)\n",
    "        scores = scores.masked_fill(mask == 0, -1e9)    \n",
    "\n",
    "        # (batch_size, h, max_len, max_len)\n",
    "        # softmax to put attention weight for all non-pad tokens\n",
    "        # max_len X max_len matrix of attention\n",
    "        weights = F.softmax(scores, dim=-1)           \n",
    "        weights = self.dropout(weights)\n",
    "\n",
    "        # (batch_size, h, max_len, max_len) matmul (batch_size, h, max_len, d_k) --> (batch_size, h, max_len, d_k)\n",
    "        context = torch.matmul(weights, value)\n",
    "\n",
    "        # (batch_size, h, max_len, d_k) --> (batch_size, max_len, h, d_k) --> (batch_size, max_len, d_model)\n",
    "        context = context.permute(0, 2, 1, 3).contiguous().view(context.shape[0], -1, self.heads * self.d_k)\n",
    "\n",
    "        # (batch_size, max_len, d_model)\n",
    "        return self.output_linear(context)\n",
    "\n",
    "class FeedForward(torch.nn.Module):\n",
    "    \"Implements FFN equation.\"\n",
    "\n",
    "    def __init__(self, d_model, middle_dim=2048, dropout=0.1):\n",
    "        super(FeedForward, self).__init__()\n",
    "        \n",
    "        self.fc1 = torch.nn.Linear(d_model, middle_dim)\n",
    "        self.fc2 = torch.nn.Linear(middle_dim, d_model)\n",
    "        self.dropout = torch.nn.Dropout(dropout)\n",
    "        self.activation = torch.nn.GELU()\n",
    "\n",
    "    def forward(self, x):\n",
    "        out = self.activation(self.fc1(x))\n",
    "        out = self.fc2(self.dropout(out))\n",
    "        return out\n",
    "\n",
    "class EncoderLayer(torch.nn.Module):\n",
    "    def __init__(\n",
    "        self, \n",
    "        d_model=768,\n",
    "        heads=12, \n",
    "        feed_forward_hidden=768 * 4, \n",
    "        dropout=0.1\n",
    "        ):\n",
    "        super(EncoderLayer, self).__init__()\n",
    "        self.layernorm = torch.nn.LayerNorm(d_model)\n",
    "        self.self_multihead = MultiHeadedAttention(heads, d_model)\n",
    "        self.feed_forward = FeedForward(d_model, middle_dim=feed_forward_hidden)\n",
    "        self.dropout = torch.nn.Dropout(dropout)\n",
    "\n",
    "    def forward(self, embeddings, mask):\n",
    "        # embeddings: (batch_size, max_len, d_model)\n",
    "        # encoder mask: (batch_size, 1, 1, max_len)\n",
    "        # result: (batch_size, max_len, d_model)\n",
    "        interacted = self.dropout(self.self_multihead(embeddings, embeddings, embeddings, mask))\n",
    "        # residual layer\n",
    "        interacted = self.layernorm(interacted + embeddings)\n",
    "        # bottleneck\n",
    "        feed_forward_out = self.dropout(self.feed_forward(interacted))\n",
    "        encoded = self.layernorm(feed_forward_out + interacted)\n",
    "        return encoded"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "33fe273b",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BERT(torch.nn.Module):\n",
    "    \"\"\"\n",
    "    BERT model : Bidirectional Encoder Representations from Transformers.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, vocab_size, d_model=768, n_layers=12, heads=12, dropout=0.1):\n",
    "        \"\"\"\n",
    "        :param vocab_size: vocab_size of total words\n",
    "        :param hidden: BERT model hidden size\n",
    "        :param n_layers: numbers of Transformer blocks(layers)\n",
    "        :param attn_heads: number of attention heads\n",
    "        :param dropout: dropout rate\n",
    "        \"\"\"\n",
    "\n",
    "        super().__init__()\n",
    "        self.d_model = d_model\n",
    "        self.n_layers = n_layers\n",
    "        self.heads = heads\n",
    "\n",
    "        # paper noted they used 4 * hidden_size for ff_network_hidden_size\n",
    "        self.feed_forward_hidden = d_model * 4\n",
    "\n",
    "        # embedding for BERT, sum of positional, segment, token embeddings\n",
    "        self.embedding = BERTEmbedding(vocab_size=vocab_size, embed_size=d_model)\n",
    "\n",
    "        # multi-layers transformer blocks, deep network\n",
    "        self.encoder_blocks = torch.nn.ModuleList(\n",
    "            [EncoderLayer(d_model, heads, d_model * 4, dropout) for _ in range(n_layers)])\n",
    "\n",
    "    def forward(self, x, segment_info):\n",
    "        # attention masking for padded token\n",
    "        # (batch_size, 1, seq_len, seq_len)\n",
    "        mask = (x > 0).unsqueeze(1).repeat(1, x.size(1), 1).unsqueeze(1)\n",
    "\n",
    "        # embedding the indexed sequence to sequence of vectors\n",
    "        x = self.embedding(x, segment_info)\n",
    "\n",
    "        # running over multiple transformer blocks\n",
    "        for encoder in self.encoder_blocks:\n",
    "            x = encoder.forward(x, mask)\n",
    "        return x\n",
    "\n",
    "class NextSentencePrediction(torch.nn.Module):\n",
    "    \"\"\"\n",
    "    2-class classification model : is_next, is_not_next\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, hidden):\n",
    "        \"\"\"\n",
    "        :param hidden: BERT model output size\n",
    "        \"\"\"\n",
    "        super().__init__()\n",
    "        self.linear = torch.nn.Linear(hidden, 2)\n",
    "        self.softmax = torch.nn.LogSoftmax(dim=-1)\n",
    "\n",
    "    def forward(self, x):\n",
    "        # use only the first token which is the [CLS]\n",
    "        return self.softmax(self.linear(x[:, 0]))\n",
    "\n",
    "class MaskedLanguageModel(torch.nn.Module):\n",
    "    \"\"\"\n",
    "    predicting origin token from masked input sequence\n",
    "    n-class classification problem, n-class = vocab_size\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, hidden, vocab_size):\n",
    "        \"\"\"\n",
    "        :param hidden: output size of BERT model\n",
    "        :param vocab_size: total vocab size\n",
    "        \"\"\"\n",
    "        super().__init__()\n",
    "        self.linear = torch.nn.Linear(hidden, vocab_size)\n",
    "        self.softmax = torch.nn.LogSoftmax(dim=-1)\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.softmax(self.linear(x))\n",
    "\n",
    "class BERTLM(torch.nn.Module):\n",
    "    \"\"\"\n",
    "    BERT Language Model\n",
    "    Next Sentence Prediction Model + Masked Language Model\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, bert: BERT, vocab_size):\n",
    "        \"\"\"\n",
    "        :param bert: BERT model which should be trained\n",
    "        :param vocab_size: total vocab size for masked_lm\n",
    "        \"\"\"\n",
    "\n",
    "        super().__init__()\n",
    "        self.bert = bert\n",
    "        self.next_sentence = NextSentencePrediction(self.bert.d_model)\n",
    "        self.mask_lm = MaskedLanguageModel(self.bert.d_model, vocab_size)\n",
    "\n",
    "    def forward(self, x, segment_label):\n",
    "        x = self.bert(x, segment_label)\n",
    "        return self.next_sentence(x), self.mask_lm(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "b8f7c1f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ScheduledOptim():\n",
    "    '''A simple wrapper class for learning rate scheduling'''\n",
    "\n",
    "    def __init__(self, optimizer, d_model, n_warmup_steps):\n",
    "        self._optimizer = optimizer\n",
    "        self.n_warmup_steps = n_warmup_steps\n",
    "        self.n_current_steps = 0\n",
    "        self.init_lr = np.power(d_model, -0.5)\n",
    "\n",
    "    def step_and_update_lr(self):\n",
    "        \"Step with the inner optimizer\"\n",
    "        self._update_learning_rate()\n",
    "        self._optimizer.step()\n",
    "\n",
    "    def zero_grad(self):\n",
    "        \"Zero out the gradients by the inner optimizer\"\n",
    "        self._optimizer.zero_grad()\n",
    "\n",
    "    def _get_lr_scale(self):\n",
    "        return np.min([\n",
    "            np.power(self.n_current_steps, -0.5),\n",
    "            np.power(self.n_warmup_steps, -1.5) * self.n_current_steps])\n",
    "\n",
    "    def _update_learning_rate(self):\n",
    "        ''' Learning rate scheduling per step '''\n",
    "\n",
    "        self.n_current_steps += 1\n",
    "        lr = self.init_lr * self._get_lr_scale()\n",
    "\n",
    "        for param_group in self._optimizer.param_groups:\n",
    "            param_group['lr'] = lr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "9dd8e50e",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BERTTrainer:\n",
    "    def __init__(\n",
    "        self, \n",
    "        model, \n",
    "        train_dataloader, \n",
    "        test_dataloader=None, \n",
    "        lr= 1e-4,\n",
    "        weight_decay=0.01,\n",
    "        betas=(0.9, 0.999),\n",
    "        warmup_steps=10000,\n",
    "        log_freq=10,\n",
    "        device='cuda'\n",
    "        ):\n",
    "\n",
    "        self.device = device\n",
    "        self.model = model\n",
    "        self.train_data = train_dataloader\n",
    "        self.test_data = test_dataloader\n",
    "\n",
    "        # Setting the Adam optimizer with hyper-param\n",
    "        self.optim = Adam(self.model.parameters(), lr=lr, betas=betas, weight_decay=weight_decay)\n",
    "        self.optim_schedule = ScheduledOptim(\n",
    "            self.optim, self.model.bert.d_model, n_warmup_steps=warmup_steps\n",
    "            )\n",
    "\n",
    "        # Using Negative Log Likelihood Loss function for predicting the masked_token\n",
    "        self.criterion = torch.nn.NLLLoss(ignore_index=0)\n",
    "        self.log_freq = log_freq\n",
    "        print(\"Total Parameters:\", sum([p.nelement() for p in self.model.parameters()]))\n",
    "    \n",
    "    def train(self, epoch):\n",
    "        self.iteration(epoch, self.train_data)\n",
    "\n",
    "    def test(self, epoch):\n",
    "        self.iteration(epoch, self.test_data, train=False)\n",
    "\n",
    "    def iteration(self, epoch, data_loader, train=True):\n",
    "        \n",
    "        avg_loss = 0.0\n",
    "        total_correct = 0\n",
    "        total_element = 0\n",
    "        \n",
    "        mode = \"train\" if train else \"test\"\n",
    "\n",
    "        # progress bar\n",
    "        data_iter = tqdm.tqdm(\n",
    "            enumerate(data_loader),\n",
    "            desc=\"EP_%s:%d\" % (mode, epoch),\n",
    "            total=len(data_loader),\n",
    "            bar_format=\"{l_bar}{r_bar}\"\n",
    "        )\n",
    "\n",
    "        for i, data in data_iter:\n",
    "\n",
    "            # 0. batch_data will be sent into the device(GPU or cpu)\n",
    "            data = {key: value.to(self.device) for key, value in data.items()}\n",
    "\n",
    "            # 1. forward the next_sentence_prediction and masked_lm model\n",
    "            next_sent_output, mask_lm_output = self.model.forward(data[\"bert_input\"], data[\"segment_label\"])\n",
    "\n",
    "            # 2-1. NLL(negative log likelihood) loss of is_next classification result\n",
    "            next_loss = self.criterion(next_sent_output, data[\"is_next\"])\n",
    "\n",
    "            # 2-2. NLLLoss of predicting masked token word\n",
    "            # transpose to (m, vocab_size, seq_len) vs (m, seq_len)\n",
    "            # criterion(mask_lm_output.view(-1, mask_lm_output.size(-1)), data[\"bert_label\"].view(-1))\n",
    "            mask_loss = self.criterion(mask_lm_output.transpose(1, 2), data[\"bert_label\"])\n",
    "\n",
    "            # 2-3. Adding next_loss and mask_loss : 3.4 Pre-training Procedure\n",
    "            loss = next_loss + mask_loss\n",
    "\n",
    "            # 3. backward and optimization only in train\n",
    "            if train:\n",
    "                self.optim_schedule.zero_grad()\n",
    "                loss.backward()\n",
    "                self.optim_schedule.step_and_update_lr()\n",
    "\n",
    "            # next sentence prediction accuracy\n",
    "            correct = next_sent_output.argmax(dim=-1).eq(data[\"is_next\"]).sum().item()\n",
    "            avg_loss += loss.item()\n",
    "            total_correct += correct\n",
    "            total_element += data[\"is_next\"].nelement()\n",
    "\n",
    "            post_fix = {\n",
    "                \"epoch\": epoch,\n",
    "                \"iter\": i,\n",
    "                \"avg_loss\": avg_loss / (i + 1),\n",
    "                \"avg_acc\": total_correct / total_element * 100,\n",
    "                \"loss\": loss.item()\n",
    "            }\n",
    "\n",
    "            if i % self.log_freq == 0:\n",
    "                data_iter.write(str(post_fix))\n",
    "        print(\n",
    "            f\"EP{epoch}, {mode}: \\\n",
    "            avg_loss={avg_loss / len(data_iter)}, \\\n",
    "            total_acc={total_correct * 100.0 / total_element}\"\n",
    "        ) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "52de2072",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total Parameters: 46699434\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "EP_train:0:   0%|| 0/6926 [01:16<?, ?it/s]\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[28], line 20\u001b[0m\n\u001b[0;32m     17\u001b[0m epochs \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m20\u001b[39m\n\u001b[0;32m     19\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m epoch \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(epochs):\n\u001b[1;32m---> 20\u001b[0m     \u001b[43mbert_trainer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtrain\u001b[49m\u001b[43m(\u001b[49m\u001b[43mepoch\u001b[49m\u001b[43m)\u001b[49m\n",
      "Cell \u001b[1;32mIn[25], line 32\u001b[0m, in \u001b[0;36mBERTTrainer.train\u001b[1;34m(self, epoch)\u001b[0m\n\u001b[0;32m     31\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mtrain\u001b[39m(\u001b[38;5;28mself\u001b[39m, epoch):\n\u001b[1;32m---> 32\u001b[0m     \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43miteration\u001b[49m\u001b[43m(\u001b[49m\u001b[43mepoch\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtrain_data\u001b[49m\u001b[43m)\u001b[49m\n",
      "Cell \u001b[1;32mIn[25], line 75\u001b[0m, in \u001b[0;36mBERTTrainer.iteration\u001b[1;34m(self, epoch, data_loader, train)\u001b[0m\n\u001b[0;32m     73\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m train:\n\u001b[0;32m     74\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39moptim_schedule\u001b[38;5;241m.\u001b[39mzero_grad()\n\u001b[1;32m---> 75\u001b[0m     \u001b[43mloss\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mbackward\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m     76\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39moptim_schedule\u001b[38;5;241m.\u001b[39mstep_and_update_lr()\n\u001b[0;32m     78\u001b[0m \u001b[38;5;66;03m# next sentence prediction accuracy\u001b[39;00m\n",
      "File \u001b[1;32m~\\AppData\\Local\\anaconda3\\lib\\site-packages\\torch\\_tensor.py:396\u001b[0m, in \u001b[0;36mTensor.backward\u001b[1;34m(self, gradient, retain_graph, create_graph, inputs)\u001b[0m\n\u001b[0;32m    387\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m has_torch_function_unary(\u001b[38;5;28mself\u001b[39m):\n\u001b[0;32m    388\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m handle_torch_function(\n\u001b[0;32m    389\u001b[0m         Tensor\u001b[38;5;241m.\u001b[39mbackward,\n\u001b[0;32m    390\u001b[0m         (\u001b[38;5;28mself\u001b[39m,),\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    394\u001b[0m         create_graph\u001b[38;5;241m=\u001b[39mcreate_graph,\n\u001b[0;32m    395\u001b[0m         inputs\u001b[38;5;241m=\u001b[39minputs)\n\u001b[1;32m--> 396\u001b[0m \u001b[43mtorch\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mautograd\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mbackward\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mgradient\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mretain_graph\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcreate_graph\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minputs\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minputs\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[1;32m~\\AppData\\Local\\anaconda3\\lib\\site-packages\\torch\\autograd\\__init__.py:173\u001b[0m, in \u001b[0;36mbackward\u001b[1;34m(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)\u001b[0m\n\u001b[0;32m    168\u001b[0m     retain_graph \u001b[38;5;241m=\u001b[39m create_graph\n\u001b[0;32m    170\u001b[0m \u001b[38;5;66;03m# The reason we repeat same the comment below is that\u001b[39;00m\n\u001b[0;32m    171\u001b[0m \u001b[38;5;66;03m# some Python versions print out the first line of a multi-line function\u001b[39;00m\n\u001b[0;32m    172\u001b[0m \u001b[38;5;66;03m# calls in the traceback and some print out the last line\u001b[39;00m\n\u001b[1;32m--> 173\u001b[0m \u001b[43mVariable\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_execution_engine\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun_backward\u001b[49m\u001b[43m(\u001b[49m\u001b[43m  \u001b[49m\u001b[38;5;66;43;03m# Calls into the C++ engine to run the backward pass\u001b[39;49;00m\n\u001b[0;32m    174\u001b[0m \u001b[43m    \u001b[49m\u001b[43mtensors\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mgrad_tensors_\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mretain_graph\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcreate_graph\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m    175\u001b[0m \u001b[43m    \u001b[49m\u001b[43mallow_unreachable\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43maccumulate_grad\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mTrue\u001b[39;49;00m\u001b[43m)\u001b[49m\n",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "train_data = BERTDataset(\n",
    "   pairs, seq_len=MAX_LEN, tokenizer=tokenizer)\n",
    "\n",
    "train_loader = DataLoader(\n",
    "   train_data, batch_size=32, shuffle=True, pin_memory=True)\n",
    "\n",
    "bert_model = BERT(\n",
    "  vocab_size=len(tokenizer.vocab),\n",
    "  d_model=768,\n",
    "  n_layers=2,\n",
    "  heads=12,\n",
    "  dropout=0.1\n",
    ")\n",
    "\n",
    "bert_lm = BERTLM(bert_model, len(tokenizer.vocab))\n",
    "bert_trainer = BERTTrainer(bert_lm, train_loader, device='cpu')\n",
    "epochs = 20\n",
    "\n",
    "for epoch in range(epochs):\n",
    "    bert_trainer.train(epoch)"
   ]
  }
 ],
 "metadata": {
  "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.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}