Upload bert.py
Browse files
bert.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import random
|
3 |
+
from transformers import AutoTokenizer, BertForSequenceClassification
|
4 |
+
from datasets import load_dataset
|
5 |
+
from transformers import LukePreTrainedModel, LukeModel, AutoTokenizer, TrainingArguments, default_data_collator, Trainer, AutoModelForQuestionAnswering
|
6 |
+
from transformers.modeling_outputs import ModelOutput
|
7 |
+
from typing import Optional, Tuple, Union
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
from tqdm import tqdm
|
11 |
+
import evaluate
|
12 |
+
import torch
|
13 |
+
from dataclasses import dataclass
|
14 |
+
from datasets import load_dataset, concatenate_datasets, load_metric
|
15 |
+
from torch import nn
|
16 |
+
from torch.nn import CrossEntropyLoss
|
17 |
+
import collections
|
18 |
+
import re
|
19 |
+
|
20 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
21 |
+
torch.backends.cudnn.allow_tf32 = True
|
22 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
23 |
+
|
24 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
25 |
+
model = BertForSequenceClassification.from_pretrained("bert-base-uncased").to(device)
|
26 |
+
|
27 |
+
def preprocess_training_examples(examples):
|
28 |
+
questions = [q.strip() for q in examples["question"]]
|
29 |
+
answers = []
|
30 |
+
labels = []
|
31 |
+
final_questions = []
|
32 |
+
# Generate close-looking answers from existing context
|
33 |
+
for i in range(len(questions)):
|
34 |
+
context = examples["context"][i]
|
35 |
+
words = context.split()
|
36 |
+
final_questions.append(questions[i])
|
37 |
+
original_answer = examples["answers"][i]["text"][0]
|
38 |
+
original_words = original_answer.split()
|
39 |
+
answers.append(original_answer)
|
40 |
+
labels.append(1)
|
41 |
+
answer_start = examples["answers"][i]["answer_start"][0]
|
42 |
+
answer_end = answer_start + len(original_answer)
|
43 |
+
|
44 |
+
begin_context = context[:answer_start]
|
45 |
+
end_context = context[answer_end:]
|
46 |
+
|
47 |
+
end = 1 if len(original_words) == 1 else 3
|
48 |
+
case_ind = random.randint(0, end)
|
49 |
+
pre_words = begin_context.rsplit(maxsplit=1)
|
50 |
+
post_words = end_context.split(maxsplit=1)
|
51 |
+
if case_ind == 0 and pre_words: # Append left
|
52 |
+
words = pre_words
|
53 |
+
wrong_context = " ".join([words[-1], original_answer])
|
54 |
+
final_questions.append(questions[i])
|
55 |
+
answers.append(wrong_context)
|
56 |
+
labels.append(0)
|
57 |
+
elif case_ind == 1 and post_words: # Append right
|
58 |
+
words = post_words
|
59 |
+
wrong_context = " ".join([original_answer, words[0]])
|
60 |
+
final_questions.append(questions[i])
|
61 |
+
answers.append(wrong_context)
|
62 |
+
labels.append(0)
|
63 |
+
elif case_ind == 3: # Drop left
|
64 |
+
wrong_context = " ".join(original_words[1:])
|
65 |
+
final_questions.append(questions[i])
|
66 |
+
answers.append(wrong_context)
|
67 |
+
labels.append(0)
|
68 |
+
elif case_ind == 4: # Drop right
|
69 |
+
wrong_context = " ".join(original_words[:len(original_words) - 1])
|
70 |
+
final_questions.append(questions[i])
|
71 |
+
answers.append(wrong_context)
|
72 |
+
labels.append(0)
|
73 |
+
|
74 |
+
inputs = tokenizer(
|
75 |
+
final_questions,
|
76 |
+
answers,
|
77 |
+
padding="max_length",
|
78 |
+
)
|
79 |
+
inputs["labels"] = labels
|
80 |
+
return inputs
|
81 |
+
|
82 |
+
raw_datasets = load_dataset("squad")
|
83 |
+
raw_train = raw_datasets["train"]
|
84 |
+
raw_eval = raw_datasets["validation"]
|
85 |
+
|
86 |
+
train_dataset = raw_train.map(
|
87 |
+
preprocess_training_examples,
|
88 |
+
batched=True,
|
89 |
+
remove_columns=raw_train.column_names,
|
90 |
+
)
|
91 |
+
|
92 |
+
eval_dataset = raw_eval.map(
|
93 |
+
preprocess_training_examples,
|
94 |
+
batched=True,
|
95 |
+
remove_columns=raw_train.column_names,
|
96 |
+
)
|
97 |
+
|
98 |
+
batch_size = 8
|
99 |
+
|
100 |
+
# train_dataset = train_dataset.with_format("torch")
|
101 |
+
|
102 |
+
args = TrainingArguments(
|
103 |
+
"right_span_bert",
|
104 |
+
evaluation_strategy = "no",
|
105 |
+
save_strategy="epoch",
|
106 |
+
learning_rate=2e-5,
|
107 |
+
per_device_train_batch_size=batch_size,
|
108 |
+
per_device_eval_batch_size=batch_size,
|
109 |
+
num_train_epochs=2,
|
110 |
+
weight_decay=0.01,
|
111 |
+
push_to_hub=True,
|
112 |
+
fp16=True
|
113 |
+
)
|
114 |
+
|
115 |
+
def compute_metrics(eval_pred):
|
116 |
+
load_accuracy = evaluate.load("accuracy")
|
117 |
+
load_f1 = evaluate.load("f1")
|
118 |
+
logits, labels = eval_pred
|
119 |
+
predictions = np.argmax(logits, axis=-1)
|
120 |
+
accuracy = load_accuracy.compute(predictions=predictions, references=labels)["accuracy"]
|
121 |
+
f1 = load_f1.compute(predictions=predictions, references=labels)["f1"]
|
122 |
+
return {"accuracy": accuracy, "f1": f1}
|
123 |
+
|
124 |
+
trainer = Trainer(
|
125 |
+
model,
|
126 |
+
args,
|
127 |
+
train_dataset=train_dataset,
|
128 |
+
eval_dataset=eval_dataset,
|
129 |
+
data_collator=default_data_collator,
|
130 |
+
tokenizer=tokenizer,
|
131 |
+
compute_metrics=compute_metrics
|
132 |
+
)
|
133 |
+
|
134 |
+
trainer.train()
|
135 |
+
|
136 |
+
res = trainer.evaluate()
|
137 |
+
print(res)
|