matmul_v2_op_npu.cc 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright (c) 2021 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 <memory>
#include <string>

#include "paddle/fluid/operators/matmul_v2_op.h"

namespace paddle {
namespace operators {

23 24 25 26
using NPUDeviceContext = platform::NPUDeviceContext;

template <typename T>
static void MatMul2D(const framework::ExecutionContext& ctx,
27
                     const aclrtStream& stream,
28 29 30
                     const phi::DenseTensor& X,
                     const phi::DenseTensor& Y,
                     phi::DenseTensor* Out,
31
                     const bool trans_x,
32 33 34
                     const bool trans_y) {
  Out->mutable_data<T>(ctx.GetPlace());
  const auto& runner =
35 36 37
      NpuOpRunner("MatMul",
                  {X, Y},
                  {*Out},
38 39 40 41 42 43
                  {{"transpose_x1", trans_x}, {"transpose_x2", trans_y}});
  runner.Run(stream);
}

template <typename T>
static void MatMulND(const framework::ExecutionContext& ctx,
44
                     const aclrtStream& stream,
45 46 47
                     const phi::DenseTensor& X,
                     const phi::DenseTensor& Y,
                     phi::DenseTensor* Out,
48
                     const bool trans_x,
49 50
                     const bool trans_y) {
  Out->mutable_data<T>(ctx.GetPlace());
51 52 53
  const auto& runner = NpuOpRunner("BatchMatMul",
                                   {X, Y},
                                   {*Out},
54 55 56 57
                                   {{"adj_x1", trans_x}, {"adj_x2", trans_y}});
  runner.Run(stream);
}

58 59 60 61
#if (CANN_VERSION_CODE < 504000)
template <>
void MatMulND<phi::dtype::float16>(const framework::ExecutionContext& ctx,
                                   const aclrtStream& stream,
62 63 64
                                   const phi::DenseTensor& X,
                                   const phi::DenseTensor& Y,
                                   phi::DenseTensor* Out,
65 66 67
                                   const bool trans_x,
                                   const bool trans_y) {
  Out->mutable_data<phi::dtype::float16>(ctx.GetPlace());
68
  phi::DenseTensor x_fp32, y_fp32, out_fp32;
69 70 71 72 73 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 100 101 102 103 104 105 106 107 108 109
  x_fp32.Resize(X.dims());
  y_fp32.Resize(Y.dims());
  out_fp32.Resize(Out->dims());
  x_fp32.mutable_data<float>(ctx.GetPlace());
  y_fp32.mutable_data<float>(ctx.GetPlace());
  out_fp32.mutable_data<float>(ctx.GetPlace());

  const auto& cast_x =
      NpuOpRunner("Cast",
                  {X},
                  {x_fp32},
                  {{"dst_type",
                    static_cast<int>(ConvertToNpuDtype(
                        framework::TransToProtoVarType(x_fp32.type())))}});
  cast_x.Run(stream);
  const auto& cast_y =
      NpuOpRunner("Cast",
                  {Y},
                  {y_fp32},
                  {{"dst_type",
                    static_cast<int>(ConvertToNpuDtype(
                        framework::TransToProtoVarType(y_fp32.type())))}});
  cast_y.Run(stream);

  const auto& runner = NpuOpRunner("BatchMatMul",
                                   {x_fp32, y_fp32},
                                   {out_fp32},
                                   {{"adj_x1", trans_x}, {"adj_x2", trans_y}});
  runner.Run(stream);

  const auto& cast_out = NpuOpRunner(
      "Cast",
      {out_fp32},
      {*Out},
      {{"dst_type",
        static_cast<int>(
            ConvertToNpuDtype(framework::TransToProtoVarType(Out->type())))}});
  cast_out.Run(stream);
}
#endif

110 111 112 113
template <typename T>
static void ReduceDims(const framework::ExecutionContext& ctx,
                       const aclrtStream& stream,
                       const std::vector<int64_t>& dims,
114
                       const std::vector<int64_t>& brd_dims,
115 116
                       const phi::DenseTensor& in,
                       phi::DenseTensor* out) {
117 118 119 120 121 122 123 124 125 126 127 128 129
  std::vector<int64_t> axes;
  int64_t size = brd_dims.size();
  int64_t diff = brd_dims.size() - dims.size();
  for (int64_t i = 0; i < size; ++i) {
    if (i < diff) {
      axes.push_back(i);
      continue;
    }
    if (brd_dims[i] > dims[i - diff]) {
      axes.push_back(i);
    }
  }
  out->mutable_data<T>(ctx.GetPlace());
130 131
  const auto& runner = NpuOpRunner(
      "ReduceSumD", {in}, {*out}, {{"axes", axes}, {"keep_dims", false}});
132 133 134 135
  runner.Run(stream);
}

template <typename T>
136 137 138
class MatMulV2NPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
139 140 141
    auto* X = ctx.Input<phi::DenseTensor>("X");
    auto* Y = ctx.Input<phi::DenseTensor>("Y");
    auto* Out = ctx.Output<phi::DenseTensor>("Out");
142 143 144
    const bool trans_x = ctx.Attr<bool>("trans_x");
    const bool trans_y = ctx.Attr<bool>("trans_y");

145 146 147
    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());
148 149 150
    int x_ndim = x_dims.size();
    int y_ndim = y_dims.size();
    int out_ndim = out_dims.size();
151

152
    auto stream = ctx.template device_context<NPUDeviceContext>().stream();
153

154 155 156
    // Case 1: [K] x [K] = [1]
    if (x_ndim == 1 && y_ndim == 1) {
      PADDLE_ENFORCE_EQ(
157 158
          X->numel(),
          Y->numel(),
159 160 161 162
          platform::errors::InvalidArgument(
              "X's numbers must be equal to Y's numbers,"
              "when X/Y's dims =1. But received X has [%d] elements,"
              "received Y has [%d] elements",
163 164
              X->numel(),
              Y->numel()));
165 166
      Out->Resize({1});
      Out->mutable_data<T>(ctx.GetPlace());
167

168
      const auto& runner = NpuOpRunner("Dot", {*X, *Y}, {*Out});
169
      runner.Run(stream);
170 171 172 173
      return;
    }

