tensor.cc 15.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* 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. */

#include "paddle/pten/api/include/tensor.h"

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

#include "glog/logging.h"
C
Chen Weihang 已提交
22
#include "paddle/pten/api/include/manual_api.h"
23 24 25
#include "paddle/pten/api/lib/ext_compat_utils.h"
#include "paddle/pten/api/lib/utils/allocator.h"
#include "paddle/pten/api/lib/utils/storage.h"
26
#include "paddle/pten/core/compat/convert_utils.h"
27
#include "paddle/pten/core/dense_tensor.h"
28
#include "paddle/pten/core/selected_rows.h"
29 30
#include "paddle/pten/core/tensor_base.h"
#include "paddle/pten/core/tensor_meta.h"
31
#include "paddle/pten/core/tensor_utils.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/**
 * [ Why still include the fluid headers? ]
 *
 * We hope to organize the basic implementation of Tensor and the logic related
 * to Tensor computation into an independent library, which we call
 * [Tensor Operation Library, pten], so we extract or rewrite the original
 * Kernels.
 *
 * In the future, the training library, inference library and custom operators
 * will link to this Tensor Operation library.
 *
 * However, if we directly split the link relation, we need to make too many
 * changes, which will affect the stability of the framework, so here we still
 * rely on the implementation of the framework, which is a intermediate state.
 *
 * In the future, the necessary components will be moved to the this library,
 * or the corresponding components will be re-implemented.
 */
#include "paddle/fluid/memory/memory.h"
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/platform/stream/cuda_stream.h"
53 54
#include "paddle/pten/common/complex.h"
#include "paddle/pten/common/float16.h"
55
#include "paddle/pten/core/ddim.h"
56
#include "paddle/pten/core/enforce.h"
57 58 59 60

