prelu_mkldnn_op.cc 8.1 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/expect.h"
16 17 18 19 20 21
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

using dnnl::memory;
22

23 24 25 26 27 28 29
using platform::MKLDNNDeviceContext;
using platform::MKLDNNGetDataType;
using platform::to_void_cast;

namespace {
template <typename T>
class PReluMKLDNNHandler
30 31
    : public platform::
          MKLDNNHandlerT<T, dnnl::prelu_forward, dnnl::prelu_backward> {
32 33
 public:
  PReluMKLDNNHandler(const MKLDNNDeviceContext& dev_ctx,
34 35
                     const dnnl::engine engine,
                     platform::Place cpu_place,
36 37
                     const phi::DenseTensor* x,
                     const phi::DenseTensor* weights,
38 39 40 41
                     const std::string& uniq_name,
                     const std::string& mode,
                     const std::string& data_format,
                     bool is_test = false)
42
      : platform::MKLDNNHandlerT<T, dnnl::prelu_forward, dnnl::prelu_backward>(
43 44 45 46 47
            dev_ctx,
            engine,
            cpu_place,
            platform::CreateKey(
                dev_ctx, phi::vectorize(x->dims()), uniq_name)) {
48
    if (unlikely(!this->isCached())) {
49
      auto weights_dims = phi::vectorize(weights->dims());
50 51 52 53 54

      // weights must have same size as X only for "element" case
      if (weights->dims().size() != x->dims().size()) {
        auto new_weights_dims = std::vector<int64_t>(x->dims().size(), 1);
        if (mode == "channel") {
J
Jacek Czaja 已提交
55 56
          new_weights_dims[1] =
              *std::max_element(weights_dims.begin(), weights_dims.end());
57 58 59
        }
        weights_dims = std::move(new_weights_dims);
      }
60 61
      auto weights_md = memory::desc(
          weights_dims, MKLDNNGetDataType<T>(), memory::format_tag::any);
62

63 64
      this->AcquireForwardPrimitiveDescriptor(
          dnnl::prop_kind::forward_training, x->mem_desc(), weights_md);
65
      if (!is_test)
66 67
        this->AcquireBackwardPrimitiveDescriptor(
            x->mem_desc(), weights_md, x->mem_desc(), weights_md);
68 69 70 71
    }
  }

  std::shared_ptr<memory> AcquireWeightsMemoryPossiblyWithReorder(
72
      const phi::DenseTensor* weights, const bool is_test) {
73
    const T* weights_data = weights->data<T>();
74 75 76

    // if weights are 1D, every format tag is correct, so we accept
    // format_tag::any's output and no reorder is needed
77
    if (weights->dims().size() == 1) {
78
      return this->AcquireMemoryFromPrimitive(this->fwd_pd_->weights_desc(),
79
                                              to_void_cast<T>(weights_data),
80 81 82
                                              "@alpha_mem_p");
    }

83 84 85 86 87
    return this->AcquireMemoryWithReorder(weights->mem_desc(),
                                          this->fwd_pd_->weights_desc(),
                                          to_void_cast<T>(weights_data),
                                          "@alpha_mem_p",
                                          is_test);
88 89
  }

90
  std::shared_ptr<memory> AcquireDiffWeightsMemory(phi::DenseTensor* output) {
91 92
    T* output_data = output->mutable_data<T>(
        this->place_, this->bwd_pd_->diff_weights_desc().get_size());
93 94
    return this->AcquireMemoryFromPrimitive(
        this->bwd_pd_->diff_weights_desc(), output_data, "@diff_weights_mem_p");
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  }
};
}  // anonymous namespace

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

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

110 111 112
    const auto* x = ctx.Input<phi::DenseTensor>("X");
    const auto* alpha = ctx.Input<phi::DenseTensor>("Alpha");
    auto* out = ctx.Output<phi::DenseTensor>("Out");
113 114
    const bool is_test = ctx.Attr<bool>("is_test");
    const auto mode = ctx.Attr<std::string>("mode");
115
    const auto data_format = ctx.Attr<std::string>("data_format");
116

117 118 119 120 121 122 123 124
    PReluMKLDNNHandler<T> handler(dev_ctx,
                                  onednn_engine,
                                  ctx.GetPlace(),
                                  x,
                                  alpha,
                                  ctx.InputName("X"),
                                  mode,
                                  data_format,
125
                                  is_test);
126 127 128 129 130 131 132 133

    auto src_memory_p = handler.AcquireSrcMemory(x);
    auto weights_memory_p =
        handler.AcquireWeightsMemoryPossiblyWithReorder(alpha, is_test);
    auto dst_memory_p = handler.AcquireDstMemory(out);
    auto prelu_p = handler.AcquireForwardPrimitive();

    auto& astream = MKLDNNDeviceContext::tls().get_stream();
134 135 136 137
    prelu_p->execute(astream,
                     {{DNNL_ARG_SRC, *src_memory_p},
                      {DNNL_ARG_WEIGHTS, *weights_memory_p},
                      {DNNL_ARG_DST, *dst_memory_p}});
138 139
    astream.wait();

140
    out->set_mem_desc(dst_memory_p->get_desc());
141 142 143 144 145 146 147 148 149 150 151 152 153 154
  }
};

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

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

155 156 157 158 159 160
    auto* x = ctx.Input<phi::DenseTensor>("X");
    auto* dx = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
    auto* dout = ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto* dalpha =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Alpha"));
    auto* alpha = ctx.Input<phi::DenseTensor>("Alpha");
161 162
    const bool is_test = ctx.Attr<bool>("is_test");
    const auto mode = ctx.Attr<std::string>("mode");
163
    const auto data_format = ctx.Attr<std::string>("data_format");
164

165 166 167 168 169 170 171
    PReluMKLDNNHandler<T> handler(dev_ctx,
                                  onednn_engine,
                                  ctx.GetPlace(),
                                  x,
                                  alpha,
                                  framework::GradVarName("X"),
                                  mode,
172
                                  data_format);
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

    auto src_memory_p = handler.AcquireSrcMemory(x);
    auto weights_memory_p =
        handler.AcquireWeightsMemoryPossiblyWithReorder(alpha, is_test);
    auto diff_src_memory_p = handler.AcquireDiffSrcMemory(dx);
    auto diff_weights_memory_p = handler.AcquireDiffWeightsMemory(dalpha);
    auto diff_dst_memory_p = handler.AcquireDiffDstMemory(dout);
    auto prelu_p = handler.AcquireBackwardPrimitive();

    auto& astream = MKLDNNDeviceContext::tls().get_stream();
    prelu_p->execute(astream,
                     {{DNNL_ARG_SRC, *src_memory_p},
                      {DNNL_ARG_WEIGHTS, *weights_memory_p},
                      {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                      {DNNL_ARG_DIFF_SRC, *diff_src_memory_p},
                      {DNNL_ARG_DIFF_WEIGHTS, *diff_weights_memory_p}});
    astream.wait();

191
    dx->set_mem_desc(diff_src_memory_p->get_desc());
192 193 194 195 196 197
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
198 199 200
REGISTER_OP_KERNEL(prelu,
                   MKLDNN,
                   paddle::platform::CPUPlace,
201 202 203
                   ops::PReluMKLDNNKernel<float>,
                   ops::PReluMKLDNNKernel<paddle::platform::bfloat16>);

204 205 206
REGISTER_OP_KERNEL(prelu_grad,
                   MKLDNN,
                   paddle::platform::CPUPlace,
207 208
                   ops::PReluGradMKLDNNKernel<float>,
                   ops::PReluGradMKLDNNKernel<paddle::platform::bfloat16>);