data_transform.cc 14.1 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
#include "paddle/phi/api/lib/kernel_dispatch.h"
18
#include "paddle/phi/api/lib/utils/allocator.h"
19
#include "paddle/phi/backends/context_pool.h"
20
#include "paddle/phi/core/kernel_registry.h"
21
#include "paddle/phi/core/tensor_utils.h"
22 23
#include "paddle/phi/kernels/cast_kernel.h"
#include "paddle/phi/kernels/transfer_layout_kernel.h"
24 25 26 27 28 29 30 31 32 33 34 35

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);
}

36
inline bool NeedTransformPlace(const phi::Place& input,
37 38
                               const Backend& target,
                               const TransformFlag& transform_flag) {
39 40
  // NOTE(dev): The default value of TransformFlag is True, if it is set with
  // False
C
Chen Weihang 已提交
41
  // somewhere such as ops.yaml or backward.yaml that means we should skip data
42 43 44 45 46 47 48 49
  // 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));
50 51 52
  return ret;
}

53
inline bool NeedTransformLayout(const DataLayout& input,
54
                                const DataLayout& target,
55
                                const phi::Place& place,
56 57 58 59
                                const TransformFlag& transform_flag) {
  bool ret = transform_flag.need_trans_layout() &&
             (input != DataLayout::ALL_LAYOUT &&
              target != DataLayout::ALL_LAYOUT && input != target);
60
  if (place.GetType() == phi::AllocationType::GPU) {
61 62
    return false;
  }
63 64 65
  return ret;
}

66 67
inline phi::DenseTensor TransDataLayout(const phi::DenseTensor& tensor,
                                        DataLayout layout) {
68
  auto& pool = phi::DeviceContextPool::Instance();
69 70
  VLOG(3) << "DataLayoutTransform src_layout: " << tensor.layout()
          << " dst_layout: " << layout;
71
  if (tensor.place().GetType() == phi::AllocationType::CPU) {
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
        "Unsupported data layout cast from CPU to GPU."));
  }
78
  return tensor;
79 80 81
}

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

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

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

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

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

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

165 166 167 168 169
inline phi::DenseTensor TransDataPlace(const phi::DenseTensor& tensor,
                                       Place dst_place) {
  VLOG(3) << "DeviceTransform in, src_place " << tensor.place()
          << " dst_place: " << dst_place;

E
engineer1109 已提交
170
  auto& pool = phi::DeviceContextPool::Instance();
171 172
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  // NOTE(yy): TransDataPlace should wait for computation of input.
173
  if (tensor.place().GetType() != phi::AllocationType::GPUPINNED) {
174 175 176 177 178 179 180 181 182 183 184 185 186 187
    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.
188
  phi::DenseTensor out;
E
engineer1109 已提交
189 190 191 192 193 194 195
  phi::DeviceContext* dev_ctx;
  if (dst_place.GetType() != AllocationType::CPU) {
    dev_ctx = pool.Get(dst_place);
  } else {
    dev_ctx = pool.Get(tensor.place());
  }
  phi::Copy(*dev_ctx, tensor, dst_place, true, &out);
196 197 198
  return out;
}

199
phi::DenseTensor TransformData(phi::DenseTensor* tensor,
200 201
                               const phi::TensorArgDef& target_args_def,
                               const TransformFlag& transform_flag) {
202 203 204
  phi::DenseTensor out = *tensor;
  bool trans_layout = false;
  bool trans_dtype = false;
205

206
  if (NeedTransformLayout(tensor->layout(),
207
                          target_args_def.layout,
208
                          tensor->place(),
209 210
                          transform_flag) &&
      tensor->dims().size() != 1) {
211
    out = TransDataLayout(out, target_args_def.layout);
212
    trans_layout = true;
213 214 215
  }

  if (NeedTransformDataType(
216
          tensor->dtype(), target_args_def.dtype, transform_flag)) {
217
    out = TransDataType(out, target_args_def.dtype);
218
    trans_dtype = true;
219 220 221 222
  }

  if (NeedTransformPlace(
          out.place(), target_args_def.backend, transform_flag)) {
223
    out = TransDataPlace(out, phi::TransToPhiPlace(target_args_def.backend));
224 225 226 227
    if (!trans_layout && !trans_dtype &&
        tensor->place().GetType() == AllocationType::GPUPINNED) {
      tensor->ShareBufferWith(out);
    }
228 229 230 231
  }
  return out;
}

232
std::shared_ptr<phi::DenseTensor> PrepareData(
233
    const Tensor& input,
234
    const phi::TensorArgDef& target_args_def,
235 236
    const TransformFlag& transform_flag) {
  const auto& tensor_in = input.impl();
Z
zyfncg 已提交
237 238 239 240 241 242 243 244
  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) &&
245
         !NeedTransformLayout(dense_tensor.layout(),
246
                              target_args_def.layout,
247
                              dense_tensor.place(),
248
                              transform_flag))) {
Z
zyfncg 已提交
249 250 251
      return std::static_pointer_cast<phi::DenseTensor>(tensor_in);
    }
    phi::DenseTensor out =
