-
Notifications
You must be signed in to change notification settings - Fork 75
/
run.py
274 lines (235 loc) · 11.8 KB
/
run.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
import ujson as json
import numpy as np
from tqdm import tqdm
import os
from torch import optim, nn
from model import Model #, NoCharModel, NoSelfModel
from sp_model import SPModel
# from normal_model import NormalModel, NoSelfModel, NoCharModel, NoSentModel
# from oracle_model import OracleModel, OracleModelV2
# from util import get_record_parser, convert_tokens, evaluate, get_batch_dataset, get_dataset
from util import convert_tokens, evaluate
from util import get_buckets, DataIterator, IGNORE_INDEX
import time
import shutil
import random
import torch
from torch.autograd import Variable
import sys
from torch.nn import functional as F
def create_exp_dir(path, scripts_to_save=None):
if not os.path.exists(path):
os.mkdir(path)
print('Experiment dir : {}'.format(path))
if scripts_to_save is not None:
if not os.path.exists(os.path.join(path, 'scripts')):
os.mkdir(os.path.join(path, 'scripts'))
for script in scripts_to_save:
dst_file = os.path.join(path, 'scripts', os.path.basename(script))
shutil.copyfile(script, dst_file)
nll_sum = nn.CrossEntropyLoss(size_average=False, ignore_index=IGNORE_INDEX)
nll_average = nn.CrossEntropyLoss(size_average=True, ignore_index=IGNORE_INDEX)
nll_all = nn.CrossEntropyLoss(reduce=False, ignore_index=IGNORE_INDEX)
def train(config):
with open(config.word_emb_file, "r") as fh:
word_mat = np.array(json.load(fh), dtype=np.float32)
with open(config.char_emb_file, "r") as fh:
char_mat = np.array(json.load(fh), dtype=np.float32)
with open(config.dev_eval_file, "r") as fh:
dev_eval_file = json.load(fh)
with open(config.idx2word_file, 'r') as fh:
idx2word_dict = json.load(fh)
random.seed(config.seed)
np.random.seed(config.seed)
torch.manual_seed(config.seed)
torch.cuda.manual_seed_all(config.seed)
config.save = '{}-{}'.format(config.save, time.strftime("%Y%m%d-%H%M%S"))
create_exp_dir(config.save, scripts_to_save=['run.py', 'model.py', 'util.py', 'sp_model.py'])
def logging(s, print_=True, log_=True):
if print_:
print(s)
if log_:
with open(os.path.join(config.save, 'log.txt'), 'a+') as f_log:
f_log.write(s + '\n')
logging('Config')
for k, v in config.__dict__.items():
logging(' - {} : {}'.format(k, v))
logging("Building model...")
train_buckets = get_buckets(config.train_record_file)
dev_buckets = get_buckets(config.dev_record_file)
def build_train_iterator():
return DataIterator(train_buckets, config.batch_size, config.para_limit, config.ques_limit, config.char_limit, True, config.sent_limit)
def build_dev_iterator():
return DataIterator(dev_buckets, config.batch_size, config.para_limit, config.ques_limit, config.char_limit, False, config.sent_limit)
if config.sp_lambda > 0:
model = SPModel(config, word_mat, char_mat)
else:
model = Model(config, word_mat, char_mat)
logging('nparams {}'.format(sum([p.nelement() for p in model.parameters() if p.requires_grad])))
ori_model = model.cuda()
model = nn.DataParallel(ori_model)
lr = config.init_lr
optimizer = optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=config.init_lr)
cur_patience = 0
total_loss = 0
global_step = 0
best_dev_F1 = None
stop_train = False
start_time = time.time()
eval_start_time = time.time()
model.train()
for epoch in range(10000):
for data in build_train_iterator():
context_idxs = Variable(data['context_idxs'])
ques_idxs = Variable(data['ques_idxs'])
context_char_idxs = Variable(data['context_char_idxs'])
ques_char_idxs = Variable(data['ques_char_idxs'])
context_lens = Variable(data['context_lens'])
y1 = Variable(data['y1'])
y2 = Variable(data['y2'])
q_type = Variable(data['q_type'])
is_support = Variable(data['is_support'])
start_mapping = Variable(data['start_mapping'])
end_mapping = Variable(data['end_mapping'])
all_mapping = Variable(data['all_mapping'])
logit1, logit2, predict_type, predict_support = model(context_idxs, ques_idxs, context_char_idxs, ques_char_idxs, context_lens, start_mapping, end_mapping, all_mapping, return_yp=False)
loss_1 = (nll_sum(predict_type, q_type) + nll_sum(logit1, y1) + nll_sum(logit2, y2)) / context_idxs.size(0)
loss_2 = nll_average(predict_support.view(-1, 2), is_support.view(-1))
loss = loss_1 + config.sp_lambda * loss_2
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.data[0]
global_step += 1
if global_step % config.period == 0:
cur_loss = total_loss / config.period
elapsed = time.time() - start_time
logging('| epoch {:3d} | step {:6d} | lr {:05.5f} | ms/batch {:5.2f} | train loss {:8.3f}'.format(epoch, global_step, lr, elapsed*1000/config.period, cur_loss))
total_loss = 0
start_time = time.time()
if global_step % config.checkpoint == 0:
model.eval()
metrics = evaluate_batch(build_dev_iterator(), model, 0, dev_eval_file, config)
model.train()
logging('-' * 89)
logging('| eval {:6d} in epoch {:3d} | time: {:5.2f}s | dev loss {:8.3f} | EM {:.4f} | F1 {:.4f}'.format(global_step//config.checkpoint,
epoch, time.time()-eval_start_time, metrics['loss'], metrics['exact_match'], metrics['f1']))
logging('-' * 89)
eval_start_time = time.time()
dev_F1 = metrics['f1']
if best_dev_F1 is None or dev_F1 > best_dev_F1:
best_dev_F1 = dev_F1
torch.save(ori_model.state_dict(), os.path.join(config.save, 'model.pt'))
cur_patience = 0
else:
cur_patience += 1
if cur_patience >= config.patience:
lr /= 2.0
for param_group in optimizer.param_groups:
param_group['lr'] = lr
if lr < config.init_lr * 1e-2:
stop_train = True
break
cur_patience = 0
if stop_train: break
logging('best_dev_F1 {}'.format(best_dev_F1))
def evaluate_batch(data_source, model, max_batches, eval_file, config):
answer_dict = {}
sp_dict = {}
total_loss, step_cnt = 0, 0
iter = data_source
for step, data in enumerate(iter):
if step >= max_batches and max_batches > 0: break
context_idxs = Variable(data['context_idxs'], volatile=True)
ques_idxs = Variable(data['ques_idxs'], volatile=True)
context_char_idxs = Variable(data['context_char_idxs'], volatile=True)
ques_char_idxs = Variable(data['ques_char_idxs'], volatile=True)
context_lens = Variable(data['context_lens'], volatile=True)
y1 = Variable(data['y1'], volatile=True)
y2 = Variable(data['y2'], volatile=True)
q_type = Variable(data['q_type'], volatile=True)
is_support = Variable(data['is_support'], volatile=True)
start_mapping = Variable(data['start_mapping'], volatile=True)
end_mapping = Variable(data['end_mapping'], volatile=True)
all_mapping = Variable(data['all_mapping'], volatile=True)
logit1, logit2, predict_type, predict_support, yp1, yp2 = model(context_idxs, ques_idxs, context_char_idxs, ques_char_idxs, context_lens, start_mapping, end_mapping, all_mapping, return_yp=True)
loss = (nll_sum(predict_type, q_type) + nll_sum(logit1, y1) + nll_sum(logit2, y2)) / context_idxs.size(0) + config.sp_lambda * nll_average(predict_support.view(-1, 2), is_support.view(-1))
answer_dict_ = convert_tokens(eval_file, data['ids'], yp1.data.cpu().numpy().tolist(), yp2.data.cpu().numpy().tolist(), np.argmax(predict_type.data.cpu().numpy(), 1))
answer_dict.update(answer_dict_)
total_loss += loss.data[0]
step_cnt += 1
loss = total_loss / step_cnt
metrics = evaluate(eval_file, answer_dict)
metrics['loss'] = loss
return metrics
def predict(data_source, model, eval_file, config, prediction_file):
answer_dict = {}
sp_dict = {}
sp_th = config.sp_threshold
for step, data in enumerate(tqdm(data_source)):
context_idxs = Variable(data['context_idxs'], volatile=True)
ques_idxs = Variable(data['ques_idxs'], volatile=True)
context_char_idxs = Variable(data['context_char_idxs'], volatile=True)
ques_char_idxs = Variable(data['ques_char_idxs'], volatile=True)
context_lens = Variable(data['context_lens'], volatile=True)
start_mapping = Variable(data['start_mapping'], volatile=True)
end_mapping = Variable(data['end_mapping'], volatile=True)
all_mapping = Variable(data['all_mapping'], volatile=True)
logit1, logit2, predict_type, predict_support, yp1, yp2 = model(context_idxs, ques_idxs, context_char_idxs, ques_char_idxs, context_lens, start_mapping, end_mapping, all_mapping, return_yp=True)
answer_dict_ = convert_tokens(eval_file, data['ids'], yp1.data.cpu().numpy().tolist(), yp2.data.cpu().numpy().tolist(), np.argmax(predict_type.data.cpu().numpy(), 1))
answer_dict.update(answer_dict_)
predict_support_np = torch.sigmoid(predict_support[:, :, 1]).data.cpu().numpy()
for i in range(predict_support_np.shape[0]):
cur_sp_pred = []
cur_id = data['ids'][i]
for j in range(predict_support_np.shape[1]):
if j >= len(eval_file[cur_id]['sent2title_ids']): break
if predict_support_np[i, j] > sp_th:
cur_sp_pred.append(eval_file[cur_id]['sent2title_ids'][j])
sp_dict.update({cur_id: cur_sp_pred})
prediction = {'answer': answer_dict, 'sp': sp_dict}
with open(prediction_file, 'w') as f:
json.dump(prediction, f)
def test(config):
with open(config.word_emb_file, "r") as fh:
word_mat = np.array(json.load(fh), dtype=np.float32)
with open(config.char_emb_file, "r") as fh:
char_mat = np.array(json.load(fh), dtype=np.float32)
if config.data_split == 'dev':
with open(config.dev_eval_file, "r") as fh:
dev_eval_file = json.load(fh)
else:
with open(config.test_eval_file, 'r') as fh:
dev_eval_file = json.load(fh)
with open(config.idx2word_file, 'r') as fh:
idx2word_dict = json.load(fh)
random.seed(config.seed)
np.random.seed(config.seed)
torch.manual_seed(config.seed)
torch.cuda.manual_seed_all(config.seed)
def logging(s, print_=True, log_=True):
if print_:
print(s)
if log_:
with open(os.path.join(config.save, 'log.txt'), 'a+') as f_log:
f_log.write(s + '\n')
if config.data_split == 'dev':
dev_buckets = get_buckets(config.dev_record_file)
para_limit = config.para_limit
ques_limit = config.ques_limit
elif config.data_split == 'test':
para_limit = None
ques_limit = None
dev_buckets = get_buckets(config.test_record_file)
def build_dev_iterator():
return DataIterator(dev_buckets, config.batch_size, para_limit,
ques_limit, config.char_limit, False, config.sent_limit)
if config.sp_lambda > 0:
model = SPModel(config, word_mat, char_mat)
else:
model = Model(config, word_mat, char_mat)
ori_model = model.cuda()
ori_model.load_state_dict(torch.load(os.path.join(config.save, 'model.pt')))
model = nn.DataParallel(ori_model)
model.eval()
predict(build_dev_iterator(), model, dev_eval_file, config, config.prediction_file)