transpose_mkldnn_op.cc 7.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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/data_layout_transform.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/malloc.h"
18
#include "paddle/fluid/operators/transpose_op.h"
19 20 21 22 23
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

24 25
using Tensor = phi::DenseTensor;
using phi::DataLayout;
26

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

    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
44 45

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

51
    auto x_vec_dims = phi::vectorize(x->dims());
52

53 54 55 56 57
    framework::proto::VarType::Type x_paddle_type =
        framework::TransToProtoVarType(x->dtype());
    dnnl::memory::data_type x_type = framework::ToMKLDNNDataType(x_paddle_type);
    platform::ReorderMKLDNNHandler reorder_handler(
        x_vec_dims, x_paddle_type, x_type, dnnl_engine);
58

59 60
    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
        x->mem_desc(), platform::to_void_cast(x->data<T>()));
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    auto dst_md =
        dnnl::memory::desc(x_vec_dims,
                           x->mem_desc().data_type(),
                           platform::GetPlainMKLDNNFormat(x_vec_dims.size()));
    // 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 已提交
82
    astream.wait();
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 110 111 112 113 114 115 116 117
    platform::SetOutMemDescWithLogicalLayoutFusesSupport(
        ctx,
        out,
        reorder_dst_memory_p->get_desc().permute_axes(
            TransposeToPermuteAxis(transpose_axis)));
  }

 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;
118 119 120
  }
};

121 122 123 124
template <typename T>
class TransposeMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
125 126
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()),
                      true,
127 128
                      paddle::platform::errors::PreconditionNotMet(
                          "Operator DNNL TransposeGrad must use CPUPlace"));
129 130 131 132

    const auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    if (!dx) return;
133 134
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
135 136 137 138 139 140
    const auto& dnnl_engine = dev_ctx.GetEngine();
    std::vector<int> transpose_axis = ctx.Attr<std::vector<int>>("axis");

    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();

    int ndims = transpose_axis.size();
141
    if (ndims == 1) {
142 143
      framework::TensorCopy(*dout, dout->place(), dx);
      dx->set_mem_desc(dout->mem_desc());
144 145 146
      return;
    }

147
    auto dout_vec_dims = phi::vectorize(dout->dims());
148

149 150 151 152
    framework::proto::VarType::Type dout_paddle_type =
        framework::TransToProtoVarType(dout->dtype());
    dnnl::memory::data_type dout_type =
        framework::ToMKLDNNDataType(dout_paddle_type);
153

154 155
    platform::ReorderMKLDNNHandler reorder_handler(
        dout_vec_dims, dout_paddle_type, dout_type, dnnl_engine);
156

157 158
    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
        dout->mem_desc(), platform::to_void_cast(dout->data<T>()));
159

160 161
    auto reorder_dst_memory_p =
        reorder_handler.AcquireDstMemory(dx, dout->mem_desc(), ctx.GetPlace());
162

163 164 165 166
    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 已提交
167
    astream.wait();
168 169
    dx->set_mem_desc(
        reorder_dst_memory_p->get_desc().permute_axes(transpose_axis));
170 171 172
  }
};

173 174 175 176 177
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

178 179 180 181
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
182 183 184
                                    ops::kTransposeMKLDNNFP32,
                                    ops::TransposeMKLDNNOpKernel<float>);

185 186 187 188
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    U8,
189 190 191
                                    ops::kTransposeMKLDNNINT8,
                                    ops::TransposeMKLDNNOpKernel<uint8_t>);

192 193 194 195
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    S8,
196 197 198
                                    ops::kTransposeMKLDNNINT8,
                                    ops::TransposeMKLDNNOpKernel<int8_t>);

199
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(
200 201 202 203
    transpose2,
    MKLDNN,
    ::paddle::platform::CPUPlace,
    BF16,
204 205 206
    ops::kTransposeMKLDNNFP32,
    ops::TransposeMKLDNNOpKernel<paddle::platform::bfloat16>);

207 208 209
REGISTER_OP_KERNEL(transpose,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
210
                   ops::TransposeMKLDNNOpKernel<float>);
211

212 213 214
REGISTER_OP_KERNEL(transpose_grad,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
215
                   ops::TransposeMKLDNNGradOpKernel<float>);