transpose_mkldnn_op.cc 8.0 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 46 47
    platform::SetInMemDescWithLogicalLayoutFusesSupport(
        ctx, const_cast<phi::DenseTensor*>(x), x->mem_desc());

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

54
    auto x_vec_dims = phi::vectorize(x->dims());
55

56 57 58 59 60
    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);
61

62 63
    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
        x->mem_desc(), platform::to_void_cast(x->data<T>()));
64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    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 已提交
85
    astream.wait();
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 118 119 120
    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;
121 122 123
  }
};

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

    const auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    if (!dx) return;
136 137
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
138 139 140 141 142 143
    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();
144
    if (ndims == 1) {
145 146
      framework::TensorCopy(*dout, dout->place(), dx);
      dx->set_mem_desc(dout->mem_desc());
147 148 149
      return;
    }

150
    auto dout_vec_dims = phi::vectorize(dout->dims());
151

152 153 154 155
    framework::proto::VarType::Type dout_paddle_type =
        framework::TransToProtoVarType(dout->dtype());
    dnnl::memory::data_type dout_type =
        framework::ToMKLDNNDataType(dout_paddle_type);
156

157 158
    platform::ReorderMKLDNNHandler reorder_handler(
        dout_vec_dims, dout_paddle_type, dout_type, dnnl_engine);
159

160 161
    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
        dout->mem_desc(), platform::to_void_cast(dout->data<T>()));
162

163 164
    auto reorder_dst_memory_p =
        reorder_handler.AcquireDstMemory(dx, dout->mem_desc(), ctx.GetPlace());
165

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

176 177 178 179 180
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

181 182 183 184
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
185 186 187
                                    ops::kTransposeMKLDNNFP32,
                                    ops::TransposeMKLDNNOpKernel<float>);

188 189 190 191
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    U8,
192 193 194
                                    ops::kTransposeMKLDNNINT8,
                                    ops::TransposeMKLDNNOpKernel<uint8_t>);

195 196 197 198
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(transpose2,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    S8,
199 200 201
                                    ops::kTransposeMKLDNNINT8,
                                    ops::TransposeMKLDNNOpKernel<int8_t>);

202
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(
203 204 205 206
    transpose2,
    MKLDNN,
    ::paddle::platform::CPUPlace,
    BF16,
207 208 209
    ops::kTransposeMKLDNNFP32,
    ops::TransposeMKLDNNOpKernel<paddle::platform::bfloat16>);

210 211 212
REGISTER_OP_KERNEL(transpose,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
213
                   ops::TransposeMKLDNNOpKernel<float>);
214

215 216 217
REGISTER_OP_KERNEL(transpose_grad,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
218
                   ops::TransposeMKLDNNGradOpKernel<float>);