    // Resize dim 1 to 2
174
    phi::DenseTensor x_temp, y_temp;
175 176 177 178 179
    x_temp.ShareDataWith(*X);
    y_temp.ShareDataWith(*Y);
    if (x_ndim == 1) {
      x_dims.insert(x_dims.begin(), 1);
      out_dims.insert(out_dims.end() - 1, 1);
180
      x_temp.Resize(phi::make_ddim(x_dims));
181 182 183 184 185 186
      x_ndim = 2;
      out_ndim += 1;
    }
    if (y_ndim == 1) {
      y_dims.push_back(1);
      out_dims.push_back(1);
187
      y_temp.Resize(phi::make_ddim(y_dims));
188 189 190 191 192 193
      y_ndim = 2;
      out_ndim += 1;
    }

    const int K = trans_x ? x_dims[x_ndim - 2] : x_dims[x_ndim - 1];
    if (trans_y) {
194 195 196 197 198 199 200 201 202 203
      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]));
204
    } else {
205 206 207 208 209 210 211 212 213 214
      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]));
215
    }
216 217 218 219 220 221 222 223 224 225 226

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

    // Case 3: [B, M, K] x [K, N] =  [B, M, N], when trans_x = false
    // Equal: [B * M, K] x [K, N] = [B * M, N] => [B, M, N]
    if (trans_x == false && y_ndim == 2) {
      std::vector<int64_t> vec_dim = {x_temp.numel() / K, K};
227
      x_temp.Resize(phi::make_ddim(vec_dim));
228 229 230 231 232 233 234 235 236 237 238 239
      MatMul2D<T>(ctx, stream, x_temp, y_temp, Out, trans_x, trans_y);
      return;
    }

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

240
    phi::DenseTensor x_temp_brd(X->type());
241 242
    if (x_dims == x_broadcast_dims) {
      x_temp_brd.ShareDataWith(*X);
243
      x_temp_brd.Resize(phi::make_ddim(x_broadcast_dims));
244
    } else {
245
      x_temp_brd.Resize(phi::make_ddim(x_broadcast_dims));
246 247 248 249 250 251 252 253 254
      x_temp_brd.mutable_data<T>(ctx.GetPlace());
      NpuOpRunner runner_brd;
      runner_brd.SetType("BroadcastTo")
          .AddInput(x_temp)
          .AddInput(std::move(x_broadcast_dims))
          .AddOutput(x_temp_brd)
          .Run(stream);
    }

255
    phi::DenseTensor y_temp_brd(Y->type());
