dense_tensor.cc 18.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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/core/dense_tensor.h"

17 18 19 20 21
// See Note [ Why still include the fluid headers? ]
#include "paddle/fluid/platform/bfloat16.h"
#include "paddle/fluid/platform/complex.h"
#include "paddle/fluid/platform/float16.h"

22 23 24
#include "paddle/pten/api/lib/utils/storage.h"
#include "paddle/pten/core/convert_utils.h"

25 26
namespace pten {

27
DenseTensor::DenseTensor(Allocator* a, const DenseTensorMeta& meta)
28
    : meta_(meta),
29
      storage_(make_intrusive<TensorStorage>(a, SizeOf(dtype()) * numel())) {}
30

31
DenseTensor::DenseTensor(Allocator* a, DenseTensorMeta&& meta)
32
    : meta_(std::move(meta)),
33
      storage_(make_intrusive<TensorStorage>(a, SizeOf(dtype()) * numel())) {}
34 35 36 37 38 39 40 41

DenseTensor::DenseTensor(intrusive_ptr<Storage> storage,
                         const DenseTensorMeta& meta)
    : meta_(meta), storage_(std::move(storage)) {}

DenseTensor::DenseTensor(intrusive_ptr<Storage> storage, DenseTensorMeta&& meta)
    : meta_(std::move(meta)), storage_(std::move(storage)) {}

42 43 44 45 46 47 48 49 50 51 52 53 54
DenseTensor::DenseTensor(const DenseTensor& other) : meta_(other.meta()) {
  if (storage_ == nullptr) {
    storage_ = make_intrusive<paddle::experimental::SharedStorage>(
        paddle::platform::CPUPlace());
  }
  if (other.storage_ != nullptr && other.storage_->data_shared()) {
    storage_->set_data_shared(other.storage_->data_shared());
  }

#ifdef PADDLE_WITH_MKLDNN
  format_ = other.format_;
#endif
}
55

56 57
DenseTensor& DenseTensor::operator=(const DenseTensor& other) {
  meta_ = other.meta();
58 59 60 61 62 63 64 65 66 67
  if (storage_ == nullptr) {
    storage_ = make_intrusive<paddle::experimental::SharedStorage>(
        paddle::platform::CPUPlace());
  }
  if (other.storage_ != nullptr && other.storage_->data_shared()) {
    storage_->set_data_shared(other.storage_->data_shared());
  }
#ifdef PADDLE_WITH_MKLDNN
  format_ = other.format_;
#endif
68 69 70
  return *this;
}

71 72 73 74 75 76
DenseTensor& DenseTensor::operator=(DenseTensor&& other) {
  meta_ = std::move(other.meta_);
  storage_.swap(other.storage_);
  return *this;
}

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
int64_t DenseTensor::numel() const {
  if (meta_.is_scalar) {
    return 1;
  }
  return product(meta_.dims);
}

bool DenseTensor::IsSharedWith(const DenseTensor& b) const {
  return storage_.get() == b.storage_.get() && storage_.get() != nullptr;
}

void* DenseTensor::mutable_data(size_t request_bytes) {
  PADDLE_ENFORCE(
      valid(),
      paddle::platform::errors::PreconditionNotMet(
          "The meta data must be valid when call the mutable data function."));
  PADDLE_ENFORCE_NOT_NULL(
      storage_,
      paddle::platform::errors::PreconditionNotMet(
          "The storage must be valid when call the mutable data function."));
97
  size_t bytes = numel() * SizeOf(dtype());
98 99 100 101 102 103 104 105 106 107
  if (request_bytes) {
    PADDLE_ENFORCE_GE(request_bytes,
                      bytes,
                      paddle::platform::errors::InvalidArgument(
                          "The reserved size %d should be enough to meet the "
                          "volume required by metadata %d.",
                          request_bytes,
                          bytes));
    bytes = request_bytes;
  }
108
  if (storage_->size() < bytes + meta_.offset || storage_->size() == 0) {
109 110
    VLOG(10) << "mutbale data realloc, original size: " << storage_->size()
             << ", new size: " << bytes;
111
    storage_->Realloc(bytes);
112
    meta_.offset = 0;
113
  }
114 115
  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(storage_->data()) +
                                 meta_.offset);
116 117 118 119
}

