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

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

namespace paddle {
namespace operators {

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

26 27 28 29 30 31
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 已提交
32 33
using platform::to_void_cast;

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

50 51
    this->AcquireForwardPrimitiveDescriptor(prop_kind::forward_scoring,
                                            input->mem_desc(), axis);
52
  }
J
Jacek Czaja 已提交
53

54
  SoftmaxMKLDNNHandler(const framework::ExecutionContext& ctx,
55
                       const dnnl::engine mkldnn_engine,
56 57 58
                       platform::Place cpu_place, const Tensor* out,
                       const Tensor* out_grad, Tensor* in_x_grad,
                       const std::string& unique_name)
59 60 61
      : platform::MKLDNNHandlerNoCachingT<T, dnnl::softmax_forward,
                                          dnnl::softmax_backward>(mkldnn_engine,
                                                                  cpu_place) {
62 63 64 65 66 67 68 69
    PADDLE_ENFORCE_EQ(out_grad->dims(), in_x_grad->dims(),
                      platform::errors::InvalidArgument(
                          "The shape of softmax_grad's input "
                          "and output must be identical, but shapes differ, "
                          "out_grad: %s in_grad: %s",
                          out_grad->dims(), in_x_grad->dims()));

    auto dims = out_grad->dims();  // input and output share the same shape
70 71
    const int axis =
        phi::funcs::CanonicalAxis(ctx.Attr<int>("axis"), dims.size());
72 73

    this->AcquireForwardPrimitiveDescriptor(prop_kind::forward_scoring,
74 75 76
                                            out->mem_desc(), axis);
    this->AcquireBackwardPrimitiveDescriptor(out_grad->mem_desc(),
                                             out->mem_desc(), axis);
77
  }
J
Jacek Czaja 已提交
78
};
79 80 81 82 83 84

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>();
85 86
    const auto& mkldnn_engine = dev_ctx.GetEngine();

87 88
    const Tensor* input = ctx.Input<Tensor>("X");
    Tensor* output = ctx.Output<Tensor>("Out");
89
    bool is_inplaced = input->IsSharedBufferWith(*output);
F
fengjiayi 已提交
90

91 92
    const int axis =
        phi::funcs::CanonicalAxis(ctx.Attr<int>("axis"), input->dims().size());
93

94 95
    SoftmaxMKLDNNHandler<T> handler(mkldnn_engine, ctx.GetPlace(), input,
                                    output, axis);
96

97
    auto softmax_src_memory_p = handler.AcquireSrcMemory(input);
98
    // For Inplace src and and dst are the same memory object
99 100 101 102 103 104 105
    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);
    }
106 107
    auto softmax_p = handler.AcquireForwardPrimitive();

108
    auto& astream = paddle::platform::MKLDNNDeviceContext::tls().get_stream();
109 110
    softmax_p->execute(astream, {{DNNL_ARG_SRC, *softmax_src_memory_p},
                                 {DNNL_ARG_DST, *softmax_dst_memory_p}});
A
Adam 已提交
111
    astream.wait();
J
Jacek Czaja 已提交
112 113 114

    const bool is_test = ctx.Attr<bool>("is_test");
    if (!is_test) {
115
      T* output_data = output->mutable_data<T>(ctx.GetPlace());
A
Adam 已提交
116
      std::for_each(output_data, &output_data[output->numel()], [](T& val) {
117 118
        val = std::max(val, static_cast<T>(exp(-64)));
      });
J
Jacek Czaja 已提交
119
    }
120

121
    output->set_mem_desc(softmax_dst_memory_p->get_desc());
122 123 124
  }
};

J
Jacek Czaja 已提交
125 126 127 128
template <typename T>
class SoftmaxMKLDNNGradKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
129 130 131
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL SoftmaxGrad must use CPUPlace"));
J
Jacek Czaja 已提交
132
    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
133
    const auto& mkldnn_engine = dev_ctx.GetEngine();
J
Jacek Czaja 已提交
134
    const Tensor* output = ctx.Input<Tensor>("Out");
135 136
    auto* out_grad = ctx.template Input<Tensor>(framework::GradVarName("Out"));
    auto* in_x_grad = ctx.template Output<Tensor>(framework::GradVarName("X"));
F
fengjiayi 已提交
137

138
    SoftmaxMKLDNNHandler<T> handler(ctx, mkldnn_engine, ctx.GetPlace(), output,
139
                                    out_grad, in_x_grad, ctx.InputName("Out"));
140

141
    auto dst_memory_p = handler.AcquireDstMemory(output);
142 143
    auto diff_dst_memory_p = handler.AcquireDiffDstMemory(out_grad);
    auto diff_src_memory_p = handler.AcquireDiffSrcMemory(in_x_grad);
J
Jacek Czaja 已提交
144

A
Adam 已提交
145
    auto softmax_bwd_p = handler.AcquireBackwardPrimitive();
J
Jacek Czaja 已提交
146

147
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
148 149 150
    softmax_bwd_p->execute(astream, {{DNNL_ARG_DST, *dst_memory_p},
                                     {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                                     {DNNL_ARG_DIFF_SRC, *diff_src_memory_p}});
A
Adam 已提交
151
    astream.wait();
152

153
    in_x_grad->set_mem_desc(diff_src_memory_p->get_desc());
J
Jacek Czaja 已提交
154 155
  }
};
156 157 158 159 160 161
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_KERNEL(softmax, MKLDNN, ::paddle::platform::CPUPlace,
162 163
                   ops::SoftmaxMKLDNNKernel<float>,
                   ops::SoftmaxMKLDNNKernel<paddle::platform::bfloat16>);
J
Jacek Czaja 已提交
164 165
REGISTER_OP_KERNEL(softmax_grad, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::SoftmaxMKLDNNGradKernel<float>);