data_transform.cc 11.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
// clang-format off
16
#include "paddle/phi/api/lib/data_transform.h"
17

18
#include "paddle/phi/api/lib/kernel_dispatch.h"
19
#include "paddle/phi/api/lib/utils/allocator.h"
20
#include "paddle/phi/backends/all_context.h"
21
#include "paddle/phi/core/kernel_registry.h"
22
#include "paddle/phi/kernels/cast_kernel.h"
23
#include "paddle/phi/kernels/copy_kernel.h"
24
#include "paddle/phi/kernels/transfer_layout_kernel.h"
25

26
#include "paddle/fluid/framework/tensor_util.h"
27
// clang-format on
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

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) {
43 44 45 46 47 48 49 50 51 52 53
  // NOTE(dev): The default value of TransformFlag is True, if it is set with
  // False
  // somewhere such as api.yaml or backward.yaml that means we should skip data
  // transform. Because "stop_transform_" has highest priority.
  if (!transform_flag.need_trans_backend()) {
    return false;
  }
  bool ret = input.GetType() == AllocationType::GPUPINNED ||
             (target != Backend::ALL_BACKEND &&
              phi::TransToPhiBackend(input) !=
                  (target != Backend::GPUDNN ? target : Backend::GPU));
54 55 56 57 58 59 60 61 62 63 64 65
  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;
}

66 67
inline phi::DenseTensor TransDataLayout(const phi::DenseTensor& tensor,
                                        DataLayout layout) {
68 69 70 71
  auto& pool = paddle::platform::DeviceContextPool::Instance();
  VLOG(3) << "DataLayoutTransform src_layout: " << tensor.layout()
          << " dst_layout: " << layout;
  if (platform::is_cpu_place(tensor.place())) {
72 73
    auto* dev_ctx = static_cast<phi::CPUContext*>(pool.Get(tensor.place()));
    return phi::TransferLayout(*dev_ctx, tensor, layout);
74
  } else {
75
    PADDLE_THROW(phi::errors::PreconditionNotMet(
76 77 78 79 80
        "Unsupported data layout cast from CPU to GPU."));
  }
}

template <typename Context>
81 82 83
phi::DenseTensor CastDateType(const Context& dev_ctx,
                              const phi::DenseTensor& tensor,
                              DataType dtype) {
84 85
  switch (tensor.dtype()) {
    case DataType::FLOAT32:
86
      return phi::Cast<float>(dev_ctx, tensor, dtype);
87
    case DataType::FLOAT64:
88
      return phi::Cast<double>(dev_ctx, tensor, dtype);
89
    case DataType::INT32:
90
      return phi::Cast<int32_t>(dev_ctx, tensor, dtype);
91
    case DataType::INT64:
92
      return phi::Cast<int64_t>(dev_ctx, tensor, dtype);
93
    case DataType::FLOAT16:
94
      return phi::Cast<phi::dtype::float16>(dev_ctx, tensor, dtype);
95
    case DataType::BFLOAT16:
96
      return phi::Cast<phi::dtype::bfloat16>(dev_ctx, tensor, dtype);
97
    case DataType::BOOL:
98
      return phi::Cast<bool>(dev_ctx, tensor, dtype);
99
    case DataType::INT16:
100
      return phi::Cast<int16_t>(dev_ctx, tensor, dtype);
101
    case DataType::UINT8:
102
      return phi::Cast<uint8_t>(dev_ctx, tensor, dtype);
103
    default:
104
      PADDLE_THROW(phi::errors::Unimplemented(
105 106 107 108 109 110
          "Data type (%s) is not supported when casting data type.",
          tensor.dtype()));
  }
}

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
111 112 113
phi::DenseTensor CastDateType(const phi::GPUContext& dev_ctx,
                              const phi::DenseTensor& tensor,
                              DataType dtype) {
114 115
  switch (tensor.dtype()) {
    case DataType::FLOAT32:
116
      return phi::Cast<float>(dev_ctx, tensor, dtype);
117
    case DataType::FLOAT64:
118
      return phi::Cast<double>(dev_ctx, tensor, dtype);
119
    case DataType::INT32:
120
      return phi::Cast<int32_t>(dev_ctx, tensor, dtype);
121
    case DataType::INT64:
122
      return phi::Cast<int64_t>(dev_ctx, tensor, dtype);
123
    case DataType::FLOAT16:
124
      return phi::Cast<phi::dtype::float16>(dev_ctx, tensor, dtype);
125
    case DataType::BOOL:
126
      return phi::Cast<bool>(dev_ctx, tensor, dtype);
127
    case DataType::INT16:
128
      return phi::Cast<int16_t>(dev_ctx, tensor, dtype);
129
    case DataType::UINT8:
130
      return phi::Cast<uint8_t>(dev_ctx, tensor, dtype);
131
    default:
132
      PADDLE_THROW(phi::errors::Unimplemented(
133 134 135 136 137 138
          "Data type (%s) is not supported when casting data type.",
          tensor.dtype()));
  }
}
#endif

