-
Notifications
You must be signed in to change notification settings - Fork 48
/
trainers.py
303 lines (249 loc) · 12.3 KB
/
trainers.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
# -*- coding: utf-8 -*-
# @Time : 2020/3/30 11:06
# @Author : Hui Wang
import numpy as np
import tqdm
import random
import torch
import torch.nn as nn
from torch.optim import Adam
from utils import recall_at_k, ndcg_k, get_metric
class Trainer:
def __init__(self, model, train_dataloader,
eval_dataloader,
test_dataloader, args):
self.args = args
self.cuda_condition = torch.cuda.is_available() and not self.args.no_cuda
self.device = torch.device("cuda" if self.cuda_condition else "cpu")
self.model = model
if self.cuda_condition:
self.model.cuda()
# Setting the train and test data loader
self.train_dataloader = train_dataloader
self.eval_dataloader = eval_dataloader
self.test_dataloader = test_dataloader
# self.data_name = self.args.data_name
betas = (self.args.adam_beta1, self.args.adam_beta2)
self.optim = Adam(self.model.parameters(), lr=self.args.lr, betas=betas, weight_decay=self.args.weight_decay)
print("Total Parameters:", sum([p.nelement() for p in self.model.parameters()]))
self.criterion = nn.BCELoss()
def train(self, epoch):
self.iteration(epoch, self.train_dataloader)
def valid(self, epoch, full_sort=False):
return self.iteration(epoch, self.eval_dataloader, full_sort, train=False)
def test(self, epoch, full_sort=False):
return self.iteration(epoch, self.test_dataloader, full_sort, train=False)
def iteration(self, epoch, dataloader, full_sort=False, train=True):
raise NotImplementedError
def get_sample_scores(self, epoch, pred_list):
pred_list = (-pred_list).argsort().argsort()[:, 0]
HIT_1, NDCG_1, MRR = get_metric(pred_list, 1)
HIT_5, NDCG_5, MRR = get_metric(pred_list, 5)
HIT_10, NDCG_10, MRR = get_metric(pred_list, 10)
post_fix = {
"Epoch": epoch,
"HIT@1": '{:.4f}'.format(HIT_1), "NDCG@1": '{:.4f}'.format(NDCG_1),
"HIT@5": '{:.4f}'.format(HIT_5), "NDCG@5": '{:.4f}'.format(NDCG_5),
"HIT@10": '{:.4f}'.format(HIT_10), "NDCG@10": '{:.4f}'.format(NDCG_10),
"MRR": '{:.4f}'.format(MRR),
}
print(post_fix)
with open(self.args.log_file, 'a') as f:
f.write(str(post_fix) + '\n')
return [HIT_1, NDCG_1, HIT_5, NDCG_5, HIT_10, NDCG_10, MRR], str(post_fix)
def get_full_sort_score(self, epoch, answers, pred_list):
recall, ndcg = [], []
for k in [5, 10, 15, 20]:
recall.append(recall_at_k(answers, pred_list, k))
ndcg.append(ndcg_k(answers, pred_list, k))
post_fix = {
"Epoch": epoch,
"HIT@5": '{:.4f}'.format(recall[0]), "NDCG@5": '{:.4f}'.format(ndcg[0]),
"HIT@10": '{:.4f}'.format(recall[1]), "NDCG@10": '{:.4f}'.format(ndcg[1]),
"HIT@20": '{:.4f}'.format(recall[3]), "NDCG@20": '{:.4f}'.format(ndcg[3])
}
print(post_fix)
with open(self.args.log_file, 'a') as f:
f.write(str(post_fix) + '\n')
return [recall[0], ndcg[0], recall[1], ndcg[1], recall[3], ndcg[3]], str(post_fix)
def save(self, file_name):
torch.save(self.model.cpu().state_dict(), file_name)
self.model.to(self.device)
def load(self, file_name):
self.model.load_state_dict(torch.load(file_name))
def cross_entropy(self, seq_out, pos_ids, neg_ids):
# [batch seq_len hidden_size]
pos_emb = self.model.item_embeddings(pos_ids)
neg_emb = self.model.item_embeddings(neg_ids)
# [batch*seq_len hidden_size]
pos = pos_emb.view(-1, pos_emb.size(2))
neg = neg_emb.view(-1, neg_emb.size(2))
seq_emb = seq_out.view(-1, self.args.hidden_size) # [batch*seq_len hidden_size]
pos_logits = torch.sum(pos * seq_emb, -1) # [batch*seq_len]
neg_logits = torch.sum(neg * seq_emb, -1)
istarget = (pos_ids > 0).view(pos_ids.size(0) * self.model.args.max_seq_length).float() # [batch*seq_len]
loss = torch.sum(
- torch.log(torch.sigmoid(pos_logits) + 1e-24) * istarget -
torch.log(1 - torch.sigmoid(neg_logits) + 1e-24) * istarget
) / torch.sum(istarget)
return loss
def predict_sample(self, seq_out, test_neg_sample):
# [batch 100 hidden_size]
test_item_emb = self.model.item_embeddings(test_neg_sample)
# [batch hidden_size]
test_logits = torch.bmm(test_item_emb, seq_out.unsqueeze(-1)).squeeze(-1) # [B 100]
return test_logits
def predict_full(self, seq_out):
# [item_num hidden_size]
test_item_emb = self.model.item_embeddings.weight
# [batch hidden_size ]
rating_pred = torch.matmul(seq_out, test_item_emb.transpose(0, 1))
return rating_pred
class PretrainTrainer(Trainer):
def __init__(self, model,
train_dataloader,
eval_dataloader,
test_dataloader, args):
super(PretrainTrainer, self).__init__(
model,
train_dataloader,
eval_dataloader,
test_dataloader, args
)
def pretrain(self, epoch, pretrain_dataloader):
desc = f'AAP-{self.args.aap_weight}-' \
f'MIP-{self.args.mip_weight}-' \
f'MAP-{self.args.map_weight}-' \
f'SP-{self.args.sp_weight}'
pretrain_data_iter = tqdm.tqdm(enumerate(pretrain_dataloader),
desc=f"{self.args.model_name}-{self.args.data_name} Epoch:{epoch}",
total=len(pretrain_dataloader),
bar_format="{l_bar}{r_bar}")
self.model.train()
aap_loss_avg = 0.0
mip_loss_avg = 0.0
map_loss_avg = 0.0
sp_loss_avg = 0.0
for i, batch in pretrain_data_iter:
# 0. batch_data will be sent into the device(GPU or CPU)
batch = tuple(t.to(self.device) for t in batch)
attributes, masked_item_sequence, pos_items, neg_items, \
masked_segment_sequence, pos_segment, neg_segment = batch
aap_loss, mip_loss, map_loss, sp_loss = self.model.pretrain(attributes,
masked_item_sequence, pos_items, neg_items,
masked_segment_sequence, pos_segment, neg_segment)
joint_loss = self.args.aap_weight * aap_loss + \
self.args.mip_weight * mip_loss + \
self.args.map_weight * map_loss + \
self.args.sp_weight * sp_loss
self.optim.zero_grad()
joint_loss.backward()
self.optim.step()
aap_loss_avg += aap_loss.item()
mip_loss_avg += mip_loss.item()
map_loss_avg += map_loss.item()
sp_loss_avg += sp_loss.item()
num = len(pretrain_data_iter) * self.args.pre_batch_size
post_fix = {
"epoch": epoch,
"aap_loss_avg": '{:.4f}'.format(aap_loss_avg /num),
"mip_loss_avg": '{:.4f}'.format(mip_loss_avg /num),
"map_loss_avg": '{:.4f}'.format(map_loss_avg / num),
"sp_loss_avg": '{:.4f}'.format(sp_loss_avg / num),
}
print(desc)
print(str(post_fix))
with open(self.args.log_file, 'a') as f:
f.write(str(desc) + '\n')
f.write(str(post_fix) + '\n')
class FinetuneTrainer(Trainer):
def __init__(self, model,
train_dataloader,
eval_dataloader,
test_dataloader, args):
super(FinetuneTrainer, self).__init__(
model,
train_dataloader,
eval_dataloader,
test_dataloader, args
)
def iteration(self, epoch, dataloader, full_sort=False, train=True):
str_code = "train" if train else "test"
# Setting the tqdm progress bar
rec_data_iter = tqdm.tqdm(enumerate(dataloader),
desc="Recommendation EP_%s:%d" % (str_code, epoch),
total=len(dataloader),
bar_format="{l_bar}{r_bar}")
if train:
self.model.train()
rec_avg_loss = 0.0
rec_cur_loss = 0.0
for i, batch in rec_data_iter:
# 0. batch_data will be sent into the device(GPU or CPU)
batch = tuple(t.to(self.device) for t in batch)
_, input_ids, target_pos, target_neg, _ = batch
# Binary cross_entropy
sequence_output = self.model.finetune(input_ids)
loss = self.cross_entropy(sequence_output, target_pos, target_neg)
self.optim.zero_grad()
loss.backward()
self.optim.step()
rec_avg_loss += loss.item()
rec_cur_loss = loss.item()
post_fix = {
"epoch": epoch,
"rec_avg_loss": '{:.4f}'.format(rec_avg_loss / len(rec_data_iter)),
"rec_cur_loss": '{:.4f}'.format(rec_cur_loss),
}
if (epoch + 1) % self.args.log_freq == 0:
print(str(post_fix))
with open(self.args.log_file, 'a') as f:
f.write(str(post_fix) + '\n')
else:
self.model.eval()
pred_list = None
if full_sort:
answer_list = None
for i, batch in rec_data_iter:
# 0. batch_data will be sent into the device(GPU or cpu)
batch = tuple(t.to(self.device) for t in batch)
user_ids, input_ids, target_pos, target_neg, answers = batch
recommend_output = self.model.finetune(input_ids)
recommend_output = recommend_output[:, -1, :]
# 推荐的结果
rating_pred = self.predict_full(recommend_output)
rating_pred = rating_pred.cpu().data.numpy().copy()
batch_user_index = user_ids.cpu().numpy()
rating_pred[self.args.train_matrix[batch_user_index].toarray() > 0] = 0
# reference: https://stackoverflow.com/a/23734295, https://stackoverflow.com/a/20104162
# argpartition 时间复杂度O(n) argsort O(nlogn) 只会做
# 加负号"-"表示取大的值
ind = np.argpartition(rating_pred, -20)[:, -20:]
# 根据返回的下标 从对应维度分别取对应的值 得到每行topk的子表
arr_ind = rating_pred[np.arange(len(rating_pred))[:, None], ind]
# 对子表进行排序 得到从大到小的顺序
arr_ind_argsort = np.argsort(arr_ind)[np.arange(len(rating_pred)), ::-1]
# 再取一次 从ind中取回 原来的下标
batch_pred_list = ind[np.arange(len(rating_pred))[:, None], arr_ind_argsort]
if i == 0:
pred_list = batch_pred_list
answer_list = answers.cpu().data.numpy()
else:
pred_list = np.append(pred_list, batch_pred_list, axis=0)
answer_list = np.append(answer_list, answers.cpu().data.numpy(), axis=0)
return self.get_full_sort_score(epoch, answer_list, pred_list)
else:
for i, batch in rec_data_iter:
# 0. batch_data will be sent into the device(GPU or cpu)
batch = tuple(t.to(self.device) for t in batch)
user_ids, input_ids, target_pos, target_neg, answers, sample_negs = batch
recommend_output = self.model.finetune(input_ids)
test_neg_items = torch.cat((answers, sample_negs), -1)
recommend_output = recommend_output[:, -1, :]
test_logits = self.predict_sample(recommend_output, test_neg_items)
test_logits = test_logits.cpu().detach().numpy().copy()
if i == 0:
pred_list = test_logits
else:
pred_list = np.append(pred_list, test_logits, axis=0)
return self.get_sample_scores(epoch, pred_list)