256 257
    if (y_dims == y_broadcast_dims) {
      y_temp_brd.ShareDataWith(*Y);
258
      y_temp_brd.Resize(phi::make_ddim(y_broadcast_dims));
259
    } else {
260
      y_temp_brd.Resize(phi::make_ddim(y_broadcast_dims));
261 262 263 264 265 266 267 268 269
      y_temp_brd.mutable_data<T>(ctx.GetPlace());
      NpuOpRunner runner_brd;
      runner_brd.SetType("BroadcastTo")
          .AddInput(y_temp)
          .AddInput(std::move(y_broadcast_dims))
          .AddOutput(y_temp_brd)
          .Run(stream);
    }
    MatMulND<T>(ctx, stream, x_temp_brd, y_temp_brd, Out, trans_x, trans_y);
270 271 272
  }
};

273
template <typename T>
274 275 276
class MatMulV2GradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
277 278 279 280 281
    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"));
282 283
    const bool trans_x = ctx.Attr<bool>("trans_x");
    const bool trans_y = ctx.Attr<bool>("trans_y");
284

285 286 287
    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());
288 289 290
    int x_ndim = x_dims.size();
    int y_ndim = y_dims.size();
    int out_ndim = out_dims.size();
291

292
    auto stream = ctx.template device_context<NPUDeviceContext>().stream();
293

294 295
    // Case 1: [K] x [K] = [1]
    if (x_ndim == 1 && y_ndim == 1) {
296
      phi::DenseTensor dout_temp(dOut->type());
297 298 299 300 301 302 303 304
      dout_temp.Resize(X->dims());
      dout_temp.mutable_data<T>(ctx.GetPlace());
      NpuOpRunner runner;
      runner.SetType("BroadcastTo")
          .AddInput(*dOut)
          .AddInput(std::move(x_dims))
          .AddOutput(dout_temp)
          .Run(stream);
305

306 307 308 309 310 311 312 313 314 315 316 317 318 319
      if (dX) {
        dX->mutable_data<T>(ctx.GetPlace());
        const auto& runner_dx = NpuOpRunner("Mul", {dout_temp, *Y}, {*dX}, {});
        runner_dx.Run(stream);
      }
      if (dY) {
        dY->mutable_data<T>(ctx.GetPlace());
        const auto& runner_dy = NpuOpRunner("Mul", {dout_temp, *X}, {*dY}, {});
        runner_dy.Run(stream);
      }
      return;
    }

    // Resize dim 1 to 2
320
    phi::DenseTensor x_temp, y_temp, dout_temp;
321 322 323 324 325 326
    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);
327 328
      x_temp.Resize(phi::make_ddim(x_dims));
      dout_temp.Resize(phi::make_ddim(out_dims));
329 330 331 332 333 334
      x_ndim = 2;
      out_ndim += 1;
    }
    if (y_ndim == 1) {
      y_dims.push_back(1);
      out_dims.push_back(1);
335 336
      y_temp.Resize(phi::make_ddim(y_dims));
      dout_temp.Resize(phi::make_ddim(out_dims));
337 338 339 340 341 342 343
      y_ndim = 2;
      out_ndim += 1;
    }

    // Case 2: [M, K] x [K, N] = [M, N]
    if (out_ndim == 2) {
      if (dX) {
344
        dX->Resize(phi::make_ddim(x_dims));
345 346 347 348
        if (trans_x) {
          MatMul2D<T>(ctx, stream, y_temp, dout_temp, dX, trans_y, true);
        } else {
          MatMul2D<T>(ctx, stream, dout_temp, y_temp, dX, false, !trans_y);
349
        }
350
        dX->Resize(X->dims());
351
      }
352
      if (dY) {
353
        dY->Resize(phi::make_ddim(y_dims));
354 355 356 357
        if (trans_y) {
          MatMul2D<T>(ctx, stream, dout_temp, x_temp, dY, true, trans_x);
        } else {
          MatMul2D<T>(ctx, stream, x_temp, dout_temp, dY, !trans_x, false);
358
        }
359 360 361 362 363 364 365
        dY->Resize(Y->dims());
      }
      return;
    }

    const int K = trans_x ? x_dims[x_ndim - 2] : x_dims[x_ndim - 1];
    const int N = trans_y ? y_dims[y_ndim - 2] : y_dims[y_ndim - 1];
366

