lookup_table_v2_op.cu 8.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2019 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/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/lookup_table_v2_op.h"
18
#include "paddle/fluid/platform/device/gpu/gpu_primitives.h"
19 20 21 22 23
#include "paddle/fluid/platform/float16.h"

namespace paddle {
namespace operators {

24
template <typename T, typename IdT, bool PaddingFlag>
25
__global__ void LookupTableV2(T *output, const T *table, const IdT *ids,
26 27 28
                              const int64_t N, const int64_t K, const int64_t D,
                              const int64_t padding_idx) {
  int idx = threadIdx.x;
29
  int idy = blockIdx.x + threadIdx.y * gridDim.x;
30 31

  while (idy < K) {
32
    auto id = static_cast<int64_t>(ids[idy]);
33 34
    T *out = output + idy * D;
    const T *tab = table + id * D;
35
    for (int i = idx; i < D; i += blockDim.x) {
36 37 38 39 40 41 42 43 44
      if (PaddingFlag) {
        if (id == padding_idx)
          out[i] = static_cast<T>(0);
        else
          out[i] = tab[i];
      } else {
        out[i] = tab[i];
      }
    }
45
    idy += blockDim.y * gridDim.x;
46 47 48
  }
}

49
template <typename T, typename IdT>
50
__global__ void LookupTableV2Grad(T *table, const T *output, const IdT *ids,
51 52 53
                                  const int64_t N, const int64_t K,
                                  const int64_t D) {
  int idx = threadIdx.x;
54
  int idy = blockIdx.x + threadIdx.y * gridDim.x;
55 56

  while (idy < K) {
57
    auto id = static_cast<int64_t>(ids[idy]);
58 59
    const T *out = output + idy * D;
    T *tab = table + id * D;
60 61 62 63
#ifdef PADDLE_WITH_CUDA
    paddle::platform::VectorizedAtomicAddPerBlock(D, idx, blockDim.x, out, tab);
#else
    for (int i = idx; i < D; i += blockDim.x) {
64 65
      paddle::platform::CudaAtomicAdd(&tab[i], out[i]);
    }
66 67
#endif
    idy += blockDim.y * gridDim.x;
68 69 70
  }
}

T
tangwei12 已提交
71
template <typename T>
72 73 74 75
struct LookupTableV2CUDAFunctor {
  LookupTableV2CUDAFunctor(const framework::ExecutionContext &context,
                           const framework::Tensor *ids_t)
      : context_(context), ids_t_(ids_t) {}
76

77 78 79 80 81
  template <typename IdT>
  void apply() {
    auto *table_t = context_.Input<framework::Tensor>("W");
    auto *output_t = context_.Output<framework::Tensor>("Out");
    int64_t padding_idx = context_.Attr<int64_t>("padding_idx");
82 83 84

    size_t N = table_t->dims()[0];
    size_t D = table_t->dims()[1];
85
    size_t K = ids_t_->numel();
86

87
    const int gridx = 2 * context_.cuda_device_context().GetSMCount();
88
    dim3 threads(256, 4);
89
    dim3 grids(gridx, 1);
90

91 92 93 94
    const auto *table = table_t->template data<T>();
    const auto *ids = ids_t_->template data<IdT>();
    auto *output = output_t->template mutable_data<T>(context_.GetPlace());
    auto stream = context_.cuda_device_context().stream();
T
tangwei12 已提交
95

96
    if (padding_idx == -1) {
97
      LookupTableV2<T, IdT, false><<<grids, threads, 0, stream>>>(
98
          output, table, ids, N, K, D, padding_idx);
T
tangwei12 已提交
99
    } else {
100
      LookupTableV2<T, IdT, true><<<grids, threads, 0, stream>>>(
101
          output, table, ids, N, K, D, padding_idx);
T
tangwei12 已提交
102
    }
103
  }
104 105 106 107

 private:
  const framework::ExecutionContext &context_;
  const framework::Tensor *ids_t_;
108 109 110
};

template <typename T>
111
class LookupTableV2CUDAKernel : public framework::OpKernel<T> {
112 113
 public:
  void Compute(const framework::ExecutionContext &context) const override {
114 115
    const auto *ids_t = context.Input<framework::Tensor>("Ids");
    LookupTableV2CUDAFunctor<T> functor(context, ids_t);
116 117
    framework::VisitIntDataType(framework::TransToProtoVarType(ids_t->dtype()),
                                functor);
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  }
};

template <typename InT, typename OutT>
__global__ void InputTypeConvert(const InT *in_ids, const int64_t K,
                                 OutT *out_ids) {
  for (int i = 0; i < K; i++) {
    out_ids[i] = static_cast<OutT>(in_ids[i]);
  }
}

template <typename T>
struct LookupTableV2GradCUDAFunctor {
  LookupTableV2GradCUDAFunctor(const framework::ExecutionContext &context,
                               const framework::Tensor *ids_t)
      : context_(context), ids_t_(ids_t) {}