139 140
inline phi::DenseTensor TransDataType(const phi::DenseTensor& tensor,
                                      DataType dtype) {
141 142 143 144 145
  auto& pool = paddle::platform::DeviceContextPool::Instance();

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

146 147
  DefaultAllocator alloc(tensor.place());
  phi::DenseTensor out(&alloc, {dtype, tensor.dims(), tensor.layout()});
148 149

  if (platform::is_cpu_place(tensor.place())) {
150
    auto* dev_ctx = static_cast<phi::CPUContext*>(pool.Get(tensor.place()));
151 152 153
    return CastDateType(*dev_ctx, tensor, dtype);
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  } else if (platform::is_gpu_place(tensor.place())) {
154
    auto* dev_ctx = static_cast<phi::GPUContext*>(pool.Get(tensor.place()));
155 156 157
    return CastDateType(*dev_ctx, tensor, dtype);
#endif
  } else {
158
    PADDLE_THROW(phi::errors::Unimplemented(
159 160 161 162 163
        "Place type is not supported when casting data type."));
  }
  return out;
}

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
inline phi::DenseTensor TransDataPlace(const phi::DenseTensor& tensor,
                                       Place dst_place) {
  VLOG(3) << "DeviceTransform in, src_place " << tensor.place()
          << " dst_place: " << dst_place;

  DefaultAllocator alloc(dst_place);
  phi::DenseTensor out(&alloc,
                       {tensor.dtype(), tensor.dims(), tensor.layout()});

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  auto& pool = paddle::platform::DeviceContextPool::Instance();
  // NOTE(yy): TransDataPlace should wait for computation of input.
  if (!platform::is_cuda_pinned_place(tensor.place())) {
    pool.Get(tensor.place())->Wait();
    pool.Get(dst_place)->Wait();
  }
#endif

  // FIXME(zcd): TransDataPlace is used to transform data from GPU to CPU and
  // the enforced checkings have been done in GetDeviceContext, so the
  // `dev_ctx->Wait()` is necessary. But `dev_ctx->Wait()` will make the program
  // slow, especially when the number of elements is little, for example,
  // the elements of learning rate are one and it's CPU side.
  // One solution is to use a CUDA kernel to complete the copy operation when
  // the transforming is from CPU to GPU and the number of elements is little.
  // But the embarrassment is that this solution this solution makes training
  // slower.
  paddle::framework::TensorCopySync(tensor, dst_place, &out);
  return out;
}

195
phi::DenseTensor TransformData(phi::DenseTensor* tensor,
196 197
                               const phi::TensorArgDef& target_args_def,
                               const TransformFlag& transform_flag) {
198 199 200
  phi::DenseTensor out = *tensor;
  bool trans_layout = false;
  bool trans_dtype = false;
201
  if (NeedTransformLayout(
202
          tensor->layout(), target_args_def.layout, transform_flag)) {
203
    out = TransDataLayout(out, target_args_def.layout);
204
    trans_layout = true;
205 206 207
  }

  if (NeedTransformDataType(
208
          tensor->dtype(), target_args_def.dtype, transform_flag)) {
209
    out = TransDataType(out, target_args_def.dtype);
210
    trans_dtype = true;
211 212 213 214
  }

  if (NeedTransformPlace(
          out.place(), target_args_def.backend, transform_flag)) {
215
    out = TransDataPlace(out, phi::TransToPhiPlace(target_args_def.backend));
216 217 218 219
    if (!trans_layout && !trans_dtype &&
        tensor->place().GetType() == AllocationType::GPUPINNED) {
      tensor->ShareBufferWith(out);
    }
220 221 222 223
  }
  return out;
}

224
std::shared_ptr<phi::DenseTensor> PrepareData(
225
    const Tensor& input,
226
    const phi::TensorArgDef& target_args_def,
227 228
    const TransformFlag& transform_flag) {
  const auto& tensor_in = input.impl();
Z
zyfncg 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241
  if (tensor_in) {
    phi::DenseTensor& dense_tensor =
        *static_cast<phi::DenseTensor*>(tensor_in.get());
    if (!transform_flag.NeedTransform() || !dense_tensor.initialized() ||
        (!NeedTransformPlace(
             dense_tensor.place(), target_args_def.backend, transform_flag) &&
         !NeedTransformDataType(
             dense_tensor.dtype(), target_args_def.dtype, transform_flag) &&
         !NeedTransformLayout(
             dense_tensor.layout(), target_args_def.layout, transform_flag))) {
      return std::static_pointer_cast<phi::DenseTensor>(tensor_in);
    }
    phi::DenseTensor out =
242
        TransformData(&dense_tensor, target_args_def, transform_flag);
Z
zyfncg 已提交
243
    return std::make_shared<phi::DenseTensor>(std::move(out));
244
  }
Z
zyfncg 已提交
245
  return nullptr;
246 247
}

248
paddle::optional<phi::DenseTensor> PrepareData(
249 250 251 252
    const paddle::optional<Tensor>& input,
    const phi::TensorArgDef& target_args_def,
    const TransformFlag& transform_flag) {
  if (input) {
253
    return {*PrepareData(*input, target_args_def, transform_flag)};
H
hong 已提交
254
  }
255
  return paddle::none;
H
hong 已提交
256 257
}

258
std::unique_ptr<std::vector<phi::DenseTensor>> PrepareData(
259
    const std::vector<Tensor>& inputs,
260
    const phi::TensorArgDef& target_args_def,
261
    const TransformFlag& transform_flag) {
262
  auto pt_tensors = std::make_unique<std::vector<phi::DenseTensor>>();
263 264 265 266 267 268 269 270 271 272 273 274
  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(
275
          *std::dynamic_pointer_cast<phi::DenseTensor>(tensor_in));
276 277
    } else {
      pt_tensors->emplace_back(
278
          TransformData((static_cast<phi::DenseTensor*>(tensor_in.get())),
279 280 281 282 283
                        target_args_def,
                        transform_flag));
    }
  }

284
  return pt_tensors;
285 286 287 288
}

}  // namespace experimental
}  // namespace paddle