c_embedding_op.cc 6.7 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 36 37 38 39
    PADDLE_ENFORCE_EQ(table_dims.size(), 2,
                      platform::errors::InvalidArgument(
                          "The dimensions of the 'c_embedding' must be 2. "
                          "But received c_embedding's dimensions = %d, "
                          "c_embedding's shape = [%s].",
                          table_dims.size(), table_dims));
40 41 42 43 44 45 46 47 48

    auto output_dims = framework::vectorize(ids_dims);
    output_dims.push_back(table_dims[1]);
    ctx->SetOutputDim("Out", framework::make_ddim(output_dims));

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

    // 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(
        (height > 0 && width > 0 && start_idx >= 0), true,
        platform::errors::InvalidArgument(
            "height:%ld width:%ld start_idx:%ld must not have negtive values",
            height, width, start_idx));
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  }

 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 已提交
77
             "An input with type int32 or int64 in CPU and GPU, int32 in NPU "
78 79 80 81 82 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
             "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 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

    // check valid
    PADDLE_ENFORCE_EQ(table_dims.size(), 2,
                      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(
        (height > 0 && width > 0 && start_idx >= 0), true,
        platform::errors::InvalidArgument(
            "height:%ld width:%ld start_idx:%ld must not have negtive values",
            height, width, start_idx));
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
  }

 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")
            << " is set to LoDTensor";
    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 已提交
166
namespace plat = paddle::platform;
167 168 169 170 171 172 173 174 175
REGISTER_OPERATOR(c_embedding, ops::CEmbeddingOp, ops::CEmbeddingOpMaker,
                  ops::CEmbeddingGradOpMaker<paddle::framework::OpDesc>,
                  ops::CEmbeddingGradOpMaker<paddle::imperative::OpBase>);

REGISTER_OPERATOR(c_embedding_grad, ops::CEmbeddingOpGrad,
                  ops::CEmbeddingGradOpNoBufferVarsInferer,
                  ops::CEmbeddingOpGradVarTypeInference);

REGISTER_OP_CPU_KERNEL(c_embedding, ops::CEmbeddingOpCPUKernel<float>,
B
Baibaifan 已提交
176 177 178 179 180 181
                       ops::CEmbeddingOpCPUKernel<double>,
                       ops::CEmbeddingOpCPUKernel<plat::float16>);

REGISTER_OP_CPU_KERNEL(c_embedding_grad, ops::CEmbeddingGradOpCPUKernel<float>,
                       ops::CEmbeddingGradOpCPUKernel<double>,
                       ops::CEmbeddingGradOpCPUKernel<plat::float16>);