252
        TransformData(&dense_tensor, target_args_def, transform_flag);
Z
zyfncg 已提交
253
    return std::make_shared<phi::DenseTensor>(std::move(out));
254
  }
Z
zyfncg 已提交
255
  return nullptr;
256 257
}

258
paddle::optional<phi::DenseTensor> PrepareData(
259 260 261 262
    const paddle::optional<Tensor>& input,
    const phi::TensorArgDef& target_args_def,
    const TransformFlag& transform_flag) {
  if (input) {
263
    return {*PrepareData(*input, target_args_def, transform_flag)};
H
hong 已提交
264
  }
265
  return paddle::none;
H
hong 已提交
266 267
}

268
std::unique_ptr<std::vector<phi::DenseTensor>> PrepareData(
269
    const std::vector<Tensor>& inputs,
270
    const phi::TensorArgDef& target_args_def,
271
    const TransformFlag& transform_flag) {
272
  auto pt_tensors = std::make_unique<std::vector<phi::DenseTensor>>();
273 274 275 276 277 278 279 280 281
  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) &&
282
         !NeedTransformLayout(tensor_in->layout(),
283
                              target_args_def.layout,
284
                              tensor_in->place(),
285
                              transform_flag))) {
286
      pt_tensors->emplace_back(
287
          *std::dynamic_pointer_cast<phi::DenseTensor>(tensor_in));
288 289
    } else {
      pt_tensors->emplace_back(
290
          TransformData((static_cast<phi::DenseTensor*>(tensor_in.get())),
291 292 293 294 295
                        target_args_def,
                        transform_flag));
    }
  }

296
  return pt_tensors;
297 298
}

299 300 301 302 303 304 305 306 307 308
paddle::optional<std::vector<phi::DenseTensor>> PrepareData(
    const paddle::optional<std::vector<Tensor>>& inputs,
    const phi::TensorArgDef& target_args_def,
    const TransformFlag& transform_flag) {
  if (inputs) {
    return {*PrepareData(*inputs, target_args_def, transform_flag)};
  }
  return paddle::none;
}

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
std::shared_ptr<phi::SelectedRows> PrepareDataForSelectedRows(
    const Tensor& input,
    const phi::TensorArgDef& target_args_def,
    const TransformFlag& transform_flag) {
  const auto& tensor_in = input.impl();
  if (tensor_in) {
    phi::SelectedRows& selected_rows =
        *static_cast<phi::SelectedRows*>(tensor_in.get());
    if (!transform_flag.NeedTransform() || !selected_rows.initialized() ||
        (!NeedTransformPlace(
            selected_rows.place(), target_args_def.backend, transform_flag))) {
      return std::static_pointer_cast<phi::SelectedRows>(tensor_in);
    }

    auto dense_out = TransDataPlace(
        selected_rows.value(), phi::TransToPhiPlace(target_args_def.backend));
    if (selected_rows.place().GetType() == AllocationType::GPUPINNED) {
      selected_rows.mutable_value()->ShareBufferWith(dense_out);
      return std::static_pointer_cast<phi::SelectedRows>(tensor_in);
    }

    auto out_new = std::make_shared<phi::SelectedRows>(selected_rows.rows(),
                                                       selected_rows.height());
    *out_new->mutable_value() = dense_out;
    return out_new;
  }
  PADDLE_THROW(phi::errors::InvalidArgument(
      "The impl() of input tensor is nullptr, it doesn't support for "
      "selected_rows data transform now."));
}

paddle::optional<phi::SelectedRows> PrepareDataForSelectedRows(
    const paddle::optional<Tensor>& input,
    const phi::TensorArgDef& target_args_def,
    const TransformFlag& transform_flag) {
  if (input) {
    return *PrepareDataForSelectedRows(*input, target_args_def, transform_flag);
  }
  return paddle::none;
}

350 351 352
void TransDataBackend(const phi::DenseTensor* tensor,
                      Backend target_backend,
                      phi::DenseTensor* out) {
353
  if (tensor && tensor->initialized()) {
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
    *out = TransDataPlace(*tensor, phi::TransToPhiPlace(target_backend));
  }
}

void TransDataBackend(const std::vector<phi::DenseTensor*>& tensors,
                      Backend target_backend,
                      std::vector<phi::DenseTensor*> outs) {
  size_t n = tensors.size();
  for (size_t i = 0; i < n; ++i) {
    TransDataBackend(tensors[i], target_backend, outs[i]);
  }
}

void TransDataBackend(const phi::SelectedRows* tensor,
                      Backend target_backend,
                      phi::SelectedRows* out) {
  if (tensor) {
    TransDataBackend(&tensor->value(), target_backend, out->mutable_value());
  }
}

375 376
}  // namespace experimental
}  // namespace paddle