lookup_table_v2_op_npu.cc 4.3 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
/* 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 <iostream>
#include <memory>
#include <string>
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/tensor_util.h"
#include "paddle/fluid/operators/npu_op_runner.h"

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
class LookupTableV2NPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    auto *ids_t = ctx.Input<framework::LoDTensor>("Ids");      // int tensor
    auto *output_t = ctx.Output<framework::LoDTensor>("Out");  // float tensor
    auto *table_t = ctx.Input<framework::LoDTensor>("W");
31

B
Baibaifan 已提交
32 33 34 35 36
    // It seems cann 20.1 accepts int64, but cann 20.2+ not.
    PADDLE_ENFORCE_EQ(ids_t->type(), framework::proto::VarType::INT32,
                      platform::errors::Unimplemented(
                          "The index of LookupTableV2 should be int32."));

37 38 39 40 41 42
    auto *table_var = ctx.InputVar("W");
    PADDLE_ENFORCE_EQ(
        table_var->IsType<framework::LoDTensor>(), true,
        platform::errors::InvalidArgument("npu only accept LoDTensor"));
    output_t->mutable_data<T>(ctx.GetPlace());

B
Baibaifan 已提交
43 44 45
    std::vector<int> ids;
    TensorToVector(*ids_t, ctx.device_context(), &ids);

46 47 48 49 50 51 52
    NpuOpRunner runner;
    runner.SetType("GatherV2")
        .AddInput(*table_t)
        .AddInput(*ids_t)
        .AddInput(std::vector<int32_t>{0})
        .AddOutput(*output_t);
    runner.Run();
53 54 55 56 57 58 59 60 61 62 63 64
  }
};

template <typename T>
class LookupTableV2GradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    auto *ids_t = ctx.Input<framework::LoDTensor>("Ids");
    auto *output_grad_t =
        ctx.Input<framework::LoDTensor>(framework::GradVarName("Out"));
    auto *table_grad_t =
        ctx.Output<framework::LoDTensor>(framework::GradVarName("W"));
65
    table_grad_t->mutable_data<T>(ctx.GetPlace());
66 67 68 69 70

    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    int embedding_dim = table_grad_t->dims()[1];

    if (embedding_dim % 32 == 0) {
      // NOTE(pangyoki): The embedding_dim of Tensor used in
      // EmbeddingDenseGrad must be an integer multiple of 32.
      int num_weights = table_grad_t->dims()[0];
      const auto &runner =
          NpuOpRunner("EmbeddingDenseGrad", {*output_grad_t, *ids_t},
                      {*table_grad_t}, {{"num_weights", num_weights},
                                        {"padding_idx", -1},
                                        {"scale_grad_by_freq", false}});
      runner.Run(stream);
    } else {
      const auto &runner_zeros =
          NpuOpRunner("ZerosLike", {*table_grad_t}, {*table_grad_t});
      runner_zeros.Run(stream);

      // NOTE(zhiqiu): It seems in cann 20.1, the first input and output
      // can be different tensor, but in cann 20.2+, it does inplace operation.
      // Thus, the first input and output should be same tensor.
      const auto &runner_scatter =
          NpuOpRunner("ScatterAdd", {*table_grad_t, *ids_t, *output_grad_t},
                      {*table_grad_t}, {{"use_locking", true}});
      runner_scatter.Run(stream);
    }
96 97 98 99 100 101 102 103 104 105
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_NPU_KERNEL(
    lookup_table_v2,
    ops::LookupTableV2NPUKernel<paddle::platform::NPUDeviceContext, float>,
106
    ops::LookupTableV2NPUKernel<paddle::platform::NPUDeviceContext, int>,
107 108 109 110 111
    ops::LookupTableV2NPUKernel<paddle::platform::NPUDeviceContext,
                                paddle::platform::float16>);

REGISTER_OP_NPU_KERNEL(
    lookup_table_v2_grad, ops::LookupTableV2GradNPUKernel<float>,
112
    ops::LookupTableV2GradNPUKernel<int>,
113
    ops::LookupTableV2GradNPUKernel<paddle::platform::float16>);