1 #include "caffe2/operators/margin_ranking_criterion_op.h" 5 #include "caffe2/utils/math.h" 10 bool MarginRankingCriterionOp<CPUContext>::RunOnDevice() {
14 auto* loss = Output(0);
16 X1.size() == X2.size(),
17 "The two inputs for computing ranking loss should have the same size.");
19 X1.size() == Y.size(),
"The input and label should have the same size.");
22 const float* X1data = X1.data<
float>();
23 const float* X2data = X2.data<
float>();
24 const int* Ydata = Y.data<
int>();
25 float* output = loss->mutable_data<
float>();
26 for (
int i = 0; i < X1.size(); ++i) {
27 output[i] = std::max(-Ydata[i] * (X1data[i] - X2data[i]) + margin_, 0.f);
33 bool MarginRankingCriterionGradientOp<CPUContext>::RunOnDevice() {
37 auto& dLoss = Input(3);
38 auto* dX1 = Output(0);
39 auto* dX2 = Output(1);
44 const float* X1data = X1.data<
float>();
45 const float* X2data = X2.data<
float>();
46 const int* Ydata = Y.data<
int>();
47 const float* dLoss_data = dLoss.data<
float>();
49 float* dX1_data = dX1->mutable_data<
float>();
50 float* dX2_data = dX2->mutable_data<
float>();
51 for (
int i = 0; i < X1.size(); ++i) {
52 auto dist = -Ydata[i] * (X1data[i] - X2data[i]) + margin_;
54 dX1_data[i] = dX2_data[i] = 0.f;
56 dX1_data[i] = -Ydata[i] * dLoss_data[i];
57 dX2_data[i] = Ydata[i] * dLoss_data[i];
63 REGISTER_CPU_OPERATOR(
64 MarginRankingCriterion,
65 MarginRankingCriterionOp<CPUContext>);
66 REGISTER_CPU_OPERATOR(
67 MarginRankingCriterionGradient,
68 MarginRankingCriterionGradientOp<CPUContext>);
70 OPERATOR_SCHEMA(MarginRankingCriterion)
74 MarginRankingCriterion takes two input data X1 (Tensor<float>), 75 X2 (Tensor<float>), and label Y (Tensor<int>) to produce the 76 loss (Tensor<float>) where the loss function, 77 loss(X1, X2, Y) = max(0, -Y * (X1 - X2) + margin), is applied to 78 the tensor elementwise. 80 If y == 1 then it assumed the first input should be ranked higher 81 (have a larger value) than the second input, and vice-versa for 84 .Input(0, "X1",
"The left input vector as a 1-dim TensorCPU.")
85 .Input(1,
"X2",
"The right input vector as a 1-dim TensorCPU.")
86 .Input(2,
"Y",
"The label as a 1-dim TensorCPU with int value of 1 or -1.")
87 .Output(0,
"loss",
"The output loss with the same dimensionality as X1.");
89 OPERATOR_SCHEMA(MarginRankingCriterionGradient)
93 MarginRankingCriterionGradient takes both X1, X2, Y and dY and 94 uses them to update dX1, and dX2 according to the chain rule 95 and derivatives of the loss function. 98 class GetMarginRankingCriterionGradient :
public GradientMakerBase {
99 using GradientMakerBase::GradientMakerBase;
100 vector<OperatorDef> GetGradientDefs()
override {
101 return SingleGradientDef(
102 "MarginRankingCriterionGradient",
104 vector<string>{I(0), I(1), I(2), GO(0)},
105 vector<string>{GI(0), GI(1)});
108 REGISTER_GRADIENT(MarginRankingCriterion, GetMarginRankingCriterionGradient);
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...