forked from boostcampaitech2/mrc-level2-nlp-13
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_reader.py
436 lines (358 loc) · 16.5 KB
/
train_reader.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
##################
# Import modules #
##################
import os
import argparse
from typing import NoReturn
from datasets import (
load_metric,
load_from_disk,
concatenate_datasets,
DatasetDict,
)
from transformers import AutoConfig, AutoModelForQuestionAnswering, AutoTokenizer
from transformers import (
DataCollatorWithPadding,
EvalPrediction,
set_seed,
)
from model.Reader.RobertaCnn import RobertaCNNForQuestionAnswering
from model.Reader.trainer_qa import QuestionAnsweringTrainer
from utils.utils_qa import postprocess_qa_predictions, check_no_error
from utils.arguments import (
ModelArguments,
DataArguments,
TrainingArguments,
CustomArguments,
train_config_setting,
wandb_config_setting,
MODEL_DIR,
CONFIG_DIR,
LOG_DIR,
)
from utils.logger import get_logger
import wandb
########################
# Set global variables #
########################
logger = None
CUSTOM_MODEL_NAMES = {
"RobertaCnn":RobertaCNNForQuestionAnswering,
}
#######################
# Classes & Functions #
#######################
def main():
global logger
# Load config json
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config_file_path", help="Configure Json path")
parser.add_argument("-l", "--log_file_path", default="reader_train.log", help="Logger file path")
parser.add_argument("-n", "--model_name", default=None, help="Logger file path")
parser.add_argument("--do_train",action="store_true")
parser.add_argument("--do_eval",action="store_true")
config = parser.parse_args()
assert config.model_name, "Output 파일 이름을 설정해 주세요"
config.config_file_path = os.path.join(CONFIG_DIR, config.config_file_path)
config.log_file_path = os.path.join(LOG_DIR, config.log_file_path)
config.model_name = os.path.join(MODEL_DIR, config.model_name)
logger = get_logger(config.log_file_path)
model_args, data_args, training_args, custom_args =\
train_config_setting(config)
training_args.do_train = config.do_train
training_args.do_eval = config.do_eval
logger.info(f"model is from {model_args.model_name_or_path}")
logger.info(f"data is from {data_args.dataset_name}")
logger.info("Training/evaluation parameters %s", training_args)
# Set random seed
set_seed(training_args.seed)
# Load datasets
datasets = load_from_disk(data_args.dataset_name)
# Load Config & tokenizer
config = AutoConfig.from_pretrained(
model_args.config_name
if model_args.config_name is not None
else model_args.model_name_or_path,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name
if model_args.tokenizer_name is not None
else model_args.model_name_or_path,
use_fast=True,
)
# Load Model
if model_args.model_name_or_path in CUSTOM_MODEL_NAMES:
model = CUSTOM_MODEL_NAMES[model_args.model_name_or_path].from_pretrained(
model_args.model_name_or_path,
config=config,
)
else:
model = AutoModelForQuestionAnswering.from_pretrained(
model_args.model_name_or_path,
from_tf=bool(".ckpt" in model_args.model_name_or_path),
config=config,
)
logger.info(
type(training_args),
type(model_args),
type(datasets),
type(custom_args),
type(tokenizer),
type(model),
)
# do_train mrc model 혹은 do_eval mrc model
if training_args.do_train or training_args.do_eval:
run_mrc(
data_args,
training_args,
model_args,
custom_args,
datasets,
tokenizer,
model,
)
def run_mrc(
data_args: DataArguments,
training_args: TrainingArguments,
model_args: ModelArguments,
custom_args: CustomArguments, # add
datasets: DatasetDict,
tokenizer,
model,
) -> NoReturn:
# Wandb 설정
if custom_args.use_wandb:
config = wandb_config_setting(data_args, training_args, model_args, custom_args)
wandb.init(
project=custom_args.project_name,
entity=custom_args.entity_name,
name=custom_args.wandb_run_name,
config=config,
)
# dataset을 전처리합니다.
# training과 evaluation에서 사용되는 전처리는 아주 조금 다른 형태를 가집니다.
if training_args.do_train:
column_names = datasets["train"].column_names
else:
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
)
# Train preprocessing / 전처리를 진행합니다.
def prepare_train_features(examples):
# truncation과 padding(length가 짧을때만)을 통해 toknization을 진행하며, stride를 이용하여 overflow를 유지합니다.
# 각 example들은 이전의 context와 조금씩 겹치게됩니다.
tokenized_examples = tokenizer(
examples[question_column_name if pad_on_right else context_column_name],
examples[context_column_name if pad_on_right else question_column_name],
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,
)
# 길이가 긴 context가 등장할 경우 truncate를 진행해야하므로, 해당 데이터셋을 찾을 수 있도록 mapping 가능한 값이 필요합니다.
sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
# token의 캐릭터 단위 position를 찾을 수 있도록 offset mapping을 사용합니다.
# start_positions과 end_positions을 찾는데 도움을 줄 수 있습니다.
offset_mapping = tokenized_examples.pop("offset_mapping")
# 데이터셋에 "start position", "enc position" label을 부여합니다.
tokenized_examples["start_positions"] = []
tokenized_examples["end_positions"] = []
for i, offsets in enumerate(offset_mapping):
input_ids = tokenized_examples["input_ids"][i]
cls_index = input_ids.index(tokenizer.cls_token_id) # cls index
# sequence id를 설정합니다 (to know what is the context and what is the question).
sequence_ids = tokenized_examples.sequence_ids(i)
# 하나의 example이 여러개의 span을 가질 수 있습니다.
sample_index = sample_mapping[i]
answers = examples[answer_column_name][sample_index]
# answer가 없을 경우 cls_index를 answer로 설정합니다(== example에서 정답이 없는 경우 존재할 수 있음).
if len(answers["answer_start"]) == 0:
tokenized_examples["start_positions"].append(cls_index)
tokenized_examples["end_positions"].append(cls_index)
else:
# text에서 정답의 Start/end character index
start_char = answers["answer_start"][0]
end_char = start_char + len(answers["text"][0])
# text에서 current span의 Start token index
token_start_index = 0
while sequence_ids[token_start_index] != (1 if pad_on_right else 0):
token_start_index += 1
# text에서 current span의 End token index
token_end_index = len(input_ids) - 1
while sequence_ids[token_end_index] != (1 if pad_on_right else 0):
token_end_index -= 1
# 정답이 span을 벗어났는지 확인합니다(정답이 없는 경우 CLS index로 label되어있음).
if not (
offsets[token_start_index][0] <= start_char
and offsets[token_end_index][1] >= end_char
):
tokenized_examples["start_positions"].append(cls_index)
tokenized_examples["end_positions"].append(cls_index)
else:
# token_start_index 및 token_end_index를 answer의 끝으로 이동합니다.
# Note: answer가 마지막 단어인 경우 last offset을 따라갈 수 있습니다(edge case).
while (
token_start_index < len(offsets)
and offsets[token_start_index][0] <= start_char
):
token_start_index += 1
tokenized_examples["start_positions"].append(token_start_index - 1)
while offsets[token_end_index][1] >= end_char:
token_end_index -= 1
tokenized_examples["end_positions"].append(token_end_index + 1)
return tokenized_examples
if training_args.do_train:
if "train" not in datasets:
raise ValueError("--do_train requires a train dataset")
if data_args.use_validation_data:
train_dataset = concatenate_datasets(
[datasets["train"], datasets["validation"]]
)
else:
train_dataset = datasets["train"]
# dataset에서 train feature를 생성합니다.
train_dataset = train_dataset.map(
prepare_train_features,
batched=True,
num_proc=data_args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not data_args.overwrite_cache,
)
# Validation preprocessing
def prepare_validation_features(examples):
# truncation과 padding(length가 짧을때만)을 통해 toknization을 진행하며, stride를 이용하여 overflow를 유지합니다.
# 각 example들은 이전의 context와 조금씩 겹치게됩니다.
tokenized_examples = tokenizer(
examples[question_column_name if pad_on_right else context_column_name],
examples[context_column_name if pad_on_right else question_column_name],
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,
)
# 길이가 긴 context가 등장할 경우 truncate를 진행해야하므로, 해당 데이터셋을 찾을 수 있도록 mapping 가능한 값이 필요합니다.
sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
# evaluation을 위해, prediction을 context의 substring으로 변환해야합니다.
# corresponding example_id를 유지하고 offset mappings을 저장해야합니다.
tokenized_examples["example_id"] = []
for i in range(len(tokenized_examples["input_ids"])):
# sequence id를 설정합니다 (to know what is the context and what is the question).
sequence_ids = tokenized_examples.sequence_ids(i)
context_index = 1 if pad_on_right else 0
# 하나의 example이 여러개의 span을 가질 수 있습니다.
sample_index = sample_mapping[i]
tokenized_examples["example_id"].append(examples["id"][sample_index])
# Set to None the offset_mapping을 None으로 설정해서 token position이 context의 일부인지 쉽게 판별 할 수 있습니다.
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
if training_args.do_eval:
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, training_args):
# Post-processing: start logits과 end logits을 original context의 정답과 match시킵니다.
predictions = postprocess_qa_predictions(
examples=examples,
features=features,
predictions=predictions,
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):
return metric.compute(predictions=p.predictions, references=p.label_ids)
# Trainer 초기화
if custom_args.use_wandb:
wandb.watch(model)
trainer = QuestionAnsweringTrainer(
model=model,
custom_args=custom_args,
model_tokenizer=tokenizer,
args=training_args,
train_dataset=train_dataset if training_args.do_train else None,
eval_dataset=eval_dataset if training_args.do_eval else None,
eval_examples=datasets["validation"] if training_args.do_eval else None,
tokenizer=tokenizer,
data_collator=data_collator,
post_process_function=post_processing_function,
compute_metrics=compute_metrics,
)
# Training
if training_args.do_train:
if last_checkpoint is not None:
checkpoint = last_checkpoint
elif os.path.isdir(model_args.model_name_or_path):
checkpoint = model_args.model_name_or_path
else:
checkpoint = None
train_result = trainer.train(resume_from_checkpoint=checkpoint)
# training_step(model, train_dataset)
trainer.save_model() # Saves the tokenizer too for easy upload
metrics = train_result.metrics
metrics["train_samples"] = len(train_dataset)
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
output_train_file = os.path.join(training_args.output_dir, "train_results.txt")
with open(output_train_file, "w") as writer:
logger.info("***** Train results *****")
for key, value in sorted(train_result.metrics.items()):
logger.info(f" {key} = {value}")
writer.write(f"{key} = {value}\n")
# State 저장
trainer.state.save_to_json(
os.path.join(training_args.output_dir, "trainer_state.json")
)
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***")
metrics = trainer.evaluate()
metrics["eval_samples"] = len(eval_dataset)
trainer.log_metrics("eval", metrics)
trainer.save_metrics("eval", metrics)
if __name__ == "__main__":
main()