-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtrain_ncc.py
276 lines (229 loc) · 10.3 KB
/
train_ncc.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
# Copyright 2020 The HuggingFace Inc. 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/text-classification/run_glue.py
import logging
import os
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,
AutoModelForSequenceClassification,
AutoTokenizer,
EarlyStoppingCallback,
HfArgumentParser,
PreTrainedTokenizerFast,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import is_main_process
from tokenization_albert_bengali_fast import AlbertBengaliTokenizerFast
from huggingface_auth import authorize_with_huggingface
logger = logging.getLogger(__name__)
os.environ["WANDB_PROJECT"] = "sahajBERT2-xlarge-ncc"
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."})
from lib.models.lean_albert import LeanAlbertConfig, LeanAlbertModel
from transformers import AlbertForSequenceClassification, PreTrainedModel
class LeanAlbertForSequenceClassification(AlbertForSequenceClassification, PreTrainedModel):
def __init__(self, config: LeanAlbertConfig):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.albert = LeanAlbertModel(config, add_pooling_layer=True)
self.dropout = nn.Dropout(config.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.
Using `HfArgumentParser` we can turn this class
into argparse arguments to be able to specify them on
the command line.
"""
task_name: Optional[str] = field(default="ncc", metadata={"help": "The name of the task to train on: ncc"})
dataset_name: Optional[str] = field(
default="indic_glue", metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
default="sna.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 `max_seq_length`. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
},
)
def __post_init__(self):
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)
# Labels
text_column_name = "text"
label_column_name = "label"
label_list = datasets["train"].features[label_column_name].names
num_labels = len(label_list)
# No need to convert the labels since they are already ints.
label_to_id = {i: i for i in range(num_labels)}
# 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 = LeanAlbertForSequenceClassification.from_pretrained(model_args.model_name_or_path, config=config)
# Preprocessing the datasets
# 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)
def preprocess_function(examples):
# Tokenize the texts
result = tokenizer(examples[text_column_name], padding=padding, max_length=max_seq_length, truncation=True)
# Map labels to IDs (not necessary for GLUE tasks)
if label_to_id is not None and "label" in examples:
result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]]
return result
train_dataset = datasets["train"]
train_dataset = train_dataset.map(preprocess_function, batched=True)
valid_dataset = datasets["validation"]
valid_dataset = valid_dataset.map(preprocess_function, batched=True)
test_dataset = datasets["test"]
test_dataset = test_dataset.map(preprocess_function, batched=True)
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding
data_collator = default_data_collator if data_args.pad_to_max_length else None
# Metrics
metric = load_metric("accuracy")
def compute_metrics(p):
preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
preds = np.argmax(preds, axis=1)
result = metric.compute(predictions=preds, references=p.label_ids)
if len(result) > 1:
result["combined_score"] = np.mean(list(result.values())).item()
return result
# 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,
compute_metrics=compute_metrics,
tokenizer=tokenizer,
data_collator=data_collator,
callbacks=callbacks,
)
trainer.args.run_name = authorizer.username
# Training
train_result = trainer.train()
metrics = train_result.metrics
metrics["train_samples"] = len(train_dataset)
trainer.save_model() # Saves the tokenizer too for easy upload
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()