-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqa.py
249 lines (191 loc) · 7.55 KB
/
qa.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
import transformers as ts
from transformers import pipeline
from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer
from datasets import Dataset
import json
import os
def load_and_preprocess_train_dataset(path, tokenizer, max_length=384, stride=128):
def load_data(path):
dataDict = {
"id": [],
"title": [],
"context": [],
"question": [],
"answers": [],
}
def load_subset(path, dataDict):
with open(path) as d:
dictData = json.load(d)
sample = dictData["data"]
for sample in dictData["data"]:
for paragraph in sample["paragraphs"]:
for qas in paragraph["qas"]:
id = qas["id"]
title = sample["title"]
context = paragraph["context"]
question = qas["question"]
for answer in qas["answers"]:
dataDict["id"].append(id)
dataDict["title"].append(title)
dataDict["context"].append(context)
dataDict["question"].append(question)
dataDict["answers"].append(
{"text": [answer["text"]], "answer_start": [answer["answer_start"]]})
load_subset(path, dataDict)
return Dataset.from_dict(dataDict)
trainDataset = load_data(path)
def preprocessing_function(examples):
questions = [q.strip() for q in examples["question"]]
inputs = tokenizer(
questions,
examples["context"],
max_length=max_length,
truncation="only_second",
stride=stride,
return_overflowing_tokens=True,
return_offsets_mapping=True,
padding="max_length",
)
offset_mapping = inputs.pop("offset_mapping")
sample_map = inputs.pop("overflow_to_sample_mapping")
answers = examples["answers"]
start_positions = []
end_positions = []
for i, offset in enumerate(offset_mapping):
sample_idx = sample_map[i]
answer = answers[sample_idx]
start_char = answer["answer_start"][0]
end_char = answer["answer_start"][0] + len(answer["text"][0])
sequence_ids = inputs.sequence_ids(i)
# Find the start and end of the context
idx = 0
while sequence_ids[idx] != 1:
idx += 1
context_start = idx
while sequence_ids[idx] == 1:
idx += 1
context_end = idx - 1
# If the answer is not fully inside the context, label is (0, 0)
if offset[context_start][0] > start_char or offset[context_end][1] < end_char:
start_positions.append(0)
end_positions.append(0)
else:
# Otherwise it's the start and end token positions
idx = context_start
while idx <= context_end and offset[idx][0] <= start_char:
idx += 1
start_positions.append(idx - 1)
idx = context_end
while idx >= context_start and offset[idx][1] >= end_char:
idx -= 1
end_positions.append(idx + 1)
inputs["start_positions"] = start_positions
inputs["end_positions"] = end_positions
return inputs
tokenizedTrainDataset = trainDataset.map(
preprocessing_function, batched=True, remove_columns=trainDataset.column_names)
return trainDataset, tokenizedTrainDataset
def load_test_dataset(path):
def load_data(path):
dataDict = {
"id": [],
"title": [],
"context": [],
"question": [],
}
def load_subset(path, dataDict):
with open(path) as d:
dictData = json.load(d)
sample = dictData["data"]
for sample in dictData["data"]:
for paragraph in sample["paragraphs"]:
for qas in paragraph["qas"]:
id = qas["id"]
title = sample["title"]
context = paragraph["context"]
question = qas["question"]
dataDict["id"].append(id)
dataDict["title"].append(title)
dataDict["context"].append(context)
dataDict["question"].append(question)
load_subset(path, dataDict)
return Dataset.from_dict(dataDict)
testDataset = load_data(path)
return testDataset
def train(tokenizedTrainDataset,
modelPath,
tokenizer,
learning_rate=3e-5,
num_epochs=5,
batch_size=16,
training_args=None):
model = AutoModelForQuestionAnswering.from_pretrained(modelPath)
"""#Training"""
data_collator = ts.DefaultDataCollator()
if training_args == None:
training_args = TrainingArguments(
"output/",
seed=42,
logging_steps=250,
save_steps=2500,
num_train_epochs=num_epochs,
learning_rate=learning_rate,
lr_scheduler_type="cosine",
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
weight_decay=0.01,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenizedTrainDataset,
tokenizer=tokenizer,
data_collator=data_collator,
)
trainer.train()
return model
def evaluate(model,
tokenizer,
testDataset,
goldenPath,
logsPath,
top_k_predictions=5,
max_seq_len=384,
doc_stride=128):
if not os.path.exists(logsPath):
os.mkdir(logsPath)
qa_model = pipeline("question-answering",
model=model,
tokenizer=tokenizer)
answersDict = {}
for testSample in testDataset:
model.cpu()
answers = []
for answer in qa_model(question=testSample["question"],
context=testSample["context"],
top_k=top_k_predictions,
max_seq_len=max_seq_len,
doc_stride=doc_stride):
answers.append(answer["answer"])
id = testSample["id"].split("_", 1)[0]
if id in answersDict:
answersDict[id].append(answers)
else:
answersDict[id] = [answers]
def write_answers_to_csv(answersDict, goldenPath):
with open(goldenPath) as f:
data = json.load(f)
questions = data["questions"]
for sample in questions:
if sample["type"] == "factoid":
if "exact_answer" in sample:
predicted_answers = answersDict[sample["id"]]
sample["ideal_answer"] = ["dummy"]
sample["exact_answer"] = predicted_answers
data["questions"] = questions
outputTitle = goldenPath.split("/")[-1]
outputPath = f"{logsPath}/prediction_{outputTitle}"
with open(outputPath, mode="w") as f:
json.dump(data, f, indent=6)
write_answers_to_csv(answersDict, goldenPath)
return answersDict