-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_trainer.py
182 lines (139 loc) · 6.1 KB
/
run_trainer.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
""" Treinamento do modelo
Este arquivo diz respeito ao processo de treinamento de um modelo BERT.
"""
#import re
from dataset import AnBertDataset
from transformers import AutoModelForMaskedLM, Trainer, BertTokenizer, DataCollatorForLanguageModeling, TrainingArguments
#import tensorflow as tf
import numpy as np
#from pathlib import Path
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import nltk, torch, logging, time
def validate(ds, model, batch_size):
accuracy = 0.0
f1score = 0.0
recall = 0.0
loss = 0.0
precision = 0.0
t0 = time.time()
tds = TensorDataset(torch.tensor(ds["input_ids"]),
torch.tensor(ds["attention_mask"]),
torch.tensor(ds["labels"]))
validation_dl = DataLoader(
tds, # The validation samples.
sampler = SequentialSampler(tds), # Pull out batches sequentially.
batch_size = batch_size # Evaluate with this batch size.
)
for batch in validation_dl:
b_labels = batch[2].to(device)
b_input_ids = batch[0].to(device)
b_input_mask = batch[1].to(device)
with torch.no_grad():
result = model(b_input_ids,
token_type_ids=None,
attention_mask=b_input_mask,
labels=b_labels,
return_dict=True)
logits = result.logits.detach().cpu().numpy()
loss += result.loss
labels = b_labels.to('cpu').numpy().flatten()
preds = np.argmax(logits, axis=-1).flatten()
pr, rc, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted',zero_division=0)
acc = accuracy_score(labels, preds)
f1score += f1
recall += rc
precision += pr
accuracy += acc
return {
'eval_accuracy': accuracy/len(validation_dl),
'eval_f1': f1score/len(validation_dl),
'eval_precision': precision/len(validation_dl),
'eval_recall': recall/len(validation_dl),
'eval_loss': loss/len(validation_dl),
'eval_runtime': (time.time()-t0)
}
def print_validate(eval):
results = ["Tempo total de validação: {:.3f}s .",
"Acurácia: {:.3f}.", "F1 Score: {:.3f}.",
"Recall: {:.3f}.", "Precisão: {:.3f}."]
log.info("\n".join(results).format(eval["eval_runtime"],eval["eval_accuracy"],eval["eval_f1"],
eval["eval_recall"],eval["eval_precision"]))
def compute_metrics(pred):
labels = pred.label_ids.flatten()
preds = pred.predictions.argmax(-1).flatten()
precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted')
acc = accuracy_score(labels, preds)
return {
'accuracy': acc,
'f1': f1,
'precision': precision,
'recall': recall
}
if __name__ == '__main__':
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
format='########\n %(asctime)s: %(message)s')
log = logging.getLogger('monitor')
log.info("Baixando o Punkt para separar frases.")
parser = ArgumentParser()
modelArguments(parser)
nltk.download('punkt')
args = getParametros()
log.info("Carregando modelo do Bert {0}.".format(args.bert_model))
model = AutoModelForMaskedLM.from_pretrained(args.bert_model)
device = "cuda:0" if torch.cuda.is_available() else "cpu"
model = model.to(device)
log.info("Baixnado tokenizer.")
tokenizer = BertTokenizer.from_pretrained(args.bert_model)
if args.train_dataset is None:
log.info("Carregando o dataset a partir do diretório {0}.".format(args.train_path))
ads = AnBertDataset(tokenizer, path = args.train_path, block_size= args.max_seq_length, file=args.train_file)
ads.load_dataset()
else:
ads = AnBertDataset(tokenizer, block_size=args.max_seq_length)
ads.load_file(args.train_dataset)
log.info("Gerando o dataset para modelos do tipo Label Masked.")
tokenized_samples = ads.getLabelMaskedDataset(target='train')
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15)
# @TODO: Trocar este pedaço de código pela outra forma de treinamento.
# Conforme está no caderno do google colab
# Show the training loss with every epoch
logging_steps = len(tokenized_samples["train"]) // args.batch_size
model_name = args.bert_model.split("/")[-1]
training_args = TrainingArguments(
output_dir=f"{model_name}-finetuned-an",
overwrite_output_dir=True,
evaluation_strategy="epoch",
learning_rate=args.learning_rate,
weight_decay=0.01,
per_device_train_batch_size=args.batch_size,
per_device_eval_batch_size=args.per_gpu_train_batch_size,
fp16=args.fp16,
num_train_epochs=args.num_train_epochs,
save_strategy='no',
logging_steps=logging_steps
)
if args.do_train or args.do_eval:
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_samples["train"],
eval_dataset=tokenized_samples["test"],
data_collator=data_collator,
compute_metrics=compute_metrics
)
if args.do_train:
log.info("Preparando o treinamento.")
log.info("Inicializando o treinamento.")
try:
trainer.train()
except:
print("")
#log.info("Finalizando o treinamento.")
#validate(trainer.evaluate())
if args.do_eval:
log.info("iniciando a validação.")
ads.block_size = args.eval_max_seq_length
tokenized_samples = ads.getLabelMaskedDataset(target='train')
print_validate(validate(tokenized_samples['validate'],model,args.eval_batch_size))