-
Notifications
You must be signed in to change notification settings - Fork 6
/
matchpyramid_rl.py
196 lines (158 loc) · 5.97 KB
/
matchpyramid_rl.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
from __future__ import print_function
import sys
import os
import shutil
import argparse
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from deeprank.dataset import DataLoader, PairGenerator, ListGenerator
from deeprank import utils
tag = 'model/matchpyramid_v1/'
if not os.path.isdir(tag):
os.mkdir(tag)
shutil.copy2('./matchpyramid_rl.py', tag+'matchpyramid_rl.py')
seed = 4321
#1.set random seed
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
loader = DataLoader('./config/letor07_mp_fold1.model')
import json
letor_config = json.loads(open('./config/letor07_mp_fold1.model').read())
#device = torch.device("cuda")
#device = torch.device("cpu")
select_device = torch.device("cpu")
rank_device = torch.device("cuda")
Letor07Path = letor_config['data_dir']
letor_config['fill_word'] = loader._PAD_
letor_config['embedding'] = loader.embedding
letor_config['feat_size'] = loader.feat_size
letor_config['vocab_size'] = loader.embedding.shape[0]
letor_config['embed_dim'] = loader.embedding.shape[1]
letor_config['pad_value'] = loader._PAD_
pair_gen = PairGenerator(rel_file=Letor07Path + '/relation.train.fold%d.txt'%(letor_config['fold']),
config=letor_config)
from deeprank import select_module
from deeprank import rank_module
letor_config['q_limit'] = 20
letor_config['d_limit'] = 2000
letor_config['max_match'] = 10
letor_config['win_size'] = 10
letor_config['q_rep_kernel'] = 1
letor_config['d_rep_kernel'] = letor_config['win_size']*2+1
letor_config['finetune_embed'] = False
letor_config['lr'] = 0.001
select_net = select_module.PointerNet(config=letor_config, out_device=rank_device)
select_net = select_net.to(select_device)
select_net.embedding.weight.data.copy_(torch.from_numpy(loader.embedding))
select_net.train()
#select_optimizer = optim.RMSprop(select_net.parameters(), lr=letor_config['lr'])
select_optimizer = optim.Adam(select_net.parameters(), lr=letor_config['lr'])
letor_config['simmat_channel'] = 1
letor_config['conv_params'] = [(8, 5, 5)]
letor_config['fc_params'] = []
letor_config['dpool_size'] = [3, 10]
letor_config['lr'] = 0.005
letor_config['finetune_embed'] = False
rank_net = rank_module.MatchPyramidNet(config=letor_config)
rank_net = rank_net.to(rank_device)
rank_net.embedding.weight.data.copy_(torch.from_numpy(loader.embedding))
rank_net.train()
rank_optimizer = optim.Adam(rank_net.parameters(), lr=letor_config['lr'])
log_file = open(tag + 'log.txt', 'w')
def print_log(*msg):
print(*msg)
print(*msg, file=log_file)
sys.stdout.flush()
def to_device(*variables, device):
return (torch.from_numpy(variable).to(device) for variable in variables)
def to_device_raw(*variables, device):
return (variable.to(device) for variable in variables)
def show_text(x):
print_log(' '.join([loader.word_dict[w.item()] for w in x]))
def evaluate_test(select_net_e, rank_net_e):
list_gen = ListGenerator(rel_file=Letor07Path+'/relation.test.fold%d.txt'%(letor_config['fold']),
config=letor_config)
map_v = 0.0
map_c = 0.0
with torch.no_grad():
for X1, X1_len, X1_id, X2, X2_len, X2_id, Y, F in \
list_gen.get_batch(data1=loader.query_data, data2=loader.doc_data):
#print_log(X1.shape, X2.shape, Y.shape)
X1, X1_len, X2, X2_len, Y, F = to_device(X1, X1_len, X2, X2_len, Y, F, device=select_device)
X1, X2, X1_len, X2_len = select_net_e(X1, X2, X1_len, X2_len, X1_id, X2_id)
X2, X2_len = utils.data_adaptor(X2, X2_len, select_net, rank_net, letor_config)
#print_log(X1.shape, X2.shape, Y.shape)
pred = rank_net_e(X1, X2, X1_len, X2_len)
map_o = utils.eval_MAP(pred.tolist(), Y.tolist())
#print_log(pred.shape, Y.shape)
map_v += map_o
map_c += 1.0
map_v /= map_c
print_log('[Test]', map_v)
return map_v
import time
rank_loss_list = []
select_loss_list = []
ret_map_list = []
it = 1000
start_t = time.time()
for i in range(10001):
print_log('[Iter]', i)
# One Step Forward
X1, X1_len, X1_id, X2, X2_len, X2_id, Y, F = \
pair_gen.get_batch(data1=loader.query_data, data2=loader.doc_data)
X1, X1_len, X2, X2_len, Y, F = \
to_device(X1, X1_len, X2, X2_len, Y, F, device=select_device)
X1, X2, X1_len, X2_len = select_net(X1, X2, X1_len, X2_len, X1_id, X2_id)
X2, X2_len = utils.data_adaptor(X2, X2_len, select_net, rank_net, letor_config)
output = rank_net(X1, X2, X1_len, X2_len)
reward = rank_net.pair_reward(output, mode=0)
# Update Rank Net
rank_loss = rank_net.pair_loss(output, Y)
print_log('[Rank Loss]', rank_loss.item())
rank_loss_list.append(rank_loss.item())
if True or i // it % 2 == 0:
#if i < 1000:
rank_optimizer.zero_grad()
rank_loss.backward()
rank_optimizer.step()
# Update Select Net
select_loss = select_net.loss(reward)
print_log('[Select Loss]', select_loss.item())
select_loss_list.append(select_loss.item())
if i // it % 2 == 1:
#if i >= 1000:
select_optimizer.zero_grad()
select_loss.backward()
select_optimizer.step()
if i % 200 == 0:
ret_map = evaluate_test(select_net, rank_net)
ret_map_list.append(ret_map)
end_t = time.time()
print_log('Time Cost: %s s' % (end_t-start_t))
fout = open(tag + 'select_loss.log', 'w')
for x in select_loss_list:
fout.write(str(x))
fout.write('\n')
fout.close()
fout = open(tag + 'rank_loss.log', 'w')
for x in rank_loss_list:
fout.write(str(x))
fout.write('\n')
fout.close()
fout = open(tag + 'map.log', 'w')
for x in ret_map_list:
fout.write(str(x))
fout.write('\n')
fout.close()
torch.save(select_net, tag + "select.model")
torch.save(rank_net, tag + "rank.model")
select_net_e = torch.load(f=tag + 'select.model')
rank_net_e = torch.load(f=tag + 'rank.model')
evaluate_test(select_net_e, rank_net_e)