-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainCode.py
3157 lines (2512 loc) · 121 KB
/
MainCode.py
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
# -*- coding: utf-8 -*-
"""MJAhmadi_NNDL_HW5_Q1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/15v_GCdX-YM8mt4yeG8u0gHrqIRW_SKJq
# 1.2. Load and Processs Data
"""
# Installing required packages
!pip install transformers
!pip install -q sentencepiece
!pip install sentencepiece
# Importing necessary libraries
import re
import json
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from tqdm.auto import tqdm
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from transformers import BertModel, BertConfig, BertTokenizer, AdamW
# Clone the PQuAD dataset from GitHub
!git clone https://github.com/AUT-NLP/PQuAD.git
# Load the PQuad dataset
train_file_path = '/content/PQuAD/Dataset/Train.json'
test_file_path = '/content/PQuAD/Dataset/Test.json'
val_file_path = '/content/PQuAD/Dataset/Validation.json'
import json
import matplotlib.pyplot as plt
import numpy as np
# Path to the dataset files
train_file_path = '/content/PQuAD/Dataset/Train.json'
test_file_path = '/content/PQuAD/Dataset/Test.json'
val_file_path = '/content/PQuAD/Dataset/Validation.json'
def load_dataset(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
dataset = json.load(file)
return dataset
def plot_answer_distribution(dataset, dataset_name, file_name):
num_answers = []
for data in dataset['data']:
for paragraph in data['paragraphs']:
for qa in paragraph['qas']:
num_answers.append(len(qa['answers']))
bins = np.arange(max(num_answers) + 2)
hist, edges = np.histogram(num_answers, bins=bins)
fig, ax = plt.subplots()
ax.bar(edges[:-1], hist, width=0.8, align='center', color='steelblue')
# Add count labels in the middle and above each bar
for i, count in enumerate(hist):
if count > 0:
ax.text(edges[i], count + 1, str(int(count)), ha='center', va='bottom')
plt.xlabel('Number of Answers')
plt.ylabel('Number of Questions')
plt.title(f'Distribution of Number of Answers for Questions ({dataset_name})')
plt.xticks(np.arange(max(num_answers) + 1), [f'{i}-answer' for i in range(max(num_answers) + 1)], rotation=90)
plt.legend([dataset_name])
plt.savefig(file_name, format='pdf', bbox_inches='tight')
plt.show()
def print_dataset_statistics(dataset, dataset_name):
total_questions = 0
total_unanswerable_questions = 0
total_paragraph_tokens = 0
total_question_tokens = 0
total_answer_tokens = 0
for data in dataset['data']:
total_questions += len(data['paragraphs'])
for paragraph in data['paragraphs']:
for qa in paragraph['qas']:
if qa['is_impossible']:
total_unanswerable_questions += 1
total_paragraph_tokens += len(paragraph['context'].split())
total_question_tokens += len(qa['question'].split())
total_answer_tokens += sum([len(answer['text'].split()) for answer in qa['answers']])
mean_paragraph_tokens = total_paragraph_tokens / total_questions
mean_question_tokens = total_question_tokens / total_questions
mean_answer_tokens = total_answer_tokens / total_questions
print(f"Dataset Statistics ({dataset_name}):")
print(f"Total Questions: {total_questions}")
print(f"Total Unanswerable Questions: {total_unanswerable_questions}")
print(f"Mean # of Paragraph Tokens: {mean_paragraph_tokens:.2f}")
print(f"Mean # of Question Tokens: {mean_question_tokens:.2f}")
print(f"Mean # of Answer Tokens: {mean_answer_tokens:.2f}")
print()
# Load the train dataset
train_dataset = load_dataset(train_file_path)
# Plot the distribution of the number of answers for train questions and save as PDF
plot_answer_distribution(train_dataset, 'Train', 'traindistribution.pdf')
# Print the statistical information of the train dataset
print_dataset_statistics(train_dataset, 'Train')
# Load the test dataset
test_dataset = load_dataset(test_file_path)
# Plot the distribution of the number of answers for test questions and save as PDF
plot_answer_distribution(test_dataset, 'Test', 'testdistribution.pdf')
# Print the statistical information of the test dataset
print_dataset_statistics(test_dataset, 'Test')
# Load the validation dataset
val_dataset = load_dataset(val_file_path)
# Plot the distribution of the number of answers for validation questions and save as PDF
plot_answer_distribution(val_dataset, 'Validation', 'validationdistribution.pdf')
# Print the statistical information of the validation dataset
print_dataset_statistics(val_dataset, 'Validation')
# Set the minimum and maximum length for data
min_len, max_len = 128, 256
# Set the value of N
N = 3
def json_to_dataframe(file):
# Open the JSON file
f = open(file, "r")
data = json.loads(f.read()) # Load the JSON file
# Create empty lists to store values
ids = []
titles = []
contexts = []
questions = []
ans_starts = []
texts = []
# Iterate over the JSON data
for i in range(len(data['data'])):
title = data['data'][i]['title'] # Extract the 'title' value
# Iterate over the paragraphs in the JSON data
for p in range(len(data['data'][i]['paragraphs'])):
context = data['data'][i]['paragraphs'][p]['context'] # Extract the 'context' value
# Iterate over the questions in the JSON data
for q in range(len(data['data'][i]['paragraphs'][p]['qas'])):
question = data['data'][i]['paragraphs'][p]['qas'][q]['question'] # Extract the 'question' value
qid = data['data'][i]['paragraphs'][p]['qas'][q]['id'] # Extract the 'id' value
# Check if the question has answers
if len(data['data'][i]['paragraphs'][p]['qas'][q]['answers']) == 0:
ans_start = -1
text = ''
# Append the values to the lists
titles.append(title)
contexts.append(context)
questions.append(question)
ids.append(qid)
ans_starts.append(ans_start)
texts.append(text)
else:
# Iterate over the answers in the JSON data
for a in range(len(data['data'][i]['paragraphs'][p]['qas'][q]['answers'])):
ans_start = data['data'][i]['paragraphs'][p]['qas'][q]['answers'][a]['answer_start'] # Extract the 'answer_start' value
text = data['data'][i]['paragraphs'][p]['qas'][q]['answers'][a]['text'] # Extract the 'text' value
# Append the values to the lists
titles.append(title)
contexts.append(context)
questions.append(question)
ids.append(qid)
ans_starts.append(ans_start)
texts.append(text)
# Create an empty DataFrame
new_df = pd.DataFrame(columns=['Id', 'title', 'context', 'question', 'ans_start', 'text'])
# Set the values of the DataFrame columns
new_df['Id'] = ids
new_df['title'] = titles
new_df['context'] = contexts
new_df['question'] = questions
new_df['ans_start'] = ans_starts
new_df['text'] = texts
# Drop duplicate rows from the DataFrame
final_df = new_df.drop_duplicates(keep='first')
return final_df
# Convert the train JSON file to a DataFrame
df_train = json_to_dataframe(train_file_path)
# Get the number of rows in the train DataFrame
train_rows = df_train.shape[0]
print('Size of the train DataFrame before concatenation is {}'.format(train_rows))
# Convert the test JSON file to a DataFrame
df_test = json_to_dataframe(test_file_path)
# Convert the validation JSON file to a DataFrame
df_validation = json_to_dataframe(val_file_path)
# Concatenate the train and validation DataFrames
# frames = [df_train, df_validation]
# df_train = pd.concat(frames)
# Get the number of rows in the concatenated train DataFrame
train_rows = df_train.shape[0]
print('Size of the train DataFrame after concatenation is {}'.format(train_rows))
# Display the first few rows of the train DataFrame
df_train.head()
def add_end_index(answers_text, answers_start, contexts):
new_answers = []
# Loop through each answer-context pair
for answer_text, answer_start, context in tqdm(zip(answers_text, answers_start, contexts)):
start_shift = 0
# Remove start half-spaces from the answer text
text = re.sub("^\u200c", "", answer_text)
# Check if the length of the text is one less than the length of the original answer
if len(list(text)) == (len(list(answer_text)) - 1):
start_shift += 1
# Remove end half-spaces from the text
text = re.sub("\u200c$", "", text)
# Remove leading and trailing whitespaces from the text
text = re.sub("^\s+", '', text)
text = re.sub("\s+$", '', text)
# Adjust the answer_start index by the start_shift value
answer_start += start_shift
# Calculate the end index of the answer
end_idx = answer_start + len(text)
# Check if the answer is correct
if context[answer_start:end_idx] == text:
# If the answer is correct, set the answer_end index to end_idx
answer_end = end_idx
else:
# If the answer is off by 1-2 tokens, adjust the answer_start and answer_end indices
for n in [1, 2]:
if context[answer_start - n:end_idx - n] == text:
answer_start = answer_start - n
answer_end = end_idx - n
# Append the modified answer to the new_answers list
new_answers.append({'text': text, 'answer_start': answer_start, 'answer_end': answer_end})
return new_answers
def prepare_data(dataset):
# Extract necessary columns from the dataset
answer_start = dataset['ans_start'].tolist()
text = dataset['text'].tolist()
questions = dataset['question'].tolist()
contexts = dataset['context'].tolist()
# Call the add_end_index function to process answers
answers = add_end_index(text, answer_start, contexts)
# Return a dictionary with the prepared data
return {
'question': questions,
'context': contexts,
'answers': answers
}
# Prepare the training dataset
train_dataset = prepare_data(df_train)
# Prepare the validation dataset
val_dataset = prepare_data(df_validation)
# Prepare the test dataset
test_dataset = prepare_data(df_test)
# Access the second answer in the training dataset
answer = train_dataset['answers'][10]
train_dataset['answers'][10]
"""# 1.3. ParsBERT (Data Processing and Training)"""
# Specify the model name or path
model_name_or_path = 'HooshvareLab/bert-base-parsbert-uncased'
# Create a tokenizer instance from the specified model
tokenizer = BertTokenizer.from_pretrained(model_name_or_path)
# Create empty lists to store the new tokenized data
new_context, new_question, new_answer = [[] for _ in range(3)]
# Get the total size of the data
len_data = len(train_dataset['answers'])
print('Total size of data is {}'.format(len_data))
# Iterate through each data instance
for i in range(len_data):
# Tokenize the answer, context, and question
tokenized_answer = tokenizer.tokenize(train_dataset['answers'][i]['text'])
tokenized_context = tokenizer.tokenize(train_dataset['context'][i])
tokenized_question = tokenizer.tokenize(train_dataset['question'][i])
# Calculate the total number of tokens
num = len(tokenized_context) + len(tokenized_question)
# Check if the total number of tokens is within the desired range
if num > (min_len - 3) and num <= (max_len - 3): # 3 for three special tokens: 1 for [CLS] and 2 for [SEP]
if '[UNK]' not in tokenized_answer:
# Append the tokenized data to the new lists
new_context.append(train_dataset['context'][i])
new_question.append(train_dataset['question'][i])
new_answer.append({
'text': train_dataset['answers'][i]['text'],
'answer_start': train_dataset['answers'][i]['answer_start'],
'answer_end': train_dataset['answers'][i]['answer_end']
})
# Print the number of data without [UNK] and containing 128-256 tokens
print('Number of data without [UNK] and containing 128-256 tokens is {}'.format(len(new_context)))
# Print the percentage of data without [UNK] and containing 128-256 tokens
print('Percentage of data without [UNK] and containing 128-256 tokens is {}'.format(100 * len(new_context) / len_data))
# Create a new training dataset with the filtered data
new_train_dataset = {
'question': new_question,
'context': new_context,
'answers': new_answer
}
# Create empty lists to store the new tokenized data
new_context, new_question, new_answer = [[] for _ in range(3)]
# Get the total size of the data
len_data = len(val_dataset['answers'])
print('Total size of data is {}'.format(len_data))
# Iterate through each data instance
for i in range(len_data):
# Tokenize the answer, context, and question
tokenized_answer = tokenizer.tokenize(val_dataset['answers'][i]['text'])
tokenized_context = tokenizer.tokenize(val_dataset['context'][i])
tokenized_question = tokenizer.tokenize(val_dataset['question'][i])
# Calculate the total number of tokens
num = len(tokenized_context) + len(tokenized_question)
# Check if the total number of tokens is within the desired range
if num > (min_len - 3) and num <= (max_len - 3): # 3 for three special tokens, [CLS] and 2 [SEP]
if '[UNK]' not in tokenized_answer:
# Append the tokenized data to the new lists
new_context.append(val_dataset['context'][i])
new_question.append(val_dataset['question'][i])
new_answer.append({
'text': val_dataset['answers'][i]['text'],
'answer_start': val_dataset['answers'][i]['answer_start'],
'answer_end': val_dataset['answers'][i]['answer_end']
})
# Print the number of data without [UNK] and containing 128-256 tokens
print('Number of data without [UNK] and containing 128-256 tokens is {}'.format(len(new_context)))
# Print the percentage of data without [UNK] and containing 128-256 tokens
print('Percentage of data without [UNK] and containing 128-256 tokens is {}'.format(100 * len(new_context) / len_data))
# Create a new validation dataset with the filtered data
new_val_dataset = {
'question': new_question,
'context': new_context,
'answers': new_answer
}
# Create empty lists to store the new tokenized data
new_context, new_question, new_answer = [[] for _ in range(3)]
# Get the total size of the data
len_data = len(test_dataset['answers'])
print('Total size of data is {}'.format(len_data))
# Iterate through each data instance
for i in range(len_data):
# Tokenize the answer, context, and question
tokenized_answer = tokenizer.tokenize(test_dataset['answers'][i]['text'])
tokenized_context = tokenizer.tokenize(test_dataset['context'][i])
tokenized_question = tokenizer.tokenize(test_dataset['question'][i])
# Calculate the total number of tokens
num = len(tokenized_context) + len(tokenized_question)
# Check if the total number of tokens is within the desired range
if num > (min_len - 3) and num <= (max_len - 3): # 3 for three special tokens, [CLS] and 2 [SEP]
if '[UNK]' not in tokenized_answer:
# Append the tokenized data to the new lists
new_context.append(test_dataset['context'][i])
new_question.append(test_dataset['question'][i])
new_answer.append({
'text': test_dataset['answers'][i]['text'],
'answer_start': test_dataset['answers'][i]['answer_start'],
'answer_end': test_dataset['answers'][i]['answer_end']
})
# Print the number of data without [UNK] and containing 128-256 tokens
print('Number of data without [UNK] and containing 128-256 tokens is {}'.format(len(new_context)))
# Print the percentage of data without [UNK] and containing 128-256 tokens
print('Percentage of data without [UNK] and containing 128-256 tokens is {}'.format(100 * len(new_context) / len_data))
# Create a new validation dataset with the filtered data
new_test_dataset = {
'question': new_question,
'context': new_context,
'answers': new_answer
}
# Create a DataFrame for the test dataset
test_df = pd.DataFrame.from_dict(new_test_dataset)
# Create a DataFrame for the validation dataset
validation_df = pd.DataFrame.from_dict(new_val_dataset)
# Create a DataFrame for the training dataset
train_df = pd.DataFrame.from_dict(new_train_dataset)
# Print the length of the training dataset
print("Length of the training dataset: {}".format(len(train_df)))
# Display the first few rows of the training dataset
print("Training dataset:")
train_df.head()
# Print the length of the validation dataset
print("Length of the validation dataset: {}".format(len(validation_df)))
# Display the first few rows of the validation dataset
print("Validation dataset:")
validation_df.head()
# Print the length of the test dataset
print("Length of the test dataset: {}".format(len(test_df)))
# Display the first few rows of the test dataset
print("Test dataset:")
test_df.head()
def prepare_data_2(dataset):
# Extract the questions, contexts, and answers from the dataset
questions = dataset['question'].tolist()
contexts = dataset['context'].tolist()
answers = dataset['answers'].tolist()
# Return a dictionary containing the prepared data
return {
'question': questions,
'context': contexts,
'answers': answers
}
# Prepare the training dataset
train_dataset = prepare_data_2(train_df)
# Prepare the validation dataset
val_dataset = prepare_data_2(validation_df)
# Prepare the test dataset
test_dataset = prepare_data_2(test_df)
# Tokenize the training data using the tokenizer
train_data = tokenizer(train_dataset['context'], train_dataset['question'],
truncation=False, padding='max_length',
max_length=max_len, return_tensors='pt')
# Tokenize the validation data using the tokenizer
validation_data = tokenizer(val_dataset['context'], val_dataset['question'],
truncation=False, padding='max_length',
max_length=max_len, return_tensors='pt')
# Tokenize the test data using the tokenizer
test_data = tokenizer(test_dataset['context'], test_dataset['question'],
truncation=False, padding='max_length',
max_length=max_len, return_tensors='pt')
# Function to convert character index to token index
def char_idx_to_token_idx(tokenizer, char_idx, sentence):
# Create a list of binary values indicating whether each character is a space or a half-space
char = [0 if sentence[i] == ' ' or sentence[i] == '' else 1 for i in range(len(sentence))]
tokens = tokenizer.tokenize(sentence)
index = char_idx
# Adjust the index to consider half-spaces
for i in range(index):
if char[i] != 1:
index -= 1
counter = 0
flag_continue = True
token_index = 0
# Find the token index corresponding to the character index
for i in range(len(tokens)):
if tokens[i].startswith('##'):
tokens[i] = tokens[i][2:]
for j in range(len(tokens[i])):
counter += 1
if counter == index:
flag_continue = False
token_index = i
break
if not flag_continue:
break
return token_index
# Function to add token positions for answer start and end
def add_token_positions(tokenizer, encodings, answers, contexts):
target_start_list = []
target_end_list = []
for i in tqdm(range(len(answers))):
target_start = [0] * max_len
target_end = [0] * max_len
start_idx = answers[i]['answer_start']
end_idx = answers[i]['answer_end']
if start_idx <= len(contexts[i]) and end_idx <= len(contexts[i]):
# Answerable question
if start_idx != -1 and end_idx != -1:
start_token_idx = char_idx_to_token_idx(tokenizer, start_idx, contexts[i]) + 1
end_token_idx = char_idx_to_token_idx(tokenizer, end_idx, contexts[i]) + 1
target_start[start_token_idx] = 1
target_end[end_token_idx] = 1
target_start_list.append(target_start)
target_end_list.append(target_end)
# Unanswerable question
else:
target_start[0] = 1
target_end[0] = 1
target_start_list.append(target_start)
target_end_list.append(target_end)
else:
continue
# Update the encodings with the target start and end lists
encodings.update({'targets_start': target_start_list, 'targets_end': target_end_list})
# Add token positions to the train_data encodings
add_token_positions(tokenizer, train_data, train_dataset['answers'], train_dataset['context'])
# Add token positions to the validation_data encodings
add_token_positions(tokenizer, validation_data, val_dataset['answers'], val_dataset['context'])
# Add token positions to the test_data encodings
add_token_positions(tokenizer, test_data, test_dataset['answers'], test_dataset['context'])
# Custom Dataset class
class CustomDataset(torch.utils.data.Dataset):
def __init__(self, data):
"""
Initialize the CustomDataset.
Args:
data (dict): The data dictionary containing input tensors.
"""
self.data = data
def __getitem__(self, idx):
"""
Get an item from the dataset.
Args:
idx (int): The index of the item.
Returns:
dict: A dictionary containing input tensors.
"""
return {key: torch.tensor(val[idx]) for key, val in self.data.items()}
def __len__(self):
"""
Get the length of the dataset.
Returns:
int: The length of the dataset.
"""
return len(self.data['input_ids'])
# Create a custom dataset for training
train_datas = CustomDataset(train_data)
print("Length of training dataset: {}".format(len(train_datas)))
# Create a data loader for training
train_loader = torch.utils.data.DataLoader(train_datas, batch_size=32, shuffle=True)
# Create a custom dataset for validation
validation_datas = CustomDataset(validation_data)
print("Length of validation dataset: {}".format(len(validation_datas)))
# Create a data loader for validation
validation_loader = torch.utils.data.DataLoader(validation_datas, batch_size=32, shuffle=False)
# Create a custom dataset for test
test_datas = CustomDataset(test_data)
print("Length of test dataset: {}".format(len(test_datas)))
# Create a data loader for test
test_loader = torch.utils.data.DataLoader(test_datas, batch_size=32, shuffle=False)
MODEL_NAME_OR_PATH = 'HooshvareLab/bert-base-parsbert-uncased'
class QAModel(nn.Module):
def __init__(self):
super(QAModel, self).__init__()
# Initialize the BERT model
self.bert = BertModel.from_pretrained(MODEL_NAME_OR_PATH, return_dict=False)
# Add a linear layer for classification
self.classifier = nn.Linear(768, 2)
def forward(self, input_ids, attention_mask, token_type_ids):
# Pass the input through the BERT model
sequence_output, pooled_output = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
# Apply linear layer to the BERT output
# Shape: (batch_size, num_tokens, 768)
logits = self.classifier(sequence_output)
# Shape: (batch_size, num_tokens, 2)
# Split the logits into start and end logits
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1)
end_logits = end_logits.squeeze(-1)
# Shape: (batch_size, num_tokens), (batch_size, num_tokens)
return start_logits, end_logits
def loss_fn(start_logits, end_logits, start_targets, end_targets):
"""
Compute the loss function given the predicted start and end logits and the target start and end positions.
Args:
start_logits (torch.Tensor): Predicted start logits of shape (batch_size, num_tokens).
end_logits (torch.Tensor): Predicted end logits of shape (batch_size, num_tokens).
start_targets (torch.Tensor): Target start positions of shape (batch_size, num_tokens).
end_targets (torch.Tensor): Target end positions of shape (batch_size, num_tokens).
Returns:
torch.Tensor: Loss value.
"""
# Compute the binary cross-entropy loss for start and end logits
start_loss = nn.BCEWithLogitsLoss()(start_logits, start_targets.float())
end_loss = nn.BCEWithLogitsLoss()(end_logits, end_targets.float())
# Return the sum of the two losses
return start_loss + end_loss
def evaluate_f1(start_pred, start_target, end_pred, end_target):
"""
Compute the F1 score given the predicted start and end positions and the target start and end positions.
Args:
start_pred (int): Predicted start position.
start_target (int): Target start position.
end_pred (int): Predicted end position.
end_target (int): Target end position.
Returns:
float: F1 score.
"""
# Generate arrays of tokens for prediction and target spans
pred = np.arange(start_pred, end_pred + 1)
tar = np.arange(start_target, end_target + 1)
# Compute the number of tokens shared between prediction and target
tp_list = list(set.intersection(*map(set, [pred, tar])))
# Compute the number of tokens in prediction not in target
fp_list = list(set(pred).symmetric_difference(set(tp_list)))
# Compute the number of tokens in target not in prediction
fn_list = list(set(tar).symmetric_difference(set(tp_list)))
tp, fp, fn = len(tp_list), len(fp_list), len(fn_list)
# Compute precision, recall, and F1 score
if (tp + fp) != 0:
precision = tp / (tp + fp)
else:
precision = 0
if (tp + fn) != 0:
recall = tp / (tp + fn)
else:
recall = 0
if (precision + recall) != 0:
f1 = (2 * precision * recall) / (precision + recall)
else:
f1 = 0
return f1
def generate_indexes(start_logits, end_logits, N, max_index_list):
"""
Generate the start and end indexes for the predicted spans.
Args:
start_logits (numpy.ndarray): Predicted start logits of shape (batch_size, num_tokens).
end_logits (numpy.ndarray): Predicted end logits of shape (batch_size, num_tokens).
N (int): Number of top start and end indexes to consider.
max_index_list (list): List of maximum indexes for each example.
Returns:
tuple: Final start and end indexes for the predicted spans.
"""
output_start = start_logits
output_end = end_logits
dimension = output_start.shape[1]
list_start, list_end = [], []
for n in range(output_start.shape[0]):
start_indexes = np.arange(output_start.shape[1])
start_probs = output_start[n]
list_start.append(dict(zip(start_indexes, start_probs)))
end_indexes = np.arange(output_start.shape[1])
end_probs = output_end[n]
list_end.append(dict(zip(end_indexes, end_probs)))
sorted_start_list, sorted_end_list = [], []
for j in range(len(list_start)):
sort_start_probs = sorted(list_start[j].items(), key=lambda x: x[1], reverse=True)
sort_end_probs = sorted(list_end[j].items(), key=lambda x: x[1], reverse=True)
sorted_start_list.append(sort_start_probs)
sorted_end_list.append(sort_end_probs)
final_start_idx, final_end_idx = [], []
for c in range(len(list_start)):
start_idx, end_idx, prob = 0, 0, 0
for a in range(N):
for b in range(N):
if (sorted_start_list[c][a][1] + sorted_end_list[c][b][1]) > prob:
if (sorted_start_list[c][a][0] <= sorted_end_list[c][b][0]) and (
sorted_end_list[c][b][0] < max_index_list[c]):
prob = sorted_start_list[c][a][1] + sorted_end_list[c][b][1]
start_idx = sorted_start_list[c][a][0]
end_idx = sorted_end_list[c][b][0]
final_start_idx.append(start_idx)
final_end_idx.append(end_idx)
return final_start_idx, final_end_idx
def evaluate_model(start_logits, end_logits, N, max_index_list, target_start, target_end):
"""
Evaluate the model by computing the F1 score.
Args:
start_logits (numpy.ndarray): Predicted start logits of shape (batch_size, num_tokens).
end_logits (numpy.ndarray): Predicted end logits of shape (batch_size, num_tokens).
N (int): Number of top start and end indexes to consider.
max_index_list (list): List of maximum indexes for each example.
target_start (list): List of target start positions.
target_end (list): List of target end positions.
Returns:
float: Mean F1 score.
"""
final_start_idx, final_end_idx = generate_indexes(start_logits, end_logits, N, max_index_list)
f1 = []
for i in range(len(final_start_idx)):
f1.append(evaluate_f1(final_start_idx[i], target_start[i], final_end_idx[i], target_end[i]))
return np.mean(f1)
import warnings
warnings.filterwarnings('ignore')
# Clear GPU cache
torch.cuda.empty_cache()
# Check if CUDA is available and set the device accordingly
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Device:", device)
# Create an instance of the QAModel
qa_model = QAModel()
qa_model.to(device) # Move the model to the appropriate device
qa_model.train() # Set the model in training mode
# Create an instance of the AdamW optimizer with a learning rate of 5e-5
optimizer = AdamW(qa_model.parameters(), lr=5e-5)
MODEL_NAME_OR_PATH = 'HooshvareLab/bert-base-parsbert-uncased'
from transformers import PreTrainedModel
class QAModel2(PreTrainedModel):
"""
QA Model based on BERT for sequence classification.
"""
def __init__(self, config):
super(QAModel2, self).__init__(config)
self.bert = BertModel.from_pretrained(MODEL_NAME_OR_PATH, return_dict=False)
# self.dropout = nn.Dropout(p=dropout_rate)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, input_ids, attention_mask, token_type_ids):
"""
Forward pass of the QA model.
Args:
input_ids (tensor): Input tensor of shape (batch_size, sequence_length).
attention_mask (tensor): Attention mask tensor of shape (batch_size, sequence_length).
token_type_ids (tensor): Token type IDs tensor of shape (batch_size, sequence_length).
Returns:
start_logits (tensor): Start logits tensor of shape (batch_size, sequence_length).
end_logits (tensor): End logits tensor of shape (batch_size, sequence_length).
"""
sequence_output, pooled_output = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids
)
# Apply dropout to the sequence output
# sequence_output = self.dropout(sequence_output)
# (batch_size, num_tokens, 768)
logits = self.classifier(sequence_output)
# (batch_size, num_tokens, 2)
# Split the logits into start and end logits
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1)
end_logits = end_logits.squeeze(-1)
# (batch_size, num_tokens), (batch_size, num_tokens)
return start_logits, end_logits
from transformers import AutoConfig, AutoTokenizer
# Clear GPU cache
torch.cuda.empty_cache()
# Determine the device (GPU or CPU)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Load the configuration for the BERT model
config = AutoConfig.from_pretrained("HooshvareLab/bert-base-parsbert-uncased")
# Create an instance of the QAModel2 using the loaded configuration
model = QAModel2(config)
# Move the model to the appropriate device (GPU or CPU)
model.to(device)
# Set the model to training mode
model.train()
# Define the optimizer
optim = AdamW(model.parameters(), lr=5e-5)
import matplotlib.pyplot as plt
# Set the number of epochs
n_epochs = 5
# Get the number of batches in the training and validation sets
n_train_batches = len(train_loader)
n_validation_batches = len(validation_loader)
# Initialize softmax function
softmax = torch.nn.Softmax(dim=1)
# Initialize best validation loss
best_valid_loss = float('inf')
# Initialize lists to store loss, EM, and F1 scores for each epoch
train_losses, valid_losses = [], []
exact_match_scores, f1_scores = [], []
# Main training loop
for epoch in range(n_epochs):
loop = tqdm(train_loader)
train_running_loss, validation_running_loss = 0.0, 0.0
exact_match = []
f1 = []
# Training phase
for batch in loop:
# Zero the gradients
optim.zero_grad()
# Move data to device
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
token_type_ids = batch['token_type_ids'].to(device)
y_start = batch['targets_start'].to(device)
y_end = batch['targets_end'].to(device)
# Forward pass
out_start, out_end = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
# Compute loss
loss = loss_fn(out_start, out_end, y_start, y_end)
train_running_loss += loss
# Backward pass
loss.backward()
# Update weights
optim.step()
loop.set_description(f'Epoch {epoch+1} - Training')
# Validation phase
with torch.no_grad():
loop2 = tqdm(validation_loader)
for content in loop2:
# Move data to device
input_ids = content['input_ids'].to(device)
temp_ids = input_ids.cpu().data.numpy().tolist()
max_ind = [temp_ids[i].index(4) for i in range(0, len(temp_ids))] # index of first [sep]
attention_mask = content['attention_mask'].to(device)
token_type_ids = content['token_type_ids'].to(device)
y_start = content['targets_start'].to(device)
y_end = content['targets_end'].to(device)
# Forward pass
out_start, out_end = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
start_pred = softmax(out_start)
end_pred = softmax(out_end)
# Compute loss
loss2 = loss_fn(out_start, out_end, y_start, y_end)
validation_running_loss += loss2
# Compute EM and F1 scores
start_label = np.nonzero(y_start).cpu().data.numpy()
end_label = np.nonzero(y_end).cpu().data.numpy()
tensor_label = torch.stack((torch.tensor(start_label[:, 1]), torch.tensor(end_label[:, 1])), -1)
start_log, end_log = generate_indexes(start_pred, end_pred, N, max_ind)
start_log = np.array(start_log)
end_log = np.array(end_log)
tensor_pred = torch.stack((torch.tensor(start_log), torch.tensor(end_log)), -1)
ex_ma = sum([1 if (tensor_pred[i][0] == tensor_label[i][0] and tensor_pred[i][1] == tensor_label[i][1]) else 0 for i in range(0, len(tensor_pred))]) / len(tensor_pred)
exact_match.append(ex_ma)
f1.append(evaluate_model(start_pred.cpu().data.numpy(), end_pred.cpu().data.numpy(), N, max_ind, start_label[:, 1], end_label[:, 1]))
loop2.set_description(f'Epoch {epoch+1} - Validation')
# Compute average losses and scores
train_loss = train_running_loss / n_train_batches
valid_loss = validation_running_loss / n_validation_batches
# Append losses to the lists
train_losses.append(train_loss)
valid_losses.append(valid_loss)
# Update best validation loss and save model weights
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), '/content/drive/MyDrive/HW5/Q2/Models/Model1.pt')
print('Model Saved in Google Drive!')
# Compute and append average EM and F1 scores
exact_match_score = 100 * np.mean(exact_match)