bpr_loss_op.cc 7.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/operators/bpr_loss_op.h"
16

S
sneaxiy 已提交
17
#include <memory>
18 19 20 21 22 23 24 25 26

namespace paddle {
namespace operators {

class BprLossOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
27 28 29
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "BprLoss");
    OP_INOUT_CHECK(ctx->HasInput("Label"), "Input", "Label", "BprLoss");
    OP_INOUT_CHECK(ctx->HasOutput("Y"), "Output", "Y", "BprLoss");
30 31

    auto x_dims = ctx->GetInputDim("X");
32
    auto label_dims = ctx->GetInputDim("Label");
33
    int rank = x_dims.size();
34
    PADDLE_ENFORCE_EQ(
35 36
        rank,
        label_dims.size(),
37 38
        platform::errors::InvalidArgument(
            "Input(X) and Input(Label) shall have the same rank."));
P
phlrain 已提交
39

40
    if (ctx->IsRuntime() ||
41
        (phi::product(x_dims) > 0 && phi::product(label_dims) > 0)) {
42
      PADDLE_ENFORCE_EQ(
43 44
          phi::slice_ddim(x_dims, 0, rank - 1),
          phi::slice_ddim(label_dims, 0, rank - 1),
45 46 47
          platform::errors::InvalidArgument(
              "Input(X) and Input(Label) shall have the same shape "
              "except the last dimension."));
P
phlrain 已提交
48
    }
49 50 51 52 53 54 55 56 57 58 59 60

    auto y_dims = x_dims;
    y_dims[rank - 1] = 1;
    ctx->SetOutputDim("Y", y_dims);
    ctx->ShareLoD("X", /*->*/ "Y");
  }

 protected:
  // Explicitly set that the data type of computation kernel of Seq-bpr
  // is determined by its input "X".
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
61 62 63
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        platform::CPUPlace());
64 65 66 67 68 69 70 71
  }
};

class BprLossGradientOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
72 73
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "BprLossGradient");
    OP_INOUT_CHECK(ctx->HasInput("Label"), "Input", "Label", "BprLossGradient");
74 75 76 77 78 79 80 81
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Y")),
                   "Input",
                   framework::GradVarName("Y"),
                   "BprLossGradient");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Output",
                   framework::GradVarName("X"),
                   "BprLossGradient");
82 83

    auto x_dims = ctx->GetInputDim("X");
84
    auto label_dims = ctx->GetInputDim("Label");
85 86
    auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y"));
    int rank = x_dims.size();
87
    PADDLE_ENFORCE_EQ(
88 89
        dy_dims.size(),
        rank,
90 91 92
        platform::errors::InvalidArgument(
            "Input(Y@Grad) and Input(X) should have the same rank."));
    PADDLE_ENFORCE_EQ(
93 94
        label_dims.size(),
        rank,
95 96
        platform::errors::InvalidArgument(
            "Input(Label) and Input(X) should have the same rank."));
97 98
    PADDLE_ENFORCE_EQ(phi::slice_ddim(x_dims, 0, rank - 1),
                      phi::slice_ddim(label_dims, 0, rank - 1),
99 100 101
                      platform::errors::InvalidArgument(
                          "The Input(X) and Input(Label) should have the same "
                          "shape except the last dimension."));
102 103
    PADDLE_ENFORCE_EQ(phi::slice_ddim(x_dims, 0, rank - 1),
                      phi::slice_ddim(dy_dims, 0, rank - 1),
104 105 106
                      platform::errors::InvalidArgument(
                          "The Input(X) and Input(Y@Grad) should have the same "
                          "shape except the last dimension."));
107 108
    PADDLE_ENFORCE_EQ(dy_dims[rank - 1],
                      1,
109 110
                      platform::errors::InvalidArgument(
                          "The last dimension of Input(Y@Grad) should be 1."));
111 112
    PADDLE_ENFORCE_EQ(label_dims[rank - 1],
                      1,
113 114
                      platform::errors::InvalidArgument(
                          " the last dimension of Input(Label) should be 1."));
115 116 117 118 119 120 121 122 123
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
    ctx->ShareLoD("X", framework::GradVarName("X"));
  }

 protected:
  // Explicitly set that the data type of computation kernel of cross_entropy
  // is determined by its input "X".
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
124 125 126
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
        platform::CPUPlace());
127 128 129 130 131 132 133 134 135 136 137
  }
};

class BprLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(Tensor, default Tensor<float>), a tensor whose last dimension "
             "size is equal to the number of classes. This input is a "
             "real number.");
    AddInput(
138
        "Label",
139 140 141 142 143 144 145 146
        "(Tensor), the tensor which represents the ground truth. It has the "
        "same shape with 'X' except the last dimension. the last dimension "
        "size is 1.");
    AddOutput("Y",
              "(Tensor, default Tensor<float>), a tensor whose shape is same "
              "with 'X' except that the last dimension size is 1. It "
              "represents the sequence bpr loss.");
    AddComment(R"DOC(
147
Bayesian Personalized Ranking Loss Operator.
148

149
This operator belongs to pairwise ranking loss. Label is the desired item.
150
The loss at a given point in one session is defined as:
151 152 153
$Y[i] = -\frac{1}{N_{i}} * \sum_{j=0}^{N_{i}}\log(\sigma(X[i, Label[i]]-X[i, j]))$

Learn more details by reading paper <session-based recommendations with recurrent
154
neural networks>(https://arxiv.org/abs/1511.06939)
155 156 157 158

)DOC");
  }
};
S
sneaxiy 已提交
159

H
hong 已提交
160 161
template <typename T>
class BprLossGradMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
162
 public:
H
hong 已提交
163
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
164 165

 protected:
166
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
167
    op->SetType("bpr_loss_grad");
H
hong 已提交
168 169 170 171 172
    op->SetInput("X", this->Input("X"));
    op->SetInput("Label", this->Input("Label"));
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
173 174
  }
};
175 176 177 178
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
L
Leo Chen 已提交
179
using CPUCtx = phi::CPUContext;
180

181 182 183
REGISTER_OPERATOR(bpr_loss,
                  ops::BprLossOp,
                  ops::BprLossOpMaker,
H
hong 已提交
184 185
                  ops::BprLossGradMaker<paddle::framework::OpDesc>,
                  ops::BprLossGradMaker<paddle::imperative::OpBase>);
186
REGISTER_OPERATOR(bpr_loss_grad, ops::BprLossGradientOp);
187 188
REGISTER_OP_CPU_KERNEL(bpr_loss,
                       ops::BprLossOpKernel<CPUCtx, float>,
189 190 191 192
                       ops::BprLossOpKernel<CPUCtx, double>);
REGISTER_OP_CPU_KERNEL(bpr_loss_grad,
                       ops::BprLossGradientOpKernel<CPUCtx, float>,
                       ops::BprLossGradientOpKernel<CPUCtx, double>);