softmax_mkldnn_op.cc 6.9 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 <iostream>
16
#include <numeric>
17 18
#include "mkldnn.hpp"
#include "paddle/fluid/operators/softmax_op.h"
J
Jacek Czaja 已提交
19
#include "paddle/fluid/platform/mkldnn_reuse.h"
20 21 22 23 24 25 26 27 28 29 30

namespace paddle {
namespace operators {

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

using mkldnn::memory;  // Note: paddle has also "memory" namespace
using mkldnn::primitive;
using mkldnn::prop_kind;
F
fengjiayi 已提交
31 32
using mkldnn::softmax_backward;
using mkldnn::softmax_forward;
33
using mkldnn::stream;
J
Jacek Czaja 已提交
34 35
using platform::to_void_cast;

36
template <typename T>
37 38 39
class SoftmaxMKLDNNHandler
    : public platform::MKLDNNHandlerT<T, mkldnn::softmax_forward,
                                      mkldnn::softmax_backward> {
J
Jacek Czaja 已提交
40
 public:
A
Adam 已提交
41
  SoftmaxMKLDNNHandler(const std::vector<int64_t>& dims,
42
                       const MKLDNNMemoryFormat fmt, const int& axis,
43
                       const platform::MKLDNNDeviceContext& dev_ctx,
44
                       platform::Place cpu_place, const std::string& uniq_name)
45 46 47
      : platform::MKLDNNHandlerT<T, mkldnn::softmax_forward,
                                 mkldnn::softmax_backward>(
            dev_ctx, dev_ctx.GetEngine(), cpu_place,
48
            platform::CreateKey(dims, uniq_name)) {
49 50 51
    auto md = mkldnn::memory::desc(dims, platform::MKLDNNGetDataType<T>(), fmt);

    this->AcquireForwardPrimitiveDescriptor(prop_kind::forward_scoring, md,
52
                                            axis);
53
  }
J
Jacek Czaja 已提交
54

A
Adam 已提交
55
  SoftmaxMKLDNNHandler(const std::vector<int64_t>& dims,
56
                       const MKLDNNMemoryFormat fmt,
57
                       const MKLDNNMemoryFormat diff_fmt, const int& axis,
58
                       const platform::MKLDNNDeviceContext& dev_ctx,
59
                       platform::Place cpu_place, const std::string& uniq_name)
60 61 62
      : platform::MKLDNNHandlerT<T, mkldnn::softmax_forward,
                                 mkldnn::softmax_backward>(
            dev_ctx, dev_ctx.GetEngine(), cpu_place,
63
            platform::CreateKey(dims, uniq_name)) {
64 65 66 67 68 69
    auto data_softmax_md =
        mkldnn::memory::desc(dims, platform::MKLDNNGetDataType<T>(), fmt);
    auto diff_softmax_md =
        mkldnn::memory::desc(dims, platform::MKLDNNGetDataType<T>(), diff_fmt);

    this->AcquireBackwardPrimitiveDescriptor(diff_softmax_md, data_softmax_md,
70
                                             axis);
71
  }
J
Jacek Czaja 已提交
72
};
73 74 75 76 77 78 79 80 81 82

template <typename T>
class SoftmaxMKLDNNKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "It must use CPUPlace.");
    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    const Tensor* input = ctx.Input<Tensor>("X");
    Tensor* output = ctx.Output<Tensor>("Out");
F
fengjiayi 已提交
83 84 85 86 87
    PADDLE_ENFORCE_EQ(
        input->dims(), output->dims(),
        "The shape of softmax's input and output must be identical.");

    auto dims = input->dims();  // input and output share the same shape
88
    const int axis = CanonicalAxis(ctx.Attr<int>("axis"), dims.size());
F
fengjiayi 已提交
89

A
Adam 已提交
90
    auto softmax_tz = paddle::framework::vectorize<int64_t>(dims);
91

92
    SoftmaxMKLDNNHandler<T> handler(softmax_tz, input->format(), axis, dev_ctx,
H
hong 已提交
93
                                    ctx.GetPlace(), ctx.OutputName("Out"));
94

95
    auto softmax_src_memory_p = handler.AcquireSrcMemory(input);
A
Adam 已提交
96
    auto softmax_p = handler.AcquireForwardPrimitive();
97 98 99 100
    // For Inplace src and and dst are the same memory object
    auto softmax_dst_memory_p = input->Holder() == output->Holder()
                                    ? softmax_src_memory_p
                                    : handler.AcquireDstMemory(output);
101

A
Adam 已提交
102 103 104 105
    mkldnn::stream astream(dev_ctx.GetEngine());
    softmax_p->execute(astream, {{MKLDNN_ARG_SRC, *softmax_src_memory_p},
                                 {MKLDNN_ARG_DST, *softmax_dst_memory_p}});
    astream.wait();
J
Jacek Czaja 已提交
106 107 108

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

    output->set_layout(framework::DataLayout::kMKLDNN);
    // Softmax output format is the same as input one
    output->set_format(input->format());
118 119 120
  }
};

J
Jacek Czaja 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133
template <typename T>
class SoftmaxMKLDNNGradKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
                   "It must use CPUPlace.");

    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    const Tensor* output = ctx.Input<Tensor>("Out");
    auto* dout = ctx.template Input<Tensor>(framework::GradVarName("Out"));
    auto* dx =
        ctx.template Output<framework::Tensor>(framework::GradVarName("X"));

F
fengjiayi 已提交
134 135 136 137 138
    PADDLE_ENFORCE_EQ(
        dout->dims(), dx->dims(),
        "The shape of softmax_grad's input and output must be identical.");

    auto dims = dout->dims();  // input and output share the same shape
139
    const int axis = CanonicalAxis(ctx.Attr<int>("axis"), dims.size());
F
fengjiayi 已提交
140

A
Adam 已提交
141
    auto softmax_tz = paddle::framework::vectorize<int64_t>(dims);
F
fengjiayi 已提交
142

143 144
    SoftmaxMKLDNNHandler<T> handler(softmax_tz, output->format(),
                                    dout->format(), axis, dev_ctx,
H
hong 已提交
145
                                    ctx.GetPlace(), ctx.InputName("Out"));
146

147 148 149
    auto dst_memory_p = handler.AcquireDstMemory(output);
    auto diff_dst_memory_p = handler.AcquireDiffDstMemory(dout);
    auto diff_src_memory_p = handler.AcquireDiffSrcMemory(dx);
J
Jacek Czaja 已提交
150

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

A
Adam 已提交
153 154 155 156 157 158
    mkldnn::stream astream(dev_ctx.GetEngine());
    softmax_bwd_p->execute(astream,
                           {{MKLDNN_ARG_DST, *dst_memory_p},
                            {MKLDNN_ARG_DIFF_DST, *diff_dst_memory_p},
                            {MKLDNN_ARG_DIFF_SRC, *diff_src_memory_p}});
    astream.wait();
159 160 161

    dx->set_layout(framework::DataLayout::kMKLDNN);
    dx->set_format(dout->format());
J
Jacek Czaja 已提交
162 163
  }
};
164 165 166 167 168 169 170
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_KERNEL(softmax, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::SoftmaxMKLDNNKernel<float>);
J
Jacek Czaja 已提交
171 172
REGISTER_OP_KERNEL(softmax_grad, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::SoftmaxMKLDNNGradKernel<float>);