data_layout_transform.cc 8.0 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

Y
Yi Wang 已提交
17
#include "paddle/fluid/operators/math/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 22 23 24

namespace paddle {
namespace framework {

25
std::vector<int> GetAxis(const DataLayout& from, const DataLayout& to) {
26 27 28 29
  PADDLE_ENFORCE_NE(
      from, to,
      platform::errors::InvalidArgument(
          "Layout transform should transform between different layout."));
30 31 32 33 34
  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 {
35 36
    PADDLE_THROW(
        platform::errors::InvalidArgument("Unsupported layout transform."));
37 38 39
  }
}

40 41 42 43 44 45 46 47 48 49 50
struct CastDataLayout {
  CastDataLayout(const platform::DeviceContext* ctx,
                 const std::vector<int>& axis, const framework::Tensor& in,
                 framework::Tensor* out)
      : in_(in), out_(out), ctx_(ctx), axis_(axis) {}
  const framework::Tensor in_;
  framework::Tensor* out_;
  const platform::DeviceContext* ctx_;
  const std::vector<int> axis_;

  template <typename T>
D
dzhwinter 已提交
51
  void apply() {
52 53 54 55 56 57 58
    auto place = ctx_->GetPlace();

    if (platform::is_cpu_place(place)) {
      operators::math::Transpose<platform::CPUDeviceContext, T, 4> trans4;
      auto* context = static_cast<const platform::CPUDeviceContext*>(ctx_);
      trans4(*context, in_, out_, axis_);
    } else {
59 60
      PADDLE_THROW(platform::errors::PreconditionNotMet(
          "Unsupported data layout cast from CPU to GPU."));
61 62 63 64
    }
  }
};

65 66 67
void TransDataLayout(const OpKernelType& kernel_type_for_var,
                     const OpKernelType& expected_kernel_type, const Tensor& in,
                     Tensor* out) {
68
  PADDLE_ENFORCE(
69 70
      platform::places_are_same_class(kernel_type_for_var.place_,
                                      expected_kernel_type.place_),
71 72
      platform::errors::PreconditionNotMet(
          "TransDataLayout only support DataLayout transform on same place."));
73

74 75 76 77 78
  PADDLE_ENFORCE_EQ(
      arity(in.dims()), 4,
      platform::errors::InvalidArgument(
          "Input dimension arity only can be 4, the input dimension is %s.",
          in.dims()));
79 80

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

82
  auto src_dim = in.dims();
83 84
  std::vector<int64_t> dst_dim;

85 86
  auto axis = GetAxis(kernel_type_for_var.data_layout_,
                      expected_kernel_type.data_layout_);
87 88 89 90 91
  dst_dim.resize(axis.size());
  for (size_t i = 0; i < axis.size(); i++) {
    dst_dim[i] = src_dim[axis[i]];
  }

92 93
  out->Resize(make_ddim(dst_dim));
  out->mutable_data(expected_kernel_type.place_, in.type());
94

95
  framework::VisitDataType(
Y
Yu Yang 已提交
96
      in.type(),
97
      CastDataLayout(pool.Get(expected_kernel_type.place_), axis, in, out));
98

99
  out->set_layout(expected_kernel_type.data_layout_);
100 101
}

M
mozga-intel 已提交
102 103 104 105 106 107 108 109 110 111
#ifdef PADDLE_WITH_MKLDNN
using mkldnn::memory;
using mkldnn::primitive;
using mkldnn::reorder;

void* GetDataFromTensor(const Tensor& tensor, mkldnn::memory::data_type type) {
  switch (type) {
    case mkldnn::memory::data_type::f32:
      return platform::to_void_cast(tensor.data<float>());
    case mkldnn::memory::data_type::s8:
Y
Yu Yang 已提交
112
      return platform::to_void_cast(tensor.data<int8_t>());
M
mozga-intel 已提交
113 114 115 116
    case mkldnn::memory::data_type::u8:
      return platform::to_void_cast(tensor.data<unsigned char>());
    case mkldnn::memory::data_type::s32:
      return platform::to_void_cast(tensor.data<int32_t>());
117 118
    case mkldnn::memory::data_type::bf16:
      return platform::to_void_cast(tensor.data<paddle::platform::bfloat16>());
M
mozga-intel 已提交
119
    default:
120 121
      PADDLE_THROW(
          platform::errors::InvalidArgument("Wrong mkldnn type provided."));
M
mozga-intel 已提交
122 123 124 125 126 127 128 129
  }
}

void TransDataLayoutFromMKLDNN(const OpKernelType& kernel_type_for_var,
                               const OpKernelType& expected_kernel_type,
                               const Tensor& in, Tensor* out) {
  auto in_layout = kernel_type_for_var.data_layout_;
  auto out_layout = expected_kernel_type.data_layout_;
130
  auto place = expected_kernel_type.place_;
M
mozga-intel 已提交
131 132 133

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

138 139 140 141
  innerTransDataLayoutFromMKLDNN(
      in_layout,
      paddle::platform::MKLDNNDeviceContext::tls().get_cur_paddle_data_layout(),
      in, out, place);
142 143 144 145
}

void innerTransDataLayoutFromMKLDNN(DataLayout in_layout, DataLayout out_layout,
                                    const Tensor& in, Tensor* out,
146
                                    platform::Place place, bool always_copy) {
A
Adam 已提交
147
  PADDLE_ENFORCE_NE(in.format(), MKLDNNMemoryFormat::undef,
148 149 150
                    platform::errors::InvalidArgument(
                        "Input tensor format is invalid. Input tensor should "
                        "have specified memory format."));
151
  PADDLE_ENFORCE_NE(in.format(), MKLDNNMemoryFormat::any,
152 153 154
                    platform::errors::InvalidArgument(
                        "Input tensor format is invalid. Input tensor should "
                        "have specified memory format."));
M
mozga-intel 已提交
155 156 157 158 159

  // Set default as NCHW in case not specified
  out_layout =
      out_layout == DataLayout::kAnyLayout ? DataLayout::kNCHW : out_layout;

160
  auto& pool = platform::DeviceContextPool::Instance();
161
  auto* dev_ctx = dynamic_cast<platform::MKLDNNDeviceContext*>(pool.Get(place));
162 163
  auto& cpu_engine = dev_ctx->GetEngine();

A
Adam 已提交
164
  auto in_tz = paddle::framework::vectorize<int64_t>(in.dims());
165
  auto out_tz = in_tz;
M
mozga-intel 已提交
166 167

  memory::data_type in_type = ToMKLDNNDataType(in.type());
A
Adam 已提交
168
  PADDLE_ENFORCE_NE(in_type, memory::data_type::undef,
169 170 171
                    platform::errors::InvalidArgument(
                        "Input tensor type (%s) is not supported.",
                        DataTypeToString(in.type())));
M
mozga-intel 已提交
172

173 174 175 176
  auto in_format = platform::MKLDNNFormatForSize(in_tz.size(), in.format());
  auto out_format =
      platform::MKLDNNFormatForSize(in_tz.size(), ToMKLDNNFormat(out_layout));

M
mozga-intel 已提交
177 178 179
  // output tensor has the same dims as input. Reorder don't change dims
  out->Resize(in.dims());

180
  if ((in_format != out_format) || always_copy) {
181
    void* in_data = GetDataFromTensor(in, in_type);
182 183
    std::string key =
        platform::CreateKey(*dev_ctx, in_tz, in_format, out_format, in_type);
M
mozga-intel 已提交
184

185 186
    platform::ReorderMKLDNNHandler handler(in_tz, in.type(), in_type, *dev_ctx,
                                           cpu_engine, key);
M
mozga-intel 已提交
187

188 189
    auto reorder_src_memory_p = handler.AcquireSrcMemory(in_format, in_data);
    auto reorder_dst_memory_p =
190
        handler.AcquireDstMemory(out, out_format, place);
191 192 193
    auto reorder_p =
        handler.AcquireReorder(reorder_dst_memory_p, reorder_src_memory_p);

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

J
Jacek Czaja 已提交
206
  out->set_layout(DataLayout::kNCHW);
207
  // reset format since the out tensor will be feed to non-MKLDNN OPkernel
A
Adam 已提交
208
  out->set_format(MKLDNNMemoryFormat::undef);
M
mozga-intel 已提交
209
}
210
#endif
M
mozga-intel 已提交
211

212 213
}  // namespace framework
}  // namespace paddle