forked from PaddlePaddle/PaddleNLP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_cls.py
210 lines (180 loc) · 8.11 KB
/
run_cls.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
# encoding=utf-8
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import collections
from functools import partial
import paddle
from paddlenlp.trainer import PdArgumentParser, TrainingArguments
from paddlenlp.trainer import get_last_checkpoint
from paddlenlp.transformers import AutoTokenizer, AutoModelForSequenceClassification
from paddlenlp.utils.log import logger
from paddle.metric import Accuracy
from datasets import load_dataset, load_metric
import datasets
from data_collator import DataCollator
from finetune_args import DataArguments, ModelArguments
from utils import PreProcessor, PostProcessor, get_label_ld
from layout_trainer import LayoutTrainer
def main():
parser = PdArgumentParser((ModelArguments, DataArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
training_args.print_config(model_args, "Model")
training_args.print_config(data_args, "Data")
paddle.set_device(training_args.device)
# Detecting last checkpoint.
last_checkpoint = None
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
"Use --overwrite_output_dir to overcome."
)
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
train_ds, dev_ds, test_ds = load_dataset(data_args.dataset_name, split=["train", "validation", "test"])
if training_args.do_train:
column_names = train_ds.column_names
elif training_args.do_eval:
column_names = dev_ds.column_names
elif training_args.do_predict:
column_names = test_ds.column_names
else:
logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.")
raise NotImplementedError
label_list, label_to_id = get_label_ld(train_ds["qas"], scheme="cls")
num_labels = len(label_list)
# Load Model and Tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
model = AutoModelForSequenceClassification.from_pretrained(model_args.model_name_or_path, num_classes=num_labels)
model.config["has_visual_segment_embedding"] = False
preprocessor = PreProcessor()
postprocessor = PostProcessor()
training_args.label_names = ["labels"]
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
preprocess_func = partial(
preprocessor.preprocess_cls,
tokenizer=tokenizer,
max_seq_length=max_seq_length,
doc_stride=data_args.doc_stride,
label_dict=label_to_id,
max_size=data_args.target_size,
target_size=data_args.target_size,
use_segment_box=data_args.use_segment_box,
preprocessing_num_workers=data_args.preprocessing_num_workers,
)
preprocess_func_for_valid = preprocess_func
postprocess_func = partial(postprocessor.postprocess_cls, label_list=label_list, tokenizer=tokenizer)
# Dataset pre-process
if training_args.do_train:
if data_args.train_nshard > 1:
logger.info(f"spliting train dataset into {data_args.train_nshard} shard")
train_shards = []
for idx in range(data_args.train_nshard):
train_shards.append(
train_ds.shard(num_shards=data_args.train_nshard, index=idx).map(
preprocess_func,
batched=True,
remove_columns=column_names,
num_proc=data_args.preprocessing_num_workers,
load_from_cache_file=not data_args.overwrite_cache,
)
)
train_dataset = datasets.concatenate_datasets(train_shards)
else:
train_dataset = train_ds.map(
preprocess_func,
batched=True,
remove_columns=column_names,
num_proc=data_args.preprocessing_num_workers,
load_from_cache_file=not data_args.overwrite_cache,
)
if training_args.do_eval:
eval_dataset = dev_ds.map(
preprocess_func_for_valid,
batched=True,
remove_columns=column_names,
num_proc=data_args.preprocessing_num_workers,
load_from_cache_file=not data_args.overwrite_cache,
)
if training_args.do_predict:
test_dataset = test_ds.map(
preprocess_func_for_valid,
batched=True,
remove_columns=column_names,
num_proc=data_args.preprocessing_num_workers,
load_from_cache_file=not data_args.overwrite_cache,
)
# Data collator
data_collator = DataCollator(
tokenizer, padding="max_length", label_pad_token_id=-100, max_length=max_seq_length, return_tensors="pd"
)
def compute_metrics(eval_preds):
preds = paddle.to_tensor(eval_preds.predictions)
labels = paddle.to_tensor(eval_preds.label_ids)
metric = Accuracy()
metric.reset()
correct = preds == labels
correct = paddle.cast(paddle.unsqueeze(correct, axis=-1), dtype="float32")
metric.update(correct)
accu = metric.accumulate()
metric.reset()
return {"acc": accu}
trainer = LayoutTrainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=train_dataset if training_args.do_train else None,
eval_dataset=eval_dataset if training_args.do_eval else None,
eval_examples=dev_ds,
tokenizer=tokenizer,
compute_metrics=compute_metrics,
post_process_function=postprocess_func,
)
checkpoint = None
if training_args.resume_from_checkpoint is not None:
checkpoint = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
checkpoint = last_checkpoint
# Training
if training_args.do_train:
train_result = trainer.train(resume_from_checkpoint=checkpoint)
metrics = train_result.metrics
trainer.save_model()
max_train_samples = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
)
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
# Evaluate and tests model
if training_args.do_eval:
eval_metrics = trainer.evaluate()
max_val_samples = data_args.max_val_samples if data_args.max_val_samples is not None else len(eval_dataset)
metrics["eval_samples"] = min(max_val_samples, len(eval_dataset))
trainer.log_metrics("eval", eval_metrics)
trainer.save_metrics("eval", metrics)
if training_args.do_predict:
postprocessor.examples_cache = collections.defaultdict(list)
postprocessor.features_cache = collections.defaultdict(list)
metrics = trainer.predict(test_dataset, test_ds)
trainer.log_metrics("test", metrics)
trainer.save_metrics("test", metrics)
if __name__ == "__main__":
main()