-
Notifications
You must be signed in to change notification settings - Fork 0
/
inference.py
341 lines (287 loc) · 11.4 KB
/
inference.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
"""
Open-Domain Question Answering 을 수행하는 inference 코드 입니다.
대부분의 로직은 train.py 와 비슷하나 retrieval, predict 부분이 추가되어 있습니다.
"""
import logging
import sys
from typing import Callable, List, Dict, NoReturn, Tuple
import numpy as np
import pandas as pd
from datasets import (
load_metric,
load_from_disk,
Sequence,
Value,
Features,
Dataset,
DatasetDict,
)
from transformers import AutoConfig, AutoModelForQuestionAnswering, AutoTokenizer
from transformers import (
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
TrainingArguments,
set_seed,
)
from utils_qa import postprocess_qa_predictions_inf, check_no_error
from trainer_qa import QuestionAnsweringTrainer
#from elastic_retrieval import SparseRetrieval
from arguments import (
ModelArguments,
DataTrainingArguments,
)
logger = logging.getLogger(__name__)
def main():
# 가능한 arguments 들은 ./arguments.py 나 transformer package 안의 src/transformers/training_args.py 에서 확인 가능합니다.
# --help flag 를 실행시켜서 확인할 수 도 있습니다.
parser = HfArgumentParser(
(ModelArguments, DataTrainingArguments, TrainingArguments)
)
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
training_args.do_train = True
print(f"model is from {model_args.model_name_or_path}")
print(f"data is from {data_args.dataset_name}")
# logging 설정
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
# verbosity 설정 : Transformers logger의 정보로 사용합니다 (on main process only)
logger.info("Training/evaluation parameters %s", training_args)
# 모델을 초기화하기 전에 난수를 고정합니다.
set_seed(training_args.seed)
datasets = load_from_disk(data_args.dataset_name)
print(datasets)
# AutoConfig를 이용하여 pretrained model 과 tokenizer를 불러옵니다.
# argument로 원하는 모델 이름을 설정하면 옵션을 바꿀 수 있습니다.
config = AutoConfig.from_pretrained(
model_args.config_name
if model_args.config_name
else model_args.model_name_or_path,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name
if model_args.tokenizer_name
else model_args.model_name_or_path,
use_fast=True,
)
model = AutoModelForQuestionAnswering.from_pretrained(
model_args.model_name_or_path,
from_tf=bool(".ckpt" in model_args.model_name_or_path),
config=config,
)
# True일 경우 : run passage retrieval
if data_args.eval_retrieval:
datasets = run_sparse_retrieval(
tokenizer.tokenize,
datasets,
training_args,
data_args,
)
# eval or predict mrc model
if training_args.do_eval or training_args.do_predict:
run_mrc(data_args, training_args, model_args, datasets, tokenizer, model)
def run_sparse_retrieval(
tokenize_fn: Callable[[str], List[str]],
datasets: DatasetDict,
training_args: TrainingArguments,
data_args: DataTrainingArguments,
data_path: str = "../data",
context_path: str = "wikipedia_documents.json",
) -> DatasetDict:
# Query에 맞는 Passage들을 Retrieval 합니다.
##retrieval = SparseRetrieval()
# df = retrieval.retrieve_ES(
# datasets["validation"],
# topk=data_args.top_k_retrieval,
# ner_path="./inference_tagged.csv",
# )
# dataframe을 불러옵니다
df = pd.read_csv('./abc.csv')
#df['context'] = df['context'].apply(eval)
for i in range(len(df)):
df['context'][i] = [df['context'][i][2:-2]]
print(df['context'][0])
print(type(df['context'][0]))
print(df['question'][0])
print('---------------------')
# df.to_csv('check.csv')
# test data 에 대해선 정답이 없으므로 id question context 로만 데이터셋이 구성됩니다.
if training_args.do_predict:
f = Features(
{
"context": Sequence(feature=Value(dtype="string", id=None)), # 바꿈!
"id": Value(dtype="string", id=None),
"question": Value(dtype="string", id=None),
}
)
# train data 에 대해선 정답이 존재하므로 id question context answer 로 데이터셋이 구성됩니다.
elif training_args.do_eval:
f = Features(
{
"answers": Sequence(
feature={
"text": Value(dtype="string", id=None),
"answer_start": Value(dtype="int32", id=None),
},
length=-1,
id=None,
),
"context": Sequence(feature=Value(dtype="string", id=None)), # 바꿈!
"id": Value(dtype="string", id=None),
"question": Value(dtype="string", id=None),
}
)
datasets = DatasetDict({"validation": Dataset.from_pandas(df, features=f)})
return datasets
def run_mrc(
data_args: DataTrainingArguments,
training_args: TrainingArguments,
model_args: ModelArguments,
datasets: DatasetDict,
tokenizer,
model,
) -> NoReturn:
# eval 혹은 prediction에서만 사용함
column_names = datasets["validation"].column_names
question_column_name = "question" if "question" in column_names else column_names[0]
context_column_name = "context" if "context" in column_names else column_names[1]
answer_column_name = "answers" if "answers" in column_names else column_names[2]
# Padding에 대한 옵션을 설정합니다.
# (question|context) 혹은 (context|question)로 세팅 가능합니다.
pad_on_right = tokenizer.padding_side == "right"
# 오류가 있는지 확인합니다.
last_checkpoint, max_seq_length = check_no_error(
data_args, training_args, datasets, tokenizer
)
# 싹 바꿈!
def prepare_validation_features(examples):
test_query = examples["question"]
test_contexts = examples["context"]
test_id = examples["id"]
#topk = len(test_contexts[0])
print('-----------------------------------------')
topk = 1
assert topk == data_args.top_k_retrieval, "topk not correct"
tq_final = []
tc_final = []
ti_final = []
for i in range(len(test_query)):
temp_q = [test_query[i] for _ in range(topk)]
temp_i = [test_id[i] for _ in range(topk)]
tq_final.extend(temp_q)
ti_final.extend(temp_i)
#a = ''.join(test_contexts[i])
#a = a[2:-2]
#tc_final.append(a)
tc_final.extend(test_contexts[i])
print(len(tq_final))
print(len(ti_final))
print(len(tc_final))
assert len(tq_final) == len(ti_final) and len(tq_final) == len(
tc_final
), "final list length not correct"
tokenized_examples = tokenizer(
tq_final if pad_on_right else tc_final,
tc_final if pad_on_right else tq_final,
truncation="only_second" if pad_on_right else "only_first",
max_length=max_seq_length,
stride=data_args.doc_stride,
return_overflowing_tokens=True,
return_offsets_mapping=True,
return_token_type_ids=False, # roberta모델을 사용할 경우 False, bert를 사용할 경우 True로 표기해야합니다.
padding="max_length" if data_args.pad_to_max_length else False,
)
sample_mapping = tokenized_examples["overflow_to_sample_mapping"]
tokenized_examples["example_id"] = []
for i in range(len(tokenized_examples["input_ids"])):
sequence_ids = tokenized_examples.sequence_ids(i)
context_index = 1 if pad_on_right else 0
sample_index = sample_mapping[i]
tokenized_examples["example_id"].append(ti_final[sample_index])
tokenized_examples["offset_mapping"][i] = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples["offset_mapping"][i])
]
return tokenized_examples
eval_dataset = datasets["validation"]
# Validation Feature 생성
eval_dataset = eval_dataset.map(
prepare_validation_features,
batched=True,
num_proc=data_args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not data_args.overwrite_cache,
)
# Data collator
# flag가 True이면 이미 max length로 padding된 상태입니다.
# 그렇지 않다면 data collator에서 padding을 진행해야합니다.
data_collator = DataCollatorWithPadding(
tokenizer, pad_to_multiple_of=8 if training_args.fp16 else None
)
# Post-processing:
def post_processing_function(
examples,
features,
predictions: Tuple[np.ndarray, np.ndarray],
training_args: TrainingArguments,
) -> EvalPrediction:
# Post-processing: start logits과 end logits을 original context의 정답과 match시킵니다.
# 바꿈!
predictions = postprocess_qa_predictions_inf(
examples=examples,
features=features,
predictions=predictions,
topk=data_args.top_k_retrieval,
max_answer_length=data_args.max_answer_length,
output_dir=training_args.output_dir,
)
# Metric을 구할 수 있도록 Format을 맞춰줍니다.
formatted_predictions = [
{"id": k, "prediction_text": v} for k, v in predictions.items()
]
if training_args.do_predict:
return formatted_predictions
elif training_args.do_eval:
references = [
{"id": ex["id"], "answers": ex[answer_column_name]}
for ex in datasets["validation"]
]
return EvalPrediction(
predictions=formatted_predictions, label_ids=references
)
metric = load_metric("squad")
def compute_metrics(p: EvalPrediction) -> Dict:
return metric.compute(predictions=p.predictions, references=p.label_ids)
print("init trainer...")
# Trainer 초기화
trainer = QuestionAnsweringTrainer(
model=model,
args=training_args,
train_dataset=None,
eval_dataset=eval_dataset,
eval_examples=datasets["validation"],
tokenizer=tokenizer,
data_collator=data_collator,
post_process_function=post_processing_function,
compute_metrics=compute_metrics,
)
logger.info("*** Evaluate ***")
#### eval dataset & eval example - predictions.json 생성됨
if training_args.do_predict:
predictions = trainer.predict(
test_dataset=eval_dataset, test_examples=datasets["validation"]
)
# predictions.json 은 postprocess_qa_predictions() 호출시 이미 저장됩니다.
print(
"No metric can be presented because there is no correct answer given. Job done!"
)
if training_args.do_eval:
metrics = trainer.evaluate()
metrics["eval_samples"] = len(eval_dataset)
trainer.log_metrics("test", metrics)
trainer.save_metrics("test", metrics)
if __name__ == "__main__":
main()