dense_tensor.cc 10.9 KB
Newer Older
1
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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/core/dense_tensor.h"
16

17 18
#include "glog/logging.h"

19 20 21 22
#include "paddle/phi/common/bfloat16.h"
#include "paddle/phi/common/complex.h"
#include "paddle/phi/common/float16.h"
#include "paddle/phi/core/compat/convert_utils.h"
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/**
 * [ 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, phi], 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.
 */
42

43
namespace phi {
44

45
DenseTensor::DenseTensor(Allocator* a, const DenseTensorMeta& meta)
46
    : meta_(meta), holder_(a->Allocate(SizeOf(dtype()) * numel())) {}
47

48
DenseTensor::DenseTensor(Allocator* a, DenseTensorMeta&& meta)
49
    : meta_(std::move(meta)), holder_(a->Allocate(SizeOf(dtype()) * numel())) {}
50

51
DenseTensor::DenseTensor(const std::shared_ptr<phi::Allocation>& holder,
52
                         const DenseTensorMeta& meta)
53
    : meta_(meta), holder_(holder) {}
54

55 56
DenseTensor::DenseTensor(const DenseTensor& other) {
  this->meta_ = other.meta();
57
  holder_ = other.holder_;
58 59
  storage_properties_ =
      std::move(CopyStorageProperties(other.storage_properties_));
60
  inplace_version_counter_ = other.inplace_version_counter_;
61

62
#ifdef PADDLE_WITH_DNNL
63
  mem_desc_ = other.mem_desc_;
64 65
#endif
}
66

67 68
DenseTensor& DenseTensor::operator=(const DenseTensor& other) {
  meta_ = other.meta();
69
  holder_ = other.holder_;
70 71
  storage_properties_ =
      std::move(CopyStorageProperties(other.storage_properties_));
72
  inplace_version_counter_ = other.inplace_version_counter_;
73
#ifdef PADDLE_WITH_DNNL
74
  mem_desc_ = other.mem_desc_;
75
#endif
76 77 78
  return *this;
}

79 80
DenseTensor& DenseTensor::operator=(DenseTensor&& other) {
  meta_ = std::move(other.meta_);
81
  std::swap(holder_, other.holder_);
82
  storage_properties_ = std::move(other.storage_properties_);
83
  std::swap(inplace_version_counter_, other.inplace_version_counter_);
84
#ifdef PADDLE_WITH_DNNL
85 86
  mem_desc_ = other.mem_desc_;
#endif
87 88 89
  return *this;
}

90 91 92 93 94 95 96 97
int64_t DenseTensor::numel() const {
  if (meta_.is_scalar) {
    return 1;
  }
  return product(meta_.dims);
}

bool DenseTensor::IsSharedWith(const DenseTensor& b) const {
98
  return holder_ && holder_ == b.Holder();
99 100
}

101 102
void* DenseTensor::AllocateFrom(Allocator* allocator,
                                DataType dtype,
103 104
                                size_t requested_size,
                                bool fake_alloc) {
105 106
  PADDLE_ENFORCE_NOT_NULL(
      allocator,
107
      phi::errors::InvalidArgument(
108 109
          "Required allocator shall not be nullptr, but received nullptr."));
  if (this->dtype() != dtype) {
C
co63oc 已提交
110
    VLOG(10) << "change data type in mutable_data, target dtype - " << dtype;
111 112
    meta_.dtype = dtype;
  }
113

114
  size_t bytes = numel() * SizeOf(this->dtype());
115 116 117 118

  if (fake_alloc) {
    bytes = 0;
  } else {
119
    PADDLE_ENFORCE_EQ(
120
        valid(),
121
        true,
122 123 124 125 126 127 128 129 130 131 132 133
        phi::errors::PreconditionNotMet("The meta data must be valid when "
                                        "call the mutable data function."));
    if (requested_size) {
      PADDLE_ENFORCE_GE(requested_size,
                        bytes,
                        phi::errors::InvalidArgument(
                            "The reserved size %d should be enough to meet the "
                            "volume required by metadata %d.",
                            requested_size,
                            bytes));
      bytes = requested_size;
    }
134
  }
135

136 137 138
  // NOTE(paddle-dev): In case of the allocator of storage_ is different with
  // the incoming allocator, we will re-alloc data using the incoming
  // allocator. See DeviceContext.Alloc in core/device_context.cc.
139 140 141
  if (!holder_ || holder_->size() < bytes + meta_.offset) {
    meta_.offset = 0;
    VLOG(10) << "Allocate data with bytes: " << bytes;
142 143 144 145 146 147 148 149 150 151
    auto holder = allocator->Allocate(bytes);
    if (holder_) {
      PADDLE_ENFORCE_LE(
          numel() * static_cast<int64_t>(SizeOf(dtype)) +
              static_cast<int64_t>(meta_.offset),
          static_cast<int64_t>(holder->size()),
          phi::errors::InvalidArgument(
              "The size of Holder is not enough to store the Tensor."));
    }
    holder_ = std::move(holder);
152 153 154 155 156 157
  }

  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(holder_->ptr()) +
                                 meta_.offset);
}

158 159
template <typename T>
const T* DenseTensor::data() const {
H
hong 已提交
160 161
  PADDLE_ENFORCE_EQ(
      dtype(),
162
      phi::CppTypeToDataType<T>::Type(),
163
      phi::errors::InvalidArgument(
164 165
          "The type of data we are trying to retrieve (%s) does not match the "
          "type of data (%s) currently contained in the container.",
166
          phi::CppTypeToDataType<T>::Type(),
167
          dtype()));
168 169 170
  return static_cast<const T*>(data());
}

