shuffle_channel_mkldnn_op.cc 2.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2022 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 16
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/phi/backends/onednn/onednn_reuse.h"
17 18 19 20 21 22

namespace paddle {
namespace operators {

template <typename T>
class ShuffleChannelMKLDNNHandler
23
    : public phi::funcs::OneDNNHandlerNoCachingT<T, dnnl::shuffle_forward> {
24
 public:
25
  ShuffleChannelMKLDNNHandler(const phi::DenseTensor* x,
26
                              const int group,
27 28
                              const dnnl::engine engine,
                              platform::Place cpu_place)
29 30
      : phi::funcs::OneDNNHandlerNoCachingT<T, dnnl::shuffle_forward>(
            engine, cpu_place) {
31
    static constexpr int channel_axis = 1;
32 33
    this->AcquireForwardPrimitiveDescriptor(
        dnnl::prop_kind::forward_training, x->mem_desc(), channel_axis, group);
34 35 36 37 38 39 40
  }
};

template <typename T>
class ShuffleChannelMKLDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
41
    const auto& dev_ctx = ctx.template device_context<phi::OneDNNContext>();
42
    const auto& onednn_engine = dev_ctx.GetEngine();
43

44 45
    const auto* x = ctx.Input<phi::DenseTensor>("X");
    auto* out = ctx.Output<phi::DenseTensor>("Out");
46 47 48 49

    // oneDNN handles group using C/g instead of g
    const int group = x->dims()[1] / ctx.Attr<int>("group");

50
    ShuffleChannelMKLDNNHandler<T> handler(
51
        x, group, onednn_engine, ctx.GetPlace());
52 53 54 55 56 57

    auto src_memory_p = handler.AcquireSrcMemory(x);
    auto dst_memory_p = handler.AcquireDstMemory(out);

    auto shuffle_p = handler.AcquireForwardPrimitive();

58
    auto& astream = phi::OneDNNContext::tls().get_stream();
59 60 61
    shuffle_p->execute(
        astream,
        {{DNNL_ARG_SRC, *src_memory_p}, {DNNL_ARG_DST, *dst_memory_p}});
62 63
    astream.wait();

64
    out->set_mem_desc(dst_memory_p->get_desc());
65 66 67 68 69 70
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
71 72
REGISTER_OP_KERNEL(shuffle_channel,
                   MKLDNN,
73
                   phi::CPUPlace,
74 75
                   ops::ShuffleChannelMKLDNNKernel<float>,
                   ops::ShuffleChannelMKLDNNKernel<paddle::platform::bfloat16>);