cvm_op.cc 6.7 KB
Newer Older
H
fix doc  
heqiaozhi 已提交
1
/* Copyright (c) 2019 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/cvm_op.h"
H
heqiaozhi 已提交
16
#include <memory>
H
heqiaozhi 已提交
17 18 19 20 21 22 23 24 25 26 27 28
#include "paddle/fluid/operators/math/math_function.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

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

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

    auto x_dims = ctx->GetInputDim("X");
    auto cvm_dims = ctx->GetInputDim("CVM");
35 36 37 38 39 40 41 42
    PADDLE_ENFORCE_EQ(x_dims.size(), 2UL, platform::errors::InvalidArgument(
                                              "Input(X)'s rank should be 2."));
    PADDLE_ENFORCE_EQ(
        cvm_dims.size(), 2UL,
        platform::errors::InvalidArgument("Input(CVM)'s rank should be 2."));
    PADDLE_ENFORCE_EQ(cvm_dims[1], 2UL, platform::errors::InvalidArgument(
                                            "The 2nd dimension of "
                                            "Input(CVM) should be 2."));
H
heqiaozhi 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

    if (ctx->Attrs().Get<bool>("use_cvm")) {
      ctx->SetOutputDim("Y", {x_dims[0], x_dims[1]});
    } else {
      ctx->SetOutputDim("Y", {x_dims[0], x_dims[1] - 2});
    }
    ctx->ShareLoD("X", /*->*/ "Y");
  }

 protected:
  // Explicitly set that the data type of computation kernel of
  // cvm
  // is determined by its input "X".
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
58 59
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"),
H
hutuxian 已提交
60
        ctx.device_context());
H
heqiaozhi 已提交
61 62 63 64 65 66 67 68
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
69 70 71 72 73 74
    OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "CVMGradient");
    OP_INOUT_CHECK(ctx->HasInput("CVM"), "Input", "CVM", "CVMGradient");
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Y")), "Input",
                   framework::GradVarName("Y"), "CVMGradient");
    OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output",
                   framework::GradVarName("X"), "CVMGradient");
H
heqiaozhi 已提交
75 76 77 78

    auto x_dims = ctx->GetInputDim("X");
    auto cvm_dims = ctx->GetInputDim("CVM");
    auto dy_dims = ctx->GetInputDim(framework::GradVarName("Y"));
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    PADDLE_ENFORCE_EQ(x_dims.size(), 2, platform::errors::InvalidArgument(
                                            "Input(X)'s rank should be 2."));
    PADDLE_ENFORCE_EQ(
        dy_dims.size(), 2,
        platform::errors::InvalidArgument("Input(Y@Grad)'s rank should be 2."));
    PADDLE_ENFORCE_EQ(
        cvm_dims.size(), 2,
        platform::errors::InvalidArgument("Input(CVM)'s rank should be 2."));

    PADDLE_ENFORCE_EQ(
        x_dims[0], dy_dims[0],
        platform::errors::InvalidArgument(
            "The 1st dimension of Input(X) and Input(Y@Grad) should "
            "be equal."));

    PADDLE_ENFORCE_EQ(
        cvm_dims[1], 2,
        platform::errors::InvalidArgument(
            "When Attr(soft_label) == false, the 2nd dimension of "
            "Input(CVM) should be 2."));
H
heqiaozhi 已提交
99 100 101 102 103 104 105 106 107 108
    ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
    ctx->ShareLoD("X", framework::GradVarName("X"));
  }

 protected:
  // Explicitly set that the data type of computation kernel of
  // cvm
  // is determined by its input "X".
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
109 110 111
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Y")),
                                   ctx.device_context());
H
heqiaozhi 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  }
};

class CVMOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(LodTensor, default LodTensor<float>), a 2-D tensor with shape "
             "[N x D],"
             " where N is the batch size and D is the emebdding dim. ");
    AddInput("CVM",
             "(Tensor),  a 2-D Tensor with shape [N x 2], where N is the batch "
             "size, 2 is show and click.");
    AddOutput("Y",
              "(LodTensor, default LodTensor<float>), a 2-D tensor with shape "
              "[N x K].");
    AddAttr<bool>("use_cvm", "bool, use cvm or not").SetDefault(true);
    AddComment(R"DOC(
CVM Operator.
H
add doc  
heqiaozhi 已提交
131

H
add doc  
heqiaozhi 已提交
132
      We assume that input X is a embedding vector with cvm_feature(show and click), which shape is [N * D] (D is 2(cvm_feature) + embedding dim, N is batch_size)
H
add doc  
heqiaozhi 已提交
133 134
      if use_cvm is True, we will log(cvm_feature), and output shape is [N * D].
      if use_cvm is False, we will remove cvm_feature from input, and output shape is [N * (D - 2)].
H
heqiaozhi 已提交
135 136 137 138

)DOC");
  }
};
H
heqiaozhi 已提交
139

H
hong 已提交
140 141
template <typename T>
class CVMGradOpMaker : public framework::SingleGradOpMaker<T> {
H
heqiaozhi 已提交
142
 public:
H
hong 已提交
143
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
H
heqiaozhi 已提交
144 145

 protected:
146
  void Apply(GradOpPtr<T> op) const override {
H
heqiaozhi 已提交
147
    op->SetType("cvm_grad");
H
hong 已提交
148
    op->SetInput("CVM", this->Input("CVM"));
149
    op->SetInput("X", this->Input("X"));
H
hong 已提交
150 151 152
    op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
    op->SetAttrMap(this->Attrs());
H
heqiaozhi 已提交
153 154
  }
};
H
heqiaozhi 已提交
155

156 157
DECLARE_NO_NEED_BUFFER_VARS_INFERER(CVMNoNeedBufferVarInference, "CVM");
DECLARE_NO_NEED_BUFFER_VARS_INFERER(CVMGradNoNeedBufferVarInference, "X");
158

H
heqiaozhi 已提交
159 160 161 162
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
163 164
REGISTER_OPERATOR(cvm, ops::CVMOp, ops::CVMOpMaker,
                  ops::CVMGradOpMaker<paddle::framework::OpDesc>,
165 166
                  ops::CVMGradOpMaker<paddle::imperative::OpBase>,
                  ops::CVMNoNeedBufferVarInference);
H
heqiaozhi 已提交
167

168 169
REGISTER_OPERATOR(cvm_grad, ops::CVMGradientOp,
                  ops::CVMGradNoNeedBufferVarInference);
H
heqiaozhi 已提交
170 171 172 173 174

REGISTER_OP_CPU_KERNEL(cvm, ops::CVMOpKernel<float>, ops::CVMOpKernel<double>);

REGISTER_OP_CPU_KERNEL(cvm_grad, ops::CVMGradOpKernel<float>,
                       ops::CVMGradOpKernel<double>);