elementwise_mkldnn_op.h 14.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2020 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.

#pragma once
16
#include <string>
17 18 19
#include <unordered_map>

#include "paddle/fluid/framework/data_layout_transform.h"
20 21
#include "paddle/fluid/operators/elementwise/elementwise_op.h"
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
22 23 24 25 26
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

27 28 29
using dnnl::memory;
using dnnl::primitive;
using dnnl::stream;
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
using framework::DataLayout;
using framework::Tensor;

inline std::vector<int64_t> CalculateBroadcastedDims(const Tensor* x,
                                                     const Tensor* y) {
  const auto src_tz = phi::vectorize(x->dims());
  const auto dst_tz = phi::vectorize(y->dims());

  size_t j = 0;
  std::vector<int64_t> dst_tz_ex(src_tz.size(), 1);
  for (size_t i = 0; i < src_tz.size(); ++i) {
    dst_tz_ex[i] = (src_tz[i] != dst_tz[j]) ? 1 : dst_tz[j++];
    if (j == dst_tz.size()) break;
  }

  return dst_tz_ex;
}
47 48 49

template <typename T, dnnl::algorithm BINARY_OP>
class EltwiseMKLDNNKernel : public framework::OpKernel<T> {
50 51 52
 private:
  dnnl::post_ops get_post_ops(const framework::ExecutionContext& ctx) const {
    dnnl::post_ops post_operations;
53
    platform::AppendActivation(ctx, post_operations);
54 55 56
    return post_operations;
  }

57 58 59 60 61 62
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const auto& dev_ctx =
        ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();

63 64
    auto* x = ctx.Input<Tensor>("X");
    auto* y = ctx.Input<Tensor>("Y");
65 66 67 68 69 70 71
    auto* z = ctx.Output<Tensor>("Out");

    float scale_x = ctx.Attr<float>("Scale_x");
    float scale_y = ctx.Attr<float>("Scale_y");
    float scale_o = ctx.Attr<float>("Scale_out");
    int axis = ctx.Attr<int>("axis");

72 73 74 75 76 77 78 79 80 81
    platform::BinaryMKLDNNHandler<T> handler(BINARY_OP,
                                             axis,
                                             mkldnn_engine,
                                             ctx.GetPlace(),
                                             x,
                                             y,
                                             z,
                                             scale_x,
                                             scale_y,
                                             scale_o,
82
                                             true,
83
                                             get_post_ops(ctx));
84

85 86 87 88 89 90
    // oneDNN's binary is optimized for broadcasting y into x, so in other case
    // we have to swap tensors to achieve optimal performance
    if (x->numel() < y->numel()) {
      std::swap(x, y);
    }

91 92
    const auto src_x_memory = handler.AcquireSrcMemory(x);
    const auto src_y_memory = handler.AcquireSecondSrcMemory(y);
93 94 95 96 97 98 99 100 101
    // (jczaja) For Inplace src and dst should be the same memory object.
    // So x should share buffer with z. But UT mechanics is testing inplace
    // execution for this op not checking that x can be bradcasted to match in
    // shape y tensor.
    // This is wrong as when x is to be broadcasted then z(out) will match the
    // shape of y which is bigger than x. Hence if x is smaller in shape than z
    // and they share a buffer (of
    // shape x) then this buffer is not big enough to hold result of elementwise
    // operation.
102 103
    const bool reuse_x_memopry =
        x->numel() == z->numel() && x->IsSharedBufferWith(*z);
104
    std::shared_ptr<dnnl::memory> dst_memory;
105 106 107 108 109 110 111 112 113 114 115 116 117
    if (reuse_x_memopry) {
      dst_memory = src_x_memory;
      // NOTE(chenfeiyu): when the output reuses memory from other tensor rather
      // than allocate its own, it's still need to take care of its data type.
      // Unfortunately, paddle's operator only infers the output' shape, but not
      // the data type. mutable_data<T> takes care of allocation and data type
      // normally, but if the memory is already allocated and there is no need
      // to re-allocate, it just set the data type. So this it added there to
      // get the right data type.
      z->mutable_data<T>(ctx.GetPlace());
    } else {
      dst_memory = handler.AcquireDstMemory(z);
    }
118 119 120

    const auto binary_prim = handler.AcquireForwardPrimitive();

121
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
122 123 124 125 126 127 128 129 130

    const std::unordered_map<int, dnnl::memory> args = {
        {DNNL_ARG_SRC_0, *src_x_memory},
        {DNNL_ARG_SRC_1, *src_y_memory},
        {DNNL_ARG_DST, *dst_memory}};

    binary_prim->execute(astream, args);
    astream.wait();

131
    if (handler.use_broadcasting_hack == false) {
132 133
      platform::SetOutMemDescWithLogicalLayoutFusesSupport(
          ctx, z, dst_memory->get_desc());
134 135 136 137
    } else {
      auto dims = dst_memory->get_desc().dims();
      dims.insert(dims.begin(), x->dims()[0]);
      dims[1] /= dims[0];
138 139
      platform::SetOutMemDescWithLogicalLayoutFusesSupport(
          ctx, z, dst_memory->get_desc().reshape(dims));
140
    }
141 142
  }
};
143

