elementwise_mul_op.h 5.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
14 15

#pragma once
16

17
#include <string>
W
Wu Yi 已提交
18
#include "paddle/fluid/operators/elementwise/elementwise_op.h"
19
#include "paddle/fluid/platform/cpu_info.h"
20

21
#include "paddle/phi/kernels/math_kernel.h"
22

23 24 25
namespace paddle {
namespace operators {

26 27 28 29 30 31 32
class ElementwiseMulOp : public ElementwiseOp {
 public:
  using Tensor = framework::Tensor;
  using ElementwiseOp::ElementwiseOp;

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
33 34
    auto input_data_type =
        OperatorWithKernel::IndicateOrPromoteVarDataTypes(ctx, "X", "Y");
35 36

#ifdef PADDLE_WITH_MKLDNN
37
    if (this->CanMKLDNNBeUsed(ctx, input_data_type)) {
38 39 40
      return framework::OpKernelType(input_data_type, ctx.GetPlace(),
                                     framework::DataLayout::kMKLDNN,
                                     framework::LibraryType::kMKLDNN);
41 42 43 44
    }
#endif
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
  }
45 46 47 48 49 50

  framework::OpKernelType GetKernelTypeForVar(
      const std::string& var_name, const framework::Tensor& tensor,
      const framework::OpKernelType& expected_kernel_type) const {
    if (framework::IsComplexType(expected_kernel_type.data_type_)) {
      // only promote inputs’s types when contains complex input
51 52 53
      return framework::OpKernelType(
          framework::TransToProtoVarType(tensor.dtype()), tensor.place(),
          tensor.layout());
54 55 56 57 58
    } else {
      return framework::OpKernelType(expected_kernel_type.data_type_,
                                     tensor.place(), tensor.layout());
    }
  }
59 60
};

61 62 63 64 65
template <typename DeviceContext, typename T>
void default_elementwise_mul(const framework::ExecutionContext& ctx,
                             const framework::Tensor* x,
                             const framework::Tensor* y, framework::Tensor* z) {
  int axis = ctx.Attr<int>("axis");
66 67 68
  auto x_dims = x->dims();
  auto y_dims = y->dims();
  if (x_dims.size() >= y_dims.size()) {
69 70 71 72 73 74
    ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(ctx, x, y, axis,
                                                          MulFunctor<T>(), z);
  } else {
    ElementwiseComputeEx<InverseMulFunctor<T>, DeviceContext, T>(
        ctx, x, y, axis, InverseMulFunctor<T>(), z);
  }
75
}
76

77 78 79 80 81 82
template <typename DeviceContext, typename T, class Enable = void>
struct SameDimsElemwiseMul {
  void operator()(const framework::ExecutionContext& ctx,
                  const framework::Tensor* x, const framework::Tensor* y,
                  framework::Tensor* z);
};
83

Q
QI JUN 已提交
84
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
85
class ElementwiseMulKernel : public framework::OpKernel<T> {
86 87
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
C
chengduo 已提交
88
    auto x_var = ctx.InputVar("X");
89 90 91 92
    PADDLE_ENFORCE_EQ(x_var != nullptr, true,
                      platform::errors::InvalidArgument(
                          "Cannot get input Variable X, Variable name = %s.",
                          ctx.InputName("X")));
C
chengduo 已提交
93
    auto* y = ctx.Input<framework::LoDTensor>("Y");
C
chengduo 已提交
94 95

    framework::Tensor x, *z;
96
    if (x_var->IsType<phi::SelectedRows>()) {
97 98 99 100 101
      PADDLE_ENFORCE_EQ(y->dims().size() == 1 && y->dims()[0] == 1, true,
                        platform::errors::InvalidArgument(
                            "For elementwise_op, if X is Sparse, Y must be "
                            "scalar. But reveived the size of Y = %s.",
                            y->dims().size()));
102 103
      auto& x_sele = x_var->Get<phi::SelectedRows>();
      auto out_sele = ctx.Output<phi::SelectedRows>("Out");
C
chengduo 已提交
104 105 106 107 108
      x = x_sele.value();
      out_sele->set_rows(x_sele.rows());
      out_sele->set_height(x_sele.height());
      out_sele->mutable_value()->Resize(x_sele.value().dims());
      out_sele->mutable_value()->mutable_data(ctx.GetPlace(), x.type());
109
      z = ctx.Output<phi::SelectedRows>("Out")->mutable_value();
Y
YuanRisheng 已提交
110 111 112 113 114 115 116 117
      z->mutable_data<T>(ctx.GetPlace());
      auto dims_equal = x.dims() == y->dims();
      if (dims_equal) {
        SameDimsElemwiseMul<DeviceContext, T> same_dims_mul;
        same_dims_mul(ctx, &x, y, z);
      } else {
        default_elementwise_mul<DeviceContext, T>(ctx, &x, y, z);
      }
C
chengduo 已提交
118
    } else if (x_var->IsType<framework::LoDTensor>()) {
Y
YuanRisheng 已提交
119 120 121 122 123 124
      auto* x_lod = ctx.Input<framework::LoDTensor>("X");
      auto* z_lod = ctx.Output<framework::LoDTensor>("Out");
      z_lod->mutable_data<T>(ctx.GetPlace());

      auto& dev_ctx = ctx.device_context<DeviceContext>();
      int axis = ctx.Attr<int>("axis");
125 126 127
      auto pt_x = paddle::experimental::MakePhiDenseTensor(*x_lod);
      auto pt_y = paddle::experimental::MakePhiDenseTensor(*y);
      auto pt_z = paddle::experimental::MakePhiDenseTensor(*z_lod);
128
      phi::MultiplyRawKernel<T>(
129
          static_cast<const typename framework::ConvertToPhiContext<
W
Wilber 已提交
130 131
              DeviceContext>::TYPE&>(dev_ctx),
          *pt_x.get(), *pt_y.get(), axis, pt_z.get());
C
chengduo 已提交
132
    } else {
133 134 135 136
      PADDLE_THROW(platform::errors::InvalidArgument(
          "X's type[%s] is not supported by elementwise_op. X's type should be "
          "LoDTensor or SelectedRows.",
          framework::ToTypeName(x_var->Type())));
C
chengduo 已提交
137
    }
G
gongweibao 已提交
138 139
  }
};
140

141 142
}  // namespace operators
}  // namespace paddle