-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
332 lines (268 loc) · 14.4 KB
/
main.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
330
331
332
import random
import json
import logging
import sys
import os
import torch
import argparse
import pickle
import numpy as np
from utils.metrics import *
from utils.helper import *
from dataloader import *
from pfn import PFN
import torch.optim as optim
from tqdm import tqdm
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
def evaluate(test_batch, rel2idx, ner2idx, args, test_or_dev):
steps, test_loss = 0, 0
total_triple_num = [0, 0, 0]
total_entity_num = [0, 0, 0]
if args.eval_metric == "macro":
total_triple_num *= len(rel2idx)
total_entity_num *= len(ner2idx)
if args.eval_metric == "micro":
metric = micro(rel2idx, ner2idx)
else:
metric = macro(rel2idx, ner2idx)
with torch.no_grad():
for data in test_batch:
steps += 1
# Inference
if args.mode == 'pretrained_frozen_emb':
emb = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
mask = data[-1].to(device)
ner_pred, re_pred = model(emb, mask, [], [], [])
elif args.mode == 'e2e_training':
text = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
mask = data[-1].to(device)
ner_pred, re_pred = model(text, mask, [], [], [])
elif args.mode == 'e2e_training_word_level':
if args.embed_mode == 'characterBERT':
words = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
attention_masks = data[3]
mask = data[-1].to(device)
ner_pred, re_pred = model(words, mask, attention_masks, [], [])
elif args.embed_mode.split('_')[0] == 'canine':
words = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
word_ranges = data[3]
mask = data[-1].to(device)
ner_pred, re_pred = model(words, mask, [], word_ranges, [])
else:
words = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
mask = data[3].to(device)
word_to_bep = data[-1]
ner_pred, re_pred = model(words, mask, [], word_to_bep, [])
# Evaluation
loss = BCEloss(ner_pred, ner_label, re_pred, re_label)
test_loss += loss
entity_num = metric.count_ner_num(ner_pred, ner_label)
triple_num = metric.count_num(ner_pred, ner_label, re_pred, re_label)
for i in range(len(entity_num)):
total_entity_num[i] += entity_num[i]
for i in range(len(triple_num)):
total_triple_num[i] += triple_num[i]
triple_result = f1(total_triple_num)
entity_result = f1(total_entity_num)
logger.info("------ {} Results ------".format(test_or_dev))
logger.info("loss : {:.4f}".format(test_loss / steps))
logger.info(
"entity: p={:.4f}, r={:.4f}, f={:.4f}".format(entity_result["p"], entity_result["r"], entity_result["f"]))
logger.info(
"triple: p={:.4f}, r={:.4f}, f={:.4f}".format(triple_result["p"], triple_result["r"], triple_result["f"]))
return triple_result, entity_result, test_loss / steps
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--data", default=None, type=str, required=True,
help="which dataset to use")
parser.add_argument("--epoch", default=100, type=int,
help="number of training epoch")
parser.add_argument("--hidden_size", default=300, type=int,
help="number of hidden neurons in the model")
parser.add_argument("--batch_size", default=20, type=int,
help="number of samples in one training batch")
parser.add_argument("--eval_batch_size", default=10, type=int,
help="number of samples in one testing batch")
parser.add_argument("--do_train", action="store_true",
help="whether or not to train from scratch")
parser.add_argument("--do_eval", action="store_true",
help="whether or not to evaluate the model")
parser.add_argument("--embed_mode", default=None, type=str, required=True,
help="BERT, ALBERT, CharacterBERT, Bio Clinical BERT, CANINE-C, CANINE-S // accepted values: bert_cased, albert, characterBERT, biobert, canine_c, canine_s")
parser.add_argument("--eval_metric", default="micro", type=str,
help="micro f1 or macro f1")
parser.add_argument("--lr", default=None, type=float,
help="initial learning rate")
parser.add_argument("--weight_decay", default=0, type=float,
help="weight decaying rate")
parser.add_argument("--linear_warmup_rate", default=0.0, type=float,
help="warmup at the start of training")
parser.add_argument("--seed", default=0, type=int,
help="random seed initiation")
parser.add_argument("--dropout", default=0.1, type=float,
help="dropout rate for input word embedding")
parser.add_argument("--dropconnect", default=0.1, type=float,
help="dropconnect rate for partition filter layer")
parser.add_argument("--steps", default=50, type=int,
help="show result for every 50 steps")
parser.add_argument("--output_file", default="test", type=str, required=True,
help="name of result file")
parser.add_argument("--clip", default=0.25, type=float,
help="grad norm clipping to avoid gradient explosion")
parser.add_argument("--max_seq_len", default=128, type=int,
help="maximum length of sequence")
parser.add_argument("--split_id", default=0, type=int, required=False,
help="the id of the split if cross-validation is applied")
parser.add_argument("--mode", default=None, type=str, required=True,
help="training mode, accepted values: pretrained_frozen_emb, e2e_training, e2e_training_word_level")
parser.add_argument("--sub_mode", default=None, type=str, required=False,
help="sub-mode of the 'pretrained_frozen_emb' mode, accepted values: word_level")
parser.add_argument("--word_pieces_aggregation", default='avg', type=str,
help="aggregation strategy in case of word-pieces split, accepted values: avg (average), sum (summation)")
parser.add_argument("--offline_emb_path", default=None, type=str, required=False,
help="the path where the pretrained extracted embeddings are stored")
args = parser.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
set_seed(args.seed)
output_dir = "save/" + args.output_file
# Create the output directory if it doesn't exist.
if not os.path.exists(output_dir):
os.makedirs(output_dir)
logger.addHandler(logging.FileHandler(output_dir + "/" + args.output_file + ".log", 'w'))
logger.info(sys.argv)
logger.info(args)
saved_file = save_results(output_dir + "/" + args.output_file + ".txt",
header="# epoch \t train_loss \t dev_loss \t test_loss \t dev_ner \t dev_rel \t test_ner \t test_rel")
model_file = args.output_file + ".pt"
with open("data/" + args.data + "/ner2idx.json", "r") as f:
ner2idx = json.load(f)
with open("data/" + args.data + "/rel2idx.json", "r") as f:
rel2idx = json.load(f)
train_batch, test_batch, dev_batch = dataloader(args, ner2idx, rel2idx)
if args.do_train:
logger.info("------Training------")
if args.mode == 'pretrained_frozen_emb':
if args.sub_mode == 'word_level':
if args.embed_mode == 'albert':
input_size = 4096
else:
input_size = 768
elif args.mode == 'e2e_training':
if args.embed_mode == 'albert':
input_size = 4096
else:
input_size = 768
elif args.mode == 'e2e_training_word_level':
if args.embed_mode == 'albert':
input_size = 4096
else:
input_size = 768
model = PFN(args, input_size, ner2idx, rel2idx)
model.to(device)
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
if args.eval_metric == "micro":
metric = micro(rel2idx, ner2idx)
else:
metric = macro(rel2idx, ner2idx)
BCEloss = loss()
best_result = 0
triple_best = None
entity_best = None
# Training
for epoch in range(args.epoch):
steps, train_loss = 0, 0
model.train()
for data in tqdm(train_batch):
steps += 1
optimizer.zero_grad()
if args.mode == 'pretrained_frozen_emb':
emb = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
mask = data[-1].to(device)
ner_pred, re_pred = model(emb, mask, [], [], [])
elif args.mode == 'e2e_training':
text = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
mask = data[-1].to(device)
ner_pred, re_pred = model(text, mask, [], [], [])
elif args.mode == 'e2e_training_word_level':
if args.embed_mode == 'characterBERT':
words = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
attention_masks = data[3]
mask = data[-1].to(device)
ner_pred, re_pred = model(words, mask, attention_masks, [], [])
elif args.embed_mode.split('_')[0] == 'canine':
words = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
word_ranges = data[3]
mask = data[-1].to(device)
ner_pred, re_pred = model(words, mask, [], word_ranges, [])
else:
words = data[0]
ner_label = data[1].to(device)
re_label = data[2].to(device)
mask = data[3].to(device)
word_to_bep = data[-1]
ner_pred, re_pred = model(words, mask, [], word_to_bep, [])
loss = BCEloss(ner_pred, ner_label, re_pred, re_label)
loss.backward()
train_loss += loss.item()
torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=args.clip)
optimizer.step()
if steps % args.steps == 0:
logger.info("Epoch: {}, step: {} / {}, loss = {:.4f}".format
(epoch, steps, len(train_batch), train_loss / steps))
logger.info("------ Training Set Results ------")
logger.info("loss : {:.4f}".format(train_loss / steps))
if args.do_eval:
model.eval()
logger.info("------ Testing ------")
dev_triple, dev_entity, dev_loss = evaluate(dev_batch, rel2idx, ner2idx, args, "dev")
test_triple, test_entity, test_loss = evaluate(test_batch, rel2idx, ner2idx, args, "test")
average_f1 = dev_triple["f"] + dev_entity["f"]
if epoch == 0 or average_f1 > best_result:
best_result = average_f1
triple_best = test_triple
entity_best = test_entity
torch.save(model.state_dict(), output_dir + "/" + model_file)
logger.info("Best result on dev saved!!!")
saved_file.save("{} \t {:.4f} \t {:.4f} \t {:.4f} \t {:.4f} \t {:.4f} \t {:.4f} \t {:.4f}".format(epoch,
train_loss / steps,
dev_loss,
test_loss,
dev_entity[
"f"],
dev_triple[
"f"],
test_entity[
"f"],
test_triple[
"f"]))
saved_file.save(
"best test result ner-p: {:.4f} \t ner-r: {:.4f} \t ner-f: {:.4f} \t re-p: {:.4f} \t re-r: {:.4f} \t re-f: {:.4f} ".format(
entity_best["p"],
entity_best["r"], entity_best["f"], triple_best["p"], triple_best["r"], triple_best["f"]))