c_embedding_op.cc 6.9 KB
Newer Older
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
/* Copyright (c) 2021 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/collective/c_embedding_op.h"

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInput("W"), "Input", "W", "CEmbeddingOp");
    OP_INOUT_CHECK(ctx->HasInput("Ids"), "Input", "Ids", "CEmbeddingOp");
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "CEmbeddingOp");

    auto table_dims = ctx->GetInputDim("W");
    auto ids_dims = ctx->GetInputDim("Ids");
    int ids_rank = ids_dims.size();

    VLOG(5) << "ids rank is " << ids_rank << std::endl;
34 35
    PADDLE_ENFORCE_EQ(table_dims.size(),
                      2,
36 37 38 39
                      platform::errors::InvalidArgument(
                          "The dimensions of the 'c_embedding' must be 2. "
                          "But received c_embedding's dimensions = %d, "
                          "c_embedding's shape = [%s].",
40 41
                          table_dims.size(),
                          table_dims));
42

43
    auto output_dims = phi::vectorize(ids_dims);
44
    output_dims.push_back(table_dims[1]);
45
    ctx->SetOutputDim("Out", phi::make_ddim(output_dims));
46 47 48 49 50

    if (ctx->GetOutputsVarType("Out")[0] ==
        framework::proto::VarType::LOD_TENSOR) {
      ctx->ShareLoD("Ids", /*->*/ "Out");
    }
B
Baibaifan 已提交
51 52 53 54 55 56 57

    // check valid
    const int64_t height = table_dims[0];
    const int64_t width = table_dims[1];
    const int64_t start_idx = ctx->Attrs().Get<int64_t>("start_index");

    PADDLE_ENFORCE_EQ(
58 59
        (height > 0 && width > 0 && start_idx >= 0),
        true,
B
Baibaifan 已提交
60 61
        platform::errors::InvalidArgument(
            "height:%ld width:%ld start_idx:%ld must not have negtive values",
62 63 64
            height,
            width,
            start_idx));
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "W");
    return framework::OpKernelType(data_type, ctx.device_context());
  }
};

class CEmbeddingOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("W",
             "(Tensor) The input represents embedding tensors, "
             "which is a learnable parameter.");
    AddInput("Ids",
B
Baibaifan 已提交
82
             "An input with type int32 or int64 in CPU and GPU, int32 in NPU "
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
             "contains the ids to be looked up in W.");
    AddOutput("Out", "The lookup results, which have the same type as W.");

    AddAttr<int64_t>("start_index",
                     "(int64, default 0), The starting index is indeed, "
                     "and the out-of-bounds will be set to 0 ")
        .SetDefault(0);
    AddComment(R"DOC(
c_embedding Operator.

This operator is used to perform lookups on the parameter W,
then concatenated into a dense tensor.

The input Ids can carry the LoD (Level of Details) information,
or not. And the output only shares the LoD information with input Ids.

)DOC");
  }
};

DECLARE_NO_NEED_BUFFER_VARS_INFERER(CEmbeddingGradOpNoBufferVarsInferer, "W");

template <typename T>
class CEmbeddingGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("c_embedding_grad");

    op->SetInput("W", this->Input("W"));
    op->SetInput("Ids", this->Input("Ids"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("W"), this->InputGrad("W"));

    op->SetAttrMap(this->Attrs());
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    auto table_dims = ctx->GetInputDim("W");
    ctx->SetOutputDim(framework::GradVarName("W"), table_dims);
B
Baibaifan 已提交
130 131

    // check valid
132 133
    PADDLE_ENFORCE_EQ(table_dims.size(),
                      2,
B
Baibaifan 已提交
134 135 136 137 138 139 140 141
                      platform::errors::InvalidArgument(
                          "Only accept the dims of table_t == 2"));

    const int64_t start_idx = ctx->Attrs().Get<int64_t>("start_index");
    const int64_t height = table_dims[0];
    const int64_t width = table_dims[1];

    PADDLE_ENFORCE_EQ(
142 143
        (height > 0 && width > 0 && start_idx >= 0),
        true,
B
Baibaifan 已提交
144 145
        platform::errors::InvalidArgument(
            "height:%ld width:%ld start_idx:%ld must not have negtive values",
146 147 148
            height,
            width,
            start_idx));
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    auto data_type = OperatorWithKernel::IndicateVarDataType(
        ctx, framework::GradVarName("Out"));
    return framework::OpKernelType(data_type, ctx.device_context());
  }
};

class CEmbeddingOpGradVarTypeInference : public framework::VarTypeInference {
 public:
  void operator()(framework::InferVarTypeContext* ctx) const override {
    auto out_var_name = framework::GradVarName("W");
    VLOG(3) << "c_embedding_grad op " << framework::GradVarName("W")
165
            << " is set to phi::DenseTensor";
166 167 168 169 170 171 172 173 174
    ctx->SetOutputType(out_var_name, framework::proto::VarType::LOD_TENSOR);
    ctx->SetOutputDataType(out_var_name, ctx->GetInputDataType("W"));
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
B
Baibaifan 已提交
175
namespace plat = paddle::platform;
176 177 178
REGISTER_OPERATOR(c_embedding,
                  ops::CEmbeddingOp,
                  ops::CEmbeddingOpMaker,
179 180 181
                  ops::CEmbeddingGradOpMaker<paddle::framework::OpDesc>,
                  ops::CEmbeddingGradOpMaker<paddle::imperative::OpBase>);

182 183
REGISTER_OPERATOR(c_embedding_grad,
                  ops::CEmbeddingOpGrad,
184 185 186
                  ops::CEmbeddingGradOpNoBufferVarsInferer,
                  ops::CEmbeddingOpGradVarTypeInference);

187 188
REGISTER_OP_CPU_KERNEL(c_embedding,
                       ops::CEmbeddingOpCPUKernel<float>,
B
Baibaifan 已提交
189 190 191
                       ops::CEmbeddingOpCPUKernel<double>,
                       ops::CEmbeddingOpCPUKernel<plat::float16>);

192 193
REGISTER_OP_CPU_KERNEL(c_embedding_grad,
                       ops::CEmbeddingGradOpCPUKernel<float>,
B
Baibaifan 已提交
194 195
                       ops::CEmbeddingGradOpCPUKernel<double>,
                       ops::CEmbeddingGradOpCPUKernel<plat::float16>);