data_layout_transform.cc 7.5 KB
Newer Older
1
//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2 3 4 5 6 7 8 9 10 11 12 13
//
// 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.
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/framework/data_layout_transform.h"
16

17
#include "paddle/phi/kernels/funcs/math_function.h"
M
mozga-intel 已提交
18
#ifdef PADDLE_WITH_MKLDNN
19
#include "paddle/fluid/platform/mkldnn_reuse.h"
M
mozga-intel 已提交
20
#endif
21
#include "paddle/fluid/framework/convert_utils.h"
22 23 24 25

namespace paddle {
namespace framework {

26
std::vector<int> GetAxis(const DataLayout& from, const DataLayout& to) {
27
  PADDLE_ENFORCE_NE(
28 29
      from,
      to,
30 31
      platform::errors::InvalidArgument(
          "Layout transform should transform between different layout."));
32 33 34 35 36
  if (from == DataLayout::kNCHW && to == DataLayout::kNHWC) {
    return {0, 2, 3, 1};
  } else if (from == DataLayout::kNHWC && to == DataLayout::kNCHW) {
    return {0, 3, 1, 2};
  } else {
37 38
    PADDLE_THROW(
        platform::errors::InvalidArgument("Unsupported layout transform."));
39 40 41
  }
}

42 43 44
template <typename T>
void CastDataLayout::apply() {
  auto place = ctx_->GetPlace();
45

46
  if (platform::is_cpu_place(place)) {
L
Leo Chen 已提交
47 48
    phi::funcs::Transpose<phi::CPUContext, T, 4> trans4;
    auto* context = static_cast<const phi::CPUContext*>(ctx_);
49 50 51 52
    trans4(*context, in_, out_, axis_);
  } else {
    PADDLE_THROW(platform::errors::PreconditionNotMet(
        "Unsupported data layout cast from CPU to GPU."));
53
  }
54
}
55

56
void TransDataLayout(const OpKernelType& kernel_type_for_var,
57
                     const OpKernelType& expected_kernel_type,
58 59
                     const phi::DenseTensor& in,
                     phi::DenseTensor* out) {
60
  PADDLE_ENFORCE(
61 62
      platform::places_are_same_class(kernel_type_for_var.place_,
                                      expected_kernel_type.place_),
63 64
      platform::errors::PreconditionNotMet(
          "TransDataLayout only support DataLayout transform on same place."));
65

66
  PADDLE_ENFORCE_EQ(
67 68
      arity(in.dims()),
      4,
69 70 71
      platform::errors::InvalidArgument(
          "Input dimension arity only can be 4, the input dimension is %s.",
          in.dims()));
72 73

  auto& pool = platform::DeviceContextPool::Instance();
74

75
  auto src_dim = in.dims();
76 77
  std::vector<int64_t> dst_dim;

78 79
  auto axis = GetAxis(kernel_type_for_var.data_layout_,
                      expected_kernel_type.data_layout_);
80 81 82 83 84
  dst_dim.resize(axis.size());
  for (size_t i = 0; i < axis.size(); i++) {
    dst_dim[i] = src_dim[axis[i]];
  }

85
  out->Resize(phi::make_ddim(dst_dim));
86
  out->mutable_data(expected_kernel_type.place_, in.dtype());
87

88
  framework::VisitDataType(
89
      framework::TransToProtoVarType(in.dtype()),
90
      CastDataLayout(pool.Get(expected_kernel_type.place_), axis, in, out));
91

92
  out->set_layout(expected_kernel_type.data_layout_);
93 94
}

M
mozga-intel 已提交
95
#ifdef PADDLE_WITH_MKLDNN
96 97 98
using dnnl::memory;
using dnnl::primitive;
using dnnl::reorder;
M
mozga-intel 已提交
99

100 101
void* GetDataFromTensor(const phi::DenseTensor& tensor,
                        dnnl::memory::data_type type) {
M
mozga-intel 已提交
102
  switch (type) {
103
    case dnnl::memory::data_type::f32:
M
mozga-intel 已提交
104
      return platform::to_void_cast(tensor.data<float>());
105
    case dnnl::memory::data_type::s8:
Y
Yu Yang 已提交
106
      return platform::to_void_cast(tensor.data<int8_t>());
107
    case dnnl::memory::data_type::u8:
M
mozga-intel 已提交
108
      return platform::to_void_cast(tensor.data<unsigned char>());
109
    case dnnl::memory::data_type::s32:
M
mozga-intel 已提交
110
      return platform::to_void_cast(tensor.data<int32_t>());
111
    case dnnl::memory::data_type::bf16:
112
      return platform::to_void_cast(tensor.data<paddle::platform::bfloat16>());
M
mozga-intel 已提交
113
    default:
114 115
      PADDLE_THROW(
          platform::errors::InvalidArgument("Wrong mkldnn type provided."));
M
mozga-intel 已提交
116 117 118 119 120
  }
}

void TransDataLayoutFromMKLDNN(const OpKernelType& kernel_type_for_var,
                               const OpKernelType& expected_kernel_type,
121 122
                               const phi::DenseTensor& in,
                               phi::DenseTensor* out) {
M
mozga-intel 已提交
123 124
  auto in_layout = kernel_type_for_var.data_layout_;
  auto out_layout = expected_kernel_type.data_layout_;
125
  auto place = expected_kernel_type.place_;
M
mozga-intel 已提交
126 127 128

  PADDLE_ENFORCE(
      in_layout == DataLayout::kMKLDNN && out_layout != DataLayout::kMKLDNN,
129 130 131
      platform::errors::InvalidArgument(
          "TransDataLayoutFromMKLDNN only supports transform from MKLDNN to "
          "non-MKLDNN"));
M
mozga-intel 已提交
132

133 134 135
  innerTransDataLayoutFromMKLDNN(
      in_layout,
      paddle::platform::MKLDNNDeviceContext::tls().get_cur_paddle_data_layout(),
136 137 138
      in,
      out,
      place);
139 140
}

141 142
void innerTransDataLayoutFromMKLDNN(DataLayout in_layout,
                                    DataLayout out_layout,
143 144
                                    const phi::DenseTensor& in,
                                    phi::DenseTensor* out,
145 146
                                    platform::Place place,
                                    bool always_copy) {
M
mozga-intel 已提交
147 148 149 150
  // Set default as NCHW in case not specified
  out_layout =
      out_layout == DataLayout::kAnyLayout ? DataLayout::kNCHW : out_layout;

151
  auto& pool = platform::DeviceContextPool::Instance();
152
  auto* dev_ctx = dynamic_cast<platform::MKLDNNDeviceContext*>(pool.Get(place));
153 154
  auto& cpu_engine = dev_ctx->GetEngine();

155
  auto in_tz = phi::vectorize<int64_t>(in.dims());
156
  auto out_tz = in_tz;
M
mozga-intel 已提交
157

158 159 160
  memory::data_type in_type =
      ToMKLDNNDataType(framework::TransToProtoVarType(in.dtype()));
  PADDLE_ENFORCE_NE(
161 162
      in_type,
      memory::data_type::undef,
163 164 165
      platform::errors::InvalidArgument(
          "Input tensor type (%s) is not supported.",
          DataTypeToString(framework::TransToProtoVarType(in.dtype()))));
M
mozga-intel 已提交
166

167 168
  auto out_format =
      platform::MKLDNNFormatForSize(in_tz.size(), ToMKLDNNFormat(out_layout));
169
  dnnl::memory::desc out_mem_desc(out_tz, in_type, out_format);
170

M
mozga-intel 已提交
171
  // output tensor has the same dims as input. Reorder don't change dims
172
  out->set_mem_desc(out_mem_desc);
M
mozga-intel 已提交
173 174
  out->Resize(in.dims());

175 176 177
  // Note(0x45f): Using initialized() to support slice Tensors
  // with shapes like [0, 0, 0].
  if (in.initialized() && ((in.mem_desc() != out->mem_desc()) || always_copy)) {
178
    void* in_data = GetDataFromTensor(in, in_type);
M
mozga-intel 已提交
179

180 181
    platform::ReorderMKLDNNHandler handler(
        in_tz, framework::TransToProtoVarType(in.dtype()), in_type, cpu_engine);
M
mozga-intel 已提交
182

183 184
    auto reorder_src_memory_p =
        handler.AcquireSrcMemory(in.mem_desc(), in_data);
185
    auto reorder_dst_memory_p =
186
        handler.AcquireDstMemory(out, out->mem_desc(), place);
187 188 189
    auto reorder_p =
        handler.AcquireReorder(reorder_dst_memory_p, reorder_src_memory_p);

190
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
191
    platform::RecordEvent record_reorder("ext_reorder",
C
chenjian 已提交
192
                                         platform::TracerEventType::UserDefined,
193 194
                                         2,
                                         platform::EventRole::kUniqueOp);
A
Adam 已提交
195 196
    reorder_p->execute(astream, *reorder_src_memory_p, *reorder_dst_memory_p);
    astream.wait();
197 198 199
  } else {
    out->ShareDataWith(in);
  }
200 201
  // For exepected NHWC data format we need to reshape the Output tensor
  // As MKL-DNN description was in NCHW and paddle is expecting NHWC
202 203
  platform::MatchShapeToLayout(out, in_layout, out_layout);

J
Jacek Czaja 已提交
204
  out->set_layout(DataLayout::kNCHW);
M
mozga-intel 已提交
205
}
206
#endif
M
mozga-intel 已提交
207

208 209
}  // namespace framework
}  // namespace paddle