template <typename T>
T* DenseTensor::mutable_data() {
120 121 122
  // In order to be compatible with the original Tensor design and
  // execution system, we have to reset the datatype in mutable_data<T>.
  // When the compatibility phase is over in the future, we can delete it
123
  if (meta_.dtype == DataType::UNDEFINED) {
124 125
    VLOG(10) << "change data type in mutbale_data, target dtype - "
             << paddle::experimental::CppTypeToDataType<T>::Type();
126
    const_cast<DataType&>(meta_.dtype) =
127 128
        paddle::experimental::CppTypeToDataType<T>::Type();
  }
129
  PADDLE_ENFORCE(
130
      (dtype() == paddle::experimental::CppTypeToDataType<T>::Type()),
131
      paddle::platform::errors::InvalidArgument(
132 133 134
          "The type of data (%d) we are trying to retrieve does not match the "
          "type of data currently contained in the container (%d).",
          static_cast<int>(paddle::experimental::CppTypeToDataType<T>::Type()),
135
          static_cast<int>(dtype())));
136 137 138 139 140
  return static_cast<T*>(mutable_data());
}

template <typename T>
const T* DenseTensor::data() const {
141
  check_memory_size();
142
  PADDLE_ENFORCE(
143
      (dtype() == paddle::experimental::CppTypeToDataType<T>::Type()),
144
      paddle::platform::errors::InvalidArgument(
145 146 147 148 149
          "The type of data we are trying to retrieve does not match the "
          "type of data currently contained in the container."));
  return static_cast<const T*>(data());
}

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
template <typename T>
T* DenseTensor::data() {
  check_memory_size();
  PADDLE_ENFORCE(
      (dtype() == paddle::experimental::CppTypeToDataType<T>::Type()),
      paddle::platform::errors::InvalidArgument(
          "The type of data we are trying to retrieve does not match the "
          "type of data currently contained in the container."));
  PADDLE_ENFORCE_NOT_NULL(
      storage_,
      paddle::platform::errors::PreconditionNotMet(
          "The storage must be valid when call the mutable data function."));
  return reinterpret_cast<T*>(data());
}

165
void* DenseTensor::data() {
166 167 168 169
  PADDLE_ENFORCE_NOT_NULL(
      storage_,
      paddle::platform::errors::PreconditionNotMet(
          "The storage must be valid when call the mutable data function."));
170 171
  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(storage_->data()) +
                                 meta_.offset);
172 173
}

174
const void* DenseTensor::data() const {
175 176 177 178
  PADDLE_ENFORCE_NOT_NULL(
      storage_,
      paddle::platform::errors::PreconditionNotMet(
          "The storage must be valid when call the mutable data function."));
179 180
  return reinterpret_cast<const void*>(
      reinterpret_cast<uintptr_t>(storage_->data()) + meta_.offset);
181 182
}

183 184 185 186 187 188
void DenseTensor::set_meta(DenseTensorMeta&& meta) {
  PADDLE_ENFORCE(!meta_.valid(),
                 paddle::platform::errors::InvalidArgument(
                     "Only when the original attribute of Tensor is "
                     "incomplete, can it be reset."));
  meta_ = std::move(meta);
石晓伟 已提交
189 190
}

191 192 193 194 195 196 197 198 199 200
/* @jim19930609: This interface will be further modified util we finalized the
   design for Allocator - Allocation
   For now, we have to temporarily accommodate two independent use cases:
   1. Designed behaviour: DenseTensor constructed with its underlying storage_
   initialized
   2. Legacy behaviour(fluid): DenseTensor constructed using default
   constructor, where
                               storage_ won't be initialized until the first
   call to mutable_data(place)
   */
201
void DenseTensor::Resize(const DDim& dims) {
石晓伟 已提交
202
  meta_.dims = dims;
203 204 205
  if (storage_ != nullptr) {
    mutable_data();
  }
石晓伟 已提交
206 207
}

208 209
void DenseTensor::ResetLoD(const LoD& lod) { meta_.lod = lod; }

