matmul_grad_kernel.cc 9.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// 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/matmul_grad_kernel.h"

#include "paddle/phi/backends/onednn/onednn_reuse.h"
#include "paddle/phi/core/kernel_registry.h"

namespace phi {

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
void CalculateMatrixDims(const std::vector<int64_t> &x_dims,
                         const std::vector<int64_t> &y_dims,
                         const std::vector<int64_t> &out_dims,
                         std::vector<int64_t> *x_bd_dims,
                         std::vector<int64_t> *y_bd_dims,
                         std::vector<int64_t> *out_bd_dims,
                         bool trans_x,
                         bool trans_y) {
  if (x_dims.size() == 1) {
    (*x_bd_dims)[x_bd_dims->size() - 1] = x_dims[0];
  } else if (x_dims.size() == 2) {
    (*x_bd_dims)[x_bd_dims->size() - 1] = x_dims[1];
    (*x_bd_dims)[x_bd_dims->size() - 2] = x_dims[0];
  } else {
    for (size_t i = 0; i < x_dims.size(); ++i) {
      (*x_bd_dims)[x_bd_dims->size() - x_dims.size() + i] = x_dims[i];
    }
  }
  if (y_dims.size() == 1) {
    (*y_bd_dims)[x_bd_dims->size() - 2] = y_dims[0];
  } else if (y_dims.size() == 2) {
    (*y_bd_dims)[y_bd_dims->size() - 1] = y_dims[1];
    (*y_bd_dims)[y_bd_dims->size() - 2] = y_dims[0];
  } else {
    for (size_t i = 0; i < y_dims.size(); ++i) {
      (*y_bd_dims)[y_bd_dims->size() - y_dims.size() + i] = y_dims[i];
    }
  }

  for (size_t i = 0; i < x_bd_dims->size() - 2; ++i) {
    (*out_bd_dims)[i] = std::max((*x_bd_dims)[i], (*y_bd_dims)[i]);
53
  }
54 55
  int h_idx = trans_x ? x_bd_dims->size() - 1 : x_bd_dims->size() - 2;
  int w_idx = trans_y ? y_bd_dims->size() - 2 : y_bd_dims->size() - 1;
56

57 58
  (*out_bd_dims)[x_bd_dims->size() - 2] = (*x_bd_dims)[h_idx];
  (*out_bd_dims)[y_bd_dims->size() - 1] = (*y_bd_dims)[w_idx];
59 60 61 62 63 64 65 66
}

template <typename T>
void CalculateGradMatrixDims(const OneDNNContext &dev_ctx,
                             DenseTensor *dx_tmp,
                             DenseTensor *dy_tmp,
                             std::vector<int64_t> *dx_bd_dims,
                             std::vector<int64_t> *dy_bd_dims) {
67 68 69 70
  for (size_t i = 0; i < dx_bd_dims->size() - 2; ++i) {
    if ((*dx_bd_dims)[i] != (*dy_bd_dims)[i]) {
      if ((*dx_bd_dims)[i] == 1) {
        (*dx_bd_dims)[i] = (*dy_bd_dims)[i];
71
      } else {
72
        (*dy_bd_dims)[i] = (*dx_bd_dims)[i];
73 74 75 76
      }
    }
  }

77
  dx_tmp->Resize(make_ddim(*dx_bd_dims));
78
  dev_ctx.template Alloc<T>(dx_tmp);
79
  dy_tmp->Resize(make_ddim(*dy_bd_dims));
80 81 82 83 84 85 86 87
  dev_ctx.template Alloc<T>(dy_tmp);
}

template <typename T>
void ReduceSumForMatmulGradOutput(const OneDNNContext &dev_ctx,
                                  const DenseTensor *dx_tmp,
                                  DenseTensor *dx,
                                  const std::vector<int64_t> &dx_dims,
88
                                  const std::vector<int64_t> &x_dims) {
89 90 91 92 93 94 95
  funcs::ReductionOneDNNHandler<T> handler(dnnl::algorithm::reduction_sum,
                                           0.0f,
                                           0.0f,
                                           dev_ctx.GetEngine(),
                                           dev_ctx.GetPlace(),
                                           dx_tmp,
                                           dx,
96
                                           x_dims);
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

  auto src_memory_p = handler.AcquireSrcMemory(dx_tmp);
  auto dst_memory_p = handler.AcquireDstMemory(dx);

  std::unordered_map<int, dnnl::memory> reduction_args = {
      {DNNL_ARG_SRC, *src_memory_p}, {DNNL_ARG_DST, *dst_memory_p}};

  auto &astream = OneDNNContext::tls().get_stream();
  auto reduction_p = handler.AcquireForwardPrimitive();

  reduction_p->execute(astream, reduction_args);
  astream.wait();
}

template <typename T, typename Context>
void MatmulGradKernel(const Context &dev_ctx,
                      const DenseTensor &x,
                      const DenseTensor &y,
                      const DenseTensor &dout,
                      bool transpose_x,
                      bool transpose_y,
                      DenseTensor *dx,
                      DenseTensor *dy) {
  auto x_dims = vectorize(x.dims());
  auto y_dims = vectorize(y.dims());
  auto dout_dims = vectorize(dout.dims());

  size_t ndims = std::max(x_dims.size(), y_dims.size());
  ndims = std::max<size_t>(ndims, 3);

  // in broadcasting scenario new memory is required because
  // reduce sum must be calculated upon broadcasted dims
  DenseTensor dx_tmp, dy_tmp;
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  std::vector<int64_t> dout_bd_dims(ndims, 1);
  std::vector<int64_t> x_bd_dims(ndims, 1);
  std::vector<int64_t> y_bd_dims(ndims, 1);

  CalculateMatrixDims(x_dims,
                      y_dims,
                      dout_dims,
                      &x_bd_dims,
                      &y_bd_dims,
                      &dout_bd_dims,
                      transpose_x,
                      transpose_y);

  std::vector<int64_t> dx_bd_dims(x_bd_dims);
  std::vector<int64_t> dy_bd_dims(y_bd_dims);
145 146

  CalculateGradMatrixDims<T>(
147
      dev_ctx, &dx_tmp, &dy_tmp, &dx_bd_dims, &dy_bd_dims);
148 149 150

  if (transpose_x && transpose_y) {
    funcs::ExecuteMatmul<T, T>(
151
        dev_ctx, y, dout, y_bd_dims, dout_bd_dims, true, true, &dx_tmp);
152
    funcs::ExecuteMatmul<T, T>(
153
        dev_ctx, dout, x, dout_bd_dims, x_bd_dims, true, true, &dy_tmp);
154 155
  } else if (transpose_x) {
    funcs::ExecuteMatmul<T, T>(
156
        dev_ctx, y, dout, y_bd_dims, dout_bd_dims, false, true, &dx_tmp);
157
    funcs::ExecuteMatmul<T, T>(
158
        dev_ctx, x, dout, x_bd_dims, dout_bd_dims, false, false, &dy_tmp);
159 160
  } else if (transpose_y) {
    funcs::ExecuteMatmul<T, T>(
161
        dev_ctx, dout, y, dout_bd_dims, y_bd_dims, false, false, &dx_tmp);
162
    funcs::ExecuteMatmul<T, T>(
163
        dev_ctx, dout, x, dout_bd_dims, x_bd_dims, true, false, &dy_tmp);
164 165
  } else {
    funcs::ExecuteMatmul<T, T>(
166
        dev_ctx, dout, y, dout_bd_dims, y_bd_dims, false, true, &dx_tmp);
167
    funcs::ExecuteMatmul<T, T>(
168
        dev_ctx, x, dout, x_bd_dims, dout_bd_dims, true, false, &dy_tmp);
169 170
  }

171
  if (x_bd_dims != dx_bd_dims) {
172
    ReduceSumForMatmulGradOutput<T>(
173
        dev_ctx, &dx_tmp, dx, dx_bd_dims, x_bd_dims);
174 175 176
  } else {
    *dx = std::move(dx_tmp);
  }
177
  if (y_bd_dims != dy_bd_dims) {
178
    ReduceSumForMatmulGradOutput<T>(
179
        dev_ctx, &dy_tmp, dy, dy_bd_dims, y_bd_dims);
180 181 182 183
  } else {
    *dy = std::move(dy_tmp);
  }

184
  dx->set_mem_desc(x.mem_desc());
185
  dx->Resize(x.dims());
186
  dy->set_mem_desc(y.mem_desc());
187 188 189
  dy->Resize(y.dims());
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
template <typename T, typename Context>
void MatmulWithFlattenGradKernel(const Context &dev_ctx,
                                 const DenseTensor &x,
                                 const DenseTensor &y,
                                 const DenseTensor &out_grad,
                                 int x_num_col_dims,
                                 int y_num_col_dims,
                                 DenseTensor *x_grad,
                                 DenseTensor *y_grad) {
  const DenseTensor reshaped_y =
      paddle::framework::ReshapeToMatrix(y, y_num_col_dims);
  const DenseTensor reshaped_x =
      paddle::framework::ReshapeToMatrix(x, x_num_col_dims);
  const DenseTensor x_matrix = x.dims().size() > 2 ? reshaped_x : x;
  const DenseTensor y_matrix = y.dims().size() > 2 ? reshaped_y : y;

  DenseTensor dout_matrix = out_grad;
  dout_matrix.Resize({flatten_to_2d(x.dims(), x_num_col_dims)[0],
                      flatten_to_2d(y.dims(), y_num_col_dims)[1]});

  // adding mb dim because MatMulV2 handler needs it
  std::vector<int64_t> x_dims(3, 1);
  std::vector<int64_t> y_dims(3, 1);
  std::vector<int64_t> dout_dims(3, 1);
  x_dims[1] = x_matrix.dims()[0];
  x_dims[2] = x_matrix.dims()[1];
  y_dims[1] = y_matrix.dims()[0];
  y_dims[2] = y_matrix.dims()[1];
  dout_dims[1] = dout_matrix.dims()[0];
  dout_dims[2] = dout_matrix.dims()[1];

  if (x_grad != nullptr) {
    x_grad->set_lod(x.lod());
    funcs::ExecuteMul<T>(
        dev_ctx, dout_matrix, y_matrix, dout_dims, y_dims, false, true, x_grad);
  }
  if (y_grad != nullptr) {
    y_grad->set_lod(y.lod());
    funcs::ExecuteMul<T>(
        dev_ctx, x_matrix, dout_matrix, x_dims, dout_dims, true, false, y_grad);
  }
}

233 234 235 236 237 238 239 240
}  // namespace phi

PD_REGISTER_KERNEL(matmul_grad,
                   OneDNN,
                   ONEDNN,
                   phi::MatmulGradKernel,
                   float,
                   phi::dtype::bfloat16) {}
241 242 243 244 245 246 247

PD_REGISTER_KERNEL(matmul_with_flatten_grad,
                   OneDNN,
                   ONEDNN,
                   phi::MatmulWithFlattenGradKernel,
                   float,
                   phi::dtype::bfloat16) {}