softmax_mkldnn_op.cc 4.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/* Copyright (c) 2016 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. */

12
#include "paddle/fluid/framework/op_registry.h"
J
Jacek Czaja 已提交
13
#include "paddle/fluid/platform/mkldnn_reuse.h"
14
#include "paddle/phi/kernels/funcs/axis_utils.h"
15 16 17 18 19 20 21 22

namespace paddle {
namespace operators {

using paddle::framework::Tensor;
using paddle::platform::MKLDNNDeviceContext;
using paddle::platform::MKLDNNMemDesc;

23 24 25 26 27 28
using dnnl::memory;  // Note: paddle has also "memory" namespace
using dnnl::primitive;
using dnnl::prop_kind;
using dnnl::softmax_backward;
using dnnl::softmax_forward;
using dnnl::stream;
J
Jacek Czaja 已提交
29 30
using platform::to_void_cast;

31
template <typename T>
32
class SoftmaxMKLDNNHandler
33 34
    : public platform::MKLDNNHandlerNoCachingT<T,
                                               dnnl::softmax_forward,
35
                                               dnnl::softmax_backward> {
J
Jacek Czaja 已提交
36
 public:
37
  SoftmaxMKLDNNHandler(const dnnl::engine mkldnn_engine,
38 39 40 41 42 43
                       platform::Place cpu_place,
                       const Tensor* input,
                       Tensor* output,
                       const int axis)
      : platform::MKLDNNHandlerNoCachingT<T,
                                          dnnl::softmax_forward,
44 45
                                          dnnl::softmax_backward>(mkldnn_engine,
                                                                  cpu_place) {
46
    PADDLE_ENFORCE_EQ(
47 48
        input->dims(),
        output->dims(),
49 50 51
        platform::errors::InvalidArgument(
            "The shape of input and output tensor must be identical."));

52 53
    this->AcquireForwardPrimitiveDescriptor(
        prop_kind::forward_scoring, input->mem_desc(), axis);
54
  }
J
Jacek Czaja 已提交
55
};
56 57 58 59 60 61

template <typename T>
class SoftmaxMKLDNNKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
62 63
    const auto& mkldnn_engine = dev_ctx.GetEngine();

64 65
    const Tensor* input = ctx.Input<Tensor>("X");
    Tensor* output = ctx.Output<Tensor>("Out");
66
    bool is_inplaced = input->IsSharedBufferWith(*output);
F
fengjiayi 已提交
67

68 69
    const int axis =
        phi::funcs::CanonicalAxis(ctx.Attr<int>("axis"), input->dims().size());
70

71 72
    SoftmaxMKLDNNHandler<T> handler(
        mkldnn_engine, ctx.GetPlace(), input, output, axis);
73

74
    auto softmax_src_memory_p = handler.AcquireSrcMemory(input);
75
    // For Inplace src and and dst are the same memory object
76 77 78 79 80 81 82
    std::shared_ptr<dnnl::memory> softmax_dst_memory_p = nullptr;
    if (is_inplaced) {
      softmax_dst_memory_p = softmax_src_memory_p;
      output->mutable_data<T>(ctx.GetPlace());
    } else {
      softmax_dst_memory_p = handler.AcquireDstMemory(output);
    }
83 84
    auto softmax_p = handler.AcquireForwardPrimitive();

85
    auto& astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
86 87 88
    softmax_p->execute(astream,
                       {{DNNL_ARG_SRC, *softmax_src_memory_p},
                        {DNNL_ARG_DST, *softmax_dst_memory_p}});
A
Adam 已提交
89
    astream.wait();
J
Jacek Czaja 已提交
90 91 92

    const bool is_test = ctx.Attr<bool>("is_test");
    if (!is_test) {
93
      T* output_data = output->mutable_data<T>(ctx.GetPlace());
A
Adam 已提交
94
      std::for_each(output_data, &output_data[output->numel()], [](T& val) {
95 96
        val = std::max(val, static_cast<T>(exp(-64)));
      });
J
Jacek Czaja 已提交
97
    }
98

99
    output->set_mem_desc(softmax_dst_memory_p->get_desc());
100 101 102 103 104 105 106 107
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

108 109 110
REGISTER_OP_KERNEL(softmax,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
111 112
                   ops::SoftmaxMKLDNNKernel<float>,
                   ops::SoftmaxMKLDNNKernel<paddle::platform::bfloat16>);