210 211 212 213
#define DATA_MEMBER_FUNC_INSTANTIATION(dtype)      \
  template dtype* DenseTensor::mutable_data();     \
  template const dtype* DenseTensor::data() const; \
  template dtype* DenseTensor::data();
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

DATA_MEMBER_FUNC_INSTANTIATION(bool);
DATA_MEMBER_FUNC_INSTANTIATION(int8_t);
DATA_MEMBER_FUNC_INSTANTIATION(uint8_t);
DATA_MEMBER_FUNC_INSTANTIATION(int16_t);
DATA_MEMBER_FUNC_INSTANTIATION(uint16_t);
DATA_MEMBER_FUNC_INSTANTIATION(int32_t);
DATA_MEMBER_FUNC_INSTANTIATION(uint32_t);
DATA_MEMBER_FUNC_INSTANTIATION(int64_t);
DATA_MEMBER_FUNC_INSTANTIATION(uint64_t);
DATA_MEMBER_FUNC_INSTANTIATION(::paddle::platform::bfloat16);
DATA_MEMBER_FUNC_INSTANTIATION(::paddle::platform::float16);
DATA_MEMBER_FUNC_INSTANTIATION(float);
DATA_MEMBER_FUNC_INSTANTIATION(double);
DATA_MEMBER_FUNC_INSTANTIATION(::paddle::experimental::complex64);
DATA_MEMBER_FUNC_INSTANTIATION(::paddle::experimental::complex128);

#undef DATA_MEMBER_FUNC_INSTANTIATION

233 234 235 236
/* --------------------------- */
/*   From framework::Tensor    */
/* --------------------------- */
DenseTensor::DenseTensor() {
237 238
  storage_ = make_intrusive<paddle::experimental::SharedStorage>(
      paddle::platform::CPUPlace());
239 240 241 242 243 244
  inplace_version_counter_ = std::make_shared<TensorInplaceVersion>(0);
  meta_.dtype = paddle::experimental::DataType::FLOAT32;
  meta_.offset = 0;
}

DenseTensor::DenseTensor(const paddle::framework::proto::VarType::Type& dtype) {
245 246
  storage_ = make_intrusive<paddle::experimental::SharedStorage>(
      paddle::platform::CPUPlace());
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  inplace_version_counter_ = std::make_shared<TensorInplaceVersion>(0);
  meta_.dtype = TransToPtenDataType(dtype);
  meta_.offset = 0;
}

size_t DenseTensor::memory_size() const {
  if (storage_ == nullptr || storage_->data_shared() == nullptr) {
    return 0UL;
  }

  return storage_->data_shared()->size() - meta_.offset;
}

void DenseTensor::check_memory_size() const {
  PADDLE_ENFORCE_NOT_NULL(storage_,
                          paddle::platform::errors::PreconditionNotMet(
                              "Tensor holds no memory. "
                              "Call Tensor::mutable_data firstly."));
  PADDLE_ENFORCE_NOT_NULL(storage_->data_shared(),
                          paddle::platform::errors::PreconditionNotMet(
                              "Tensor holds no memory. "
                              "Call Tensor::mutable_data firstly."));
  size_t size = numel() * SizeOf(dtype());

  PADDLE_ENFORCE_LE(
      size,
      memory_size(),
      paddle::platform::errors::PreconditionNotMet(
          "Tensor's dimension is out of bound."
          "Tensor's dimension must be equal or less than the size of its "
          "memory."
          "But received  Tensor's dimension is d%, memory's size is %d.",
          size,
          memory_size()));
}

const paddle::platform::Place& DenseTensor::place() const {
  PADDLE_ENFORCE_NOT_NULL(
      storage_,
      paddle::platform::errors::PreconditionNotMet(
          "Tensor not initialized yet when Tensor::place() is called."));
288 289 290
  if (storage_->data_shared()) {
    return storage_->data_shared()->place();
  }
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  return storage_->place();
}

paddle::framework::proto::VarType::Type DenseTensor::type() const {
  PADDLE_ENFORCE_NOT_NULL(
      storage_,
      paddle::platform::errors::PreconditionNotMet(
          "Tensor not initialized yet when Tensor::type() is called."));
  return TransToProtoVarType(meta_.dtype);
}

