-
Notifications
You must be signed in to change notification settings - Fork 2
/
train.py
223 lines (213 loc) · 10.6 KB
/
train.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
import argparse
import os
import numpy as np
import torch
import ujson as json
from torch.utils.data import DataLoader
from transformers import AutoConfig, AutoModel, AutoTokenizer
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from model import LACEModel
from utils import set_seed, collate_fn
from prepro import read_docred
from evaluation import to_official, official_evaluate
def train(args, model, train_features, dev_features, test_features):
def finetune(features, optimizer, num_epoch, num_steps):
best_score = -1
train_dataloader = DataLoader(features, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True)
train_iterator = range(int(num_epoch))
total_steps = int(len(train_dataloader) * num_epoch // args.gradient_accumulation_steps)
warmup_steps = int(total_steps * args.warmup_ratio)
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=total_steps)
for epoch in train_iterator:
model.zero_grad()
for step, batch in enumerate(train_dataloader):
model.train()
inputs = {'input_ids': batch[0].to(args.device),
'attention_mask': batch[1].to(args.device),
'labels': batch[2],
'entity_pos': batch[3],
'hts': batch[4],
}
outputs = model(**inputs)
loss = outputs[0] / args.gradient_accumulation_steps
loss.backward()
if step % args.gradient_accumulation_steps == 0:
if args.max_grad_norm > 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step()
model.zero_grad()
num_steps += 1
if (step + 1) == len(train_dataloader) - 1 or (args.evaluation_steps > 0 and num_steps % args.evaluation_steps == 0 and step % args.gradient_accumulation_steps == 0):
dev_score, dev_output = evaluate(args, model, dev_features, tag="dev")
if dev_score > best_score:
best_score = dev_score
pred = report(args, model, test_features)
with open(args.result_jsonfile, "w") as fh:
json.dump(pred, fh)
if args.save_path != "":
torch.save(model.state_dict(), args.save_path)
return num_steps
new_layer = ["extractor", "bilinear", "gat", "layer_norm", "linear"]
optimizer_grouped_parameters = [
{"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in new_layer)], },
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in new_layer)], "lr": 1e-4},
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
num_steps = 0
set_seed(args)
model.zero_grad()
finetune(train_features, optimizer, args.num_train_epochs, num_steps)
def evaluate(args, model, features, tag="dev"):
dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False)
preds = []
for batch in dataloader:
model.eval()
inputs = {'input_ids': batch[0].to(args.device),
'attention_mask': batch[1].to(args.device),
'entity_pos': batch[3],
'hts': batch[4],
}
with torch.no_grad():
pred, *_ = model(**inputs)
pred = pred.cpu().numpy()
pred[np.isnan(pred)] = 0
preds.append(pred)
preds = np.concatenate(preds, axis=0).astype(np.float32)
ans = to_official(preds, features)
if len(ans) > 0:
best_f1, _, best_f1_ign, _, re_p, re_r = official_evaluate(ans, args.data_dir)
else: best_f1, best_f1_ign = 0.0, 0.0
output = {
tag + "_F1": best_f1 * 100, 'precision:': re_p, 'recall:': re_r,
tag + "_F1_ign": best_f1_ign * 100,
}
return best_f1, output
def report(args, model, features):
dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False)
preds = []
for batch in dataloader:
model.eval()
inputs = {'input_ids': batch[0].to(args.device),
'attention_mask': batch[1].to(args.device),
'entity_pos': batch[3],
'hts': batch[4],
}
with torch.no_grad():
pred, *_ = model(**inputs)
pred = pred.cpu().numpy()
pred[np.isnan(pred)] = 0
preds.append(pred)
preds = np.concatenate(preds, axis=0).astype(np.float32)
preds = to_official(preds, features)
return preds
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", default="./dataset/docred", type=str)
parser.add_argument("--transformer_type", default="bert", type=str)
parser.add_argument("--model_name_or_path", default="bert-base-cased", type=str)
parser.add_argument("--train_file", default="train_annotated.json", type=str)
parser.add_argument("--dev_file", default="dev.json", type=str)
parser.add_argument("--test_file", default="test.json", type=str)
parser.add_argument("--save_path", default="", type=str)
parser.add_argument("--load_path", default="", type=str)
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_length", default=1024, 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("--train_batch_size", default=4, type=int,
help="Batch size for training.")
parser.add_argument("--test_batch_size", default=4, type=int, # default=8
help="Batch size for testing.")
parser.add_argument("--gradient_accumulation_steps", default=1, type=int,
help="Number of updates steps to accumulate before performing a backward/update pass.")
parser.add_argument("--num_labels", default=4, type=int,
help="Max number of labels in prediction.")
parser.add_argument("--learning_rate", default=5e-5, type=float,
help="The initial learning rate for Adam.")
parser.add_argument("--adam_epsilon", default=1e-6, 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_ratio", default=0.06, type=float,
help="Warm up ratio for Adam.")
parser.add_argument("--num_train_epochs", default=30.0, type=float,
help="Total number of training epochs to perform.")
parser.add_argument("--evaluation_steps", default=-1, type=int,
help="Number of training steps between evaluations.")
parser.add_argument("--seed", type=int, default=66,
help="random seed for initialization")
parser.add_argument("--num_class", type=int, default=97,
help="Number of relation types in dataset.")
parser.add_argument("--result_jsonfile", type=str, default="result.json",
help="save the generated result.json.")
args = parser.parse_args()
print('Loaded Model: ', args.load_path)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
args.n_gpu = torch.cuda.device_count()
args.device = device
config = AutoConfig.from_pretrained(
args.config_name if args.config_name else args.model_name_or_path,
num_labels=args.num_class,
)
tokenizer = AutoTokenizer.from_pretrained(
args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
)
read = read_docred
train_file = os.path.join(args.data_dir, args.train_file)
dev_file = os.path.join(args.data_dir, args.dev_file)
test_file = os.path.join(args.data_dir, args.test_file)
train_features = read(train_file, tokenizer, max_seq_length=args.max_seq_length)
for doc in train_features:
doc_labels = doc['labels']
doc_hts = doc['hts']
pos_label = []
neg_label = []
pos_hts = []
neg_hts = []
for i in range(len(doc_labels)):
if doc_labels[i][0] == 0:
pos_label.append(doc_labels[i])
pos_hts.append(doc_hts[i])
else:
neg_label.append(doc_labels[i])
neg_hts.append(doc_hts[i])
neg_label = neg_label[:10*len(pos_label)+5]
np.random.seed(10)
np.random.shuffle(neg_hts)
neg_hts = neg_hts[:10*len(pos_label)+5]
pos_and_neg_label = pos_label + neg_label
pos_and_neg_hts = pos_hts + neg_hts
state = np.random.get_state()
np.random.shuffle(pos_and_neg_label)
np.random.set_state(state)
np.random.shuffle(pos_and_neg_hts)
doc['labels'] = pos_and_neg_label
doc['hts'] = pos_and_neg_hts
dev_features = read(dev_file, tokenizer, max_seq_length=args.max_seq_length)
test_features = read(test_file, tokenizer, max_seq_length=args.max_seq_length)
model = AutoModel.from_pretrained(
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
)
config.cls_token_id = tokenizer.cls_token_id
config.sep_token_id = tokenizer.sep_token_id
config.transformer_type = args.transformer_type
set_seed(args)
model = LACEModel(config, model, num_labels=args.num_labels)
model.to(0)
if args.load_path == "":
train(args, model, train_features, dev_features, test_features)
else:
model.load_state_dict(torch.load(args.load_path))
dev_score, dev_output = evaluate(args, model, dev_features, tag="dev")
print('dev_score: ', dev_score, 'dev_output: ', dev_output)
pred = report(args, model, test_features)
with open(args.result_jsonfile, "w") as fh:
json.dump(pred, fh)
if __name__ == "__main__":
main()