-
Notifications
You must be signed in to change notification settings - Fork 4
/
train_ner.py
329 lines (277 loc) · 12.4 KB
/
train_ner.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
# Copyright 2020 The HuggingFace Team 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.
# Source: https://github.com/huggingface/transformers/blob/master/examples/pytorch/token-classification/run_ner.py
import os
import logging
import sys
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
import torch
import torch.nn as nn
from datasets import load_dataset, load_metric
import transformers
from transformers import (
AutoConfig,
AutoModelForTokenClassification,
AutoTokenizer,
DataCollatorForTokenClassification,
EarlyStoppingCallback,
HfArgumentParser,
PreTrainedTokenizerFast,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import is_main_process
from tokenization_albert_bengali_fast import AlbertBengaliTokenizerFast
from huggingface_auth import authorize_with_huggingface
from lib.models.lean_albert import LeanAlbertConfig, LeanAlbertModel
from transformers import AlbertForTokenClassification, PreTrainedModel
logger = logging.getLogger(__name__)
os.environ["WANDB_PROJECT"] = "sahajBERT2-xlarge-ner"
os.environ["HF_EXPERIMENT_ID"] = "15"
os.environ["WANDB_API_KEY"] = "61612ca9b99e6a477893d7eb93a390462543fe7f"
@dataclass
class ModelArguments:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
default='Upload/sahajbert2',
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
)
dropout_prob: float = field(default=0.1, metadata={"help": "Dropout probability for model."})
class LeanAlbertForTokenClassification(AlbertForTokenClassification, PreTrainedModel):
def __init__(self, config: LeanAlbertConfig):
super().__init__(config)
self.num_labels = config.num_labels
self.albert = LeanAlbertModel(config, add_pooling_layer=False)
classifier_dropout_prob = (
config.classifier_dropout_prob
if config.classifier_dropout_prob is not None
else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
self.init_weights()
@dataclass
class DataTrainingArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, pos...)."})
dataset_name: Optional[str] = field(
default="wikiann", metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
default="bn", metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
)
max_seq_length: int = field(
default=128,
metadata={
"help": "The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
},
)
pad_to_max_length: bool = field(
default=True,
metadata={
"help": "Whether to pad all samples to model maximum sentence length. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
"efficient on GPU but very bad for TPU."
},
)
label_all_tokens: bool = field(
default=False,
metadata={
"help": "Whether to put the label for one word on all tokens of generated by that word or just on the "
"one (in which case the other tokens will have a padding index)."
},
)
def __post_init__(self):
if self.dataset_name is None:
raise ValueError("Need a dataset name.")
self.task_name = self.task_name.lower()
@dataclass
class AdditionalTrainingArguments:
early_stopping_patience: int = field(
default=1,
metadata={"help": "The number of evaluation calls to wait before stopping training while metric worsens."},
)
early_stopping_threshold: float = field(
default=0.0,
metadata={"help": "How much the metric must improve to satisfy early stopping conditions."},
)
def parse_arguments():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments, AdditionalTrainingArguments))
model_args, data_args, training_args, additional_training_args = parser.parse_args_into_dataclasses()
training_args.do_train = True
training_args.do_eval = True
training_args.load_best_model_at_end = True
training_args.metric_for_best_model = "loss"
training_args.evaluation_strategy = "epoch"
return model_args, data_args, training_args, additional_training_args
def setup_logging(training_args):
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
)
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank):
transformers.utils.logging.set_verbosity_info()
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.info(f"Training/evaluation parameters {training_args}")
def run(model_args, data_args, training_args, additional_training_args):
authorizer = authorize_with_huggingface()
setup_logging(training_args)
# Set seed before initializing model.
set_seed(training_args.seed)
# Get the datasets.
datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name)
# Set text and label column names
features = datasets["train"].features
text_column_name = "tokens"
label_column_name = "ner_tags"
label_list = features[label_column_name].feature.names
# No need to convert the labels since they are already ints.
label_to_id = {i: i for i in range(len(label_list))}
num_labels = len(label_list)
# Load pretrained model and tokenizer
tokenizer = AlbertBengaliTokenizerFast.from_pretrained(model_args.model_name_or_path)
config = LeanAlbertConfig.from_pretrained(
model_args.model_name_or_path,
num_labels=num_labels,
hidden_dropout_prob=model_args.dropout_prob,
finetuning_task=data_args.task_name,
vocab_size=len(tokenizer),
)
model = LeanAlbertForTokenClassification.from_pretrained(model_args.model_name_or_path, config=config)
# Preprocessing the dataset
# Padding strategy
padding = "max_length" if data_args.pad_to_max_length else False
if data_args.max_seq_length > tokenizer.model_max_length:
logger.warning(
f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
)
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
# Tokenize all texts and align the labels with them.
def tokenize_and_align_labels(examples):
tokenized_inputs = tokenizer(
examples[text_column_name],
padding=padding,
max_length=max_seq_length,
truncation=True,
# We use this argument because the texts in our dataset are lists of words (with a label for each word).
is_split_into_words=True,
)
labels = []
for i, label in enumerate(examples[label_column_name]):
word_ids = tokenized_inputs.word_ids(batch_index=i)
previous_word_idx = None
label_ids = []
for word_idx in word_ids:
# Special tokens have a word id that is None. We set the label to -100 so they are automatically
# ignored in the loss function.
if word_idx is None:
label_ids.append(-100)
# We set the label for the first token of each word.
elif word_idx != previous_word_idx:
label_ids.append(label_to_id[label[word_idx]])
# For the other tokens in a word, we set the label to either the current label or -100, depending on
# the label_all_tokens flag.
else:
label_ids.append(label_to_id[label[word_idx]] if data_args.label_all_tokens else -100)
previous_word_idx = word_idx
labels.append(label_ids)
tokenized_inputs["labels"] = labels
return tokenized_inputs
train_dataset = datasets["train"]
train_dataset = train_dataset.map(tokenize_and_align_labels, batched=True)
valid_dataset = datasets["validation"]
valid_dataset = valid_dataset.map(tokenize_and_align_labels, batched=True)
test_dataset = datasets["test"]
test_dataset = test_dataset.map(tokenize_and_align_labels, batched=True)
# Data collator
data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8 if training_args.fp16 else None)
# Metrics
metric = load_metric("seqeval")
def compute_metrics(p):
predictions, labels = p
predictions = np.argmax(predictions, axis=2)
# Remove ignored index (special tokens)
true_predictions = [
[label_list[p] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(predictions, labels)
]
true_labels = [
[label_list[l] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(predictions, labels)
]
results = metric.compute(predictions=true_predictions, references=true_labels)
return {
"precision": results["overall_precision"],
"recall": results["overall_recall"],
"f1": results["overall_f1"],
"accuracy": results["overall_accuracy"],
}
# Early stopping
early_stopping = EarlyStoppingCallback(
early_stopping_patience=additional_training_args.early_stopping_patience,
early_stopping_threshold=additional_training_args.early_stopping_threshold,
)
callbacks = [early_stopping]
# Initialize Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=valid_dataset,
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics,
callbacks=callbacks,
)
trainer.args.run_name = authorizer.username
# Training
train_result = trainer.train()
metrics = train_result.metrics
trainer.save_model() # Saves the tokenizer too for easy upload
metrics["train_samples"] = len(train_dataset)
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
# Evaluation
logger.info("*** Evaluate ***")
metrics = trainer.evaluate(eval_dataset=test_dataset)
metrics["eval_samples"] = len(test_dataset)
trainer.log_metrics("eval", metrics)
trainer.save_metrics("eval", metrics)
def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
model_args, data_args, training_args, additional_training_args = parse_arguments()
run(model_args, data_args, training_args, additional_training_args)
if __name__ == "__main__":
main()