sum_op.cu 9.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10
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. */
Z
zhaoyuchen2018 已提交
11 12

#include <paddle/fluid/platform/device_context.h>
13

Z
zhaoyuchen2018 已提交
14
#include "paddle/fluid/framework/op_registry.h"
15
#include "paddle/fluid/memory/malloc.h"
Y
Yi Wang 已提交
16
#include "paddle/fluid/operators/sum_op.h"
C
chengduo 已提交
17
#include "paddle/fluid/platform/float16.h"
18

Z
zhaoyuchen2018 已提交
19 20 21 22 23 24 25 26 27 28
namespace plat = paddle::platform;

namespace paddle {
namespace operators {

#define CEIL_DIV(x, y) (((x) + (y)-1) / (y))

using LoDTensor = framework::LoDTensor;

template <class T>
29 30 31
__global__ void Sum2CUDAKernel(const T *in_0,
                               const T *in_1,
                               T *out,
Z
zhaoyuchen2018 已提交
32 33 34 35 36 37 38 39 40
                               int64_t N) {
  int id = blockIdx.x * blockDim.x + threadIdx.x;
  while (id < N) {
    out[id] = in_0[id] + in_1[id];
    id += blockDim.x * gridDim.x;
  }
}

template <class T>
41 42
__global__ void SumArrayCUDAKernel(
    T **in, T *out, int64_t N, size_t in_size, bool read_dst) {
Z
zhaoyuchen2018 已提交
43 44
  int id = blockIdx.x * blockDim.x + threadIdx.x;
  while (id < N) {
45
    T total(read_dst ? out[id] : static_cast<T>(0));
Z
zhaoyuchen2018 已提交
46 47 48 49 50 51
    for (int i = 0; i < in_size; ++i) {
      const T *tmp = in[i];
      if (tmp) {
        total += tmp[id];
      }
    }
52
    out[id] = total;
Z
zhaoyuchen2018 已提交
53 54 55 56 57
    id += blockDim.x * gridDim.x;
  }
}

template <class T>
58 59
__global__ void SumSelectedRowsCUDAKernel(T **sr_in_out,
                                          int64_t N,
Z
zhaoyuchen2018 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
                                          size_t rows) {
  int id = blockIdx.x * blockDim.x + threadIdx.x;
  while (id < N) {
    for (int i = 0; i < 2 * rows; i += 2) {
      const T *tmp = sr_in_out[i];
      T *tmp_out = sr_in_out[i + 1];
      if (tmp && tmp_out) {
        tmp_out[id] += tmp[id];
      }
    }
    id += blockDim.x * gridDim.x;
  }
}

template <class T>
75
void SumToLoDTensor(const framework::ExecutionContext &context) {
Z
zhaoyuchen2018 已提交
76 77 78 79
  auto in_vars = context.MultiInputVar("X");
  const size_t in_num = in_vars.size();

  constexpr size_t theory_sm_threads = 1024;
L
Leo Chen 已提交
80
  auto &dev_ctx = context.template device_context<phi::GPUContext>();
Z
zhaoyuchen2018 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  auto stream = dev_ctx.stream();

  auto max_threads = dev_ctx.GetMaxPhysicalThreadCount();
  auto sm_count = max_threads / theory_sm_threads;
  size_t tile_size = 0;
  dim3 grids;
  dim3 blocks;

  auto ComputeKernelParameter = [&](size_t length) {
    if (length >= max_threads)
      tile_size = 1024;
    else if (length < max_threads && length > sm_count * 128)
      tile_size = 512;
    else if (length <= sm_count * 128)
      tile_size = 256;
    grids = dim3(CEIL_DIV(length, tile_size), 1, 1);
    blocks = dim3(tile_size, 1, 1);
  };

  auto *out = context.Output<LoDTensor>("Out");
101
  bool in_place = in_vars[0] == context.OutputVar("Out");
102

Z
zhaoyuchen2018 已提交
103
  if (!in_place) {
104 105 106 107 108 109 110
    auto *out_ptr = out->mutable_data<T>(context.GetPlace());
    if (in_num >= 1 && in_vars[0]->IsType<framework::LoDTensor>()) {
      auto &in_0_tensor = in_vars[0]->Get<framework::LoDTensor>();
      if (in_0_tensor.numel() > 0) {
        in_place = (in_0_tensor.data<T>() == out_ptr);
      }
    }
Z
zhaoyuchen2018 已提交
111 112
  }

113 114 115 116 117
  // Sum of two tensors
  if (in_num == 2 && in_vars[0]->IsType<framework::LoDTensor>() &&
      in_vars[1]->IsType<framework::LoDTensor>()) {
    auto &in_0 = in_vars[0]->Get<framework::LoDTensor>();
    auto &in_1 = in_vars[1]->Get<framework::LoDTensor>();
118 119 120
    int64_t length_0 = in_0.numel();
    int64_t length_1 = in_1.numel();
    if (length_0 && length_1 && in_0.IsInitialized() && in_1.IsInitialized()) {
121 122 123 124 125
      auto result = EigenVector<T>::Flatten(*out);
      auto &place = *dev_ctx.eigen_device();
      auto in_0_e = EigenVector<T>::Flatten(in_0);
      auto in_1_e = EigenVector<T>::Flatten(in_1);
      result.device(place) = in_0_e + in_1_e;
126
    } else if (length_0 && in_0.IsInitialized()) {
127 128 129
      auto result = EigenVector<T>::Flatten(*out);
      auto &place = *dev_ctx.eigen_device();
      result.device(place) = EigenVector<T>::Flatten(in_0);
130
    } else if (length_1 && in_1.IsInitialized()) {
131 132 133
      auto result = EigenVector<T>::Flatten(*out);
      auto &place = *dev_ctx.eigen_device();
      result.device(place) = EigenVector<T>::Flatten(in_1);
Z
zhaoyuchen2018 已提交
134
    }
135
    return;
Z
zhaoyuchen2018 已提交
136
  }
137 138

  int start = in_place ? 1 : 0;
Z
zhaoyuchen2018 已提交
139
  if (!in_place) {
L
Leo Chen 已提交
140 141 142 143
    phi::funcs::SetConstant<phi::GPUContext, T> constant_functor;
    constant_functor(context.template device_context<phi::GPUContext>(),
                     out,
                     static_cast<T>(0));
Z
zhaoyuchen2018 已提交
144 145 146 147 148 149 150 151 152 153
  }

  std::vector<const T *> in_data;
  std::vector<int> selectrow_index;
  int64_t lod_length = 0;
  bool dst_write = false;
  for (int i = start; i < in_num; ++i) {
    if (in_vars[i]->IsType<framework::LoDTensor>()) {
      auto &in_i = in_vars[i]->Get<framework::LoDTensor>();
      lod_length = in_i.numel();
154 155 156
      if (lod_length && in_i.IsInitialized()) {
        in_data.emplace_back(in_i.data<T>());
      }
157
    } else if (in_vars[i]->IsType<phi::SelectedRows>()) {
Z
zhaoyuchen2018 已提交
158 159 160 161
      selectrow_index.push_back(i);
    }
  }

162
  // compute select rows separately.
Z
zhaoyuchen2018 已提交
163 164 165 166 167
  if (!selectrow_index.empty()) {
    std::vector<const T *> sr_in_out_data;
    size_t rows = 0;
    int64_t length = 0;
    for (auto index : selectrow_index) {
168
      auto &sr = in_vars[index]->Get<phi::SelectedRows>();
Z
zhaoyuchen2018 已提交
169 170 171 172 173 174
      auto &sr_value = sr.value();
      auto &sr_rows = sr.rows();

      auto row_numel = sr_value.numel() / sr_rows.size();
      auto out_dims = out->dims();

175 176
      PADDLE_ENFORCE_EQ(sr.height(),
                        out_dims[0],
177 178 179 180
                        platform::errors::InvalidArgument(
                            "The table height of input must be same as output, "
                            "but received input height is %d"
                            ", output height is %d",
181 182 183 184
                            sr.height(),
                            out_dims[0]));
      PADDLE_ENFORCE_EQ(row_numel,
                        out->numel() / sr.height(),
185 186 187 188
                        platform::errors::InvalidArgument(
                            "The table width of input must be same as output, "
                            "but received input width is %d"
                            ", output width is %d",
189 190
                            row_numel,
                            out->numel() / sr.height()));
Z
zhaoyuchen2018 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203

      auto *sr_data = sr_value.data<T>();
      auto *sr_out_data = out->data<T>();
      rows += sr_rows.size();
      length = row_numel;

      for (size_t i = 0; i < sr_rows.size(); ++i) {
        sr_in_out_data.emplace_back(&sr_data[i * row_numel]);
        sr_in_out_data.emplace_back(&sr_out_data[sr_rows[i] * row_numel]);
      }
    }
    if (!sr_in_out_data.empty()) {
      auto tmp_sr_in_out_array =
204
          memory::Alloc(dev_ctx, sr_in_out_data.size() * sizeof(T *));
Z
zhaoyuchen2018 已提交
205

206 207
      memory::Copy(dev_ctx.GetPlace(),
                   tmp_sr_in_out_array->ptr(),
208
                   platform::CPUPlace(),
Z
zhaoyuchen2018 已提交
209
                   reinterpret_cast<void *>(sr_in_out_data.data()),
210 211
                   sr_in_out_data.size() * sizeof(T *),
                   dev_ctx.stream());
Z
zhaoyuchen2018 已提交
212 213 214 215 216

      T **sr_in_out_array_data =
          reinterpret_cast<T **>(tmp_sr_in_out_array->ptr());

      ComputeKernelParameter(length);
217 218
      SumSelectedRowsCUDAKernel<T>
          <<<grids, blocks, 0, stream>>>(sr_in_out_array_data, length, rows);
Z
zhaoyuchen2018 已提交
219 220 221 222 223
      dst_write = true;
    }
  }
  // if indata not null, merge into one kernel call.
  if (!in_data.empty()) {
224
    auto tmp_in_array = memory::Alloc(dev_ctx, in_data.size() * sizeof(T *));
Z
zhaoyuchen2018 已提交
225

226 227 228
    memory::Copy(dev_ctx.GetPlace(),
                 tmp_in_array->ptr(),
                 platform::CPUPlace(),
Z
zhaoyuchen2018 已提交
229
                 reinterpret_cast<void *>(in_data.data()),
230 231
                 in_data.size() * sizeof(T *),
                 dev_ctx.stream());
Z
zhaoyuchen2018 已提交
232 233 234

    T **in_array_data = reinterpret_cast<T **>(tmp_in_array->ptr());
    ComputeKernelParameter(lod_length);
235 236 237 238 239
    SumArrayCUDAKernel<T><<<grids, blocks, 0, stream>>>(in_array_data,
                                                        out->data<T>(),
                                                        lod_length,
                                                        in_data.size(),
                                                        dst_write | in_place);
Z
zhaoyuchen2018 已提交
240 241 242 243
  }
}

template <typename T>
L
Leo Chen 已提交
244
class SumKernel<phi::GPUContext, T> : public framework::OpKernel<T> {
Z
zhaoyuchen2018 已提交
245 246 247 248 249
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    auto out_var = context.OutputVar("Out");

