matmul_v2_op_mlu.cc 14.3 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/fluid/operators/matmul_v2_op.h"
#include "paddle/fluid/operators/mlu/mlu_baseop.h"

namespace paddle {
namespace operators {

template <typename T>
22
static void Mul(const framework::ExecutionContext& ctx,
23 24 25
                const phi::DenseTensor& X,
                const phi::DenseTensor& Y,
                phi::DenseTensor* Out) {
26 27 28 29 30 31
  Out->mutable_data<T>(ctx.GetPlace());

  MLUCnnlTensorDesc x_desc(X, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnlTensorDesc y_desc(Y, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnlTensorDesc out_desc(*Out, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());

32 33 34 35 36 37 38 39 40 41 42
  MLUCnnlOpTensorDesc mul_op_desc(
      CNNL_OP_TENSOR_MUL, ToCnnlDataType<T>(), CNNL_NOT_PROPAGATE_NAN);
  MLUCnnl::OpTensor(ctx,
                    mul_op_desc.get(),
                    x_desc.get(),
                    GetBasePtr(&X),
                    y_desc.get(),
                    GetBasePtr(&Y),
                    out_desc.get(),
                    GetBasePtr(Out),
                    ToCnnlDataType<T>());
43 44 45
}

template <typename T>
46
static void MatMul2D(const framework::ExecutionContext& ctx,
47 48 49
                     const phi::DenseTensor& X,
                     const phi::DenseTensor& Y,
                     phi::DenseTensor* Out,
50
                     const bool trans_x,
51 52 53 54 55 56 57
                     const bool trans_y) {
  Out->mutable_data<T>(ctx.GetPlace());

  MLUCnnlTensorDesc x_desc(X, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnlTensorDesc y_desc(Y, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnlTensorDesc out_desc(*Out, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());

58 59 60 61 62 63 64 65
  MLUCnnl::Matmul(ctx,
                  trans_x,
                  trans_y,
                  x_desc.get(),
                  GetBasePtr(&X),
                  y_desc.get(),
                  GetBasePtr(&Y),
                  out_desc.get(),
66 67 68
                  GetBasePtr(Out));
}

69 70
template <typename T>
static void MatMul2DwithReduceBatch(const framework::ExecutionContext& ctx,
71 72 73
                                    const phi::DenseTensor& X,
                                    const phi::DenseTensor& Y,
                                    phi::DenseTensor* Out,
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
                                    const bool trans_x,
                                    const bool trans_y) {
  if (!Out->initialized()) {
    Out->mutable_data<T>(ctx.GetPlace());
  }
  // reshape to 2D matmul
  std::vector<int64_t> x_dims = phi::vectorize(X.dims());
  std::vector<int64_t> y_dims = phi::vectorize(Y.dims());
  std::vector<int> realx_dims(
      {static_cast<int>(x_dims[0] * x_dims[1]), static_cast<int>(x_dims[2])});
  std::vector<int> realy_dims(
      {static_cast<int>(y_dims[0] * y_dims[1]), static_cast<int>(y_dims[2])});
  MLUCnnlTensorDesc x_desc(2, realx_dims.data(), ToCnnlDataType<T>());
  MLUCnnlTensorDesc y_desc(2, realy_dims.data(), ToCnnlDataType<T>());
  MLUCnnlTensorDesc out_desc(*Out, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnl::Matmul(ctx,
                  trans_x,
                  trans_y,
                  x_desc.get(),
                  GetBasePtr(&X),
                  y_desc.get(),
                  GetBasePtr(&Y),
                  out_desc.get(),
                  GetBasePtr(Out));
}

100
template <typename T>
101
static void MatMulND(const framework::ExecutionContext& ctx,
102 103 104
                     const phi::DenseTensor& X,
                     const phi::DenseTensor& Y,
                     phi::DenseTensor* Out,
105
                     const bool trans_x,
106 107 108 109 110 111 112 113 114
                     const bool trans_y) {
  if (!Out->initialized()) {
    Out->mutable_data<T>(ctx.GetPlace());
  }

  MLUCnnlTensorDesc x_desc(X, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnlTensorDesc y_desc(Y, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnlTensorDesc out_desc(*Out, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());

115 116 117 118 119 120 121 122
  MLUCnnl::BatchMatmul(ctx,
                       trans_x,
                       trans_y,
                       x_desc.get(),
                       GetBasePtr(&X),
                       y_desc.get(),
                       GetBasePtr(&Y),
                       out_desc.get(),
123 124 125 126 127 128
                       GetBasePtr(Out));
}

template <typename T>
static void ReduceDims(const framework::ExecutionContext& ctx,
                       const std::vector<int64_t>& dims,
129
                       const std::vector<int64_t>& bcast_dims,
130 131
                       const phi::DenseTensor& in,
                       phi::DenseTensor* out) {
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  std::vector<int64_t> axes;
  int64_t size = bcast_dims.size();
  int64_t diff = bcast_dims.size() - dims.size();
  for (int64_t i = 0; i < size; ++i) {
    if (i < diff) {
      axes.push_back(i);
      continue;
    }
    if (bcast_dims[i] > dims[i - diff]) {
      axes.push_back(i);
    }
  }
  out->mutable_data<T>(ctx.GetPlace());

  MLUCnnlTensorDesc in_desc(in, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());
  MLUCnnlTensorDesc out_desc(*out, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());

  std::vector<int> reduce_dims(axes.begin(), axes.end());
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  MLUCnnlReduceDesc reduce_desc(reduce_dims,
                                CNNL_REDUCE_ADD,
                                ToCnnlDataType<T>(),
                                CNNL_NOT_PROPAGATE_NAN,
                                CNNL_REDUCE_NO_INDICES,
                                CNNL_32BIT_INDICES);

  MLUCnnl::Reduce(ctx,
                  true /*need_workspace*/,
                  reduce_desc.get(),
                  nullptr,
                  in_desc.get(),
                  GetBasePtr(&in),
                  0 /*indices_size*/,
                  nullptr,
                  nullptr,
                  out_desc.get(),
                  GetBasePtr(out));
168 169 170 171 172 173
}

template <typename T>
class MatMulV2MLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
174 175 176
    auto* X = ctx.Input<phi::DenseTensor>("X");
    auto* Y = ctx.Input<phi::DenseTensor>("Y");
    auto* Out = ctx.Output<phi::DenseTensor>("Out");
177 178 179
    const bool trans_x = ctx.Attr<bool>("trans_x");
    const bool trans_y = ctx.Attr<bool>("trans_y");

180 181 182
    std::vector<int64_t> x_dims = phi::vectorize(X->dims());
    std::vector<int64_t> y_dims = phi::vectorize(Y->dims());
    std::vector<int64_t> out_dims = phi::vectorize(Out->dims());
183 184 185 186 187 188 189 190 191 192 193
    int x_ndim = x_dims.size();
    int y_ndim = y_dims.size();

    // Case 1: [K] x [K] = [1]
    // Equal: [1, K] x [K, 1] = [1, 1] => [1]
    const bool all_one_dim = (x_ndim == 1 && y_ndim == 1);
    if (all_one_dim) {
      Out->Resize({1, 1});
    }

    // Resize dim 1 to 2
194
    phi::DenseTensor x_temp, y_temp;
195 196 197 198
    x_temp.ShareDataWith(*X);
    y_temp.ShareDataWith(*Y);
    if (x_ndim == 1) {
      x_dims.insert(x_dims.begin(), 1);
199
      x_temp.Resize(phi::make_ddim(x_dims));
200 201 202 203 204
      x_ndim = 2;
      // matmul op of mlu needs `std::max(x->dim, y->dim) == out->dim`
      if (out_dims.size() < y_dims.size()) {
        std::vector<int64_t> temp_out_dims(out_dims.begin(), out_dims.end());
        temp_out_dims.insert(temp_out_dims.end() - 1, 1);
205
        Out->Resize(phi::make_ddim(temp_out_dims));
206 207 208 209
      }
    }
    if (y_ndim == 1) {
      y_dims.push_back(1);
210
      y_temp.Resize(phi::make_ddim(y_dims));
211 212 213 214 215
      y_ndim = 2;
      // matmul op of mlu needs `std::max(x->dim, y->dim) == out->dim`
      if (out_dims.size() < x_dims.size()) {
        std::vector<int64_t> temp_out_dims(out_dims.begin(), out_dims.end());
        temp_out_dims.push_back(1);
216
        Out->Resize(phi::make_ddim(temp_out_dims));
217 218 219 220 221
      }
    }

    const int K = trans_x ? x_dims[x_ndim - 2] : x_dims[x_ndim - 1];
    if (trans_y) {
222 223 224 225 226 227 228 229 230 231
      PADDLE_ENFORCE_EQ(
          y_dims[y_ndim - 1],
          K,
          platform::errors::InvalidArgument("Input(Y) has error dim."
                                            "Y'dims[%d] must be equal to %d"
                                            "But received Y'dims[%d] is %d",
                                            y_ndim - 1,
                                            K,
                                            y_ndim - 1,
                                            y_dims[y_ndim - 1]));
232
    } else {
233 234 235 236 237 238 239 240 241 242
      PADDLE_ENFORCE_EQ(
          y_dims[y_ndim - 2],
          K,
          platform::errors::InvalidArgument("Input(Y) has error dim."
                                            "Y'dims[%d] must be equal to %d"
                                            "But received Y'dims[%d] is %d",
                                            y_ndim - 2,
                                            K,
                                            y_ndim - 2,
                                            y_dims[y_ndim - 2]));
243 244 245 246 247 248 249 250 251 252 253
    }

    if (x_ndim == 2 && y_ndim == 2) {
      // Case 2: [M, K] x [K, N] = [M, N]
      MatMul2D<T>(ctx, x_temp, y_temp, Out, trans_x, trans_y);
    } else {
      // Case 3: [B, M, K] x [K, N] =  [B, M, N]
      // Case 4: [B, M, K] x  [B, K, N] = [B, M, N]
      MatMulND<T>(ctx, x_temp, y_temp, Out, trans_x, trans_y);
    }

254 255
    if (phi::vectorize(Out->dims()) != out_dims) {
      Out->Resize(phi::make_ddim(out_dims));
256 257 258 259 260 261 262 263
    }
  }
};

template <typename T>
class MatMulGradV2MLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
264 265 266 267 268
    auto* X = ctx.Input<phi::DenseTensor>("X");
    auto* Y = ctx.Input<phi::DenseTensor>("Y");
    auto* dOut = ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto* dX = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
    auto* dY = ctx.Output<phi::DenseTensor>(framework::GradVarName("Y"));
269 270 271
    const bool trans_x = ctx.Attr<bool>("trans_x");
    const bool trans_y = ctx.Attr<bool>("trans_y");

272 273 274
    std::vector<int64_t> x_dims = phi::vectorize(X->dims());
    std::vector<int64_t> y_dims = phi::vectorize(Y->dims());
    std::vector<int64_t> out_dims = phi::vectorize(dOut->dims());
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    int x_ndim = x_dims.size();
    int y_ndim = y_dims.size();
    int out_ndim = out_dims.size();

    // Case 1: [K] x [K] = [1]
    if (x_ndim == 1 && y_ndim == 1) {
      if (dX) {
        Mul<T>(ctx, *dOut, *Y, dX);
      }
      if (dY) {
        Mul<T>(ctx, *dOut, *X, dY);
      }
      return;
    }

    // Resize dim 1 to 2
291
    phi::DenseTensor x_temp, y_temp, dout_temp;
292 293 294 295 296 297
    x_temp.ShareDataWith(*X);
    y_temp.ShareDataWith(*Y);
    dout_temp.ShareDataWith(*dOut);
    if (x_ndim == 1) {
      x_dims.insert(x_dims.begin(), 1);
      out_dims.insert(out_dims.end() - 1, 1);
298 299
      x_temp.Resize(phi::make_ddim(x_dims));
      dout_temp.Resize(phi::make_ddim(out_dims));
300 301 302 303 304 305
      x_ndim = 2;
      out_ndim += 1;
    }
    if (y_ndim == 1) {
      y_dims.push_back(1);
      out_dims.push_back(1);
306 307
      y_temp.Resize(phi::make_ddim(y_dims));
      dout_temp.Resize(phi::make_ddim(out_dims));
308 309 310 311 312 313 314
      y_ndim = 2;
      out_ndim += 1;
    }

    // Case 2: [M, K] x [K, N] = [M, N]
    if (out_ndim == 2) {
      if (dX) {
315
        dX->Resize(phi::make_ddim(x_dims));
316 317 318 319 320 321 322 323
        if (trans_x) {
          MatMul2D<T>(ctx, y_temp, dout_temp, dX, trans_y, true);
        } else {
          MatMul2D<T>(ctx, dout_temp, y_temp, dX, false, !trans_y);
        }
        dX->Resize(X->dims());
      }
      if (dY) {
324
        dY->Resize(phi::make_ddim(y_dims));
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
        if (trans_y) {
          MatMul2D<T>(ctx, dout_temp, x_temp, dY, true, trans_x);
        } else {
          MatMul2D<T>(ctx, x_temp, dout_temp, dY, !trans_x, false);
        }
        dY->Resize(Y->dims());
      }
      return;
    }

    // Case 3: [B, M, K] x [K, N] =  [B, M, N]
    // Case 4: [B, M, K] x  [B, K, N] = [B, M, N]
    std::vector<int64_t> x_bcast_dims(out_ndim, 1);
    std::vector<int64_t> y_bcast_dims(out_ndim, 1);
    std::copy(out_dims.begin(), out_dims.end() - 2, x_bcast_dims.begin());
    std::copy(out_dims.begin(), out_dims.end() - 2, y_bcast_dims.begin());
    std::copy(x_dims.end() - 2, x_dims.end(), x_bcast_dims.end() - 2);
    std::copy(y_dims.end() - 2, y_dims.end(), y_bcast_dims.end() - 2);

    if (dX) {
345
      phi::DenseTensor dx_temp(X->type());
346
      if (x_dims != x_bcast_dims) {
347
        dx_temp.Resize(phi::make_ddim(x_bcast_dims));
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
      } else {
        dX->mutable_data<T>(ctx.GetPlace());
        dx_temp.ShareDataWith(*dX);
      }

      if (trans_x) {
        MatMulND<T>(ctx, y_temp, dout_temp, &dx_temp, trans_y, true);
      } else {
        MatMulND<T>(ctx, dout_temp, y_temp, &dx_temp, false, !trans_y);
      }

      if (x_dims != x_bcast_dims) {
        ReduceDims<T>(ctx, x_dims, x_bcast_dims, dx_temp, dX);
      }
    }

    if (dY) {
365 366 367 368 369 370 371 372 373 374
      // Case 3: [B, M, K] x [K, N] =  [B, M, N]  better performance
      // otherwise, tensor dy_temp in else branch might encounter
      // numel overflow due to cnnlTensorDescriptor limitation
      if (x_dims.size() == 3 && phi::vectorize(Y->dims()).size() == 2) {
        if (trans_y) {
          MatMul2DwithReduceBatch<T>(ctx, dout_temp, x_temp, dY, true, trans_x);
        } else {
          MatMul2DwithReduceBatch<T>(
              ctx, x_temp, dout_temp, dY, !trans_x, false);
        }
375
      } else {
376
        phi::DenseTensor dy_temp(Y->type());
377 378 379 380 381 382 383 384 385 386 387 388 389 390
        if (y_dims != y_bcast_dims) {
          dy_temp.Resize(phi::make_ddim(y_bcast_dims));
        } else {
          dY->mutable_data<T>(ctx.GetPlace());
          dy_temp.ShareDataWith(*dY);
        }
        if (trans_y) {
          MatMulND<T>(ctx, dout_temp, x_temp, &dy_temp, true, trans_x);
        } else {
          MatMulND<T>(ctx, x_temp, dout_temp, &dy_temp, !trans_x, false);
        }
        if (y_dims != y_bcast_dims) {
          ReduceDims<T>(ctx, y_dims, y_bcast_dims, dy_temp, dY);
        }
391 392 393 394 395 396 397 398 399 400
      }
    }
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

401 402
REGISTER_OP_MLU_KERNEL(matmul_v2,
                       ops::MatMulV2MLUKernel<float>,
403
                       ops::MatMulV2MLUKernel<plat::float16>);
404 405
REGISTER_OP_MLU_KERNEL(matmul_v2_grad,
                       ops::MatMulGradV2MLUKernel<float>,
406
                       ops::MatMulGradV2MLUKernel<plat::float16>);