  template <typename IdT>
  void apply() {
137
    auto &dev_ctx =
138 139
        context_.template device_context<platform::CUDADeviceContext>();
    bool is_sparse = context_.Attr<bool>("is_sparse");
140 141 142 143

    // Since paddings are not trainable and fixed in forward, the gradient of
    // paddings makes no sense and we don't deal with it in backward.
    if (is_sparse) {
144 145 146
      auto *table = context_.Input<framework::Tensor>("W");
      auto *d_output =
          context_.Input<framework::Tensor>(framework::GradVarName("Out"));
147
      auto *d_table =
148
          context_.Output<phi::SelectedRows>(framework::GradVarName("W"));
149

150 151
      const auto *ids_data = ids_t_->template data<IdT>();
      int64_t ids_num = ids_t_->numel();
T
tangwei12 已提交
152 153
      dim3 threads(128, 8);
      dim3 grids(8, 1);
154 155 156
      auto stream = dev_ctx.stream();
      framework::Vector<int64_t> new_rows;
      new_rows.resize(ids_num);
157
      auto gpu_place = context_.GetPlace();
158

159
      paddle::framework::MixVector<int64_t> mixv_new_rows(&new_rows);
160 161
      if (!std::is_same<IdT, int64_t>::value) {
        InputTypeConvert<<<grids, threads, 0, stream>>>(
162
            ids_data, ids_num, mixv_new_rows.MutableData(gpu_place));
T
tangwei12 已提交
163
      } else {
164 165
        memory::Copy(gpu_place, mixv_new_rows.CUDAMutableData(gpu_place),
                     gpu_place, ids_data, ids_num * sizeof(int64_t), stream);
T
tangwei12 已提交
166 167
      }

168
      mixv_new_rows.CopyToCPU();
169 170 171 172
      d_table->set_rows(new_rows);

      auto *d_table_value = d_table->mutable_value();
      d_table_value->Resize({ids_num, table->dims()[1]});
173
      d_table_value->template mutable_data<T>(gpu_place);
174

175 176
      auto *d_table_data = d_table_value->template data<T>();
      auto *d_output_data = d_output->template data<T>();
177
      auto d_output_dims = d_output->dims();
178
      auto d_output_dims_2d =
179
          phi::flatten_to_2d(d_output_dims, d_output_dims.size() - 1);
180
      PADDLE_ENFORCE_EQ(d_table_value->dims(), d_output_dims_2d,
181 182 183 184 185 186
                        platform::errors::InvalidArgument(
                            "ShapeError: The shape of lookup_table@Grad and "
                            "output@Grad should be same. "
                            "But received lookup_table@Grad's shape = [%s], "
                            "output@Grad's shape = [%s].",
                            d_table_value->dims(), d_output_dims_2d));
187 188 189 190
      memory::Copy(gpu_place, d_table_data, gpu_place, d_output_data,
                   d_output->numel() * sizeof(T), stream);

    } else {
191 192 193 194
      auto d_output_t =
          context_.Input<framework::Tensor>(framework::GradVarName("Out"));
      auto d_table_t =
          context_.Output<framework::Tensor>(framework::GradVarName("W"));
195 196 197

      int N = d_table_t->dims()[0];
      int D = d_table_t->dims()[1];
198
      int K = ids_t_->numel();
T
tangwei12 已提交
199

200 201 202
      const T *d_output = d_output_t->template data<T>();
      const auto *ids = ids_t_->template data<IdT>();
      T *d_table = d_table_t->mutable_data<T>(context_.GetPlace());
203

204 205 206 207 208 209 210
#ifdef PADDLE_WITH_HIP
      PADDLE_ENFORCE_GPU_SUCCESS(
          hipMemsetAsync(d_table, 0, N * D * sizeof(T), dev_ctx.stream()));
#else
      PADDLE_ENFORCE_GPU_SUCCESS(
          cudaMemsetAsync(d_table, 0, N * D * sizeof(T), dev_ctx.stream()));
#endif
211

212 213 214 215
      const int gridx = 2 * dev_ctx.GetSMCount();
      dim3 threads(128, 8);
      dim3 grids(gridx, 1);
      LookupTableV2Grad<T, IdT><<<grids, threads, 0, dev_ctx.stream()>>>(
216
          d_table, d_output, ids, N, K, D);
217 218
    }
  }
219 220 221 222 223 224 225 226 227 228 229 230

 private:
  const framework::ExecutionContext &context_;
  const framework::Tensor *ids_t_;
};

template <typename T>
class LookupTableV2GradCUDAKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    const auto *ids_t = context.Input<framework::Tensor>("Ids");
    LookupTableV2GradCUDAFunctor<T> functor(context, ids_t);
231 232
    framework::VisitIntDataType(framework::TransToProtoVarType(ids_t->dtype()),
                                functor);
233
  }
234 235 236 237 238 239 240 241 242 243 244 245 246 247
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OP_CUDA_KERNEL(lookup_table_v2, ops::LookupTableV2CUDAKernel<float>,
                        ops::LookupTableV2CUDAKernel<double>,
                        ops::LookupTableV2CUDAKernel<plat::float16>);
REGISTER_OP_CUDA_KERNEL(lookup_table_v2_grad,
                        ops::LookupTableV2GradCUDAKernel<float>,
                        ops::LookupTableV2GradCUDAKernel<double>,
                        ops::LookupTableV2GradCUDAKernel<plat::float16>);