144 145 146 147 148 149
template <typename T, dnnl::algorithm BINARY_OP>
class EltwiseMKLDNNGradKernel : public ElemwiseGradKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    ElemwiseGradKernel<T>::Compute(ctx);
    using Tensor = framework::Tensor;
150

151 152 153
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& onednn_engine = dev_ctx.GetEngine();
154

155 156 157 158 159 160 161
    auto* x = ctx.Input<Tensor>("X");
    auto* y = ctx.Input<Tensor>("Y");
    auto* out = ctx.Input<Tensor>("Out");

    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* dy = ctx.Output<Tensor>(framework::GradVarName("Y"));
    auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
162
    VLOG(4) << "element sub: dx " << dx << " dy " << dy << " dout " << dout;
163

164 165
    // oneDNN's binary is optimized for broadcasting y into x, so in other case
    // we have to swap tensors to achieve optimal performance
166
    bool swap_x_y = false;
167 168 169
    if (x->numel() < y->numel()) {
      std::swap(x, y);
      std::swap(dx, dy);
170 171 172 173 174 175
      swap_x_y = true;
    }

    std::vector<float> scales{1.0};
    if (swap_x_y) {
      scales[0] = (BINARY_OP == dnnl::algorithm::binary_add) ? 1 : -1;
176 177
    }

178 179 180 181 182 183
    int axis = ctx.Attr<int>("axis");

    auto tz = phi::vectorize<int64_t>(dout->dims());
    auto proto_type_dout = framework::TransToProtoVarType(dout->dtype());

    platform::ReorderMKLDNNHandler reorder_handler(
184 185 186
        tz,
        proto_type_dout,
        framework::ToMKLDNNDataType(proto_type_dout),
187 188 189
        onednn_engine);

    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
190
        dout->mem_desc(), platform::to_void_cast(dout->data<T>()));
