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

namespace paddle {
namespace operators {

22
using phi::DataLayout;
23
using phi::OneDNNContext;
24 25 26 27 28

template <typename T>
class TransposeMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
29 30
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()),
                      true,
31 32
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL Transpose must use CPUPlace"));
33
    auto& dev_ctx = ctx.template device_context<OneDNNContext>();
34 35 36
    const auto& dnnl_engine = dev_ctx.GetEngine();
    std::vector<int> transpose_axis = ctx.Attr<std::vector<int>>("axis");
    int ndims = transpose_axis.size();
37 38
    const phi::DenseTensor* x = ctx.Input<phi::DenseTensor>("X");
    auto* out = ctx.Output<phi::DenseTensor>("Out");
39

40
    auto& astream = OneDNNContext::tls().get_stream();
41 42

    if (ndims == 1) {
43 44
      framework::TensorCopy(*x, x->place(), out);
      out->set_mem_desc(x->mem_desc());
45 46 47
      return;
    }

48
    auto x_vec_dims = phi::vectorize(x->dims());
49

50 51 52
    auto x_type = phi::funcs::ToOneDNNDataType(x->dtype());
    phi::funcs::ReorderOneDNNHandler reorder_handler(
        x_vec_dims, x->dtype(), x_type, dnnl_engine);
53

54
    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
55
        x->mem_desc(), phi::funcs::to_void_cast(x->data<T>()));
56

57 58 59
    auto dst_md =
        dnnl::memory::desc(x_vec_dims,
                           x->mem_desc().data_type(),
60
                           phi::funcs::GetPlainOneDNNFormat(x_vec_dims.size()));
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    // a trick is used here to fake transpose of out_md, so later it will be
    // "untransposed", leaving output data in plain format tag
    auto dst_strides = FakeTranposeStrides(dst_md, transpose_axis);

    dst_md =
        dnnl::memory::desc(x_vec_dims, x->mem_desc().data_type(), dst_strides);
    auto dst_data =
        out->mutable_data(ctx.GetPlace(), x->type(), dst_md.get_size());

    auto reorder_dst_memory_p =
        std::make_shared<dnnl::memory>(dst_md, dnnl_engine, dst_data);

    auto reorder_p = reorder_handler.AcquireReorder(reorder_dst_memory_p,
                                                    reorder_src_memory_p);

    reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p);
A
Adam 已提交
77
    astream.wait();
78

79 80
    out->set_mem_desc(reorder_dst_memory_p->get_desc().permute_axes(
        TransposeToPermuteAxis(transpose_axis)));
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  }

 private:
  // it is needed because oneDNN's permute axis understand axes order in
  // different way PaddlePaddle's transpose
  std::vector<int> TransposeToPermuteAxis(
      const std::vector<int>& transpose_axis) const {
    std::vector<int> permute_axis(transpose_axis.size());

    for (size_t i = 0; i < transpose_axis.size(); ++i) {
      permute_axis[transpose_axis[i]] = i;
    }
    return permute_axis;
  }

  std::vector<int64_t> FakeTranposeStrides(
      const dnnl::memory::desc& dst_md,
      const std::vector<int>& transpose_axis) const {
    std::vector<int64_t> fake_strides(transpose_axis.size());
    auto dims = dst_md.dims();
    int total_stride = 1;
    int ndims = static_cast<int>(dims.size());

    for (int i = ndims - 1; i >= 0; --i) {
      fake_strides[transpose_axis[i]] = total_stride;
      total_stride *= dims[transpose_axis[i]];
    }

    return fake_strides;
110 111 112
  }
};

113 114 115 116
template <typename T>
class TransposeMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
117 118
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()),
                      true,
119 120
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL TransposeGrad must use CPUPlace"));
121

122 123 124
    const auto* dout =
        ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
125
    if (!dx) return;
126
    auto& dev_ctx = ctx.template device_context<OneDNNContext>();
127 128 129
    const auto& dnnl_engine = dev_ctx.GetEngine();
    std::vector<int> transpose_axis = ctx.Attr<std::vector<int>>("axis");

130
    auto& astream = OneDNNContext::tls().get_stream();
131 132

    int ndims = transpose_axis.size();
133
    if (ndims == 1) {
134 135
      framework::TensorCopy(*dout, dout->place(), dx);
      dx->set_mem_desc(dout->mem_desc());
136 137 138
      return;
    }

139
    auto dout_vec_dims = phi::vectorize(dout->dims());
140
    auto dout_type = phi::funcs::ToOneDNNDataType(dout->dtype());
141

142 143
    phi::funcs::ReorderOneDNNHandler reorder_handler(
        dout_vec_dims, dout->dtype(), dout_type, dnnl_engine);
144

145
    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
146
        dout->mem_desc(), phi::funcs::to_void_cast(dout->data<T>()));
147

148 149
    auto reorder_dst_memory_p =
        reorder_handler.AcquireDstMemory(dx, dout->mem_desc(), ctx.GetPlace());
150

151 152 153 154
    auto reorder_p = reorder_handler.AcquireReorder(reorder_dst_memory_p,
                                                    reorder_src_memory_p);

    reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p);
A
Adam 已提交
155
    astream.wait();
156 157
    dx->set_mem_desc(
        reorder_dst_memory_p->get_desc().permute_axes(transpose_axis));
158 159 160
  }
};

161 162 163 164 165
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

166 167
REGISTER_OP_KERNEL(transpose,
                   MKLDNN,
168
                   ::phi::CPUPlace,
169
                   ops::TransposeMKLDNNOpKernel<float>);
170

171 172
REGISTER_OP_KERNEL(transpose_grad,
                   MKLDNN,
173
                   ::phi::CPUPlace,
174
                   ops::TransposeMKLDNNGradOpKernel<float>);