forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listwise_l2r_op.cc
263 lines (222 loc) · 8.63 KB
/
listwise_l2r_op.cc
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
#include "caffe2/operators/listwise_l2r_op.h"
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
#include "caffe2/utils/eigen_utils.h"
namespace caffe2 {
namespace {
// Returns the indices that would sort an array. For example:
// data = [3, 1, 2, 4]
// return = [1, 2, 0, 3] (reverse = false)
// return = [3, 0, 2, 1] (reverse = true)
template <typename TDATA, typename TIDX>
void arg_sort(const TDATA* data, TIDX* idx, const size_t N, bool reverse) {
std::function<bool(size_t, size_t)> cmp_lambda;
if (reverse) {
cmp_lambda = [data](size_t i, size_t j) { return data[i] > data[j]; };
} else {
cmp_lambda = [data](size_t i, size_t j) { return data[i] < data[j]; };
}
size_t n = 0;
std::generate(idx, idx + N, [&n] { return n++; });
std::sort(idx, idx + N, cmp_lambda);
}
#define PAIRWISE_DIFF(vec, N) \
((vec.matrix() * Eigen::MatrixXf::Ones(1, N) - \
Eigen::MatrixXf::Ones(N, 1) * vec.matrix().transpose()) \
.array())
#define CWISE_SIGM(vec) (1. / (1. + (-(vec)).exp()))
#define CWISE_GT(vec1, vec2) ((vec1) > (vec2))
#define CWISE_LT(vec1, vec2) ((vec1) < (vec2))
#define CWISE_SIGN(vec) (CWISE_GT((vec), 0).cast<float>() * 2. - 1.)
#define CWISE_LOG_SIGM(vec, huge) \
(CWISE_GT((vec), (huge)) \
.select( \
0, CWISE_LT((vec), -(huge)).select(vec, CWISE_SIGM((vec)).log())))
} // namespace
template <>
void LambdaRankNdcgOp<float, CPUContext>::ResizeInvLogITensor(int size) {
int old_size = inv_log_i_.numel();
int new_size = std::max(old_size, 1);
while (new_size < size) {
new_size <<= 1;
}
if (new_size != old_size) {
ReinitializeTensor(&inv_log_i_, {new_size}, at::dtype<float>().device(CPU));
auto* data = inv_log_i_.template mutable_data<float>();
EigenVectorArrayMap<float> vec(data, inv_log_i_.numel());
const float log2f_ = std::log(2.f);
vec = log2f_ *
(Eigen::ArrayXf::LinSpaced(new_size, 2, 1 + new_size).log().inverse());
}
return;
}
template <>
void LambdaRankNdcgOp<float, CPUContext>::ComputeDiscounts(int* idx, int N) {
ReinitializeTensor(&discount_, {N}, at::dtype<float>().device(CPU));
auto* discount_data = discount_.template mutable_data<float>();
auto* inv_log_i_data = inv_log_i_.template mutable_data<float>();
for (int i = 0; i < N; i++) {
discount_data[idx[i]] = inv_log_i_data[i];
}
return;
}
template <>
float LambdaRankNdcgOp<float, CPUContext>::LambdaRankNdcgSession(
int start_index,
int end_index,
const Tensor& y,
const Tensor& r,
Tensor** dy) {
CAFFE_ENFORCE(start_index >= 0);
CAFFE_ENFORCE(start_index < y.numel());
const auto* y_data = y.template data<float>();
const auto* r_data = r.template data<float>();
int N = end_index - start_index + 1;
ConstEigenVectorArrayMap<float> y_vec(&y_data[start_index], N);
ConstEigenVectorArrayMap<float> r_vec(&r_data[start_index], N);
if (N <= 0) {
return 0;
}
ReinitializeTensor(&ideal_idx_, {N}, at::dtype<int>().device(CPU));
ReinitializeTensor(&rank_idx_, {N}, at::dtype<int>().device(CPU));
auto* rank_idx_data = rank_idx_.template mutable_data<int>();
auto* ideal_idx_data = ideal_idx_.template mutable_data<int>();
// current ranked list is obtained by sorting by current score
arg_sort(&y_data[start_index], rank_idx_data, N, true);
// ideal ranked list is same as sorting by label
arg_sort(&r_data[start_index], ideal_idx_data, N, true);
auto* dy_data = (*dy)->template mutable_data<float>();
EigenVectorArrayMap<float> dy_vec(&dy_data[start_index], N);
float loss = 0;
dy_vec = 0;
// in case that all docs in a session have zero ratings, no op
if (r_vec.abs().sum() < 1e-6) {
return 0;
}
const double log2f_ = std::log(2.f);
ReinitializeTensor(&gain_, {N}, at::dtype<float>().device(CPU));
auto* gain_data = gain_.template mutable_data<float>();
EigenVectorArrayMap<float> gain_vec(gain_data, gain_.numel());
if (use_ndcg_as_loss_ && !use_exp_gain_) {
gain_vec = r_vec;
} else {
// Gain vector = 2^rel = exp{rel * log(2)}
gain_vec = (r_vec * log2f_).exp();
}
ResizeInvLogITensor(N);
ComputeDiscounts(ideal_idx_data, N);
auto* ideal_discount_data = discount_.template mutable_data<float>();
EigenVectorArrayMap<float> ideal_discount_vec(
ideal_discount_data, discount_.numel());
// ideal dcg = \sum gain_i * ideal_discount_i
double idcg = (gain_vec * ideal_discount_vec).sum();
ComputeDiscounts(rank_idx_data, N);
auto* discount_data = discount_.template mutable_data<float>();
EigenVectorArrayMap<float> discount_vec(discount_data, discount_.numel());
// similar to ideal but replace with actual discounts
double dcg = (gain_vec * discount_vec).sum();
ReinitializeTensor(&lambda_, {N * N}, at::dtype<float>().device(CPU));
auto* lambda_data = lambda_.template mutable_data<float>();
EigenArrayMap<float> lambda_mat(lambda_data, N, N);
// computes lambda weight (i, j) = abs(gain_dff * discount_diff)
lambda_mat =
(PAIRWISE_DIFF(discount_vec, N) * PAIRWISE_DIFF(gain_vec, N)).abs();
// dy_i =
// \sum_j lambda_{i, j} -sign(i > j) * sigm( -sign(i > j)*(yi - yj) )
// |++ gradient of rank loss between i & j ++|
dy_vec =
-(lambda_mat * CWISE_SIGN(PAIRWISE_DIFF(r_vec, N)) *
CWISE_SIGM(
-CWISE_SIGN(PAIRWISE_DIFF(r_vec, N)) * PAIRWISE_DIFF(y_vec, N)))
.rowwise()
.sum();
if (use_ndcg_as_loss_) {
// DCG loss function
loss = (idcg - dcg);
} else {
loss = -(lambda_mat *
CWISE_LOG_SIGM(
CWISE_SIGN(PAIRWISE_DIFF(r_vec, N)) * PAIRWISE_DIFF(y_vec, N),
100))
.sum();
}
// if use_idcg_normalization_ is true, the loss function is normalized by idcg
// (e.g. NDCG), else un-normalized loss function (e.g. DCG)
// Note that normalization is mathematically correct if idcg is guaranteed to
// be positive!
if (use_idcg_normalization_) {
dy_vec /= std::max(idcg, 1e-5);
loss /= std::max(idcg, 1e-5);
}
return loss;
}
template <>
bool LambdaRankNdcgOp<float, CPUContext>::RunOnDevice() {
auto& y = Input(PRED);
auto& r = Input(REL);
auto& sid = Input(SESSION_LENS);
auto* dy = Output(DPRED);
const auto* session_lengths = sid.template data<int>();
CAFFE_ENFORCE(y.dim() == 1);
CAFFE_ENFORCE(y.numel() == r.numel());
dy->Resize(y.numel());
auto* loss = Output(LOSS, {sid.numel()}, at::dtype<float>());
auto loss_vec = loss->template mutable_data<float>();
int start_id = 0;
for (int i = 0; i < sid.numel(); i++) {
loss_vec[i] = LambdaRankNdcgSession(
start_id, session_lengths[i] + start_id - 1, y, r, &dy);
start_id += session_lengths[i];
}
return true;
}
template <>
bool LambdaRankNdcgGradientOp<float, CPUContext>::RunOnDevice() {
auto& y = Input(Y);
auto& sids = Input(SESSION_LENS);
auto& dy_cache = Input(DY_CACHE);
auto& dLoss = Input(DLOSS);
CAFFE_ENFORCE(y.dim() == 1);
CAFFE_ENFORCE(dy_cache.dim() == 1);
CAFFE_ENFORCE(dy_cache.numel() > 0);
CAFFE_ENFORCE(y.numel() == dy_cache.numel());
const auto* session_lengths = sids.template data<int>();
CAFFE_ENFORCE(dLoss.numel() == sids.numel());
ConstEigenVectorArrayMap<float> dy_cache_vec(
dy_cache.template data<float>(), dy_cache.numel());
auto* dy = Output(DY, {dy_cache.numel()}, at::dtype<float>());
EigenVectorArrayMap<float> dy_vec(
dy->template mutable_data<float>(), dy->numel());
auto multiplier = dLoss.template data<float>();
int count = 0;
for (int j = 0; j < sids.numel(); j++) {
dy_vec.segment(count, session_lengths[j]) =
multiplier[j] * dy_cache_vec.segment(count, session_lengths[j]);
count += session_lengths[j];
}
return true;
}
namespace {
REGISTER_CPU_OPERATOR(LambdaRankNdcg, LambdaRankNdcgOp<float, CPUContext>);
REGISTER_CPU_OPERATOR(
LambdaRankNdcgGradient,
LambdaRankNdcgGradientOp<float, CPUContext>);
OPERATOR_SCHEMA(LambdaRankNdcg).NumInputs(3).NumOutputs(2).SetDoc(R"DOC(
It implements the LambdaRank as appeared in Wu, Qiang, et al. "Adapting boosting
for information retrieval measures." Information Retrieval 13.3 (2010): 254-270.
This method heuristically optimizes the NDCG.
)DOC");
OPERATOR_SCHEMA(LambdaRankNdcgGradient).NumInputs(4).NumOutputs(1);
class GetLambdaRankNdcgGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"LambdaRankNdcgGradient",
"",
vector<string>{I(0), I(2), O(1), GO(0)},
vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(LambdaRankNdcg, GetLambdaRankNdcgGradient);
} // namespace
} // namespace caffe2