teacher_student_sigmoid_loss_op.cc 9.8 KB
Newer Older
H
add API  
heqiaozhi 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
H
heqiaozhi 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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/teacher_student_sigmoid_loss_op.h"
H
Huihuang Zheng 已提交
16 17 18

#include <memory>

19
#include "paddle/phi/kernels/funcs/math_function.h"
H
heqiaozhi 已提交
20 21 22 23 24 25 26 27 28

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext* ctx) const override {
29 30 31 32 33
    OP_INOUT_CHECK(
        ctx->HasInput("X"), "Input", "X", "teacher_student_sigmoid_loss");
    OP_INOUT_CHECK(ctx->HasInput("Label"),
                   "Input",
                   "Label",
34
                   "teacher_student_sigmoid_loss");
35 36
    OP_INOUT_CHECK(
        ctx->HasOutput("Y"), "Output", "Y", "teacher_student_sigmoid_loss");
H
heqiaozhi 已提交
37 38 39

    auto x_dims = ctx->GetInputDim("X");
    auto label_dims = ctx->GetInputDim("Label");
40 41
    PADDLE_ENFORCE_EQ(x_dims.size(),
                      2UL,
42 43 44 45
                      platform::errors::InvalidArgument(
                          "Input(X)'s rank should be 2. But received: "
                          "Input(X)'s rank is [%d]",
                          x_dims.size()));
46 47
    PADDLE_ENFORCE_EQ(label_dims.size(),
                      2UL,
48 49 50 51
                      platform::errors::InvalidArgument(
                          "Input(Label)'s rank should be 2. But "
                          "received Input(Label)'s rank is [%d]",
                          label_dims.size()));
H
heqiaozhi 已提交
52
    if (ctx->IsRuntime()) {
53
      PADDLE_ENFORCE_EQ(
54 55
          x_dims[0],
          label_dims[0],
56 57
          platform::errors::InvalidArgument(
              "The 1st dimension of Input(X) and Input(Label) should "
58
              "be equal. The difference is [%d]: [%d]",
59 60 61 62
              x_dims[0],
              label_dims[0]));
      PADDLE_ENFORCE_EQ(label_dims[1],
                        1UL,
63 64 65 66 67
                        platform::errors::InvalidArgument(
                            "The 2nd dimension of "
                            "Input(Label) should be 1. But received "
                            "Input(Label)'s 2nd dim is [%d]",
                            label_dims[1]));
H
heqiaozhi 已提交
68
    }
H
heqiaozhi 已提交
69 70 71 72 73 74 75 76
    ctx->SetOutputDim("Y", {x_dims[0], 1});
    ctx->ShareLoD("X", /*->*/ "Y");
  }

 protected:
  // Explicitly set that the data type of computation kernel of
  // teacher_student_sigmoid_loss
  // is determined by its input "X".
77
  phi::KernelKey GetExpectedKernelType(
H
heqiaozhi 已提交
78
      const framework::ExecutionContext& ctx) const override {
79 80
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                          ctx.GetPlace());
H
heqiaozhi 已提交
81 82 83
  }
};

H
hong 已提交
84 85 86
template <typename T>
class TeacherStudentSigmoidLossGradOpMaker
    : public framework::SingleGradOpMaker<T> {
H
Huihuang Zheng 已提交
87
 public:
H
hong 已提交
88
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
H
Huihuang Zheng 已提交
89 90

 protected:
91
  void Apply(GradOpPtr<T> op) const override {
H
Huihuang Zheng 已提交
92 93
    op->SetType("teacher_student_sigmoid_loss_grad");

H
hong 已提交
94 95 96
    op->SetInput("X", this->Input("X"));
    op->SetInput("Label", this->Input("Label"));
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
H
Huihuang Zheng 已提交
97

H
hong 已提交
98
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
H
Huihuang Zheng 已提交
99

H
hong 已提交
100
    op->SetAttrMap(this->Attrs());
H
Huihuang Zheng 已提交
101 102 103
  }
};

H
heqiaozhi 已提交
104 105 106 107 108 109
class TeacherStudentSigmoidLossGradientOp
    : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
110 111 112 113 114 115 116 117 118
    OP_INOUT_CHECK(
        ctx->HasInput("X"), "Input", "X", "teacher_student_sigmoid_loss_grad");
    OP_INOUT_CHECK(ctx->HasInput("Label"),
                   "Input",
                   "X",
                   "teacher_student_sigmoid_loss_grad");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Y")),
                   "Input",
                   "Y@Grad",
119
                   "teacher_student_sigmoid_loss_grad");
120 121 122
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")),
                   "Input",
                   "X@Grad",
123
                   "teacher_student_sigmoid_loss_grad");
H
heqiaozhi 已提交
124 125 126 127

    auto x_dims = ctx->GetInputDim("X");
    auto label_dims = ctx->GetInputDim("Label");
    auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y"));
128
    PADDLE_ENFORCE_EQ(
129 130
        x_dims.size(),
        2,
131 132 133
        platform::errors::InvalidArgument(
            "Input(X)'s rank should be 2. But received Input(X)'s rank is [%d]",
            x_dims.size()));
134 135
    PADDLE_ENFORCE_EQ(dy_dims.size(),
                      2,
136 137 138 139
                      platform::errors::InvalidArgument(
                          "Input(Y@Grad)'s rank should be 2. But received "
                          "Input(Y@Grad)'s rank is [%d]",
                          dy_dims.size()));
140 141
    PADDLE_ENFORCE_EQ(label_dims.size(),
                      2,
142 143 144 145
                      platform::errors::InvalidArgument(
                          "Input(Label)'s rank should be 2. But received "
                          "Input(Y@Grad)'s rank is [%d]",
                          label_dims.size()));
