tensor.cc 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 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/include/tensor.h"
16 17 18 19 20 21

#include <memory>
#include <utility>
#include <vector>

#include "glog/logging.h"
22

23
#include "paddle/phi/api/include/context_pool.h"
24
#include "paddle/phi/api/lib/utils/allocator.h"
25
#include "paddle/phi/backends/gpu/gpu_context.h"
26 27
#include "paddle/phi/backends/gpu/gpu_info.h"
#include "paddle/phi/core/ddim.h"
28
#include "paddle/phi/core/dense_tensor.h"
29
#include "paddle/phi/core/enforce.h"
30
#include "paddle/phi/core/selected_rows.h"
31 32
#include "paddle/phi/core/sparse_coo_tensor.h"
#include "paddle/phi/core/sparse_csr_tensor.h"
J
Jack Zhou 已提交
33
#include "paddle/phi/core/string_tensor.h"
34 35 36
#include "paddle/phi/core/tensor_base.h"
#include "paddle/phi/core/tensor_meta.h"
#include "paddle/phi/core/tensor_utils.h"
37 38

namespace paddle {
39 40 41

using DeviceContextPool = experimental::DeviceContextPool;
using DefaultAllocator = experimental::DefaultAllocator;
42 43 44 45 46

/////// Tensor Methods ////////

/* Part 1: Construction and destruction methods */

47
Tensor::Tensor(std::shared_ptr<phi::TensorBase> tensor_impl)
48
    : impl_(std::move(tensor_impl)) {
49 50 51
  PADDLE_ENFORCE_NOT_NULL(
      impl_,
      phi::errors::InvalidArgument("TensorImpl with nullptr is not supported"));
52 53
}

54
Tensor::Tensor(const Place &place) {
55 56 57 58 59 60 61 62
  LOG_FIRST_N(WARNING, 1)
      << "The Tensor(place) constructor is deprecated since version "
         "2.3, and will be removed in version 2.4! Please use "
         "`paddle::empty/full` method to create a new "
         "Tensor instead. "
         "Reason: A legal tensor cannot be constructed only based on "
         "the `place`, and datatype, shape, layout, etc. is also "
         "required.";
63
  DefaultAllocator alloc(place);
64 65 66 67 68 69 70
  impl_ = std::move(std::make_shared<phi::DenseTensor>(
      &alloc,
      std::move(phi::DenseTensorMeta(
          phi::DataType::FLOAT32, phi::make_ddim({}), phi::DataLayout::NCHW))));
}

Tensor::Tensor(const Place &place, const std::vector<int64_t> &shape) {
71 72 73 74 75 76 77 78
  LOG_FIRST_N(WARNING, 1)
      << "The Tensor(place, shape) constructor is deprecated since "
         "version 2.3, and will be removed in version 2.4! Please use "
         "`paddle::empty/full` method to create a new "
         "Tensor instead. "
         "Reason: A legal tensor cannot be constructed only based on "
         "the `place` and `shape`, and datatype, layout, etc. is also "
         "required.";
79
  DefaultAllocator alloc(place);
80 81 82 83 84 85
  impl_ = std::move(std::make_shared<phi::DenseTensor>(
      &alloc,
      std::move(phi::DenseTensorMeta(phi::DataType::FLOAT32,
                                     phi::make_ddim({shape}),
                                     phi::DataLayout::NCHW))));
}
86

87
Tensor::Tensor(std::shared_ptr<phi::TensorBase> tensor_impl,
88 89
               const std::string &name)
    : impl_(std::move(tensor_impl)), name_(std::move(name)) {}
90

91 92 93 94 95 96
/* Part 2: Dimension, DataType and DataLayout methods */

int64_t Tensor::numel() const { return impl_->numel(); }

int64_t Tensor::size() const { return impl_->numel(); }

97
const phi::DDim &Tensor::dims() const { return impl_->dims(); }
98 99

std::vector<int64_t> Tensor::shape() const {
100
  const auto &dims = impl_->dims();
101
  return phi::vectorize<int64_t>(dims);
102 103 104
}

void Tensor::reshape(const std::vector<int64_t> &shape) {
105 106 107 108 109 110 111 112 113
  LOG_FIRST_N(WARNING, 1)
      << "The function of resetting the shape of the uninitialized "
         "Tensor of the `reshape` method is deprecated since version "
         "2.3, and will be removed in version 2.4, please use "
         "`paddle::empty/full` method to create a new Tensor "
         "instead. "
         "reason: `reshape` means changing the tensor shape without "
         "touching underlying data, this requires the total size of "
         "the tensor to remain constant.";
C
Chen Weihang 已提交
114
  if (is_dense_tensor()) {
115
    static_cast<phi::DenseTensor *>(impl_.get())->Resize(phi::make_ddim(shape));
116
  } else {
117
    PADDLE_THROW(phi::errors::Unimplemented(
118 119
        "Only support reshape operation on DenseTensor now."));
  }
120 121
}

122
DataType Tensor::dtype() const { return impl_->dtype(); }
123

124
DataType Tensor::type() const { return impl_->dtype(); }
125 126 127

DataLayout Tensor::layout() const { return impl_->layout(); }

C
Chen Weihang 已提交
128
bool Tensor::is_dense_tensor() const {
129
  return phi::DenseTensor::classof(impl_.get());
C
Chen Weihang 已提交
130
}
131
bool Tensor::is_selected_rows() const {
132
  return phi::SelectedRows::classof(impl_.get());
133
}
134 135 136 137 138 139
bool Tensor::is_sparse_coo_tensor() const {
  return phi::SparseCooTensor::classof(impl_.get());
}
bool Tensor::is_sparse_csr_tensor() const {
  return phi::SparseCsrTensor::classof(impl_.get());
}
J
Jack Zhou 已提交
140 141 142
bool Tensor::is_string_tensor() const {
  return phi::StringTensor::classof(impl_.get());
}
143 144
/* Part 3: Device and Backend methods */

145
const Place &Tensor::place() const {
146 147 148 149 150 151
  PADDLE_ENFORCE_NOT_NULL(
      impl_,
      phi::errors::PermissionDenied(
          "Null pointer error, the impl_ of Tensor should not be "
          "Null when calling Tensor::place()."));
  return impl_->place();
152 153
}

154 155 156
bool Tensor::is_cpu() const {
  return place().GetType() == phi::AllocationType::CPU;
}
157

158 159 160
bool Tensor::is_gpu() const {
  return place().GetType() == phi::AllocationType::GPU;
}
161

162
bool Tensor::is_gpu_pinned() const {
163
  return place().GetType() == phi::AllocationType::GPUPINNED;
164 165
}

166 167 168
bool Tensor::is_xpu() const {
  return place().GetType() == phi::AllocationType::XPU;
}
C
Chen Weihang 已提交
169

170
bool Tensor::is_custom_device() const {
171
  return place().GetType() == phi::AllocationType::CUSTOM;
172 173
}

174 175 176 177
/* Part 4: Data Access methods */

template <typename T>
T *Tensor::mutable_data() {
178 179 180 181 182 183 184 185 186 187
  LOG_FIRST_N(WARNING, 1)
      << "Allocating memory through `mutable_data` method is "
         "deprecated since version 2.3, and `mutable_data` method "
         "will be removed in version 2.4! Please use "
         "`paddle::empty/full` method to create a new "
         "Tensor with allocated memory, and use data<T>() method "
         "to get the memory pointer of tensor instead. "
         "Reason: When calling `mutable_data` to allocate memory, "
         "the place, datatype, and data layout of tensor may be in "
         "an illegal state.";
C
Chen Weihang 已提交
188
  if (is_dense_tensor()) {
189 190
    return static_cast<phi::DenseTensor *>(impl_.get())
        ->mutable_data<T>(place());
191 192 193 194
  }
  return nullptr;
}

195
template PADDLE_API bool *Tensor::mutable_data<bool>();
196
template PADDLE_API int8_t *Tensor::mutable_data<int8_t>();
197
template PADDLE_API uint8_t *Tensor::mutable_data<uint8_t>();
198
template PADDLE_API int16_t *Tensor::mutable_data<int16_t>();
199 200 201 202 203 204 205 206 207 208 209
template PADDLE_API uint16_t *Tensor::mutable_data<uint16_t>();
template PADDLE_API int32_t *Tensor::mutable_data<int32_t>();
template PADDLE_API uint32_t *Tensor::mutable_data<uint32_t>();
template PADDLE_API int64_t *Tensor::mutable_data<int64_t>();
template PADDLE_API uint64_t *Tensor::mutable_data<uint64_t>();
template PADDLE_API phi::dtype::bfloat16 *
Tensor::mutable_data<phi::dtype::bfloat16>();
template PADDLE_API phi::dtype::float16 *
Tensor::mutable_data<phi::dtype::float16>();
template PADDLE_API float *Tensor::mutable_data<float>();
template PADDLE_API double *Tensor::mutable_data<double>();
210 211 212 213
template PADDLE_API phi::dtype::complex<float>
    *Tensor::mutable_data<phi::dtype::complex<float>>();
template PADDLE_API phi::dtype::complex<double>
    *Tensor::mutable_data<phi::dtype::complex<double>>();
214 215

template <typename T>
216
T *Tensor::mutable_data(const Place &place) {
217 218 219 220 221 222 223 224 225 226
  LOG_FIRST_N(WARNING, 1)
      << "Allocating memory through `mutable_data` method is "
         "deprecated since version 2.3, and `mutable_data` method "
         "will be removed in version 2.4! Please use "
         "`paddle::empty/full` method to create a new "
         "Tensor with allocated memory, and use data<T>() method "
         "to get the memory pointer of tensor instead. "
         "Reason: When calling `mutable_data` to allocate memory, "
         "the datatype, and data layout of tensor may be in "
         "an illegal state.";
227
  if (is_dense_tensor()) {
228
    return static_cast<phi::DenseTensor *>(impl_.get())->mutable_data<T>(place);
229 230
  }
  return nullptr;
231 232
}

233
template PADDLE_API bool *Tensor::mutable_data<bool>(const Place &place);
234
template PADDLE_API int8_t *Tensor::mutable_data<int8_t>(const Place &place);
235
template PADDLE_API uint8_t *Tensor::mutable_data<uint8_t>(const Place &place);
236
template PADDLE_API int16_t *Tensor::mutable_data<int16_t>(const Place &place);
237 238 239 240 241 242
template PADDLE_API int32_t *Tensor::mutable_data<int32_t>(const Place &place);
template PADDLE_API int64_t *Tensor::mutable_data<int64_t>(const Place &place);
template PADDLE_API phi::dtype::float16 *
Tensor::mutable_data<phi::dtype::float16>(const Place &place);
template PADDLE_API float *Tensor::mutable_data<float>(const Place &place);
template PADDLE_API double *Tensor::mutable_data<double>(const Place &place);
243
template PADDLE_API phi::dtype::complex<float>
244
    *Tensor::mutable_data<phi::dtype::complex<float>>(const Place &place);
245
template PADDLE_API phi::dtype::complex<double>
246
    *Tensor::mutable_data<phi::dtype::complex<double>>(const Place &place);
247 248 249

template <typename T>
const T *Tensor::data() const {
C
Chen Weihang 已提交
250
  if (is_dense_tensor()) {
251 252 253
    return static_cast<phi::DenseTensor *>(impl_.get())->data<T>();
  } else if (is_selected_rows()) {
    return static_cast<phi::SelectedRows *>(impl_.get())->value().data<T>();
254 255 256 257
  }
  return nullptr;
}

258
template PADDLE_API const bool *Tensor::data<bool>() const;
259
template PADDLE_API const int8_t *Tensor::data<int8_t>() const;
260
template PADDLE_API const uint8_t *Tensor::data<uint8_t>() const;
261
template PADDLE_API const int16_t *Tensor::data<int16_t>() const;
262 263 264 265 266 267 268 269 270 271 272
template PADDLE_API const uint16_t *Tensor::data<uint16_t>() const;
template PADDLE_API const int32_t *Tensor::data<int32_t>() const;
template PADDLE_API const uint32_t *Tensor::data<uint32_t>() const;
template PADDLE_API const int64_t *Tensor::data<int64_t>() const;
template PADDLE_API const uint64_t *Tensor::data<uint64_t>() const;
template PADDLE_API const phi::dtype::bfloat16 *
Tensor::data<phi::dtype::bfloat16>() const;
template PADDLE_API const phi::dtype::float16 *
Tensor::data<phi::dtype::float16>() const;
template PADDLE_API const float *Tensor::data<float>() const;
template PADDLE_API const double *Tensor::data<double>() const;
273 274 275 276
template PADDLE_API const phi::dtype::complex<float>
    *Tensor::data<phi::dtype::complex<float>>() const;
template PADDLE_API const phi::dtype::complex<double>
    *Tensor::data<phi::dtype::complex<double>>() const;
277 278 279

template <typename T>
T *Tensor::data() {
280
  if (is_dense_tensor()) {
281 282 283
    return static_cast<phi::DenseTensor *>(impl_.get())->data<T>();
  } else if (is_selected_rows()) {
    return static_cast<phi::SelectedRows *>(impl_.get())
284 285 286
        ->mutable_value()
        ->data<T>();
  }
287 288 289
  return nullptr;
}

290
template PADDLE_API bool *Tensor::data<bool>();
291
template PADDLE_API int8_t *Tensor::data<int8_t>();
292
template PADDLE_API uint8_t *Tensor::data<uint8_t>();
293
template PADDLE_API int16_t *Tensor::data<int16_t>();
294 295 296 297 298 299 300 301 302
template PADDLE_API uint16_t *Tensor::data<uint16_t>();
template PADDLE_API int32_t *Tensor::data<int32_t>();
template PADDLE_API uint32_t *Tensor::data<uint32_t>();
template PADDLE_API int64_t *Tensor::data<int64_t>();
template PADDLE_API uint64_t *Tensor::data<uint64_t>();
template PADDLE_API phi::dtype::bfloat16 *Tensor::data<phi::dtype::bfloat16>();
template PADDLE_API phi::dtype::float16 *Tensor::data<phi::dtype::float16>();
template PADDLE_API float *Tensor::data<float>();
template PADDLE_API double *Tensor::data<double>();
303 304 305 306
template PADDLE_API phi::dtype::complex<float>
    *Tensor::data<phi::dtype::complex<float>>();
template PADDLE_API phi::dtype::complex<double>
    *Tensor::data<phi::dtype::complex<double>>();
307

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
const void *Tensor::data() const {
  if (is_dense_tensor()) {
    return static_cast<phi::DenseTensor *>(impl_.get())->data();
  } else if (is_selected_rows()) {
    return static_cast<phi::SelectedRows *>(impl_.get())->value().data();
  }
  return nullptr;
}

void *Tensor::data() {
  if (is_dense_tensor()) {
    return static_cast<phi::DenseTensor *>(impl_.get())->data();
  } else if (is_selected_rows()) {
    return static_cast<phi::SelectedRows *>(impl_.get())
        ->mutable_value()
        ->data();
  }
  return nullptr;
}

328
// TODO(chenweihang): replace slice impl by API
329
Tensor Tensor::slice(int64_t begin_idx, int64_t end_idx) const {
C
Chen Weihang 已提交
330
  if (is_dense_tensor()) {
331 332
    return Tensor(std::make_shared<phi::DenseTensor>(
        std::move(phi::DenseTensorUtils::Slice(
333
            *(static_cast<phi::DenseTensor *>(impl_.get())),
334 335 336
            begin_idx,
            end_idx))));
  } else {
337
    PADDLE_THROW(phi::errors::Unimplemented(
338
        "Only support slice operation on DenseTensor now."));
339
  }
340 341
}

342
const std::shared_ptr<phi::TensorBase> &Tensor::impl() const { return impl_; }
343

344
void Tensor::set_impl(const std::shared_ptr<phi::TensorBase> &impl) {
345 346 347
  impl_ = impl;
}

348 349 350 351
void Tensor::set_impl(std::shared_ptr<phi::TensorBase> &&impl) {
  impl_ = std::move(impl);
}

352 353
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
gpuStream_t Tensor::stream() const {
354
  int device_id = phi::backends::gpu::GetCurrentDeviceId();
355 356
  auto *gpu_context = DeviceContextPool::Instance().Get<AllocationType::GPU>(
      GPUPlace(device_id));
357
  return gpu_context->stream();
358 359 360
}
#endif

361 362 363 364
const std::string &Tensor::name() const { return name_; }

void Tensor::set_name(const std::string &name) { name_ = name; }

365
/* Part 5: Status utils methods */
366 367 368

bool Tensor::defined() const { return impl_ != nullptr; }

369
bool Tensor::initialized() const { return defined() && impl_->initialized(); }
370 371

bool Tensor::is_initialized() const {
372 373 374 375
  LOG_FIRST_N(WARNING, 1)
      << "The `is_initialized` method is deprecated since version "
         "2.3, and will be removed in version 2.4! "
         "Please use `initialized` method instead.";
376
  return defined() && impl_->initialized();
377 378
}

379 380 381 382 383
void Tensor::reset() {
  impl_.reset();
  autograd_meta_.reset();
  name_ = "";
}
384

385
/* Part 6: Operator overloading */
386 387 388 389

Tensor &Tensor::operator=(const Tensor &x) & {
  impl_ = x.impl_;
  autograd_meta_ = x.autograd_meta_;
390
  name_ = x.name_;
391 392 393 394 395 396
  return *this;
}

Tensor &Tensor::operator=(Tensor &&x) & {
  impl_ = std::move(x.impl_);
  autograd_meta_ = std::move(x.autograd_meta_);
397
  name_ = std::move(x.name_);
398 399 400 401 402 403 404
  return *this;
}

AbstractAutogradMeta *Tensor::get_autograd_meta() const {
  return autograd_meta_.get();
}

405 406 407 408 409
const std::shared_ptr<AbstractAutogradMeta> &Tensor::mutable_autograd_meta()
    const {
  return autograd_meta_;
}

410 411 412 413 414
void Tensor::set_autograd_meta(
    std::shared_ptr<AbstractAutogradMeta> autograd_meta) {
  autograd_meta_ = std::move(autograd_meta);
}

415 416 417
void Tensor::bump_inplace_version() {
  if (is_dense_tensor()) {
    auto &inplace_version_counter =
418
        static_cast<phi::DenseTensor *>(impl_.get())->InplaceVersionCounter();
419 420 421 422 423 424 425 426 427 428
    inplace_version_counter.Bump();
  } else {
    PADDLE_THROW(phi::errors::Unimplemented(
        "bump_inplace_version is only supported on DenseTensor now."));
  }
}

uint32_t Tensor::current_inplace_version() {
  if (is_dense_tensor()) {
    auto &inplace_version_counter =
429
        static_cast<phi::DenseTensor *>(impl_.get())->InplaceVersionCounter();
430 431
    return inplace_version_counter.CurrentVersion();
  } else {
432 433
    LOG_FIRST_N(WARNING, 1)
        << "current_inplace_version is only supported on DenseTensor now.";
434 435 436 437
  }
  return 0;
}

438 439 440 441
void Tensor::reset_inplace_version(bool set_to_zero) {
  if (set_to_zero) {
    if (is_dense_tensor()) {
      auto &inplace_version_counter =
442
          static_cast<phi::DenseTensor *>(impl_.get())->InplaceVersionCounter();
443 444 445 446 447
      inplace_version_counter.SetInplaceVersionToZero();
    }
  }
}

448
}  // namespace paddle