171 172
template <typename T>
T* DenseTensor::data() {
173
  T* ret = static_cast<T*>(data());
174 175 176
  PADDLE_ENFORCE_EQ(
      dtype(),
      phi::CppTypeToDataType<T>::Type(),
177
      phi::errors::InvalidArgument(
178 179
          "The type of data we are trying to retrieve (%s) does not match the "
          "type of data (%s) currently contained in the container.",
180
          phi::CppTypeToDataType<T>::Type(),
181
          dtype()));
182
  return ret;
183 184
}

185
void* DenseTensor::data() {
186
  check_memory_size();
187
  PADDLE_ENFORCE_NOT_NULL(
188
      holder_,
189
      phi::errors::PreconditionNotMet(
190 191
          "The storage must be valid when call the data function."));
  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(holder_->ptr()) +
192
                                 meta_.offset);
193 194
}

195
const void* DenseTensor::data() const {
196
  check_memory_size();
197
  PADDLE_ENFORCE_NOT_NULL(
198
      holder_,
199
      phi::errors::PreconditionNotMet(
200
          "The storage must be valid when call the data function."));
201
  return reinterpret_cast<const void*>(
202
      reinterpret_cast<uintptr_t>(holder_->ptr()) + meta_.offset);
203 204
}

205
void DenseTensor::set_meta(DenseTensorMeta&& meta) {
206 207 208 209 210
  PADDLE_ENFORCE_EQ(meta_.valid(),
                    false,
                    phi::errors::InvalidArgument(
                        "Only when the original attribute of Tensor is "
                        "incomplete, can it be reset."));
211
  meta_ = std::move(meta);
石晓伟 已提交
212 213
}

214
void DenseTensor::set_meta(const DenseTensorMeta& meta) {
215
  PADDLE_ENFORCE_EQ(
216
      meta.valid(),
217
      true,
218
      phi::errors::InvalidArgument(
219 220 221 222 223 224 225
          "Input meta is invalid, please check the meta attribute."));
  meta_.dims = meta.dims;
  meta_.dtype = meta.dtype;
  meta_.is_scalar = meta.is_scalar;
  meta_.layout = meta.layout;
  meta_.lod = meta.lod;
  meta_.offset = meta.offset;
226
  meta_.use_gpudnn = meta.use_gpudnn;
W
wanghuancoder 已提交
227 228 229 230 231
  if (meta.strides.size() == -1) {
    meta_.strides = meta_.calc_strides(meta_.dims);
  } else {
    meta_.strides = meta.strides;
  }
232 233
}

234
/* @jim19930609: This interface will be further modified until we finalized the
235 236 237 238 239 240 241 242 243
   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)
   */
244
void DenseTensor::ResizeAndAllocate(const DDim& dims) {
W
wanghuancoder 已提交
245 246 247 248 249 250 251 252 253 254 255 256
  if (meta_.dims.size() != -1 && meta_.dims != dims) {
    PADDLE_ENFORCE_EQ(meta_.is_contiguous(),
                      true,
                      phi::errors::InvalidArgument(
                          "Right now Resize is only supported for contiguous "
                          "Tensor. Tensor dims is %s, Tensor layout is %s, "
                          "Tensor stride is %s. New dims is %s.",
                          meta_.dims,
                          meta_.layout,
                          meta_.strides,
                          dims));
  }
石晓伟 已提交
257
  meta_.dims = dims;
W
wanghuancoder 已提交
258 259
  meta_.strides = meta_.calc_strides(meta_.dims);

260 261
  if (holder_ != nullptr && place().GetType() != AllocationType::UNDEFINED) {
    mutable_data(place());
262
  }
石晓伟 已提交
263 264
}

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

267 268 269
#define DATA_MEMBER_FUNC_INSTANTIATION(dtype)      \
  template const dtype* DenseTensor::data() const; \
  template dtype* DenseTensor::data();
270 271 272 273 274 275 276 277 278 279

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);
280 281
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::bfloat16);
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::float16);
282 283
DATA_MEMBER_FUNC_INSTANTIATION(float);
DATA_MEMBER_FUNC_INSTANTIATION(double);
284 285
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::complex<float>);
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::complex<double>);
286 287 288

#undef DATA_MEMBER_FUNC_INSTANTIATION

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
template <typename DeviceT>
const DeviceT& DenseTensor::storage_properties() const {
  PADDLE_ENFORCE_NOT_NULL(
      storage_properties_,
      phi::errors::PreconditionNotMet(
          "The storage_properties of current DenseTensor is nullptr."));
  if (DeviceT::classof(storage_properties_.get())) {
    return static_cast<DeviceT&>(*storage_properties_);
  } else {
    PADDLE_THROW(phi::errors::InvalidArgument(
        "The actual type of storage_properties is inconsistent with the type "
        "of the template parameter passed in."));
  }
}

template const NPUStorageProperties& DenseTensor::storage_properties() const;
305
#ifdef PADDLE_WITH_DNNL
306 307 308
template const OneDNNStorageProperties& DenseTensor::storage_properties() const;
#endif

309 310 311 312
bool DenseTensor::storage_properties_initialized() const {
  return storage_properties_ != nullptr;
}

313 314 315 316 317
void DenseTensor::set_storage_properties(
    std::unique_ptr<StorageProperties>&& storage_properties) {
  storage_properties_ = std::move(storage_properties);
}

318
}  // namespace phi