namespace paddle {
namespace experimental {

61 62 63
// declare cast api
Tensor cast(const Tensor &x, DataType out_dtype);

64 65 66 67 68 69 70
/////// Tensor Methods ////////

/* Part 1: Construction and destruction methods */

Tensor::Tensor(std::shared_ptr<pten::TensorBase> tensor_impl)
    : impl_(std::move(tensor_impl)) {
  PADDLE_ENFORCE_NOT_NULL(impl_,
71
                          pten::errors::InvalidArgument(
72 73 74 75 76 77 78 79
                              "TensorImpl with nullptr is not supported"));
}

Tensor::Tensor(const PlaceType &place)
    : impl_(std::move(std::make_shared<pten::DenseTensor>(
          std::move(pten::make_intrusive<SharedStorage>(
              ConvertExtPlaceToInnerPlace(place))),
          std::move(pten::DenseTensorMeta(pten::DataType::UNDEFINED,
80
                                          pten::framework::make_ddim({}),
81 82
                                          pten::DataLayout::NCHW))))),
      place_{place} {}
83 84 85 86 87 88

Tensor::Tensor(const PlaceType &place, const std::vector<int64_t> &shape)
    : impl_(std::move(std::make_shared<pten::DenseTensor>(
          std::move(pten::make_intrusive<SharedStorage>(
              ConvertExtPlaceToInnerPlace(place))),
          std::move(pten::DenseTensorMeta(pten::DataType::UNDEFINED,
89
                                          pten::framework::make_ddim(shape),
90 91
                                          pten::DataLayout::NCHW))))),
      place_{place} {}
92

93 94 95
Tensor::Tensor(std::shared_ptr<pten::TensorBase> tensor_impl,
               const std::string &name)
    : impl_(std::move(tensor_impl)), name_(std::move(name)) {}
96 97 98 99 100 101
/* Part 2: Dimension, DataType and DataLayout methods */

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

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

102
pten::framework::DDim Tensor::dims() const { return impl_->dims(); }
103 104

std::vector<int64_t> Tensor::shape() const {
105
  return pten::framework::vectorize<int64_t>(impl_->dims());
106 107 108
}

void Tensor::reshape(const std::vector<int64_t> &shape) {
109 110 111 112 113 114 115 116
  LOG(WARNING) << "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::experimental::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 已提交
117
  if (is_dense_tensor()) {
118
    std::dynamic_pointer_cast<pten::DenseTensor>(impl_)->set_meta(
119
        pten::DenseTensorMeta(dtype(), pten::framework::make_ddim(shape)));
120
  } else {
121
    PADDLE_THROW(pten::errors::Unimplemented(
122 123
        "Only support reshape operation on DenseTensor now."));
  }
124 125
}

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

128
DataType Tensor::type() const { return impl_->dtype(); }
129 130 131

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

C
Chen Weihang 已提交
132 133 134
bool Tensor::is_dense_tensor() const {
  return pten::DenseTensor::classof(impl_.get());
}
135 136 137
bool Tensor::is_selected_rows() const {
  return pten::SelectedRows::classof(impl_.get());
}
138 139 140
/* Part 3: Device and Backend methods */

PlaceType Tensor::place() const {
141 142 143 144 145
  if (!impl_->initialized()) {
    return place_;
  } else {
    return ConvertInnerPlaceToExtPlace(impl_->place());
  }
146 147
}

148 149 150
paddle::platform::Place Tensor::inner_place() const {
  return ConvertExtPlaceToInnerPlace(place());
}
151 152

bool Tensor::is_cpu() const {
153
  return paddle::platform::is_cpu_place(inner_place());
154 155 156
}

bool Tensor::is_cuda() const {
157
  return paddle::platform::is_gpu_place(inner_place());
158 159 160 161 162 163
}

/* Part 4: Data Access methods */

template <typename T>
T *Tensor::mutable_data() {
C
Chen Weihang 已提交
164
  if (is_dense_tensor()) {
165 166
    return std::dynamic_pointer_cast<pten::DenseTensor>(impl_)->mutable_data<T>(
        ConvertExtPlaceToInnerPlace(place()));
167 168 169 170
  }
  return nullptr;
}

171 172 173 174 175 176 177 178 179
template PADDLE_API float *Tensor::mutable_data<float>();
template PADDLE_API double *Tensor::mutable_data<double>();
template PADDLE_API int64_t *Tensor::mutable_data<int64_t>();
template PADDLE_API int32_t *Tensor::mutable_data<int32_t>();
template PADDLE_API uint8_t *Tensor::mutable_data<uint8_t>();
template PADDLE_API int8_t *Tensor::mutable_data<int8_t>();
template PADDLE_API int16_t *Tensor::mutable_data<int16_t>();
template PADDLE_API bool *Tensor::mutable_data<bool>();
template PADDLE_API paddle::platform::complex<float>
180
    *Tensor::mutable_data<paddle::platform::complex<float>>();
181
template PADDLE_API paddle::platform::complex<double>
182
    *Tensor::mutable_data<paddle::platform::complex<double>>();
183
template PADDLE_API paddle::platform::float16 *
184 185 186 187 188
Tensor::mutable_data<paddle::platform::float16>();

template <typename T>
T *Tensor::mutable_data(const PlaceType &place) {
  auto inner_place = ConvertExtPlaceToInnerPlace(place);
189 190 191 192
  if (impl_->initialized()) {
    PADDLE_ENFORCE_EQ(
        platform::is_same_place(inner_place, impl_->place()),
        true,
193 194
        pten::errors::Unimplemented("Modification of tensor place through "
                                    "mutable_data is not supported now"));
195 196 197 198 199 200
  }
  if (is_dense_tensor()) {
    return std::dynamic_pointer_cast<pten::DenseTensor>(impl_)->mutable_data<T>(
        inner_place);
  }
  return nullptr;
201 202
}

203 204
template PADDLE_API float *Tensor::mutable_data<float>(const PlaceType &place);
template PADDLE_API double *Tensor::mutable_data<double>(
205
    const PlaceType &place);
206
template PADDLE_API int64_t *Tensor::mutable_data<int64_t>(
207
    const PlaceType &place);
208
template PADDLE_API int32_t *Tensor::mutable_data<int32_t>(
209
    const PlaceType &place);
210
template PADDLE_API uint8_t *Tensor::mutable_data<uint8_t>(
211
    const PlaceType &place);
212
template PADDLE_API int8_t *Tensor::mutable_data<int8_t>(
213
    const PlaceType &place);
214
template PADDLE_API int16_t *Tensor::mutable_data<int16_t>(
215
    const PlaceType &place);
216 217
template PADDLE_API bool *Tensor::mutable_data<bool>(const PlaceType &place);
template PADDLE_API paddle::platform::complex<float> *
218
Tensor::mutable_data<paddle::platform::complex<float>>(const PlaceType &place);
219
template PADDLE_API paddle::platform::complex<double> *
220
Tensor::mutable_data<paddle::platform::complex<double>>(const PlaceType &place);
221
template PADDLE_API paddle::platform::float16 *
222 223 224 225
Tensor::mutable_data<paddle::platform::float16>(const PlaceType &place);

template <typename T>
const T *Tensor::data() const {
C
Chen Weihang 已提交
226
  if (is_dense_tensor()) {
227 228 229 230 231
    return std::dynamic_pointer_cast<pten::DenseTensor>(impl_)->data<T>();
  } else if (pten::SelectedRows::classof(impl_.get())) {
    return std::dynamic_pointer_cast<pten::SelectedRows>(impl_)
        ->value()
        .data<T>();
232 233 234 235
  }
  return nullptr;
}

236 237 238 239 240 241 242 243 244
template PADDLE_API const float *Tensor::data<float>() const;
template PADDLE_API const double *Tensor::data<double>() const;
template PADDLE_API const int64_t *Tensor::data<int64_t>() const;
template PADDLE_API const int32_t *Tensor::data<int32_t>() const;
template PADDLE_API const uint8_t *Tensor::data<uint8_t>() const;
template PADDLE_API const int8_t *Tensor::data<int8_t>() const;
template PADDLE_API const int16_t *Tensor::data<int16_t>() const;
template PADDLE_API const bool *Tensor::data<bool>() const;
template PADDLE_API const paddle::platform::complex<float>
245
    *Tensor::data<paddle::platform::complex<float>>() const;
246
template PADDLE_API const paddle::platform::complex<double>
247
    *Tensor::data<paddle::platform::complex<double>>() const;
248
template PADDLE_API const paddle::platform::float16 *
249
Tensor::data<paddle::platform::float16>() const;
250
template PADDLE_API const paddle::platform::bfloat16 *
251
Tensor::data<paddle::platform::bfloat16>() const;
252 253 254

template <typename T>
T *Tensor::data() {
255
  PADDLE_THROW(pten::errors::Unimplemented(
256 257 258 259 260 261
      "It is not currently supported to directly obtain the modifiable data "
      "address through the tensor::data<T>() method, please use the "
      "tensor::mutable_data<T>() method."));
  return nullptr;
}

262 263 264 265 266 267 268 269 270
template PADDLE_API float *Tensor::data<float>();
template PADDLE_API double *Tensor::data<double>();
template PADDLE_API int64_t *Tensor::data<int64_t>();
template PADDLE_API int32_t *Tensor::data<int32_t>();
template PADDLE_API uint8_t *Tensor::data<uint8_t>();
template PADDLE_API int8_t *Tensor::data<int8_t>();
template PADDLE_API int16_t *Tensor::data<int16_t>();
template PADDLE_API bool *Tensor::data<bool>();
template PADDLE_API paddle::platform::complex<float>
271
    *Tensor::data<paddle::platform::complex<float>>();
272
template PADDLE_API paddle::platform::complex<double>
273
    *Tensor::data<paddle::platform::complex<double>>();
274
template PADDLE_API paddle::platform::float16 *
275 276
Tensor::data<paddle::platform::float16>();

277
// TODO(chenweihang): replace slice impl by API
278
Tensor Tensor::slice(int64_t begin_idx, int64_t end_idx) const {
C
Chen Weihang 已提交
279
  if (is_dense_tensor()) {
280
    return Tensor(std::make_shared<pten::DenseTensor>(
281
        std::move(pten::DenseTensorUtils::Slice(
282
            *(std::dynamic_pointer_cast<pten::DenseTensor>(impl_).get()),
283 284 285
            begin_idx,
            end_idx))));
  } else {
286
    PADDLE_THROW(pten::errors::Unimplemented(
287
        "Only support slice operation on DenseTensor now."));
288
  }
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
}

std::shared_ptr<pten::TensorBase> Tensor::impl() const { return impl_; }

void Tensor::set_impl(const std::shared_ptr<pten::TensorBase> &impl) {
  impl_ = impl;
}

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
gpuStream_t Tensor::stream() const {
  return platform::stream::get_current_stream(-1)->raw_stream();
}
#endif

/* Part 5: Data Transform methods */

template <typename T>
Tensor Tensor::copy_to(const PlaceType &target_place) const {
307
  LOG(WARNING) << "The Tensor's `copy_to` method is deprecated since version "
308
                  "2.3, and will be removed in version 2.4, please use "
309
                  "`copy_to` method without template argument instead. "
310 311
                  "reason: copying a Tensor to another device does not need "
                  "to specify the data type template argument.";
312
  return copy_to(ConvertExtPlaceToBackend(target_place), /*blocking=*/false);
313 314
}

315
template PADDLE_API Tensor
316
Tensor::copy_to<float>(const PlaceType &target_place) const;
317
template PADDLE_API Tensor
318
Tensor::copy_to<double>(const PlaceType &target_place) const;
319
template PADDLE_API Tensor
320
Tensor::copy_to<int64_t>(const PlaceType &target_place) const;
321
template PADDLE_API Tensor
322
Tensor::copy_to<int32_t>(const PlaceType &target_place) const;
323
template PADDLE_API Tensor
324
Tensor::copy_to<uint8_t>(const PlaceType &target_place) const;
325
template PADDLE_API Tensor
326
Tensor::copy_to<int8_t>(const PlaceType &target_place) const;
327
template PADDLE_API Tensor
328
Tensor::copy_to<int16_t>(const PlaceType &target_place) const;
329
template PADDLE_API Tensor
330
Tensor::copy_to<bool>(const PlaceType &target_place) const;
331
template PADDLE_API Tensor Tensor::copy_to<paddle::platform::complex<float>>(
332
    const PlaceType &target_place) const;
333
template PADDLE_API Tensor Tensor::copy_to<paddle::platform::complex<double>>(
334
    const PlaceType &target_place) const;
335
template PADDLE_API Tensor
336 337
Tensor::copy_to<paddle::platform::float16>(const PlaceType &target_place) const;

338 339
Tensor Tensor::copy_to(Backend backend, bool blocking) const {
  return experimental::copy_to(*this, backend, blocking);
340 341
}

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
void Tensor::copy_(const Tensor &src, bool blocking) {
  if (!src.is_initialized()) {
    return;
  }
  VLOG(3) << "Deep copy Tensor from " << src.name() << " to " << name();
  if (defined()) {
    PADDLE_ENFORCE_EQ(dtype(),
                      src.dtype(),
                      platform::errors::PreconditionNotMet(
                          "Tensor %s has different data type with Tensor %s, "
                          "Tensor Copy cannot be performed!",
                          name(),
                          src.name()));
    PADDLE_ENFORCE_EQ(impl()->type_info().id(),
                      src.impl()->type_info().id(),
                      platform::errors::PreconditionNotMet(
                          "Tensor %s has different type with Tensor %s, Tensor "
                          "Copy cannot be performed!",
                          name(),
                          src.name()));
  }
  auto copy_tensor =
      src.copy_to(pten::TransToPtenBackend(src.inner_place()), blocking);
  set_impl(copy_tensor.impl());
}
367 368
Tensor Tensor::cast(DataType target_type) const {
  return experimental::cast(*this, target_type);
369 370 371 372 373 374
}

/* Part 6: Status utils methods */

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

375
bool Tensor::initialized() const { return defined() && impl_->initialized(); }
376 377

bool Tensor::is_initialized() const {
378
  return defined() && impl_->initialized();
379 380 381 382 383 384 385 386 387
}

void Tensor::reset() { impl_.reset(); }

/* Part 7: Operator overloading */

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

Tensor &Tensor::operator=(Tensor &&x) & {
  impl_ = std::move(x.impl_);
  autograd_meta_ = std::move(x.autograd_meta_);
396 397
  name_ = std::move(x.name_);
  place_ = std::move(x.place_);
398 399 400 401 402 403 404 405 406 407 408 409 410 411
  return *this;
}

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

void Tensor::set_autograd_meta(
    std::shared_ptr<AbstractAutogradMeta> autograd_meta) {
  autograd_meta_ = std::move(autograd_meta);
}

}  // namespace experimental
}  // namespace paddle