convolution_grad_kernel.cu 10.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2022 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. */

15
#include "glog/logging.h"
16 17 18 19 20
#include "paddle/phi/backends/gpu/gpu_context.h"
#include "paddle/phi/backends/gpu/gpu_info.h"
#include "paddle/phi/backends/gpu/gpu_launch_config.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/core/tensor_meta.h"
21
#include "paddle/phi/kernels/copy_kernel.h"
22 23 24 25 26
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/math_function.h"
#include "paddle/phi/kernels/sparse/convolution_grad_kernel.h"
#include "paddle/phi/kernels/sparse/gpu/convolution.cu.h"

27 28
#include "paddle/phi/api/ext/dispatch.h"

29 30 31 32 33 34 35 36 37 38 39
namespace phi {
namespace sparse {

// rulebook[3, rulebook_len]:
//[
//  [kernel_index],
//  [in_i],
//  [out_i],
//]
// x_grad = out_grad * transpose(kenrel)
// kernel_grad = transpose(x) * out_grad
40 41 42 43 44 45 46 47 48 49 50 51 52
template <typename T, typename IntT>
void Conv3dGradGPUKernel(const GPUContext& dev_ctx,
                         const SparseCooTensor& x,
                         const DenseTensor& kernel,
                         const DenseTensor& rulebook,
                         const SparseCooTensor& out_grad,
                         const std::vector<int>& paddings,
                         const std::vector<int>& dilations,
                         const std::vector<int>& strides,
                         const int groups,
                         const bool subm,
                         SparseCooTensor* x_grad,
                         DenseTensor* kernel_grad) {
53 54 55 56
  const auto& kernel_dims = kernel.dims();
  const int kernel_size = kernel_dims[0] * kernel_dims[1] * kernel_dims[2];
  const int in_channels = kernel_dims[3];
  const int out_channels = kernel_dims[4];
57
  const IntT* rulebook_ptr = rulebook.data<IntT>();
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

  const int rulebook_len = rulebook.dims()[1];

  DenseTensorMeta in_features_meta(
      x.dtype(), {rulebook_len, in_channels}, DataLayout::NCHW);
  DenseTensorMeta d_x_features_meta(
      x.dtype(), {rulebook_len, in_channels}, DataLayout::NCHW);
  DenseTensorMeta out_grad_features_meta(
      x.dtype(), {rulebook_len, out_channels}, DataLayout::NCHW);
  phi::DenseTensor in_features =
      phi::Empty(dev_ctx, std::move(in_features_meta));
  phi::DenseTensor d_x_features =
      phi::Empty(dev_ctx, std::move(d_x_features_meta));
  phi::DenseTensor out_grad_features =
      phi::Empty(dev_ctx, std::move(out_grad_features_meta));

  T* in_features_ptr = in_features.data<T>();
  T* d_x_features_ptr = d_x_features.data<T>();
  T* out_grad_features_ptr = out_grad_features.data<T>();
77
  *kernel_grad = phi::EmptyLike<T>(dev_ctx, kernel);
78
  T* d_kernel_ptr = kernel_grad->data<T>();
79
  phi::funcs::SetConstant<GPUContext, T> set_zero;
80 81
  set_zero(dev_ctx, kernel_grad, static_cast<T>(0.0f));

Z
zhangkaihuo 已提交
82
  int half_kernel_size = kernel_size / 2;
83
  auto blas = phi::funcs::GetBlas<GPUContext, T>(dev_ctx);
84
  DenseTensor x_grad_indices =
85
      phi::EmptyLike<IntT>(dev_ctx, x.non_zero_indices());
86 87 88
  DenseTensor x_grad_values = phi::EmptyLike<T>(dev_ctx, x.non_zero_elements());
  T* x_grad_values_ptr = x_grad_values.data<T>();
  set_zero(dev_ctx, &x_grad_values, static_cast<T>(0.0f));
Z
zhangkaihuo 已提交
89
  set_zero(dev_ctx, &d_x_features, static_cast<T>(0.0f));
90 91 92 93 94
  phi::Copy<GPUContext>(dev_ctx,
                        x.non_zero_indices(),
                        dev_ctx.GetPlace(),
                        false,
                        &x_grad_indices);
95
  x_grad->SetMember(x_grad_indices, x_grad_values, x.dims(), true);
Z
zhangkaihuo 已提交
96

97
  std::vector<IntT> offsets(kernel_size + 1), counter(kernel_size, 0),
98 99 100
      h_counter(rulebook_len, 0);
  phi::backends::gpu::GpuMemcpyAsync(&h_counter[0],
                                     rulebook_ptr,
101
                                     rulebook_len * sizeof(IntT),
102 103 104 105 106 107 108 109 110 111 112 113
#ifdef PADDLE_WITH_HIP
                                     hipMemcpyDeviceToHost,
#else
                                     cudaMemcpyDeviceToHost,
#endif

                                     dev_ctx.stream());
  dev_ctx.Wait();

  for (int i = 0; i < rulebook_len; i++) {
    counter[h_counter[i]] += 1;
  }
114
  IntT offset = 0, max_count = 0;
115 116 117
  for (int i = 0; i < kernel_size; i++) {
    offsets[i] = offset;
    offset += counter[i];
Z
zhangkaihuo 已提交
118 119 120
    if (i < half_kernel_size) {
      max_count = std::max(max_count, counter[i]);
    }
121 122 123
  }
  offsets[kernel_size] = offset;

Z
zhangkaihuo 已提交
124
  if (subm) {
125 126 127 128 129 130 131 132 133 134
    phi::funcs::sparse::SubmPreProcess<T, GPUContext>(
        dev_ctx,
        x,
        kernel,
        out_grad.non_zero_elements(),
        in_channels,
        out_channels,
        half_kernel_size,
        kernel_grad,
        &x_grad_values);
Z
zhangkaihuo 已提交
135 136 137 138 139 140 141
    if (max_count == 0) {
      return;
    }
  }

  auto config = phi::backends::gpu::GetGpuLaunchConfig1D(
      dev_ctx, rulebook_len * in_channels, 1);
142 143 144 145 146 147 148 149
  GatherKernel<T, IntT><<<config.block_per_grid.x,
                          config.thread_per_block.x,
                          0,
                          dev_ctx.stream()>>>(x.non_zero_elements().data<T>(),
                                              rulebook_ptr + rulebook_len,
                                              in_features_ptr,
                                              rulebook_len,
                                              in_channels);
Z
zhangkaihuo 已提交
150 151 152

  config = phi::backends::gpu::GetGpuLaunchConfig1D(
      dev_ctx, rulebook_len * out_channels, 1);
153 154 155 156
  GatherKernel<T, IntT><<<config.block_per_grid.x,
                          config.thread_per_block.x,
                          0,
                          dev_ctx.stream()>>>(
157 158 159 160 161
      out_grad.non_zero_elements().data<T>(),
      rulebook_ptr + rulebook_len * 2,
      out_grad_features_ptr,
      rulebook_len,
      out_channels);
Z
zhangkaihuo 已提交
162

163 164
  const T* kernel_ptr = kernel.data<T>();
  for (int i = 0; i < kernel_size; i++) {
Z
zhangkaihuo 已提交
165
    if (counter[i] <= 0 || (subm && i == half_kernel_size)) {
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
      continue;
    }

    const int M = counter[i];
    const int K = in_channels;
    const int N = out_channels;
    T* tmp_in_ptr = in_features_ptr + offsets[i] * in_channels;
    T* tmp_out_grad_ptr = out_grad_features_ptr + offsets[i] * out_channels;
    const T* tmp_kernel_ptr = kernel_ptr + i * in_channels * out_channels;
    T* tmp_d_x_ptr = d_x_features_ptr + offsets[i] * out_channels;
    T* tmp_d_kernel_ptr = d_kernel_ptr + i * in_channels * out_channels;

    // call gemm: d_kernel = transpose(x) * out_grad
    // (in_channels, n) * (n, out_channels)
    blas.GEMM(CblasTrans,
              CblasNoTrans,
              M,
              N,
              K,
              static_cast<T>(1),
              tmp_in_ptr,
              tmp_out_grad_ptr,
              static_cast<T>(0),
              tmp_d_kernel_ptr);

    // call gemm: d_x = out_grad * transpose(kernel)
    // (n, out_channels) * (out_channels, in_channels)
    blas.GEMM(CblasNoTrans,
              CblasTrans,
              M,
              K,
              N,
              static_cast<T>(1),
              tmp_out_grad_ptr,
              tmp_kernel_ptr,
              static_cast<T>(0),
              tmp_d_x_ptr);
  }

  // 4. scatter
206
  // x_grad->ResizeAndAllocate(x.non_zero_elements().dims());
Z
zhangkaihuo 已提交
207 208
  DenseTensorMeta index_meta(DataType::INT32, {rulebook_len}, DataLayout::NCHW);
  DenseTensor out_index = phi::Empty(dev_ctx, std::move(index_meta));
209 210 211 212 213
  DenseTensor unique_key = phi::Empty(
      dev_ctx,
      DenseTensorMeta(paddle::experimental::CppTypeToDataType<IntT>::Type(),
                      {rulebook_len},
                      DataLayout::NCHW));
Z
zhangkaihuo 已提交
214
  DenseTensor unique_value = phi::Empty(dev_ctx, std::move(index_meta));
215

216 217 218 219 220 221
  SortedAndUniqueIndex<GPUContext, IntT>(dev_ctx,
                                         rulebook_ptr + rulebook_len,
                                         rulebook_len,
                                         &out_index,
                                         &unique_key,
                                         &unique_value);
222 223 224 225 226 227 228 229 230 231 232 233 234

  config = phi::backends::gpu::GetGpuLaunchConfig1D(
      dev_ctx, rulebook_len * in_channels, 1);

  ScatterKernel<T><<<config.block_per_grid.x,
                     config.thread_per_block.x,
                     0,
                     dev_ctx.stream()>>>(d_x_features_ptr,
                                         unique_value.data<int>(),
                                         out_index.data<int>(),
                                         x.nnz(),
                                         rulebook_len,
                                         in_channels,
Z
zhangkaihuo 已提交
235 236
                                         x_grad_values_ptr,
                                         subm);
237 238
}

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
template <typename T, typename Context>
void Conv3dGradKernel(const Context& dev_ctx,
                      const SparseCooTensor& x,
                      const DenseTensor& kernel,
                      const DenseTensor& rulebook,
                      const SparseCooTensor& out_grad,
                      const std::vector<int>& paddings,
                      const std::vector<int>& dilations,
                      const std::vector<int>& strides,
                      const int groups,
                      const bool subm,
                      SparseCooTensor* x_grad,
                      DenseTensor* kernel_grad) {
  PD_DISPATCH_INTEGRAL_TYPES(
      x.non_zero_indices().dtype(), "Conv3dGradGPUKernel", ([&] {
        Conv3dGradGPUKernel<T, data_t>(dev_ctx,
                                       x,
                                       kernel,
                                       rulebook,
                                       out_grad,
                                       paddings,
                                       dilations,
                                       strides,
                                       groups,
                                       subm,
                                       x_grad,
                                       kernel_grad);
      }));
}

269 270 271 272 273 274 275 276 277 278 279 280
}  // namespace sparse
}  // namespace phi

PD_REGISTER_KERNEL(sparse_conv3d_grad,
                   GPU,
                   ALL_LAYOUT,
                   phi::sparse::Conv3dGradKernel,
                   float,
                   double,
                   phi::dtype::float16) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
}