-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine_utils.py
208 lines (169 loc) · 7.21 KB
/
engine_utils.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
import numpy as np
import torch
import random
import os
import logging
import argparse
from transformers import AdamW, get_linear_schedule_with_warmup
logger = logging.getLogger(__name__)
def set_seed(args):
os.environ['PYTHONHASHSEED'] = str(args.seed)
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
torch.backends.cudnn.deterministic = True
# default params
def arg_parse():
parser = argparse.ArgumentParser()
parser.add_argument("--baseline", action="store_true",
help="Whether to run training.")
# True for uncased BERT
parser.add_argument(
"--do_lower_case",
default=True,
# action="store_true",
help="Set this flag if you are using an uncased model."
)
parser.add_argument(
"--model_type",
default="bert",
type=str,
help="Model type selected in the list: [bert, roberta]",
)
parser.add_argument(
"--model_name_or_path",
default="/root/MODELS/bert-base-uncased/",
# default='bert-large-uncased',
type=str,
help="Path to pre-trained model or shortcut name",
)
parser.add_argument(
"--config_name", default="", type=str,
help="Pretrained config name or path if not the same as model_name"
)
parser.add_argument(
"--tokenizer_name",
default="",
type=str,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--max_seq_len",
default=128,
type=int,
help="The maximum total input sequence length after tokenization. "
"Sequences longer than this will be truncated, "
"sequences shorter will be padded.",
)
parser.add_argument(
"--max_span_len",
default=4,
type=int,
help="The maximum word num of a span.",
)
parser.add_argument("--bert_lr", default=1e-5, type=float,
help="The initial learning rate for BERT.")
parser.add_argument("--lr", default=1e-5, type=float,
help="The initial learning rate of classifier.")
parser.add_argument("--weight_decay", default=0.01, type=float,
help="Weight decay if we apply some.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float,
help="Epsilon for Adam optimizer.")
parser.add_argument("--max_grad_norm", default=1.0, type=float,
help="Max gradient norm.")
parser.add_argument("--warmup_steps", default=0.1, type=int,
help="Linear warmup over warmup_steps.")
parser.add_argument("--logging_steps", type=float, default=1.0,
help="Log every X updates steps.")
# TODO, try different seed
parser.add_argument("--seed", type=int, default=42,
help="random seed for initialization")
return parser
def prepare_optimizer_scheduler(args, model, training_steps):
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ["bias", "LayerNorm.weight"]
bert_parameters = eval('model.{}'.format(args.model_type)).named_parameters()
other_parameters = list(model.bn_encoder.named_parameters()) \
+ list(model.span_layer.named_parameters()) \
+ list(model.span_classifier.named_parameters()) \
+ list(model.oov_reg.named_parameters())
# + list(model.z_reg.named_parameters())
optimizer_grouped_parameters = [
# other params
{"params": [p for n, p in other_parameters if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
"lr": args.lr},
{"params": [p for n, p in other_parameters if any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
"lr": args.lr},
# bert params
{"params": [p for n, p in bert_parameters if
not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
"lr": args.bert_lr},
{"params": [p for n, p in bert_parameters if
any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
"lr": args.bert_lr},
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.lr, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=training_steps
)
return optimizer, scheduler
def model_save(args, output_dir, model, tokenizer):
# output_dir = args.output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
model_to_save = (
model.module if hasattr(model, "module") else model
) # Take care of distributed/parallel training
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, "training_args.bin"))
logger.info("Saving model checkpoint to %s", output_dir)
# save predictions result
def predictions_save(origin_file, predictions, output_file, labels):
pred_label_idx = [x['pred_label_idx'].tolist() for x in predictions]
all_span_idxs = [x['all_span_idxs'].tolist() for x in predictions]
span_label_ltoken = [x['span_label_ltoken'].tolist() for x in predictions]
# idx2label = {0:'O', 1:'ORG', 2:'PER', 3:'LOC', 4:'MISC'}
idx2label = {k: v for k, v in enumerate(labels)}
with open(output_file, "w") as writer:
with open(origin_file, "r") as f:
words = []
lines = []
for line in f:
if line.startswith("-DOCSTART-") or line == "" or line == "\n":
if words:
lines.append(words)
words = []
else:
splits = line.split()
if len(splits) not in [2, 4]:
print('line segs num {}'.format(len(splits)))
print(line)
words.append(splits[0])
if words:
lines.append(words)
cnt = 0
for i in range(len(pred_label_idx)):
for span_idxs, lps, lts in zip(all_span_idxs[i], pred_label_idx[i], span_label_ltoken[i]):
word_list = (lines[cnt])[:]
for sid, lp,lt in zip(span_idxs, lps, lts):
if lp != 0 or lt != 0:
plabel = idx2label[int(lp)]
tlabel = idx2label[int(lt)]
sidx, eidx = sid
for k in range(int(sidx), int(eidx) + 1):
word_list[k] = word_list[k] + ' ' + tlabel + ' ' + plabel
for k in range(len(word_list)):
if ' ' not in word_list[k]:
word_list[k] = word_list[k] + ' O O'
text = '\n'.join(word_list)
writer.write(text + '\n\n')
cnt += 1
f.close()
writer.close()