367 368 369 370 371
    // Case 3: [B, M, K] x [K, N] =  [B, M, N], when trans_x = false
    // Equal: [B * M, K] x [K, N] = [B * M, N] => [B, M, N]
    if (trans_x == false && y_ndim == 2) {
      std::vector<int64_t> x_vec_dim = {x_temp.numel() / K, K};
      dout_temp.Resize(
372
          phi::make_ddim(std::vector<int64_t>{dout_temp.numel() / N, N}));
373
      if (dX) {
374
        dX->Resize(phi::make_ddim(x_vec_dim));
375 376 377 378
        MatMul2D<T>(ctx, stream, dout_temp, y_temp, dX, false, !trans_y);
        dX->Resize(X->dims());
      }
      if (dY) {
379
        x_temp.Resize(phi::make_ddim(x_vec_dim));
380 381 382 383
        if (trans_y) {
          MatMul2D<T>(ctx, stream, dout_temp, x_temp, dY, true, false);
        } else {
          MatMul2D<T>(ctx, stream, x_temp, dout_temp, dY, true, false);
384
        }
385 386 387 388 389 390 391 392 393 394 395 396
      }
      return;
    }

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

397
    phi::DenseTensor x_temp_brd(X->type());
398 399
    if (x_dims == x_broadcast_dims) {
      x_temp_brd.ShareDataWith(*X);
400
      x_temp_brd.Resize(phi::make_ddim(x_broadcast_dims));
401
    } else {
402
      x_temp_brd.Resize(phi::make_ddim(x_broadcast_dims));
403 404 405 406 407 408 409 410
      x_temp_brd.mutable_data<T>(ctx.GetPlace());
      NpuOpRunner runner_brd;
      runner_brd.SetType("BroadcastTo")
          .AddInput(x_temp)
          .AddInput(std::move(x_broadcast_dims))
          .AddOutput(x_temp_brd)
          .Run(stream);
    }
411

412
    phi::DenseTensor y_temp_brd(Y->type());
413 414
    if (y_dims == y_broadcast_dims) {
      y_temp_brd.ShareDataWith(*Y);
415
      y_temp_brd.Resize(phi::make_ddim(y_broadcast_dims));
416
    } else {
417
      y_temp_brd.Resize(phi::make_ddim(y_broadcast_dims));
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
      y_temp_brd.mutable_data<T>(ctx.GetPlace());
      NpuOpRunner runner_brd;
      runner_brd.SetType("BroadcastTo")
          .AddInput(y_temp)
          .AddInput(std::move(y_broadcast_dims))
          .AddOutput(y_temp_brd)
          .Run(stream);
    }

    if (dX) {
      if (x_dims == x_broadcast_dims) {
        if (trans_x) {
          MatMulND<T>(ctx, stream, y_temp_brd, dout_temp, dX, trans_y, true);
        } else {
          MatMulND<T>(ctx, stream, dout_temp, y_temp_brd, dX, false, !trans_y);
433
        }
434
      } else {
435
        phi::DenseTensor dx_temp(X->type());
436
        dx_temp.Resize(phi::make_ddim(x_broadcast_dims));
437
        if (trans_x) {
438 439
          MatMulND<T>(
              ctx, stream, y_temp_brd, dout_temp, &dx_temp, trans_y, true);
440
        } else {
441 442
          MatMulND<T>(
              ctx, stream, dout_temp, y_temp_brd, &dx_temp, false, !trans_y);
443
        }
444 445 446 447 448 449 450 451 452 453 454
        ReduceDims<T>(ctx, stream, x_dims, x_broadcast_dims, dx_temp, dX);
      }
    }
    if (dY) {
      if (y_dims == y_broadcast_dims) {
        if (trans_y) {
          MatMulND<T>(ctx, stream, dout_temp, x_temp_brd, dY, true, trans_x);
        } else {
          MatMulND<T>(ctx, stream, x_temp_brd, dout_temp, dY, !trans_x, false);
        }
      } else {
455
        phi::DenseTensor dy_temp(Y->type());
456
        dy_temp.Resize(phi::make_ddim(y_broadcast_dims));
457
        if (trans_y) {
458 459
          MatMulND<T>(
              ctx, stream, dout_temp, x_temp_brd, &dy_temp, true, trans_x);
460
        } else {
461 462
          MatMulND<T>(
              ctx, stream, x_temp_brd, dout_temp, &dy_temp, !trans_x, false);
463 464
        }
        ReduceDims<T>(ctx, stream, y_dims, y_broadcast_dims, dy_temp, dY);
465 466 467 468
      }
    }
  }
};
469

470 471 472 473 474
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

475 476
REGISTER_OP_NPU_KERNEL(matmul_v2,
                       ops::MatMulV2NPUKernel<float>,
477
                       ops::MatMulV2NPUKernel<paddle::platform::float16>);
478 479
REGISTER_OP_NPU_KERNEL(matmul_v2_grad,
                       ops::MatMulV2GradNPUKernel<float>,
480
                       ops::MatMulV2GradNPUKernel<paddle::platform::float16>);