paddle::framework::proto::VarType::Type DenseTensor::saved_type() const {
  return TransToProtoVarType(meta_.dtype);
}

void DenseTensor::set_layout(const paddle::framework::DataLayout layout) {
  meta_.layout = layout;
}

void DenseTensor::ResetHolder(
    const std::shared_ptr<paddle::memory::Allocation>& holder) {
  PADDLE_ENFORCE_EQ(
      meta_.offset,
      0,
      paddle::platform::errors::Fatal(
          "Only the offset is supported to zero when the holder is reset."));

318 319 320 321
  PADDLE_ENFORCE_NOT_NULL(
      storage_,
      paddle::platform::errors::PreconditionNotMet(
          "The storage must be valid when call the mutable data function."));
322 323 324 325

  if (storage_->data_shared()) {
    PADDLE_ENFORCE_LE(
        numel() * SizeOf(dtype()) + meta_.offset,
326
        holder->size(),
327 328 329 330 331 332 333 334 335 336 337 338 339 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 367 368 369 370 371 372 373 374
        paddle::platform::errors::InvalidArgument(
            "The size of Holder is not enough to store the Tensor."));
  }

  storage_->set_data_shared(holder);
}

void DenseTensor::ResetHolderWithType(
    const std::shared_ptr<paddle::memory::Allocation>& holder,
    const paddle::framework::proto::VarType::Type& type) {
  set_type(type);
  ResetHolder(holder);
}

void DenseTensor::set_type(
    const paddle::framework::proto::VarType::Type& type) {
  meta_.dtype = TransToPtenDataType(type);
}

void* DenseTensor::mutable_data(const paddle::platform::Place& place,
                                paddle::framework::proto::VarType::Type type,
                                size_t requested_size) {
  set_type(type);
  PADDLE_ENFORCE_GE(
      numel(),
      0,
      paddle::platform::errors::PreconditionNotMet(
          "The Tensor's element number must be equal or greater than zero. "
          "The Tensor's shape is [",
          dims(),
          "] now"));
  size_t size = numel() * SizeOf(dtype());
  if (requested_size && (requested_size > size)) {
    size = requested_size;
  }

  if (storage_ == nullptr) {
    storage_ = make_intrusive<paddle::experimental::SharedStorage>(place);
  }

  /* some versions of boost::variant don't have operator!= */
  if (storage_->data_shared() == nullptr ||
      !(storage_->data_shared()->place() == place) ||
      storage_->data_shared()->size() < size + meta_.offset) {
    storage_->Clear();
    storage_->set_data_shared(paddle::memory::AllocShared(place, size));
    meta_.offset = 0;
  }
375 376
  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(storage_->data()) +
                                 meta_.offset);
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
}

void* DenseTensor::mutable_data(const paddle::platform::Place& place,
                                size_t requested_size) {
  return mutable_data(place, type(), requested_size);
}

void* DenseTensor::mutable_data(const paddle::platform::Place& place,
                                paddle::framework::proto::VarType::Type type,
                                const paddle::platform::Stream& stream) {
  set_type(type);
  PADDLE_ENFORCE_GE(
      numel(),
      0,
      paddle::platform::errors::PreconditionNotMet(
          "The Tensor's element number must be equal or greater than zero. "
          "The Tensor's shape is [",
          dims(),
          "] now"));
  size_t size = numel() * SizeOf(dtype());

398 399 400 401
  if (storage_ == nullptr) {
    storage_ = make_intrusive<paddle::experimental::SharedStorage>(place);
  }

402
  /* some versions of boost::variant don't have operator!= */
403
  if (storage_->data_shared() == nullptr ||
404 405 406 407 408 409 410 411
      !(storage_->data_shared()->place() == place) ||
      storage_->data_shared()->size() < size + meta_.offset ||
      !(paddle::platform::is_gpu_place(place) &&
        paddle::memory::InSameStream(storage_->data_shared(), stream))) {
    storage_->Clear();
    storage_->set_data_shared(paddle::memory::AllocShared(place, size, stream));
    meta_.offset = 0;
  }
412 413
  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(storage_->data()) +
                                 meta_.offset);
