data_transform.cc 9.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2022 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. */

15
#include "paddle/phi/api/lib/data_transform.h"
16

17 18
#include "paddle/phi/api/ext/dispatch.h"
#include "paddle/phi/api/lib/kernel_dispatch.h"
19
#include "paddle/phi/api/lib/utils/storage.h"
20 21 22
#include "paddle/phi/backends/all_context.h"
#include "paddle/phi/kernels/cast_kernel.h"
#include "paddle/phi/kernels/transfer_layout_kernel.h"
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

#include "paddle/fluid/framework/data_device_transform.h"

namespace paddle {
namespace experimental {

inline bool NeedTransformDataType(const DataType& input,
                                  const DataType& target,
                                  const TransformFlag& transform_flag) {
  return input != target &&
         (transform_flag.need_trans_data_type() ||
          target == DataType::COMPLEX64 || target == DataType::COMPLEX128);
}

inline bool NeedTransformPlace(const paddle::platform::Place& input,
                               const Backend& target,
                               const TransformFlag& transform_flag) {
  bool ret = transform_flag.need_trans_backend() &&
             target != Backend::ALL_BACKEND &&
42
             !platform::is_same_place(input, phi::TransToPhiPlace(target));
43 44 45 46 47 48 49 50 51 52 53 54
  return ret;
}

inline bool NeedTransformLayout(const DataLayout& input,
                                const DataLayout& target,
                                const TransformFlag& transform_flag) {
  bool ret = transform_flag.need_trans_layout() &&
             (input != DataLayout::ALL_LAYOUT &&
              target != DataLayout::ALL_LAYOUT && input != target);
  return ret;
}

55 56
inline phi::DenseTensor TransDataLayout(const phi::DenseTensor& tensor,
                                        DataLayout layout) {
57 58 59 60
  auto& pool = paddle::platform::DeviceContextPool::Instance();
  VLOG(3) << "DataLayoutTransform src_layout: " << tensor.layout()
          << " dst_layout: " << layout;
  if (platform::is_cpu_place(tensor.place())) {
61 62
    auto* dev_ctx = static_cast<phi::CPUContext*>(pool.Get(tensor.place()));
    return phi::TransferLayout(*dev_ctx, tensor, layout);
63
  } else {
64
    PADDLE_THROW(phi::errors::PreconditionNotMet(
65 66 67 68 69
        "Unsupported data layout cast from CPU to GPU."));
  }
}

template <typename Context>
70 71 72
phi::DenseTensor CastDateType(const Context& dev_ctx,
                              const phi::DenseTensor& tensor,
                              DataType dtype) {
73 74
  switch (tensor.dtype()) {
    case DataType::FLOAT32:
75
      return phi::Cast<float>(dev_ctx, tensor, dtype);
76
    case DataType::FLOAT64:
77
      return phi::Cast<double>(dev_ctx, tensor, dtype);
78
    case DataType::INT32:
79
      return phi::Cast<int32_t>(dev_ctx, tensor, dtype);
80
    case DataType::INT64:
81
      return phi::Cast<int64_t>(dev_ctx, tensor, dtype);
82
    case DataType::FLOAT16:
83
      return phi::Cast<phi::dtype::float16>(dev_ctx, tensor, dtype);
84
    case DataType::BFLOAT16:
85
      return phi::Cast<phi::dtype::bfloat16>(dev_ctx, tensor, dtype);
86
    case DataType::BOOL:
87
      return phi::Cast<bool>(dev_ctx, tensor, dtype);
88
    case DataType::INT16:
89
      return phi::Cast<int16_t>(dev_ctx, tensor, dtype);
90
    case DataType::UINT8:
91
      return phi::Cast<uint8_t>(dev_ctx, tensor, dtype);
92
    default:
93
      PADDLE_THROW(phi::errors::Unimplemented(
94 95 96 97 98 99
          "Data type (%s) is not supported when casting data type.",
          tensor.dtype()));
  }
}

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
100 101 102
phi::DenseTensor CastDateType(const phi::GPUContext& dev_ctx,
                              const phi::DenseTensor& tensor,
                              DataType dtype) {
103 104
  switch (tensor.dtype()) {
    case DataType::FLOAT32:
105
      return phi::Cast<float>(dev_ctx, tensor, dtype);
106
    case DataType::FLOAT64:
107
      return phi::Cast<double>(dev_ctx, tensor, dtype);
108
    case DataType::INT32:
109
      return phi::Cast<int32_t>(dev_ctx, tensor, dtype);
110
    case DataType::INT64:
111
      return phi::Cast<int64_t>(dev_ctx, tensor, dtype);
112
    case DataType::FLOAT16:
113
      return phi::Cast<phi::dtype::float16>(dev_ctx, tensor, dtype);
114
    case DataType::BOOL:
115
      return phi::Cast<bool>(dev_ctx, tensor, dtype);
116
    case DataType::INT16:
117
      return phi::Cast<int16_t>(dev_ctx, tensor, dtype);
118
    case DataType::UINT8:
119
      return phi::Cast<uint8_t>(dev_ctx, tensor, dtype);
120
    default:
121
      PADDLE_THROW(phi::errors::Unimplemented(
122 123 124 125 126 127
          "Data type (%s) is not supported when casting data type.",
          tensor.dtype()));
  }
}
#endif

128 129
inline phi::DenseTensor TransDataType(const phi::DenseTensor& tensor,
                                      DataType dtype) {
130 131 132 133 134
  auto& pool = paddle::platform::DeviceContextPool::Instance();

  VLOG(3) << "DataTypeTransform src_dtype: " << tensor.dtype()
          << " dst_dtype: " << dtype;

135 136
  phi::DenseTensor out(
      phi::make_intrusive<paddle::experimental::SharedStorage>(tensor.place()),
137 138 139
      {dtype, tensor.dims(), tensor.layout()});

  if (platform::is_cpu_place(tensor.place())) {
140
    auto* dev_ctx = static_cast<phi::CPUContext*>(pool.Get(tensor.place()));
141 142 143
    return CastDateType(*dev_ctx, tensor, dtype);
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  } else if (platform::is_gpu_place(tensor.place())) {
144
    auto* dev_ctx = static_cast<phi::GPUContext*>(pool.Get(tensor.place()));
145 146 147
    return CastDateType(*dev_ctx, tensor, dtype);
#endif
  } else {
148
    PADDLE_THROW(phi::errors::Unimplemented(
149 150 151 152 153
        "Place type is not supported when casting data type."));
  }
  return out;
}

154 155 156 157
phi::DenseTensor TransformData(const phi::DenseTensor& tensor,
                               const phi::TensorArgDef& target_args_def,
                               const TransformFlag& transform_flag) {
  phi::DenseTensor out = tensor;
158 159 160 161 162 163 164 165 166 167 168 169
  if (NeedTransformLayout(
          tensor.layout(), target_args_def.layout, transform_flag)) {
    out = TransDataLayout(out, target_args_def.layout);
  }

  if (NeedTransformDataType(
          tensor.dtype(), target_args_def.dtype, transform_flag)) {
    out = TransDataType(out, target_args_def.dtype);
  }

  if (NeedTransformPlace(
          out.place(), target_args_def.backend, transform_flag)) {
170
    phi::DenseTensor result;
171
    framework::TransDataDevice(
172
        out, phi::TransToPhiPlace(target_args_def.backend), &result);
173 174 175 176 177
    out = result;
  }
  return out;
}

178
std::shared_ptr<phi::DenseTensor> PrepareData(
179
    const Tensor& input,
180
    const phi::TensorArgDef& target_args_def,
181 182
    const TransformFlag& transform_flag) {
  const auto& tensor_in = input.impl();
H
hong 已提交
183
  VLOG(6) << tensor_in->dtype() << "\t" << target_args_def.dtype;
184 185 186 187 188 189 190
  if (!transform_flag.NeedTransform() || !tensor_in->initialized() ||
      (!NeedTransformPlace(
           tensor_in->place(), target_args_def.backend, transform_flag) &&
       !NeedTransformDataType(
           tensor_in->dtype(), target_args_def.dtype, transform_flag) &&
       !NeedTransformLayout(
           tensor_in->layout(), target_args_def.layout, transform_flag))) {
191
    return std::static_pointer_cast<phi::DenseTensor>(tensor_in);
192 193
  }

194 195
  phi::DenseTensor out =
      TransformData(*(static_cast<phi::DenseTensor*>(tensor_in.get())),
196 197
                    target_args_def,
                    transform_flag);
198
  return std::make_shared<phi::DenseTensor>(std::move(out));
199 200
}

201 202 203 204 205 206 207 208 209 210
std::shared_ptr<phi::DenseTensor> PrepareData(
    const paddle::optional<Tensor>& input,
    const phi::TensorArgDef& target_args_def,
    const TransformFlag& transform_flag) {
  if (input) {
    return PrepareData(*input, target_args_def, transform_flag);
  }
  return {nullptr};
}

211
std::unique_ptr<std::vector<phi::DenseTensor>> PrepareData(
212
    const std::vector<Tensor>& inputs,
213
    const phi::TensorArgDef& target_args_def,
214
    const TransformFlag& transform_flag) {
215
  auto pt_tensors = std::make_unique<std::vector<phi::DenseTensor>>();
216 217 218 219 220 221 222 223 224 225 226 227
  pt_tensors->reserve(inputs.size());

  for (const auto& input : inputs) {
    const auto& tensor_in = input.impl();
    if (!transform_flag.NeedTransform() || !tensor_in->initialized() ||
        (!NeedTransformPlace(
             tensor_in->place(), target_args_def.backend, transform_flag) &&
         !NeedTransformDataType(
             tensor_in->dtype(), target_args_def.dtype, transform_flag) &&
         !NeedTransformLayout(
             tensor_in->layout(), target_args_def.layout, transform_flag))) {
      pt_tensors->emplace_back(
228
          *std::dynamic_pointer_cast<phi::DenseTensor>(tensor_in));
229 230
    } else {
      pt_tensors->emplace_back(
231
          TransformData(*(static_cast<phi::DenseTensor*>(tensor_in.get())),
232 233 234 235 236 237 238 239 240 241
                        target_args_def,
                        transform_flag));
    }
  }

  return std::move(pt_tensors);
}

}  // namespace experimental
}  // namespace paddle