matmul_grad_kernel.cu 6.0 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 16
#include "paddle/phi/kernels/sparse/matmul_grad_kernel.h"

17 18 19 20
#include <vector>

#include "paddle/phi/backends/gpu/gpu_context.h"
#include "paddle/phi/core/kernel_registry.h"
21
#include "paddle/phi/core/tensor_utils.h"
22 23
#include "paddle/phi/kernels/empty_kernel.h"
#include "paddle/phi/kernels/funcs/sparse/sparse_blas.h"
24
#include "paddle/phi/kernels/sparse/empty_kernel.h"
25
#include "paddle/phi/kernels/sparse/sparse_utils_kernel.h"
26 27 28 29 30 31
#include "paddle/phi/kernels/transpose_kernel.h"

namespace phi {
namespace sparse {

template <typename T, typename Context>
32 33 34 35 36 37 38 39 40 41 42 43 44 45
void MatmulCooDenseGradKernel(const Context& dev_ctx,
                              const SparseCooTensor& x,
                              const DenseTensor& y,
                              const DenseTensor& dout,
                              SparseCooTensor* dx,
                              DenseTensor* dy) {
#if CUDA_VERSION >= 11030
  auto sparse_blas = phi::funcs::sparse::GetSparseBlas<Context, T>(dev_ctx);

  // dx{SparseCoo} = dout{Dense} * y'{Dense}
  if (dx) {
    // 'cusparseSDDMM' only support CSR now, so use COO->CSR->COO,
    // which will increase some expenses.
    EmptyLikeCooKernel<T, Context>(dev_ctx, x, dx);
46
    SparseCsrTensor dx_csr = CooToCsr<T, Context>(dev_ctx, *dx);
47 48
    sparse_blas.SDDMM(
        false, true, static_cast<T>(1), dout, y, static_cast<T>(0), &dx_csr);
49
    CsrToCooKernel<T, Context>(dev_ctx, dx_csr, dx);
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  }

  // dy{Dense} = x'{SparseCoo} * dout{Dense}
  if (dy) {
    MetaTensor meta_dy(dy);
    meta_dy.set_dims(y.dims());
    meta_dy.set_dtype(y.dtype());
    dev_ctx.template Alloc<T>(dy);

    sparse_blas.SPMM(
        true, false, static_cast<T>(1), x, dout, static_cast<T>(0), dy);
  }
#else
  PADDLE_THROW(phi::errors::Unimplemented(
      "backward of 'sparse.matmul' use cusparseSDDMM, which is supported from "
      "CUDA 11.3"));
#endif
}

template <typename T, typename Context>
void MatmulCsrDenseGradKernel(const Context& dev_ctx,
71 72 73 74 75 76 77 78 79 80
                              const SparseCsrTensor& x,
                              const DenseTensor& y,
                              const DenseTensor& dout,
                              SparseCsrTensor* dx,
                              DenseTensor* dy) {
#if CUDA_VERSION >= 11030
  auto sparse_blas = phi::funcs::sparse::GetSparseBlas<Context, T>(dev_ctx);

  // dx{SparseCsr} = dout{Dense} * y'{Dense}
  if (dx) {
81 82
    // InferMeta of SparseCsrTensor 'dx', CreateLikeInferMeta
    EmptyLikeCsrKernel<T, Context>(dev_ctx, x, dx);
83 84 85 86 87 88 89 90 91 92 93 94 95 96

    sparse_blas.SDDMM(
        false, true, static_cast<T>(1), dout, y, static_cast<T>(0), dx);
  }

  // dy{Dense} = x'{SparseCsr} * dout{Dense}
  if (dy) {
    // InferMeta of DenseTensor 'dy'
    MetaTensor meta_dy(dy);
    meta_dy.set_dims(y.dims());
    meta_dy.set_dtype(y.dtype());

    dev_ctx.template Alloc<T>(dy);

97
    sparse_blas.SPMM(
98 99 100 101
        true, false, static_cast<T>(1), x, dout, static_cast<T>(0), dy);
  }
#else
  PADDLE_THROW(phi::errors::Unimplemented(
102 103
      "backward of 'sparse.matmul' use cusparseSDDMM, which is supported from "
      "CUDA 11.3"));
104 105 106 107
#endif
}

template <typename T, typename Context>
108
void MaskedMatmulCsrGradKernel(const Context& dev_ctx,
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
                               const DenseTensor& x,
                               const DenseTensor& y,
                               const SparseCsrTensor& dout,
                               DenseTensor* dx,
                               DenseTensor* dy) {
#if CUDA_VERSION >= 11000
  auto sparse_blas = phi::funcs::sparse::GetSparseBlas<Context, T>(dev_ctx);

  // dx{Dense} = dout{SparseCsr} * y'{Dense}
  if (dx) {
    // InferMeta of DenseTensor 'dx'
    MetaTensor meta_dx(dx);
    meta_dx.set_dims(x.dims());
    meta_dx.set_dtype(x.dtype());

    dev_ctx.template Alloc<T>(dx);
125
    sparse_blas.SPMM(
126 127 128 129 130 131 132 133 134 135 136
        false, true, static_cast<T>(1), dout, y, static_cast<T>(0), dx);
  }

  // dy{Dense} = x'{Dense} * dout{SparseCsr}
  // That is: dy'{Dense} = dout'{SparseCsr} * x{Dense}
  if (dy) {
    std::vector<int> trans_dim_vec = phi::vectorize<int>(y.dims());
    size_t rank = trans_dim_vec.size();
    std::swap(trans_dim_vec[rank - 1], trans_dim_vec[rank - 2]);
    DenseTensor trans_dy = phi::Empty<T, Context>(dev_ctx, trans_dim_vec);

137
    sparse_blas.SPMM(
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        true, false, static_cast<T>(1), dout, x, static_cast<T>(0), &trans_dy);

    // InferMeta of DenseTensor 'dy'
    MetaTensor meta_dy(dy);
    meta_dy.set_dims(y.dims());
    meta_dy.set_dtype(y.dtype());

    dev_ctx.template Alloc<T>(dy);

    size_t y_ndim = y.dims().size();
    std::vector<int> axis(y_ndim);
    for (size_t i = 0; i < y_ndim; ++i) {
      axis[i] = i;
    }
    std::swap(axis[y_ndim - 1], axis[y_ndim - 2]);
    TransposeKernel<T, Context>(dev_ctx, trans_dy, axis, dy);
  }
#endif
}

}  // namespace sparse
}  // namespace phi

161 162 163 164 165 166 167 168 169 170
PD_REGISTER_KERNEL(matmul_coo_dense_grad,
                   GPU,
                   ALL_LAYOUT,
                   phi::sparse::MatmulCooDenseGradKernel,
                   float,
                   double) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
}

PD_REGISTER_KERNEL(matmul_csr_dense_grad,
171 172
                   GPU,
                   ALL_LAYOUT,
173
                   phi::sparse::MatmulCsrDenseGradKernel,
174 175 176 177 178
                   float,
                   double) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_CSR);
}

179
PD_REGISTER_KERNEL(masked_matmul_csr_grad,
180 181
                   GPU,
                   ALL_LAYOUT,
182
                   phi::sparse::MaskedMatmulCsrGradKernel,
183 184
                   float,
                   double) {}