data_transform.cc 6.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Q
Qiao Longfei 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

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

Y
Yi Wang 已提交
17 18 19
#include "paddle/fluid/framework/data_device_transform.h"
#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/data_type_transform.h"
Q
Qiao Longfei 已提交
20

W
wanghuancoder 已提交
21 22 23 24 25 26
namespace paddle {
namespace framework {
class Variable;
}  // namespace framework
}  // namespace paddle

27 28 29 30
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif

Q
Qiao Longfei 已提交
31 32 33
namespace paddle {
namespace framework {

34
static void PassTensorData(phi::DenseTensor *from, phi::DenseTensor *to) {
35
  to->ShareDataWith(*from);
36
  *from = phi::DenseTensor();
37 38
}

39 40
void TransformData(const phi::KernelKey &expected_kernel_type,
                   const phi::KernelKey &kernel_type_for_var,
41
                   const phi::DenseTensor &input_tensor,
42 43
                   phi::DenseTensor *output_tensor,
                   const phi::Place &place) {
44
  bool transformed = false;
45
  phi::DenseTensor in;
46
  in.ShareDataWith(input_tensor);
47
  phi::DenseTensor out;
48 49
  const DataLayout lin = kernel_type_for_var.layout();
  const DataLayout lout = expected_kernel_type.layout();
50
  // do layout transform
M
mozga-intel 已提交
51
  if (NeedTransformLayout(lout, lin)) {
52
#ifdef PADDLE_WITH_MKLDNN
53
    if (lin == DataLayout::ONEDNN || lout == DataLayout::ONEDNN) {
54
      PADDLE_ENFORCE_EQ(
55
          !(lin == DataLayout::ONEDNN && lout == DataLayout::ONEDNN),
56
          true,
57
          platform::errors::PreconditionNotMet(
58
              "No layout transform needed between two oneDNN OPKernels."));
M
mozga-intel 已提交
59

60
      if (lin != DataLayout::ONEDNN && lout == DataLayout::ONEDNN) {
61
        // Case1 - transform from Non-ONEDNN OPKernel to ONEDNN OPKernel
M
mozga-intel 已提交
62
        // Just set layout/format. No real transform occur
63

64 65
        auto out_format = phi::funcs::OneDNNFormatForSize(
            in.dims().size(), phi::funcs::ToOneDNNFormat(lin));
66
        out.ShareDataWith(input_tensor);
67 68
        // For NHWC data we need reshape of tensors as MKL-DNN
        // is expecting NHWC dims description order
69
        if (lin == DataLayout::kNHWC || lin == DataLayout::kNDHWC) {
70
          phi::funcs::MatchShapeToLayout(&out, lin, lout);
J
Jacek Czaja 已提交
71 72
          // We register only NHWC assuming that model is consistent e.g. either
          // NHWC or NCHW
73
          phi::OneDNNContext::tls().set_cur_paddle_data_layout(lin);
J
Jacek Czaja 已提交
74
        }
75 76
        dnnl::memory::desc out_mem_desc(
            vectorize(out.dims()),
77
            phi::funcs::ToOneDNNDataType(in.dtype()),
78
            out_format);
79
        out.set_mem_desc(out_mem_desc);
M
mozga-intel 已提交
80
      } else {
81 82
        // Case2 - transfrom from ONEDNN OPKernel to Non-ONEDNN OPKernel
        // Do transform via ONEDNN lib
83 84 85 86
        PADDLE_ENFORCE(lin == DataLayout::ONEDNN && lout != DataLayout::ONEDNN,
                       platform::errors::InvalidArgument(
                           "TransDataLayoutFromOneDNN only supports "
                           "transform from ONEDNN to non-ONEDNN"));
87 88

        phi::funcs::TransDataLayoutFromOneDNN(
89
            lin,
90 91 92
            phi::OneDNNContext::tls().get_cur_paddle_data_layout(),
            in,
            &out,
93
            place);
M
mozga-intel 已提交
94 95
      }
    } else {
96
      // Case3 - transfrom between Non-ONEDNN OPKernels
97 98
      TransDataLayout(
          kernel_type_for_var, expected_kernel_type, in, &out, place);
M
mozga-intel 已提交
99
    }
100
#else
101
    // Case3 - transfrom between Non-ONEDNN OPKernels
102
    TransDataLayout(kernel_type_for_var, expected_kernel_type, in, &out, place);
103
#endif
104 105 106 107
    transformed = true;
    PassTensorData(&out, &in);
  }

108
  // do data type transform
109
  if (NeedTransformDataType(expected_kernel_type, kernel_type_for_var)) {
Q
Qiao Longfei 已提交
110 111 112 113 114
    TransDataType(kernel_type_for_var, expected_kernel_type, in, &out);
    transformed = true;
    PassTensorData(&out, &in);
  }

115
  // do device transform
116 117 118
  if (kernel_type_for_var.backend() != phi::Backend::ALL_BACKEND &&
      !platform::is_same_place(in.place(), place)) {
    TransDataDevice(in, place, &out);
119 120
    transformed = true;
    PassTensorData(&out, &in);
121
  }
122

123
  PADDLE_ENFORCE_EQ(
124 125
      transformed,
      true,
126 127
      platform::errors::PreconditionNotMet(
          "No transform is applied for the data needs to be transformed."));
128 129
  // get output data
  output_tensor->ShareDataWith(in);
130 131
}

132
void SetTensorToVariable(const Variable &in_var,
133
                         const phi::DenseTensor &tensor,
Y
yuyang18 已提交
134
                         Variable *out_var) {
135 136 137
  if (in_var.IsType<phi::DenseTensor>()) {
    auto &in_lod_tensor = in_var.Get<phi::DenseTensor>();
    auto *tran_lod_tensor = out_var->GetMutable<phi::DenseTensor>();
138 139
    tran_lod_tensor->set_lod(in_lod_tensor.lod());
    tran_lod_tensor->set_layout(in_lod_tensor.layout());
J
Jacek Czaja 已提交
140
#ifdef PADDLE_WITH_MKLDNN
141
    tran_lod_tensor->set_mem_desc(in_lod_tensor.mem_desc());
J
Jacek Czaja 已提交
142
#endif
143
    tran_lod_tensor->ShareDataWith(tensor);
144 145 146
  } else if (in_var.IsType<phi::SelectedRows>()) {
    auto &in_selected_rows = in_var.Get<phi::SelectedRows>();
    auto *trans_selected_rows = out_var->GetMutable<phi::SelectedRows>();
147 148 149 150
    trans_selected_rows->set_height(in_selected_rows.height());
    trans_selected_rows->set_rows(in_selected_rows.rows());
    trans_selected_rows->mutable_value()->ShareDataWith(tensor);
  } else {
151
    PADDLE_THROW(platform::errors::Unavailable(
152 153
        "Unsupported variable type, only supports phi::DenseTensor or "
        "SelectedRows, "
154 155
        "but the input variable type is %s.",
        ToTypeName(in_var.Type())));
156 157 158
  }
}

159 160 161 162 163
phi::GetKernelTypeForVarContext BuildGetKernelTypeForVarContext(
    const phi::KernelKey &kernel_key,
    const AttributeMap &fluid_attrs,
    phi::AttributeMap *phi_attrs,
    bool has_infer_varkernel_fn) {
164
  // According to "GetKernelTypeForVar" in some ops executed with oneDNN,
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  // the only "string" member, such as "data_layout" 、"data_format" of
  // AttibuteMap is useful. In the future the other args maybe used. Because the
  // "phi" module should not depend on the "fluid", transform
  // "framework::AttributeMap" to "phi::AttributeMap".
  if (has_infer_varkernel_fn) {
    for (auto &attr : fluid_attrs) {
      switch (attr.second.index()) {
        case 3:  // string type in framwork::Attribute
          (*phi_attrs)[attr.first] = PADDLE_GET_CONST(std::string, attr.second);
          break;
        default:
          VLOG(6) << "GetKernelTypeForVarContext currently only use "
                     "std::string. You add other type if need.";
          break;
      }
    }
  }
  return phi::GetKernelTypeForVarContext(&kernel_key, phi_attrs);
}

Q
Qiao Longfei 已提交
185 186
}  // namespace framework
}  // namespace paddle