H
heqiaozhi 已提交
146
    if (ctx->IsRuntime()) {
147
      PADDLE_ENFORCE_EQ(
148 149
          x_dims[0],
          label_dims[0],
150 151
          platform::errors::InvalidArgument(
              "The 1st dimension of Input(X) and Input(Label) should "
152
              "be equal. The difference is [%d]: [%d]",
153 154
              x_dims[0],
              label_dims[0]));
H
heqiaozhi 已提交
155
      PADDLE_ENFORCE_EQ(
156 157
          x_dims[0],
          dy_dims[0],
158 159
          platform::errors::InvalidArgument(
              "The 1st dimension of Input(X) and Input(Y@Grad) should "
160
              "be equal. The difference is [%d]: [%d]",
161 162
              x_dims[0],
              dy_dims[0]));
163
      PADDLE_ENFORCE_EQ(
164 165
          dy_dims[1],
          1,
166 167 168 169
          platform::errors::InvalidArgument(
              "The 2nd dimension of Input(Y@Grad) should be 1. "
              "But received Input(Y@Grad)'s 2nd dimension is [%d]",
              dy_dims[1]));
170
      PADDLE_ENFORCE_EQ(
171 172
          label_dims[1],
          1,
173 174
          platform::errors::InvalidArgument(
              "When Attr(soft_label) == false, the 2nd dimension of "
175 176
              "Input(Label) should be 1. But received Input(Label)'s 2nd "
              "dimemsion "
177 178
              "is [%d]",
              label_dims[1]));
H
heqiaozhi 已提交
179
    }
H
heqiaozhi 已提交
180 181 182 183 184 185 186 187
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
    ctx->ShareLoD("X", framework::GradVarName("X"));
  }

 protected:
  // Explicitly set that the data type of computation kernel of
  // teacher_student_sigmoid_loss
  // is determined by its input "X".
188
  phi::KernelKey GetExpectedKernelType(
H
heqiaozhi 已提交
189
      const framework::ExecutionContext& ctx) const override {
190 191
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(ctx, "X"),
                          ctx.GetPlace());
H
heqiaozhi 已提交
192 193 194 195 196 197 198 199
  }
};

class TeacherStudentSigmoidLossOpMaker
    : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
200 201
             "(phi::DenseTensor, default phi::DenseTensor<float>), a 2-D "
             "tensor with shape [N x 1],"
H
heqiaozhi 已提交
202 203 204 205
             " where N is the batch size and D is the output. "
             "This input is a probability computed by the previous operator, "
             "which is almost always the result of a softmax operator.");
    AddInput("Label",
206 207
             "(phi::DenseTensor), the ground truth which is a 2-D tensor. "
             "Label is a phi::DenseTensor<float> with shape [N x 1]. ");
H
heqiaozhi 已提交
208
    AddOutput("Y",
209 210
              "(phi::DenseTensor, default phi::DenseTensor<float>), a 2-D "
              "tensor with shape "
H
heqiaozhi 已提交
211
              "[N x 1]. The teacher student sigmoid loss.");
212 213
    AddAttr<float>(
        "soft_max_up_bound",
H
heqiaozhi 已提交
214
        "fp32, if input > soft_max_up_bound, input will be bound, default 15.0")
215
        .SetDefault(15.0);
H
heqiaozhi 已提交
216 217 218
    AddAttr<float>("soft_max_lower_bound",
                   "fp32, if input < soft_max_lower_bound, input will be "
                   "bound, default -15.0")
H
heqiaozhi 已提交
219 220 221 222 223 224 225 226
        .SetDefault(-15.0);
    AddComment(R"DOC(
TeacherStudentSigmoidLoss Operator.

It's similarity to SigmoidCrossEntropyWithLogits Operator. The difference is that
we add another label(z') to original.
        loss = max(x, 0) - x * z + log(1 + exp(-abs(x))) + max(x, 0) - x * z' + log(1 + exp(-abs(x)))
        z is click or not
227
        z' is teacher value
H
heqiaozhi 已提交
228 229 230
        label = {-2, -1, [0, 2]}
        when z' is not exist, clk = 0 : label = -2;
        when z' is not exist, clk = 1 : label = -1;
H
heqiaozhi 已提交
231
        when z' is exist , clk = 0 : label = 0 + z';
H
heqiaozhi 已提交
232 233 234 235 236 237 238 239 240 241
        when z' is exist    , clk = 1 : label = 1 + z';

)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
242
REGISTER_OPERATOR(
243 244
    teacher_student_sigmoid_loss,
    ops::TeacherStudentSigmoidLossOp,
H
hong 已提交
245 246 247
    ops::TeacherStudentSigmoidLossOpMaker,
    ops::TeacherStudentSigmoidLossGradOpMaker<paddle::framework::OpDesc>,
    ops::TeacherStudentSigmoidLossGradOpMaker<paddle::imperative::OpBase>);
H
heqiaozhi 已提交
248 249 250 251

REGISTER_OPERATOR(teacher_student_sigmoid_loss_grad,
                  ops::TeacherStudentSigmoidLossGradientOp);

H
huangjiyi 已提交
252 253 254 255 256 257 258 259 260 261 262 263
PD_REGISTER_STRUCT_KERNEL(teacher_student_sigmoid_loss,
                          CPU,
                          ALL_LAYOUT,
                          ops::TeacherStudentSigmoidLossOpKernel,
                          float,
                          double) {}
PD_REGISTER_STRUCT_KERNEL(teacher_student_sigmoid_loss_grad,
                          CPU,
                          ALL_LAYOUT,
                          ops::TeacherStudentSigmoidLossGradOpKernel,
                          float,
                          double) {}