/* 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. */ #include #include "mkldnn.hpp" #include "paddle/fluid/operators/softmax_op.h" #include "paddle/fluid/platform/mkldnn_reuse.h" 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; using mkldnn::softmax_backward; using mkldnn::softmax_forward; using mkldnn::stream; using platform::to_void_cast; class SoftmaxMKLDNNHandler : public platform::MKLDNNHandler { public: SoftmaxMKLDNNHandler( std::shared_ptr softmax_pd, const platform::MKLDNNDeviceContext& dev_ctx, mkldnn::engine engine, const std::string& base_key) : platform::MKLDNNHandler(dev_ctx, engine, base_key), softmax_pd_(softmax_pd) {} SoftmaxMKLDNNHandler( std::shared_ptr softmax_pd, std::shared_ptr softmax_bwd_pd, const platform::MKLDNNDeviceContext& dev_ctx, mkldnn::engine engine, const std::string& base_key) : platform::MKLDNNHandler(dev_ctx, engine, base_key), softmax_pd_(softmax_pd), softmax_bwd_pd_(softmax_bwd_pd) { // If we are in Grad operatgor then update a key with BWD suffix to // distinguish from FWD memory primitives key_ += "-BWD"; } std::shared_ptr AcquireSoftmax( std::shared_ptr dst_memory_p, std::shared_ptr src_memory_p) { /*Generate key*/ auto prim_key = key_ + "@softmax_p"; auto softmax_p = std::static_pointer_cast( dev_ctx_.GetBlob(prim_key)); PADDLE_ENFORCE((softmax_p != nullptr) || (is_reusing_ == false), "Fail to find softmax primitive in device context"); if (softmax_p == nullptr) { softmax_p = std::make_shared( *softmax_pd_, *(static_cast(src_memory_p.get())), *(static_cast(dst_memory_p.get()))); dev_ctx_.SetBlob(prim_key, softmax_p); } else { is_reusing_ = true; } return softmax_p; } std::shared_ptr AcquireSoftmaxBackward( std::shared_ptr dst_memory_p, std::shared_ptr diff_dst_memory_p, std::shared_ptr diff_src_memory_p) { auto prim_key = key_ + "@softmax_bwd_p"; auto softmax_bwd_p = std::static_pointer_cast( dev_ctx_.GetBlob(prim_key)); PADDLE_ENFORCE((softmax_bwd_p != nullptr) || (is_reusing_ == false), "Fail to find softmax backward primitive in device context"); if (softmax_bwd_p == nullptr) { softmax_bwd_p = std::make_shared( *softmax_bwd_pd_, *dst_memory_p, *diff_dst_memory_p, *diff_src_memory_p); dev_ctx_.SetBlob(prim_key, softmax_bwd_p); } else { is_reusing_ = true; } return softmax_bwd_p; } private: std::shared_ptr softmax_pd_; std::shared_ptr softmax_bwd_pd_; }; template class SoftmaxMKLDNNKernel : public paddle::framework::OpKernel { 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(); auto mkldnn_engine = dev_ctx.GetEngine(); const Tensor* X = ctx.Input("X"); Tensor* Out = ctx.Output("Out"); PADDLE_ENFORCE_EQ( X->dims(), Out->dims(), "The shape of softmax's input and output must be identical."); const int axis = ctx.Attr("axis"); int rank = X->dims().size(); // make sure 'output' holds memory, which will be shared by // 'flattened_output' later. Out->mutable_data(ctx.GetPlace()); std::vector perm, shape; CalcTransPermAndShapeByAxis(*X, axis, &perm, &shape); Tensor X_2d, Out_2d; Tensor X_trans, Out_trans; if (axis != -1 && axis != rank - 1) { X_trans.mutable_data(framework::make_ddim(shape), ctx.GetPlace()); Out_trans.mutable_data(framework::make_ddim(shape), ctx.GetPlace()); TransCompute(rank, dev_ctx, *X, &X_trans, perm); TransCompute(rank, dev_ctx, *Out, &Out_trans, perm); auto dims = X_trans.dims(); auto flattened_dims = framework::flatten_to_2d(dims, dims.size() - 1); X_2d.ShareDataWith(X_trans).Resize(flattened_dims); Out_2d.ShareDataWith(Out_trans).Resize(flattened_dims); } else { auto dims = X->dims(); auto flattened_dims = framework::flatten_to_2d(dims, dims.size() - 1); X_2d.ShareDataWith(*X).Resize(flattened_dims); Out_2d.ShareDataWith(*Out).Resize(flattened_dims); } const T* input_data = X_2d.data(); T* output_data = Out_2d.mutable_data(ctx.GetPlace()); std::vector src_tz = paddle::framework::vectorize2int(X_2d.dims()); std::vector dst_tz = src_tz; // Same memory descriptor to be used for input and output memory::dims softmax_tz = {src_tz[0], src_tz[1]}; // Generate keys for storing/retriving primitives for this operator const std::string key = platform::MKLDNNHandler::GetHash(softmax_tz, ctx.op().Output("Out")); const std::string key_softmax_pd = key + "@softmax_pd"; // Currently only NC data format is supported auto softmax_md = MKLDNNMemDesc( {softmax_tz}, platform::MKLDNNGetDataType(), memory::format::nc); // Normalization is made after innermost dimension eg. C out of NC auto softmax_desc = softmax_forward::desc(prop_kind::forward_scoring, softmax_md, 1 /*dim: C*/); auto softmax_pd = std::make_shared( softmax_desc, mkldnn_engine); dev_ctx.SetBlob(key_softmax_pd, softmax_pd); SoftmaxMKLDNNHandler handler(softmax_pd, dev_ctx, mkldnn_engine, key); auto softmax_src_memory_p = handler.AcquireSrcMemory(softmax_md, to_void_cast(input_data)); auto softmax_dst_memory_p = handler.AcquireDstMemory(softmax_md, to_void_cast(output_data)); auto softmax_p = handler.AcquireSoftmax(softmax_dst_memory_p, softmax_src_memory_p); // We cannot use softmax_dst_memory_p to get prim desc as // it contains flattened dims (2D) while output tensor can // have 2,3,4+ dims if (axis != -1 && axis != rank - 1) { auto output_mem_pd = paddle::platform::create_prim_desc_from_dims( shape, mkldnn::memory::format::blocked); Out_trans.set_mkldnn_prim_desc(output_mem_pd); } else { auto output_mem_pd = paddle::platform::create_prim_desc_from_dims( paddle::framework::vectorize2int(Out->dims()), mkldnn::memory::format::blocked); Out->set_mkldnn_prim_desc(output_mem_pd); } std::vector pipeline{ *(static_cast(softmax_p.get()))}; stream(stream::kind::eager).submit(pipeline).wait(); const bool is_test = ctx.Attr("is_test"); if (!is_test) { T threshold = exp(-64); for (int i = 0; i < dst_tz[0] * dst_tz[1]; ++i) { output_data[i] = output_data[i] < threshold ? threshold : output_data[i]; } } if (axis != -1 && axis != rank - 1) { TransCompute(rank, dev_ctx, Out_trans, Out, perm); } } }; template class SoftmaxMKLDNNGradKernel : public paddle::framework::OpKernel { 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(); auto mkldnn_engine = dev_ctx.GetEngine(); const Tensor* Out = ctx.Input("Out"); auto* dOut = ctx.template Input(framework::GradVarName("Out")); auto* dX = ctx.template Output(framework::GradVarName("X")); PADDLE_ENFORCE_EQ( dOut->dims(), dX->dims(), "The shape of softmax_grad's input and output must be identical."); const int axis = ctx.Attr("axis"); int rank = Out->dims().size(); // make sure 'dx' holds memory, which will be shared by 'flattened_dx' // later. dX->template mutable_data(ctx.GetPlace()); std::vector perm, shape; CalcTransPermAndShapeByAxis(*dX, axis, &perm, &shape); Tensor dX_2d, Out_2d, dOut_2d; Tensor dX_trans, Out_trans, dOut_trans; if (axis != -1 && axis != rank - 1) { dX_trans.mutable_data(framework::make_ddim(shape), ctx.GetPlace()); Out_trans.mutable_data(framework::make_ddim(shape), ctx.GetPlace()); dOut_trans.mutable_data(framework::make_ddim(shape), ctx.GetPlace()); TransCompute(rank, dev_ctx, *dX, &dX_trans, perm); TransCompute(rank, dev_ctx, *Out, &Out_trans, perm); TransCompute(rank, dev_ctx, *dOut, &dOut_trans, perm); auto dims = dX_trans.dims(); auto flattened_dims = framework::flatten_to_2d(dims, dims.size() - 1); dX_2d.ShareDataWith(dX_trans).Resize(flattened_dims); Out_2d.ShareDataWith(Out_trans).Resize(flattened_dims); dOut_2d.ShareDataWith(dOut_trans).Resize(flattened_dims); } else { auto dims = dX->dims(); auto flattened_dims = framework::flatten_to_2d(dims, dims.size() - 1); dX_2d.ShareDataWith(*dX).Resize(flattened_dims); Out_2d.ShareDataWith(*Out).Resize(flattened_dims); dOut_2d.ShareDataWith(*dOut).Resize(flattened_dims); } const T* dst_data = Out_2d.data(); const T* diff_dst_ptr = dOut_2d.template data(); T* diff_src_ptr = dX_2d.template mutable_data(ctx.GetPlace()); std::vector dst_tz = paddle::framework::vectorize2int(Out_2d.dims()); std::vector src_tz(dst_tz); // Same memory descriptor to be used for input and output memory::dims softmax_tz = {src_tz[0], src_tz[1]}; // Currently only supports NC data format // retrieve eltwise primitive desc from device context const std::string key = platform::MKLDNNHandler::GetHash(softmax_tz, ctx.op().Input("Out")); const std::string key_softmax_pd = key + "@softmax_pd"; auto softmax_pd = std::static_pointer_cast( dev_ctx.GetBlob(key_softmax_pd)); PADDLE_ENFORCE(softmax_pd != nullptr, "Fail to find softmax_pd in device context"); // TODO(jczaja): Add layouts support when there is a need to do so // Two dimensional softmax does support NC format auto data_softmax_md = MKLDNNMemDesc( {softmax_tz}, platform::MKLDNNGetDataType(), memory::format::nc); auto diff_softmax_md = MKLDNNMemDesc( {softmax_tz}, platform::MKLDNNGetDataType(), memory::format::nc); // Normalization is made after innermost dimension eg. C out of NC auto softmax_bwd_desc = softmax_backward::desc(diff_softmax_md, data_softmax_md, 1 /* dim: C*/); auto softmax_bwd_pd = std::make_shared( softmax_bwd_desc, mkldnn_engine, *softmax_pd); SoftmaxMKLDNNHandler handler(softmax_pd, softmax_bwd_pd, dev_ctx, mkldnn_engine, key); auto dst_memory_p = handler.AcquireDstMemory(data_softmax_md, to_void_cast(dst_data)); auto diff_dst_memory_p = handler.AcquireDiffDstMemory( diff_softmax_md, to_void_cast(diff_dst_ptr)); auto diff_src_memory_p = handler.AcquireDiffSrcMemory( diff_softmax_md, to_void_cast(diff_src_ptr)); // Get primitve from device context auto softmax_bwd_p = handler.AcquireSoftmaxBackward( dst_memory_p, diff_dst_memory_p, diff_src_memory_p); std::vector pipeline{*softmax_bwd_p}; stream(stream::kind::eager).submit(pipeline).wait(); if (axis != -1 && axis != rank - 1) { TransCompute(rank, dev_ctx, dX_trans, dX, perm); } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(softmax, MKLDNN, ::paddle::platform::CPUPlace, ops::SoftmaxMKLDNNKernel); REGISTER_OP_KERNEL(softmax_grad, MKLDNN, ::paddle::platform::CPUPlace, ops::SoftmaxMKLDNNGradKernel);