expand_v2_mkldnn_op.cc 5.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

15
#include "paddle/fluid/framework/convert_utils.h"
J
jakpiase 已提交
16
#include "paddle/fluid/operators/expand_v2_op.h"
17 18 19 20 21
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace {

using paddle::framework::ExecutionContext;
22 23
using paddle::framework::GradVarName;
using paddle::framework::Tensor;
24
using paddle::platform::MKLDNNDeviceContext;
25
using phi::vectorize;
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

template <typename T>
class ExpandMKLDNNKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const ExecutionContext& ctx) const override {
    this->RunKernel(ctx);
  }

  void RunKernel(const ExecutionContext& ctx) const {
    const auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    const auto& onednn_engine = dev_ctx.GetEngine();

    const auto* x = ctx.Input<Tensor>("X");
    auto* out = ctx.Output<Tensor>("Out");

    auto x_vec_dims = vectorize(x->dims());
J
jakpiase 已提交
42 43 44 45 46

    auto out_new_dims = paddle::operators::get_expand_shape(ctx);
    for (size_t i = 0; i < out_new_dims.size(); ++i) {
      out_new_dims[i] = out_new_dims[i] > 0 ? out_new_dims[i] : x_vec_dims[i];
    }
47

J
jakpiase 已提交
48
    if (x_vec_dims.size() != out_new_dims.size()) {
49
      x_vec_dims = GetExtendedXDims(x_vec_dims, out_new_dims.size());
50 51
    }

52
    out->Resize(phi::make_ddim(out_new_dims));
53
    paddle::platform::BroadcastDataMKLDNNHandler<T> handler(
54 55 56 57 58 59 60 61
        dnnl::algorithm::binary_add,
        onednn_engine,
        ctx.GetPlace(),
        x,
        out,
        0.0f,
        1.0f,
        x_vec_dims);
62 63

    auto src_memory_p = handler.AcquireSrcMemory(x);
64
    auto dst_memory_p = handler.AcquireZeroedDstMemory(out);
65 66 67 68 69 70 71 72 73 74 75
    auto binary_p = handler.AcquireForwardPrimitive();

    const std::unordered_map<int, dnnl::memory> args = {
        {DNNL_ARG_SRC_0, *dst_memory_p},
        {DNNL_ARG_SRC_1, *src_memory_p},
        {DNNL_ARG_DST, *dst_memory_p}};

    auto& astream = MKLDNNDeviceContext::tls().get_stream();
    binary_p->execute(astream, args);
    astream.wait();

76
    out->set_mem_desc(dst_memory_p->get_desc());
77 78 79
  }

 private:
80 81 82
  std::vector<int64_t> GetExtendedXDims(const std::vector<int64_t>& x_vec_dims,
                                        int new_size) const {
    std::vector<int64_t> extended_x_dims(new_size, 1);
83 84
    std::copy(x_vec_dims.begin(),
              x_vec_dims.end(),
85
              extended_x_dims.begin() + new_size - x_vec_dims.size());
86

87
    return extended_x_dims;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  }
};

template <typename T>
class ExpandGradMKLDNNKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const ExecutionContext& ctx) const override {
    this->RunKernel(ctx);
  }

  void RunKernel(const ExecutionContext& ctx) const {
    const auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    const auto& onednn_engine = dev_ctx.GetEngine();

    auto* dout = ctx.Input<Tensor>(GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(GradVarName("X"));

    auto dx_vec_dims = vectorize(dx->dims());
    auto dout_vec_dims = vectorize(dout->dims());

    if (dx_vec_dims.size() != dout_vec_dims.size()) {
109 110
      dx_vec_dims.insert(
          dx_vec_dims.begin(), dout_vec_dims.size() - dx_vec_dims.size(), 1);
111 112 113 114
    }

    auto& astream = MKLDNNDeviceContext::tls().get_stream();
    if (dout_vec_dims == dx_vec_dims) {
115 116
      dnnl::memory::data_type dout_type = paddle::framework::ToMKLDNNDataType(
          paddle::framework::TransToProtoVarType(dout->dtype()));
117
      paddle::platform::ReorderMKLDNNHandler reorder_handler(
118 119 120 121
          dout_vec_dims,
          paddle::framework::TransToProtoVarType(dout->dtype()),
          dout_type,
          onednn_engine);
122 123

      auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
124
          dout->mem_desc(), paddle::platform::to_void_cast(dout->data<T>()));
125

126
      auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
127 128
          dx,
          paddle::platform::GetPlainMKLDNNFormat(dx_vec_dims.size()),
129
          ctx.GetPlace());
130 131 132 133 134 135 136

      auto reorder_p = reorder_handler.AcquireReorder(reorder_src_memory_p,
                                                      reorder_dst_memory_p);

      reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p);
      astream.wait();

137
      dx->set_mem_desc(reorder_dst_memory_p->get_desc());
138 139
    } else {
      paddle::platform::ReductionMKLDNNHandler<T> handler(
140 141 142 143 144 145 146 147
          dnnl::algorithm::reduction_sum,
          0.0f,
          0.0f,
          onednn_engine,
          ctx.GetPlace(),
          dout,
          dx,
          dx_vec_dims);
148 149 150 151 152 153 154 155 156 157 158 159

      auto src_memory_p = handler.AcquireSrcMemory(dout);
      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 reduction_p = handler.AcquireForwardPrimitive();

      reduction_p->execute(astream, reduction_args);
      astream.wait();
      dx->set_layout(paddle::framework::DataLayout::kMKLDNN);
160 161
      dx->set_mem_desc(
          dst_memory_p->get_desc().reshape(vectorize<int64_t>(dx->dims())));
162 163 164 165 166
    }
  }
};
}  // anonymous namespace

167 168 169
REGISTER_OP_KERNEL(expand_v2,
                   MKLDNN,
                   paddle::platform::CPUPlace,
170 171 172
                   ExpandMKLDNNKernel<float>,
                   ExpandMKLDNNKernel<paddle::platform::bfloat16>);

173 174 175
REGISTER_OP_KERNEL(expand_v2_grad,
                   MKLDNN,
                   paddle::platform::CPUPlace,
176 177
                   ExpandGradMKLDNNKernel<float>,
                   ExpandGradMKLDNNKernel<paddle::platform::bfloat16>);