414 415 416 417 418 419 420 421 422 423 424 425
}

/* @jim19930609: The following "mutable_data" only supports specific dtypes
   defined in OpProto. This part need another clean up once the data type across
   Fluid
   and Pten get unified.
   */
template <typename T>
inline T* DenseTensor::mutable_data(const DDim& dims,
                                    const paddle::platform::Place& place,
                                    size_t requested_size) {
  static_assert(std::is_pod<T>::value, "T must be POD");
426
  meta_.dims = dims;
427 428 429 430 431 432 433 434 435 436 437
  return mutable_data<T>(place, requested_size);
}

template <typename T>
inline T* DenseTensor::mutable_data(const paddle::platform::Place& place,
                                    size_t requested_size) {
  static_assert(std::is_pod<T>::value, "T must be POD");
  return reinterpret_cast<T*>(mutable_data(
      place, paddle::framework::DataTypeTrait<T>::DataType(), requested_size));
}

438
void DenseTensor::ShareBufferWith(const DenseTensor& tensor) {
B
Baibaifan 已提交
439 440 441 442
  if (storage_ == nullptr) {
    storage_ = make_intrusive<paddle::experimental::SharedStorage>(
        paddle::platform::CPUPlace());
  }
443 444 445 446 447 448
  if (storage_ != nullptr && tensor.storage_ != nullptr) {
    storage_->set_data_shared(tensor.storage_->data_shared());
  }
  meta_.offset = tensor.meta().offset;
}

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
#define LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(dtype) \
  template dtype* DenseTensor::mutable_data(         \
      const DDim& dims,                              \
      const paddle::platform::Place& place,          \
      size_t requested_size);                        \
  template dtype* DenseTensor::mutable_data(         \
      const paddle::platform::Place& place, size_t requested_size);

LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(bool)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(int8_t)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(uint8_t)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(int16_t)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(int)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(int64_t)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(float)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(double)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(::paddle::platform::bfloat16)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(::paddle::platform::float16)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(::paddle::experimental::complex64)
LEGACY_DATA_MEMBER_FUNC_INSTANTIATION(::paddle::experimental::complex128)

#undef LEGACY_DATA_MEMBER_FUNC_INSTANTIATION

/* ------------------------------ */
/*   From framework::LoDTensor    */
/* ------------------------------ */

DenseTensor::DenseTensor(const LoD& lod) : DenseTensor() { meta_.lod = lod; }

void DenseTensor::set_lod(const LoD& lod) { meta_.lod = lod; }

LoD* DenseTensor::mutable_lod() { return &meta_.lod; }

std::pair<size_t, size_t> DenseTensor::lod_element(size_t level,
                                                   size_t elem) const {
  PADDLE_ENFORCE_LT(
      level,
      NumLevels(),
      paddle::platform::errors::InvalidArgument(
          "The input level of LoD is invalid, it should be less than LoD "
          "size. The input level is %zu, the LoD size is %zu.",
          level,
          NumLevels()));

  PADDLE_ENFORCE_LT(elem,
                    NumElements(level),
                    paddle::platform::errors::InvalidArgument(
                        "The input element of LoD is invalid, it should be "
                        "less than the number of elements in its level."
                        "The input element is %zu, the number of elements in "
                        "its level is %zu.",
                        elem,
                        NumElements(level)));

  return std::make_pair((meta_.lod)[level][elem], (meta_.lod)[level][elem + 1]);
}

size_t DenseTensor::NumLevels() const { return meta_.lod.size(); }

size_t DenseTensor::NumElements(size_t level) const {
  PADDLE_ENFORCE_LT(
      level,
      NumLevels(),
      paddle::platform::errors::InvalidArgument(
          "The input level of LoD is invalid, it should be less than LoD "
          "size. The input level is %zu, the LoD size is %zu.",
          level,
          NumLevels()));

  // the last offset is the end of last element
  return (meta_.lod)[level].size() - 1;
}

522
}  // namespace pten