conv_grad_kernel.cc 8.4 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. */

Z
zhangkaihuo 已提交
15
#include "paddle/phi/kernels/sparse/conv_grad_kernel.h"
16

17
#include "paddle/phi/core/visit_type.h"
18
#include "paddle/phi/kernels/funcs/blas/blas.h"
19
#include "paddle/phi/kernels/funcs/math_function.h"
20
#include "paddle/phi/kernels/sparse/cpu/conv.h"
21 22 23 24 25 26 27 28 29 30 31 32

namespace phi {
namespace sparse {

// rulebook:
//[
//  [kernel_index],
//  [in_i],
//  [out_i],
//]
// x_grad = out_grad * transpose(kenrel)
// kernel_grad = transpose(x) * out_grad
33
template <typename T, typename IntT = int>
Z
zhangkaihuo 已提交
34 35 36
void Conv3dCooGradCPUKernel(const CPUContext& dev_ctx,
                            const SparseCooTensor& x,
                            const DenseTensor& kernel,
37
                            const SparseCooTensor& out,
Z
zhangkaihuo 已提交
38
                            const DenseTensor& rulebook,
39
                            const DenseTensor& counter,
Z
zhangkaihuo 已提交
40 41 42 43 44 45
                            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,
46
                            const std::string& key,
Z
zhangkaihuo 已提交
47 48
                            SparseCooTensor* x_grad,
                            DenseTensor* kernel_grad) {
49 50 51 52 53
  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];

54 55 56 57
  int rulebook_len = 0;
  const IntT* rulebook_ptr = phi::funcs::sparse::GetRulebookPtr<IntT>(
      out, rulebook, key, &rulebook_len);
  const int* counter_ptr = phi::funcs::sparse::GetCounterPtr(out, counter, key);
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

  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>();
75
  *kernel_grad = phi::EmptyLike<T>(dev_ctx, kernel);
76
  T* d_kernel_ptr = kernel_grad->data<T>();
77
  memset(d_kernel_ptr, 0, sizeof(T) * kernel_grad->numel());
78

Z
zhangkaihuo 已提交
79
  int half_kernel_size = kernel_size / 2;
80
  auto blas = phi::funcs::GetBlas<CPUContext, T>(dev_ctx);
81
  DenseTensor x_grad_indices =
82
      phi::EmptyLike<IntT>(dev_ctx, x.non_zero_indices());
83 84 85
  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 已提交
86
  memset(d_x_features_ptr, 0, sizeof(T) * d_x_features.numel());
87 88 89 90 91
  phi::Copy<CPUContext>(dev_ctx,
                        x.non_zero_indices(),
                        dev_ctx.GetPlace(),
                        false,
                        &x_grad_indices);
92
  x_grad->SetMember(x_grad_indices, x_grad_values, x.dims(), true);
Z
zhangkaihuo 已提交
93

94 95 96
  std::vector<IntT> offsets(kernel_size + 1);
  IntT offset = 0;
  int max_count = 0;
97 98
  for (int i = 0; i < kernel_size; i++) {
    offsets[i] = offset;
99
    offset += counter_ptr[i];
Z
zhangkaihuo 已提交
100
    if (i < half_kernel_size) {
101
      max_count = std::max(max_count, counter_ptr[i]);
Z
zhangkaihuo 已提交
102
    }
103 104 105
  }
  offsets[kernel_size] = offset;

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

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

133 134
  const T* kernel_ptr = kernel.data<T>();
  for (int i = 0; i < kernel_size; i++) {
135
    if (counter_ptr[i] <= 0 || (subm && i == half_kernel_size)) {
136 137 138
      continue;
    }

139
    const int M = counter_ptr[i];
140 141 142 143 144
    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;
145
    T* tmp_d_x_ptr = d_x_features_ptr + offsets[i] * in_channels;
146 147 148 149 150 151 152
    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,
              K,
153 154
              N,
              M,
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
              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
176
  Scatter<T, IntT>(d_x_features_ptr,
177
                   rulebook_ptr + rulebook_len,
178 179 180 181 182 183
                   rulebook_len,
                   in_channels,
                   x_grad_values_ptr);
}

template <typename T, typename Context>
Z
zhangkaihuo 已提交
184 185 186
void Conv3dCooGradKernel(const Context& dev_ctx,
                         const SparseCooTensor& x,
                         const DenseTensor& kernel,
187
                         const SparseCooTensor& out,
Z
zhangkaihuo 已提交
188
                         const DenseTensor& rulebook,
189
                         const DenseTensor& counter,
Z
zhangkaihuo 已提交
190 191 192 193 194 195
                         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,
196
                         const std::string& key,
Z
zhangkaihuo 已提交
197 198
                         SparseCooTensor* x_grad,
                         DenseTensor* kernel_grad) {
199
  PD_VISIT_INTEGRAL_TYPES(
Z
zhangkaihuo 已提交
200 201 202 203
      x.non_zero_indices().dtype(), "Conv3dCooGradCPUKernel", ([&] {
        Conv3dCooGradCPUKernel<T, data_t>(dev_ctx,
                                          x,
                                          kernel,
204
                                          out,
Z
zhangkaihuo 已提交
205
                                          rulebook,
206
                                          counter,
Z
zhangkaihuo 已提交
207 208 209 210 211 212
                                          out_grad,
                                          paddings,
                                          dilations,
                                          strides,
                                          groups,
                                          subm,
213
                                          key,
Z
zhangkaihuo 已提交
214 215
                                          x_grad,
                                          kernel_grad);
216
      }));
217 218 219 220 221
}

}  // namespace sparse
}  // namespace phi

Z
zhangkaihuo 已提交
222
PD_REGISTER_KERNEL(conv3d_coo_grad,
223 224
                   CPU,
                   ALL_LAYOUT,
Z
zhangkaihuo 已提交
225
                   phi::sparse::Conv3dCooGradKernel,
226 227 228 229
                   float,
                   double) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
}