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

S
seemingwang 已提交
15
#include "paddle/fluid/framework/op_registry.h"
16
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
17 18 19

namespace paddle {
namespace operators {
20
using Tensor = phi::DenseTensor;
21

22 23
template <typename IndexT>
void IndexSampleGather(const paddle::platform::NPUDeviceContext& dev_ctx,
24 25 26
                       const phi::DenseTensor* index,
                       const phi::DenseTensor* input,
                       phi::DenseTensor* out) {
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
  auto index_dims = index->dims();
  auto input_dims = input->dims();
  auto batch_size = input_dims[0];
  auto index_length = index_dims[1];

  std::vector<IndexT> gather_index_vec;
  std::vector<IndexT> index_vec;
  framework::TensorToVector(*index, dev_ctx, &index_vec);
  for (auto i = 0; i < batch_size; ++i) {
    for (auto j = 0; j < index_length; j++) {
      gather_index_vec.push_back(i);
      gather_index_vec.push_back(index_vec[i * index_length + j]);
    }
  }
  Tensor gather_index;
  framework::TensorFromVector(gather_index_vec, dev_ctx, &gather_index);
  gather_index.Resize({batch_size, index_length, 2});

  NpuOpRunner runner;
  runner.SetType("GatherNd")
      .AddInput(*input)
      .AddInput(gather_index)
      .AddOutput(*out);
  runner.Run(dev_ctx.stream());
}

53 54 55 56 57 58
template <typename T>
class IndexSampleNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::NPUDeviceContext>();
59 60 61
    auto* input = ctx.Input<phi::DenseTensor>("X");
    auto* index = ctx.Input<phi::DenseTensor>("Index");
    auto* out = ctx.Output<phi::DenseTensor>("Out");
62 63
    out->mutable_data<T>(ctx.GetPlace());

64
    const auto& index_type = framework::TransToProtoVarType(index->dtype());
65
    if (index_type == framework::proto::VarType::INT32) {
66
      IndexSampleGather<int32_t>(dev_ctx, index, input, out);
67
    } else {
68
      IndexSampleGather<int64_t>(dev_ctx, index, input, out);
69 70 71 72 73 74
    }
  }
};

template <typename IndexT>
void IndexSampleGradScatter(const paddle::platform::NPUDeviceContext& dev_ctx,
75 76 77
                            const phi::DenseTensor* index,
                            const phi::DenseTensor* out_grad,
                            phi::DenseTensor* x_grad) {
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  auto index_dims = index->dims();
  auto input_dims = x_grad->dims();
  auto batch_size = input_dims[0];
  auto index_length = index_dims[1];

  std::vector<IndexT> scatter_index_vec;
  std::vector<IndexT> index_vec;
  framework::TensorToVector(*index, dev_ctx, &index_vec);
  for (auto i = 0; i < batch_size; ++i) {
    for (auto j = 0; j < index_length; j++) {
      scatter_index_vec.push_back(i);
      scatter_index_vec.push_back(index_vec[i * index_length + j]);
    }
  }
  Tensor scatter_index;
  framework::TensorFromVector(scatter_index_vec, dev_ctx, &scatter_index);
  scatter_index.Resize({batch_size, index_length, 2});

  NpuOpRunner runner;
  runner.SetType("ScatterNd")
      .AddInput(scatter_index)
      .AddInput(*out_grad)
100
      .AddInput(phi::vectorize<IndexT>(x_grad->dims()))
101 102 103 104 105 106 107 108 109 110
      .AddOutput(*x_grad);
  runner.Run(dev_ctx.stream());
}

template <typename T>
class IndexSampleGradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::NPUDeviceContext>();
111 112 113
    auto* index = ctx.Input<phi::DenseTensor>("Index");
    auto* out_grad = ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto* x_grad = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
114 115
    x_grad->mutable_data<T>(ctx.GetPlace());

116
    const auto& index_type = framework::TransToProtoVarType(index->dtype());
117 118 119 120 121 122 123 124 125 126 127 128 129 130
    if (index_type == framework::proto::VarType::INT32) {
      IndexSampleGradScatter<int32_t>(dev_ctx, index, out_grad, x_grad);
    } else {
      IndexSampleGradScatter<int64_t>(dev_ctx, index, out_grad, x_grad);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

131 132
REGISTER_OP_NPU_KERNEL(index_sample,
                       ops::IndexSampleNPUKernel<plat::float16>,
133 134 135 136 137 138 139 140
                       ops::IndexSampleNPUKernel<float>,
                       ops::IndexSampleNPUKernel<int32_t>,
                       ops::IndexSampleNPUKernel<int64_t>);
REGISTER_OP_NPU_KERNEL(index_sample_grad,
                       ops::IndexSampleGradNPUKernel<plat::float16>,
                       ops::IndexSampleGradNPUKernel<float>,
                       ops::IndexSampleGradNPUKernel<int32_t>,
                       ops::IndexSampleGradNPUKernel<int64_t>);