lookup_table_v2_op_npu.cc 6.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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>
17

18 19 20 21 22 23
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/tensor_util.h"

namespace paddle {
namespace operators {

24 25
constexpr int64_t kNoPadding = -1;

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

34 35
    auto *table_var = ctx.InputVar("W");
    PADDLE_ENFORCE_EQ(
36
        table_var->IsType<phi::DenseTensor>(),
37
        true,
38
        platform::errors::InvalidArgument("npu only accept phi::DenseTensor"));
39 40
    output_t->mutable_data<T>(ctx.GetPlace());

41 42 43 44 45 46 47 48 49 50 51 52 53
    int64_t padding_idx = ctx.Attr<int64_t>("padding_idx");
    if (padding_idx == kNoPadding) {
      NpuOpRunner runner;
      runner.SetType("GatherV2")
          .AddInput(*table_t)
          .AddInput(*ids_t)
          .AddInput(std::vector<int32_t>{0})
#if (CANN_VERSION_CODE >= 503003)
          .AddAttrs({{"batch_dims", 0}})
#endif
          .AddOutput(*output_t);
      runner.Run();
    } else {
54
      phi::DenseTensor tmp_table_t(table_t->type());
55 56
      tmp_table_t.mutable_data<T>(table_t->dims(), ctx.GetPlace());

57
      phi::DenseTensor index;
58 59 60 61
      index.mutable_data<int32_t>({1, 1}, ctx.GetPlace());
      FillNpuTensorWithConstant<int32_t>(&index,
                                         static_cast<int32_t>(padding_idx));

62
      auto updata_dim = phi::make_ddim({1, table_t->dims()[1]});
63
      phi::DenseTensor update;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
      update.mutable_data<T>(updata_dim, ctx.GetPlace());
      FillNpuTensorWithConstant<T>(&update, static_cast<T>(0));
      update.Resize(updata_dim);

      NpuOpRunner update_runner;
      update_runner.SetType("TensorScatterUpdate")
          .AddInput(*table_t)
          .AddInput(index)
          .AddInput(update)
          .AddOutput(tmp_table_t);
      update_runner.Run();

      NpuOpRunner runner;
      runner.SetType("GatherV2")
          .AddInput(tmp_table_t)
          .AddInput(*ids_t)
          .AddInput(std::vector<int32_t>{0})
81
#if (CANN_VERSION_CODE >= 503003)
82
          .AddAttrs({{"batch_dims", 0}})
83
#endif
84 85 86
          .AddOutput(*output_t);
      runner.Run();
    }
87 88 89 90 91 92 93
  }
};

template <typename T>
class LookupTableV2GradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
94
    auto *ids_t = ctx.Input<phi::DenseTensor>("Ids");
95
    auto *output_grad_t =
96
        ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
97
    auto *table_grad_t =
98
        ctx.Output<phi::DenseTensor>(framework::GradVarName("W"));
99
    table_grad_t->mutable_data<T>(ctx.GetPlace());
100 101 102 103

    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
104
    int64_t padding_idx = ctx.Attr<int64_t>("padding_idx");
105

106
    /* EmbeddingDenseGrad has bug on large shape, temporarily disable it.
107

108
    int embedding_dim = table_grad_t->dims()[1];
109
    if (embedding_dim % 32 == 0) {
110
      // NOTE(pangyoki): The embedding_dim of phi::DenseTensor used in
111 112 113 114 115 116 117 118
      // 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);
119
      return;
120
    }
121 122 123 124 125 126
    */

    const auto &runner_zeros =
        NpuOpRunner("ZerosLike", {*table_grad_t}, {*table_grad_t});
    runner_zeros.Run(stream);

127 128 129 130 131
    if (padding_idx == kNoPadding) {
      // 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 =
132 133 134 135
          NpuOpRunner("ScatterAdd",
                      {*table_grad_t, *ids_t, *output_grad_t},
                      {*table_grad_t},
                      {{"use_locking", true}});
136 137
      runner_scatter.Run(stream);
    } else {
138
      phi::DenseTensor casted_ids_t;
139 140
      if (framework::TransToProtoVarType(ids_t->dtype()) !=
          framework::proto::VarType::INT32) {
141
        casted_ids_t.mutable_data<int32_t>(ids_t->dims(), ctx.GetPlace());
142 143
        const auto &cast_runner = NpuOpRunner(
            "Cast", {*ids_t}, {casted_ids_t}, {{"dst_type", ACL_INT32}});
144 145 146 147 148 149 150 151 152 153 154 155 156 157
        cast_runner.Run(stream);
      } else {
        casted_ids_t.ShareDataWith(*ids_t);
      }
      auto table_grad_dims = table_grad_t->dims();

      NpuOpRunner runner;
      runner.SetType("UnsortedSegmentSum")
          .AddInput(*output_grad_t)
          .AddInput(casted_ids_t)
          .AddInput(std::vector<int64_t>{table_grad_dims[0]})
          .AddOutput(*table_grad_t);
      runner.Run(stream);
    }
158 159 160 161 162 163 164 165 166 167
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_NPU_KERNEL(
    lookup_table_v2,
    ops::LookupTableV2NPUKernel<paddle::platform::NPUDeviceContext, float>,
168
    ops::LookupTableV2NPUKernel<paddle::platform::NPUDeviceContext, int>,
169 170 171 172
    ops::LookupTableV2NPUKernel<paddle::platform::NPUDeviceContext,
                                paddle::platform::float16>);

REGISTER_OP_NPU_KERNEL(
173 174
    lookup_table_v2_grad,
    ops::LookupTableV2GradNPUKernel<float>,
175
    ops::LookupTableV2GradNPUKernel<int>,
176
    ops::LookupTableV2GradNPUKernel<paddle::platform::float16>);