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

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 已提交
30 31
using mkldnn::softmax_backward;
using mkldnn::softmax_forward;
32
using mkldnn::stream;
J
Jacek Czaja 已提交
33 34
using platform::to_void_cast;

35
template <typename T>
36 37 38
class SoftmaxMKLDNNHandler
    : public platform::MKLDNNHandlerT<T, mkldnn::softmax_forward,
                                      mkldnn::softmax_backward> {
J
Jacek Czaja 已提交
39
 public:
40
  SoftmaxMKLDNNHandler(const std::vector<int>& dims,
41
                       const MKLDNNMemoryFormat fmt,
42
                       const platform::MKLDNNDeviceContext& dev_ctx,
43
                       platform::Place cpu_place, const std::string& uniq_name)
44 45 46 47
      : platform::MKLDNNHandlerT<T, mkldnn::softmax_forward,
                                 mkldnn::softmax_backward>(
            dev_ctx, dev_ctx.GetEngine(), cpu_place,
            platform::CreateKey(dims, uniq_name)) {
48 49
    this->AcquireSoftmaxPrimitiveDescriptor(dims, fmt);
  }
J
Jacek Czaja 已提交
50

51
  SoftmaxMKLDNNHandler(const std::vector<int>& dims,
52 53
                       const MKLDNNMemoryFormat fmt,
                       const MKLDNNMemoryFormat diff_fmt,
54
                       const platform::MKLDNNDeviceContext& dev_ctx,
55
                       platform::Place cpu_place, const std::string& uniq_name)
56 57 58 59
      : platform::MKLDNNHandlerT<T, mkldnn::softmax_forward,
                                 mkldnn::softmax_backward>(
            dev_ctx, dev_ctx.GetEngine(), cpu_place,
            platform::CreateKey(dims, uniq_name)) {
J
Jacek Czaja 已提交
60 61
    // If we are in Grad operatgor then update a key with BWD suffix to
    // distinguish from FWD memory primitives
62
    // Key_common will allow to access FWD_PD from cache
63 64
    this->AcquireSoftmaxPrimitiveDescriptor(dims, fmt);
    this->AcquireSoftmaxBackwardPrimitiveDescriptor(dims, fmt, diff_fmt);
J
Jacek Czaja 已提交
65 66 67 68 69 70
  }

  std::shared_ptr<mkldnn::softmax_forward> AcquireSoftmax(
      std::shared_ptr<mkldnn::memory> dst_memory_p,
      std::shared_ptr<mkldnn::memory> src_memory_p) {
    /*Generate key*/
71
    auto prim_key = this->key_ + "@softmax_p";
J
Jacek Czaja 已提交
72 73

    auto softmax_p = std::static_pointer_cast<mkldnn::softmax_forward>(
74
        this->dev_ctx_.GetBlob(prim_key));
J
Jacek Czaja 已提交
75 76
    if (softmax_p == nullptr) {
      softmax_p = std::make_shared<mkldnn::softmax_forward>(
77
          *this->fwd_pd_, *(static_cast<mkldnn::memory*>(src_memory_p.get())),
J
Jacek Czaja 已提交
78
          *(static_cast<mkldnn::memory*>(dst_memory_p.get())));
79
      this->dev_ctx_.SetBlob(prim_key, softmax_p);
J
Jacek Czaja 已提交
80 81 82 83 84 85 86 87 88
    }

    return softmax_p;
  }

  std::shared_ptr<mkldnn::softmax_backward> AcquireSoftmaxBackward(
      std::shared_ptr<mkldnn::memory> dst_memory_p,
      std::shared_ptr<mkldnn::memory> diff_dst_memory_p,
      std::shared_ptr<mkldnn::memory> diff_src_memory_p) {
89
    auto prim_key = this->key_ + "@softmax_bwd_p";
J
Jacek Czaja 已提交
90
    auto softmax_bwd_p = std::static_pointer_cast<mkldnn::softmax_backward>(
91
        this->dev_ctx_.GetBlob(prim_key));
J
Jacek Czaja 已提交
92 93
    if (softmax_bwd_p == nullptr) {
      softmax_bwd_p = std::make_shared<mkldnn::softmax_backward>(
94 95 96
          *this->bwd_pd_, *dst_memory_p, *diff_dst_memory_p,
          *diff_src_memory_p);
      this->dev_ctx_.SetBlob(prim_key, softmax_bwd_p);
J
Jacek Czaja 已提交
97 98 99 100 101
    }

    return softmax_bwd_p;
  }

102
 protected:
103 104
  void AcquireSoftmaxPrimitiveDescriptor(const std::vector<int>& dims,
                                         const mkldnn::memory::format fmt) {
105 106 107
    // Softmax PD has to be passed to Grad op that
    // may be executed by diffrent thread, hence
    // for that one we use key that does not contain TID
108
    const std::string key_softmax_pd = this->key_common_ + "@softmax_pd";
109

110 111 112
    this->fwd_pd_ = std::static_pointer_cast<softmax_forward::primitive_desc>(
        this->dev_ctx_.GetBlob(key_softmax_pd));
    if (this->fwd_pd_ == nullptr) {
113 114 115
      static std::mutex acquire_barrier;
      std::lock_guard<std::mutex> block_threads_until_finish_this_job(
          acquire_barrier);
116 117 118
      this->fwd_pd_ = std::static_pointer_cast<softmax_forward::primitive_desc>(
          this->dev_ctx_.GetBlob(key_softmax_pd));
      if (this->fwd_pd_ == nullptr) {
119 120 121 122
        // TODO(jczaja): Make it working along chosen axis and for
        // forward_training
        // Normalization is made after innermost dimension eg. C out of NC
        auto md =
123
            mkldnn::memory::desc(dims, platform::MKLDNNGetDataType<T>(), fmt);
124 125
        auto softmax_desc =
            softmax_forward::desc(prop_kind::forward_scoring, md, 1 /*dim: C*/);
126 127 128
        this->fwd_pd_.reset(
            new softmax_forward::primitive_desc(softmax_desc, this->engine_));
        this->dev_ctx_.SetBlob(key_softmax_pd, this->fwd_pd_);
129 130 131 132
      }
    }
  }

133 134 135 136
  void AcquireSoftmaxBackwardPrimitiveDescriptor(
      const std::vector<int>& dims, const mkldnn::memory::format fmt,
      const mkldnn::memory::format diff_fmt) {
    // Fwd_PD_ has to exists when to create BWD_PD_
137 138 139
    PADDLE_ENFORCE_NOT_NULL(this->fwd_pd_);
    const std::string key_bwd_pd = this->key_ + "@softmax_bwd_pd";
    this->bwd_pd_ =
140
        std::static_pointer_cast<mkldnn::softmax_backward::primitive_desc>(
141 142
            this->dev_ctx_.GetBlob(key_bwd_pd));
    if (this->bwd_pd_ == nullptr) {
143 144 145 146 147 148 149
      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);
      // TODO(jczaja): Add support for other axes
      auto backward_desc = softmax_backward::desc(
          diff_softmax_md, data_softmax_md, 1 /* dim: C*/);
150 151 152
      this->bwd_pd_.reset(new mkldnn::softmax_backward::primitive_desc(
          backward_desc, this->engine_, *this->fwd_pd_));
      this->dev_ctx_.SetBlob(key_bwd_pd, this->bwd_pd_);
153 154
    }
  }
