You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by GitBox <gi...@apache.org> on 2022/02/01 11:39:30 UTC

[GitHub] [incubator-mxnet] bartekkuncer commented on a change in pull request #20853: Improve MaskedSoftmax by oneDNN

bartekkuncer commented on a change in pull request #20853:
URL: https://github.com/apache/incubator-mxnet/pull/20853#discussion_r796503011



##########
File path: src/operator/nn/dnnl/dnnl_masked_softmax.cc
##########
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*!
+ * \file dnnl_maskedsoftmax.cc
+ */
+
+#include "dnnl_masked_softmax-inl.h"
+#include "dnnl_softmax-inl.h"
+
+#if MXNET_USE_ONEDNN == 1
+namespace mxnet {
+namespace op {
+
+bool SupportDNNLMaskedSoftmax(const MaskedSoftmaxParam& param,
+                              const std::vector<NDArray>& inputs,
+                              const NDArray& output) {
+  CHECK_EQ(inputs.size(), 2);
+  const auto mask = inputs[1];
+  SoftmaxParam softmax_param;
+  softmax_param.axis        = param.axis;
+  softmax_param.dtype       = inputs[0].dtype();
+  softmax_param.temperature = param.temperature;
+  return mask.dtype() == mshadow::kBool && SupportDNNLSoftmax(softmax_param, inputs[0], output);
+}
+
+inline static dnnl::memory::dims GetOneDNNDims(const NDArray& arr) {
+  return dnnl::memory::dims(arr.shape().begin(), arr.shape().end());
+}
+
+typedef ParamOpSign<MaskedSoftmaxParam> MaskedSoftmaxSignature;
+
+DNNLMaskedSoftmaxFwd& DNNLMaskedSoftmaxFwd::GetCached(
+    const MaskedSoftmaxParam& param,
+    const DNNLMaskedSoftmaxFwd::Tensors& tensors) {
+  using maskedsoftmax_fwd_map =
+      std::unordered_map<MaskedSoftmaxSignature, DNNLMaskedSoftmaxFwd, OpHash>;
+#if DMLC_CXX11_THREAD_LOCAL
+  static thread_local maskedsoftmax_fwd_map fwds;
+#else
+  static MX_THREAD_LOCAL maskedsoftmax_fwd_map fwds;
+#endif
+  MaskedSoftmaxSignature key(param);
+  key.AddSign(tensors.input);
+  key.AddSign(tensors.mask);
+  key.AddSign(tensors.output);
+
+  auto it = fwds.find(key);
+  if (it == fwds.end()) {
+    const DNNLMaskedSoftmaxFwd fwd(param, tensors);
+    it = AddToCache(&fwds, key, fwd);
+  }
+  return it->second;
+}
+
+std::shared_ptr<Primitives> DNNLMaskedSoftmaxFwd::CreatePrimitives(const MaskedSoftmaxParam& param,
+                                                                   const Tensors& tensors) {
+  const dnnl::engine engine = CpuEngine::Get()->get_engine();
+
+  auto prim = std::make_shared<Primitives>();
+
+  auto mem_format =
+      static_cast<dnnl::memory::format_tag>(GetDefaultFormat(tensors.input.shape().ndim()));
+  dnnl::memory::dims input_dims = GetOneDNNDims(tensors.input);
+  // output_desc is the same
+  dnnl::memory::desc input_desc =
+      dnnl::memory::desc(input_dims, dnnl::memory::data_type::f32, mem_format);
+
+  dnnl::memory::dims mask_dims = GetOneDNNDims(tensors.mask);
+  dnnl::memory::desc mask_desc =
+      dnnl::memory::desc(mask_dims, dnnl::memory::data_type::s8, mem_format);
+
+  // (mask - 1)
+  auto minusone_desc = dnnl::eltwise_forward::desc(dnnl::prop_kind::forward_scoring,
+                                                   dnnl::algorithm::eltwise_linear,
+                                                   mask_desc,
+                                                   1.0f,    // multiply factor
+                                                   -1.0f);  // minus one
+  prim->minusone_pd  = dnnl::eltwise_forward::primitive_desc(minusone_desc, engine);
+  prim->minusone     = dnnl::eltwise_forward(prim->minusone_pd);
+
+  // input * mask
+  auto mask_input_desc =
+      dnnl::binary::desc(dnnl::algorithm::binary_add,
+                         input_desc,
+                         dnnl::memory::desc(mask_dims, dnnl::memory::data_type::f32, mem_format),
+                         input_desc);
+  prim->mask_input_pd = dnnl::binary::primitive_desc(mask_input_desc, engine);
+  prim->mask_input    = dnnl::binary(prim->mask_input_pd);
+
+  // output * mask
+  auto mask_output_desc =
+      dnnl::binary::desc(dnnl::algorithm::binary_mul, input_desc, mask_desc, input_desc);
+  prim->mask_output_pd = dnnl::binary::primitive_desc(mask_output_desc, engine);
+  prim->mask_output    = dnnl::binary(prim->mask_output_pd);
+
+  return prim;
+}
+
+void DNNLMaskedSoftmaxForward(const nnvm::NodeAttrs& attrs,
+                              const OpContext& ctx,
+                              const std::vector<NDArray>& inputs,
+                              const std::vector<OpReqType>& req,
+                              const std::vector<NDArray>& outputs) {
+  TmpMemMgr::Get()->Init(ctx.requested[0]);
+  const auto& param  = nnvm::get<MaskedSoftmaxParam>(attrs.parsed);
+  const auto tensors = DNNLMaskedSoftmaxFwd::Tensors(inputs, outputs);
+  const auto& fwd    = DNNLMaskedSoftmaxFwd::GetCached(param, tensors);
+  fwd.Execute(tensors, req, param, ctx.is_train);
+}
+
+void DNNLMaskedSoftmaxFwd::Execute(const Tensors& tensors,
+                                   const std::vector<OpReqType>& req,
+                                   const MaskedSoftmaxParam& param,
+                                   bool is_train) const {
+  using namespace mxnet::op;
+  using namespace mxnet::op::mxnet_op;
+  using namespace dnnl;
+  /*
+   1. out = input * [(mask - 1) * inf]

Review comment:
       Maybe add a title to this e.g. Three steps of masked softmax.

##########
File path: src/operator/nn/dnnl/dnnl_softmax.cc
##########
@@ -195,6 +218,24 @@ DNNLSoftmaxBwd& DNNLSoftmaxBwd::GetCached(const SoftmaxParam& param, const Tenso
   return it->second;
 }
 
+DNNLSoftmaxBwd::DNNLSoftmaxBwd(const SoftmaxParam& param, const Tensors& tensors) {
+  const float temperature   = param.temperature.has_value() ? param.temperature.value() : 1.0f;
+  const int axis            = CheckAxis(param.axis, tensors.out.shape().ndim());
+  const auto out_grad_mem   = tensors.out_grad.GetDNNLData();
+  const auto out_mem        = tensors.out.GetDNNLData();
+  const auto softmax_fwd_pd = DNNLSoftmaxFwd::GetSoftmaxFwdPd(*out_mem, axis, /*is_train*/ true);
+
+  softmax_bwd_pd = std::make_shared<softmax_bwd_pd_t>(
+      GetSoftmaxBwdPd(*out_grad_mem, *out_mem, axis, softmax_fwd_pd));
+  softmax_bwd = std::make_shared<softmax_bwd_t>(*softmax_bwd_pd);
+
+  if (temperature != 1.0f) {  // avoid dividing by 1

Review comment:
       Should we not check somewhere if temperature == 0?

##########
File path: src/operator/nn/masked_softmax.cc
##########
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*!
+ * \file masked_softmax.cc
+ */
+
+#include "./softmax-inl.h"
+#include "../tensor/elemwise_unary_op.h"

Review comment:
       Please avoid dots in includes.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@mxnet.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org