191 192 193 194 195 196 197 198

    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
    if (dx) {
      std::shared_ptr<dnnl::memory> dst_memory;

      // elementwise_add & elementwise_sub
      if (BINARY_OP == dnnl::algorithm::binary_add ||
          BINARY_OP == dnnl::algorithm::binary_sub) {
199 200
        dst_memory = reorder_handler.AcquireDstMemory(
            dx, dout->mem_desc(), ctx.GetPlace());
201 202 203 204 205

        dnnl::primitive_attr reorder_attr;
        reorder_attr.set_output_scales(0, scales);
        auto reorder_p = reorder_handler.AcquireReorder(
            dst_memory, reorder_src_memory_p, reorder_attr);
206
        platform::RecordEvent record_reorder(
207 208 209
            "int_reorder",
            platform::TracerEventType::UserDefined,
            2,
210 211 212
            platform::EventRole::kUniqueOp);

        reorder_p->execute(astream, *reorder_src_memory_p, *dst_memory);
213

214
      } else {  // elementwise_mul & elementwise_div
215 216 217 218 219 220 221 222 223
        platform::BinaryMKLDNNHandler<T> binary_handler(BINARY_OP,
                                                        axis,
                                                        onednn_engine,
                                                        ctx.GetPlace(),
                                                        dout,
                                                        y,
                                                        dx,
                                                        1.0f,
                                                        1.0f,
224 225
                                                        1.0f,
                                                        false);
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

        const auto src_dout_memory = binary_handler.AcquireSrcMemory(dout);
        const auto src_y_memory = binary_handler.AcquireSecondSrcMemory(y);
        dst_memory = binary_handler.AcquireDstMemory(dx);

        const auto binary_prim = binary_handler.AcquireForwardPrimitive();

        const std::unordered_map<int, dnnl::memory> args = {
            {DNNL_ARG_SRC_0, *src_dout_memory},
            {DNNL_ARG_SRC_1, *src_y_memory},
            {DNNL_ARG_DST, *dst_memory}};

        binary_prim->execute(astream, args);
      }
      astream.wait();

242
      dx->set_mem_desc(dst_memory->get_desc());
243 244 245 246 247 248 249 250 251 252 253 254
    }

    if (dy) {
      dnnl::primitive_attr broadcast_reduction_attr;
      std::shared_ptr<dnnl::memory> broadcast_src_memory;
      std::shared_ptr<dnnl::memory> dst_memory;

      // elementwise_add & elementwise_sub
      if (BINARY_OP == dnnl::algorithm::binary_add ||
          BINARY_OP == dnnl::algorithm::binary_sub) {
        if (dout->dims() == dy->dims()) {
          auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
255
              dy, dout->mem_desc(), ctx.GetPlace());
256 257 258

          dnnl::primitive_attr reorder_attr;
          reorder_attr.set_output_scales(0, scales);
259 260 261

          auto reorder_p = reorder_handler.AcquireReorder(
              reorder_dst_memory_p, reorder_src_memory_p, reorder_attr);
262
          platform::RecordEvent record_reorder(
263 264 265
              "int_reorder",
              platform::TracerEventType::UserDefined,
              2,
266
              platform::EventRole::kUniqueOp);
267 268
          reorder_p->execute(
              astream, *reorder_src_memory_p, *reorder_dst_memory_p);
269 270 271 272 273

          dst_memory = reorder_dst_memory_p;
        } else {
          broadcast_src_memory = reorder_src_memory_p;
        }
274
      } else {  // elementwise_mul & elementwise_div
275 276 277 278 279 280 281
        std::unordered_map<int, dnnl::memory> args;
        std::shared_ptr<dnnl::binary> binary_prim;
        std::shared_ptr<dnnl::memory> post_op_memory;
        std::shared_ptr<dnnl::memory> src_0_memory;
        std::shared_ptr<dnnl::memory> src_1_memory;

        platform::BinaryMKLDNNHandler<T> binary_handler(
282 283 284 285 286 287 288 289 290
            dnnl::algorithm::binary_mul,
            axis,
            onednn_engine,
            ctx.GetPlace(),
            dout,
            x,
            nullptr,
            1.0f,
            1.0f,
291 292
            1.0f,
            false);
293 294 295 296 297

        src_1_memory = binary_handler.AcquireSecondSrcMemory(x);

        if (BINARY_OP == dnnl::algorithm::binary_div) {
          platform::BinaryMKLDNNHandler<T> post_op_binary_handler(
298 299 300 301 302 303 304 305 306
              dnnl::algorithm::binary_div,
              axis,
              onednn_engine,
              ctx.GetPlace(),
              y,
              y,
              nullptr,
              1.0f,
              1.0f,
307 308
              1.0f,
              false);
309 310 311 312 313 314 315

          post_op_memory = post_op_binary_handler.AcquireSrcMemory(y);

          dnnl::post_ops po;
          po.append_binary(dnnl::algorithm::binary_div,
                           post_op_memory->get_desc());

316 317 318 319 320 321 322 323 324 325 326
          binary_handler =
              platform::BinaryMKLDNNHandler<T>(dnnl::algorithm::binary_mul,
                                               axis,
                                               onednn_engine,
                                               ctx.GetPlace(),
                                               dout,
                                               out,
                                               nullptr,
                                               -1.0f,
                                               1.0f,
                                               1.0f,
327
                                               false,
328
                                               po);
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

          src_1_memory = binary_handler.AcquireSecondSrcMemory(out);
        }

        src_0_memory = binary_handler.AcquireSrcMemory(dout);

        const auto dst_dy_memory = (dout->dims() == dy->dims())
                                       ? binary_handler.AcquireDstMemory(dy)
                                       : binary_handler.AcquireDstMemory();

        binary_prim = binary_handler.AcquireForwardPrimitive();
        args = {{DNNL_ARG_SRC_0, *src_0_memory},
                {DNNL_ARG_SRC_1, *src_1_memory},
                {DNNL_ARG_DST, *dst_dy_memory}};

        if (BINARY_OP == dnnl::algorithm::binary_div)
          args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(0) | DNNL_ARG_SRC_1,
                       *post_op_memory});

        binary_prim->execute(astream, args);
        broadcast_src_memory = dst_dy_memory;
        dst_memory = dst_dy_memory;
      }
      astream.wait();

      if (dout->dims() != dy->dims()) {
        // Broadcasting
        if (BINARY_OP == dnnl::algorithm::binary_sub) {
          dnnl::post_ops po;
358 359
          po.append_eltwise(
              1.0f, dnnl::algorithm::eltwise_linear, scales[0], 0);
360 361 362 363
          broadcast_reduction_attr.set_post_ops(po);
        }

        platform::ReductionMKLDNNHandler<T> reduction_handler(
364 365 366 367 368 369 370 371
            dnnl::algorithm::reduction_sum,
            0.0f,
            0.0f,
            onednn_engine,
            ctx.GetPlace(),
            dout,
            dy,
            CalculateBroadcastedDims(dout, dy),
372 373 374 375 376
            broadcast_reduction_attr);
        dst_memory = reduction_handler.AcquireDstMemory(dy);

        auto reduction_p = reduction_handler.AcquireForwardPrimitive();

377 378 379 380 381
        reduction_p->execute(astream,
                             {
                                 {DNNL_ARG_SRC, *broadcast_src_memory},
                                 {DNNL_ARG_DST, *dst_memory},
                             });
382
        astream.wait();
383 384
        dy->set_mem_desc(dst_memory->get_desc().reshape(
            phi::vectorize<int64_t>(dy->dims())));
385
      } else {
386
        dy->set_mem_desc(dst_memory->get_desc());
387 388 389 390
      }
    }
  }
};
391 392
}  // namespace operators
}  // namespace paddle