J
Jacek Czaja 已提交
155
};
156 157 158 159 160 161 162 163 164 165

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 已提交
166 167 168 169 170 171 172 173
    PADDLE_ENFORCE_EQ(
        input->dims(), output->dims(),
        "The shape of softmax's input and output must be identical.");

    // flatten input and output to 2-D matrixs
    auto dims = input->dims();  // input and output share the same shape
    auto flattened_dims = framework::flatten_to_2d(dims, dims.size() - 1);

174 175
    auto src_tz = paddle::framework::vectorize<int>(flattened_dims);
    auto dst_tz = src_tz;
176 177
    // Same memory descriptor to be used for input and output
    memory::dims softmax_tz = {src_tz[0], src_tz[1]};
178

179
    SoftmaxMKLDNNHandler<T> handler(softmax_tz, MKLDNNMemoryFormat::nc, dev_ctx,
180
                                    ctx.GetPlace(), ctx.op().Output("Out"));
181
    // Currently only NC data format is supported
182 183
    auto softmax_src_memory_p = handler.AcquireSrcMemory(input);
    auto softmax_dst_memory_p = handler.AcquireDstMemory(output);
J
Jacek Czaja 已提交
184 185
    auto softmax_p =
        handler.AcquireSoftmax(softmax_dst_memory_p, softmax_src_memory_p);
186 187 188

    std::vector<primitive> pipeline{
        *(static_cast<softmax_forward::primitive*>(softmax_p.get()))};
189
    stream(stream::kind::eager).submit(pipeline).wait();
J
Jacek Czaja 已提交
190

191
    T* output_data = output->mutable_data<T>(ctx.GetPlace());
J
Jacek Czaja 已提交
192 193 194
    const bool is_test = ctx.Attr<bool>("is_test");
    if (!is_test) {
      T threshold = exp(-64);
195
      for (int i = 0; i < dst_tz[0] * dst_tz[1]; ++i) {
J
Jacek Czaja 已提交
196 197 198 199
        output_data[i] =
            output_data[i] < threshold ? threshold : output_data[i];
      }
    }
200 201 202 203

    output->set_layout(framework::DataLayout::kMKLDNN);
    // Softmax output format is the same as input one
    output->set_format(input->format());
204 205 206
  }
};

J
Jacek Czaja 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219
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 已提交
220 221 222 223 224 225 226
    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
    auto flattened_dims = framework::flatten_to_2d(dims, dims.size() - 1);

227 228
    std::vector<int> dst_tz = paddle::framework::vectorize<int>(flattened_dims);
    std::vector<int> src_tz(dst_tz);
F
fengjiayi 已提交
229

J
Jacek Czaja 已提交
230 231 232 233 234 235
    // Same memory descriptor to be used for input and output
    memory::dims softmax_tz = {src_tz[0], src_tz[1]};

    // TODO(jczaja): Add layouts support when there is a need to do so
    // Two dimensional softmax does support NC format
    // Normalization is made after innermost dimension eg. C out of NC
236 237
    SoftmaxMKLDNNHandler<T> handler(softmax_tz, MKLDNNMemoryFormat::nc,
                                    MKLDNNMemoryFormat::nc, dev_ctx,
238
                                    ctx.GetPlace(), ctx.op().Input("Out"));
239

240 241 242
    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 已提交
243 244 245 246 247 248 249 250 251

    // Get primitve from device context
    auto softmax_bwd_p = handler.AcquireSoftmaxBackward(
        dst_memory_p, diff_dst_memory_p, diff_src_memory_p);

    std::vector<primitive> pipeline{*softmax_bwd_p};
    stream(stream::kind::eager).submit(pipeline).wait();
  }
};
252 253 254 255 256 257 258
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

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