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

#include "paddle/phi/kernels/sparse/convolution_grad_kernel.h"
16
#include "paddle/phi/kernels/copy_kernel.h"
17
#include "paddle/phi/kernels/funcs/blas/blas.h"
18
#include "paddle/phi/kernels/funcs/math_function.h"
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include "paddle/phi/kernels/sparse/cpu/convolution.h"

namespace phi {
namespace sparse {

// rulebook:
//[
//  [kernel_index],
//  [in_i],
//  [out_i],
//]
// x_grad = out_grad * transpose(kenrel)
// kernel_grad = transpose(x) * out_grad
template <typename T, typename Context>
void Conv3dGradKernel(const Context& dev_ctx,
                      const SparseCooTensor& x,
                      const DenseTensor& kernel,
36 37
                      const DenseTensor& rulebook,
                      const SparseCooTensor& out_grad,
38 39 40 41
                      const std::vector<int>& paddings,
                      const std::vector<int>& dilations,
                      const std::vector<int>& strides,
                      const int groups,
Z
zhangkaihuo 已提交
42
                      const bool subm,
43
                      SparseCooTensor* x_grad,
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
                      DenseTensor* kernel_grad) {
  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];
  const int* rulebook_ptr = rulebook.data<int>();

  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>();
  kernel_grad->Resize(kernel_dims);
  dev_ctx.Alloc(
      kernel_grad, kernel_grad->dtype(), kernel_grad->numel() * sizeof(T));
  T* d_kernel_ptr = kernel_grad->data<T>();
73
  memset(d_kernel_ptr, 0, sizeof(T) * kernel_grad->numel());
74

Z
zhangkaihuo 已提交
75
  int half_kernel_size = kernel_size / 2;
76
  auto blas = phi::funcs::GetBlas<Context, T>(dev_ctx);
77 78 79 80 81
  DenseTensor x_grad_indices =
      phi::EmptyLike<int>(dev_ctx, x.non_zero_indices());
  DenseTensor x_grad_values = phi::EmptyLike<T>(dev_ctx, x.non_zero_elements());
  T* x_grad_values_ptr = x_grad_values.data<T>();
  memset(x_grad_values_ptr, 0, sizeof(T) * x_grad_values.numel());
Z
zhangkaihuo 已提交
82
  memset(d_x_features_ptr, 0, sizeof(T) * d_x_features.numel());
83 84 85 86 87 88
  phi::Copy<Context>(dev_ctx,
                     x.non_zero_indices(),
                     dev_ctx.GetPlace(),
                     false,
                     &x_grad_indices);
  x_grad->SetMember(x_grad_indices, x_grad_values, x.dims(), true);
Z
zhangkaihuo 已提交
89

90 91 92 93
  std::vector<int> offsets(kernel_size + 1), counter(kernel_size, 0);
  for (int i = 0; i < rulebook_len; i++) {
    counter[rulebook_ptr[i]] += 1;
  }
Z
zhangkaihuo 已提交
94
  int offset = 0, max_count = 0;
95 96 97
  for (int i = 0; i < kernel_size; i++) {
    offsets[i] = offset;
    offset += counter[i];
Z
zhangkaihuo 已提交
98 99 100
    if (i < half_kernel_size) {
      max_count = std::max(max_count, counter[i]);
    }
101 102 103
  }
  offsets[kernel_size] = offset;

Z
zhangkaihuo 已提交
104
  if (subm) {
105 106 107
    phi::funcs::sparse::SubmPreProcess<T, Context>(dev_ctx,
                                                   x,
                                                   kernel,
108
                                                   out_grad.non_zero_elements(),
109 110 111 112
                                                   in_channels,
                                                   out_channels,
                                                   half_kernel_size,
                                                   kernel_grad,
113
                                                   &x_grad_values);
Z
zhangkaihuo 已提交
114 115 116 117 118 119 120 121 122 123
    if (max_count == 0) {
      return;
    }
  }

  Gather<T>(x.non_zero_elements().data<T>(),
            rulebook_ptr + rulebook_len,
            rulebook_len,
            in_channels,
            in_features_ptr);
124
  Gather<T>(out_grad.non_zero_elements().data<T>(),
Z
zhangkaihuo 已提交
125 126 127 128 129
            rulebook_ptr + rulebook_len * 2,
            rulebook_len,
            out_channels,
            out_grad_features_ptr);

130 131
  const T* kernel_ptr = kernel.data<T>();
  for (int i = 0; i < kernel_size; i++) {
Z
zhangkaihuo 已提交
132
    if (counter[i] <= 0 || (subm && i == half_kernel_size)) {
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
      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
  Scatter<T>(d_x_features_ptr,
             rulebook.data<int>() + rulebook_len,
             rulebook_len,
             in_channels,
             x_grad_values_ptr);
}

}  // namespace sparse
}  // namespace phi

183
PD_REGISTER_KERNEL(sparse_conv3d_grad,
184 185 186 187 188 189 190
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::Conv3dGradKernel,
                   float,
                   double) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
}