    if (out_var->IsType<framework::LoDTensor>()) {
250
      SumToLoDTensor<T>(context);
251
    } else if (out_var->IsType<phi::SelectedRows>()) {
L
Leo Chen 已提交
252
      SelectedRowsCompute<phi::GPUContext, T>(context);
Z
zhaoyuchen2018 已提交
253
    } else if (out_var->IsType<framework::LoDTensorArray>()) {
L
Leo Chen 已提交
254
      LodTensorArrayCompute<phi::GPUContext, T>(context);
Z
zhaoyuchen2018 已提交
255
    } else {
256
      PADDLE_THROW(platform::errors::InvalidArgument(
257
          "Expected type of Output(out) must be Tensor,  SelectedRows or "
258 259 260
          "LodTensorArray. But got "
          "unsupport type: %s.",
          framework::ToTypeName(out_var->Type())));
Z
zhaoyuchen2018 已提交
261 262 263 264 265 266
    }
  }
};
}  // namespace operators
}  // namespace paddle

267
namespace ops = paddle::operators;
C
chengduo 已提交
268
namespace plat = paddle::platform;
L
Leo Chen 已提交
269 270 271 272 273 274 275
REGISTER_OP_CUDA_KERNEL(sum,
                        ops::SumKernel<phi::GPUContext, float>,
                        ops::SumKernel<phi::GPUContext, double>,
                        ops::SumKernel<phi::GPUContext, int>,
                        ops::SumKernel<phi::GPUContext, int64_t>,
                        ops::SumKernel<phi::GPUContext, plat::float16>,
                        ops::SumKernel<phi::GPUContext, plat::bfloat16>);