data_transform.cc 13.4 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 "glog/logging.h"

19
#include "paddle/phi/api/lib/kernel_dispatch.h"
20
#include "paddle/phi/api/lib/utils/allocator.h"
21
#include "paddle/phi/backends/context_pool.h"
22
#include "paddle/phi/core/kernel_registry.h"
23
#include "paddle/phi/core/tensor_utils.h"
24 25
#include "paddle/phi/kernels/cast_kernel.h"
#include "paddle/phi/kernels/transfer_layout_kernel.h"
26 27 28 29 30 31 32 33 34 35 36 37

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

38
inline bool NeedTransformLayout(const DataLayout& input,
39
                                const DataLayout& target,
40
                                const phi::Place& place,
41 42 43 44
                                const TransformFlag& transform_flag) {
  bool ret = transform_flag.need_trans_layout() &&
             (input != DataLayout::ALL_LAYOUT &&
              target != DataLayout::ALL_LAYOUT && input != target);
45
  if (place.GetType() == phi::AllocationType::GPU) {
46 47
    return false;
  }
48 49 50
  return ret;
}

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

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

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

125 126
inline phi::DenseTensor TransDataType(const phi::DenseTensor& tensor,
                                      DataType dtype) {
127
  auto& pool = phi::DeviceContextPool::Instance();
128 129 130 131

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

132 133
  DefaultAllocator alloc(tensor.place());
  phi::DenseTensor out(&alloc, {dtype, tensor.dims(), tensor.layout()});
134

135
  if (tensor.place().GetType() == phi::AllocationType::CPU) {
136
    auto* dev_ctx = static_cast<phi::CPUContext*>(pool.Get(tensor.place()));
137
    return CastDataType(*dev_ctx, tensor, dtype);
138
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
139
  } else if (tensor.place().GetType() == phi::AllocationType::GPU) {
140
    auto* dev_ctx = static_cast<phi::GPUContext*>(pool.Get(tensor.place()));
141
    return CastDataType(*dev_ctx, tensor, dtype);
142 143
#endif
  } else {
144
    PADDLE_THROW(phi::errors::Unimplemented(
145 146 147 148 149
        "Place type is not supported when casting data type."));
  }
  return out;
}

150 151 152 153 154
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 已提交
155
  auto& pool = phi::DeviceContextPool::Instance();
156 157
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  // NOTE(yy): TransDataPlace should wait for computation of input.
158
  if (tensor.place().GetType() != phi::AllocationType::GPUPINNED) {
159 160 161 162 163 164 165 166 167 168 169 170 171 172
    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.
173
  phi::DenseTensor out;
E
engineer1109 已提交
174 175 176 177 178 179 180
  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);
181 182 183
  return out;
}

184
phi::DenseTensor TransformData(phi::DenseTensor* tensor,
185 186
                               const phi::TensorArgDef& target_args_def,
                               const TransformFlag& transform_flag) {
187 188 189
  phi::DenseTensor out = *tensor;
  bool trans_layout = false;
  bool trans_dtype = false;
190

191
  if (NeedTransformLayout(tensor->layout(),
192
                          target_args_def.layout,
193
                          tensor->place(),
194 195
                          transform_flag) &&
      tensor->dims().size() != 1) {
196
    out = TransDataLayout(out, target_args_def.layout);
197
    trans_layout = true;
198 199 200
  }

  if (NeedTransformDataType(
201
          tensor->dtype(), target_args_def.dtype, transform_flag)) {
202
    out = TransDataType(out, target_args_def.dtype);
203
    trans_dtype = true;
204 205 206 207
  }

  if (NeedTransformPlace(
          out.place(), target_args_def.backend, transform_flag)) {
208
    out = TransDataPlace(out, phi::TransToPhiPlace(target_args_def.backend));
209 210 211 212
    if (!trans_layout && !trans_dtype &&
        tensor->place().GetType() == AllocationType::GPUPINNED) {
      tensor->ShareBufferWith(out);
    }
213 214 215 216
  }
  return out;
}

217
std::shared_ptr<phi::DenseTensor> PrepareData(
218
    const Tensor& input,
219
    const phi::TensorArgDef& target_args_def,
220 221
    const TransformFlag& transform_flag) {
  const auto& tensor_in = input.impl();
Z
zyfncg 已提交
222 223 224 225 226 227 228 229
  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) &&
230
         !NeedTransformLayout(dense_tensor.layout(),
231
                              target_args_def.layout,
232
                              dense_tensor.place(),
233
                              transform_flag))) {
Z
zyfncg 已提交
234 235 236
      return std::static_pointer_cast<phi::DenseTensor>(tensor_in);
    }
    phi::DenseTensor out =
237
        TransformData(&dense_tensor, target_args_def, transform_flag);
Z
zyfncg 已提交
238
    return std::make_shared<phi::DenseTensor>(std::move(out));
239
  }
Z
zyfncg 已提交
240
  return nullptr;
241 242
}

243
paddle::optional<phi::DenseTensor> PrepareData(
244 245 246 247
    const paddle::optional<Tensor>& input,
    const phi::TensorArgDef& target_args_def,
    const TransformFlag& transform_flag) {
  if (input) {
248
    return {*PrepareData(*input, target_args_def, transform_flag)};
H
hong 已提交
249
  }
250
  return paddle::none;
H
hong 已提交
251 252
}

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

281
  return pt_tensors;
282 283
}

284 285 286 287 288 289 290 291 292 293
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;
}

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 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
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;
}

335 336 337
void TransDataBackend(const phi::DenseTensor* tensor,
                      Backend target_backend,
                      phi::DenseTensor* out) {
338
  if (tensor && tensor->initialized()) {
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    *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());
  }
}

360 361
}  // namespace experimental
}  // namespace paddle