dense_tensor.cc 7.4 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 19 20
#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"
21

22 23
// See Note [ Why still include the fluid headers? ]
#include "paddle/fluid/memory/malloc.h"
24

25
namespace phi {
26

27
DenseTensor::DenseTensor(Allocator* a, const DenseTensorMeta& meta)
28
    : meta_(meta), holder_(a->Allocate(SizeOf(dtype()) * numel())) {}
29

30
DenseTensor::DenseTensor(Allocator* a, DenseTensorMeta&& meta)
31
    : meta_(std::move(meta)), holder_(a->Allocate(SizeOf(dtype()) * numel())) {}
32

33
DenseTensor::DenseTensor(const std::shared_ptr<phi::Allocation>& holder,
34
                         const DenseTensorMeta& meta)
35
    : meta_(meta), holder_(holder) {}
36

37
DenseTensor::DenseTensor(const DenseTensor& other) : meta_(other.meta()) {
38
  holder_ = other.holder_;
39
  inplace_version_counter_ = other.inplace_version_counter_;
40 41 42 43 44

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

46 47
DenseTensor& DenseTensor::operator=(const DenseTensor& other) {
  meta_ = other.meta();
48
  holder_ = other.holder_;
49
  inplace_version_counter_ = other.inplace_version_counter_;
50 51 52
#ifdef PADDLE_WITH_MKLDNN
  format_ = other.format_;
#endif
53 54 55
  return *this;
}

56 57
DenseTensor& DenseTensor::operator=(DenseTensor&& other) {
  meta_ = std::move(other.meta_);
58
  std::swap(holder_, other.holder_);
59
  std::swap(inplace_version_counter_, other.inplace_version_counter_);
60 61 62
  return *this;
}

63 64 65 66 67 68 69 70
int64_t DenseTensor::numel() const {
  if (meta_.is_scalar) {
    return 1;
  }
  return product(meta_.dims);
}

bool DenseTensor::IsSharedWith(const DenseTensor& b) const {
71
  return holder_ && holder_ == b.Holder();
72 73
}

74 75 76 77 78
void* DenseTensor::AllocateFrom(Allocator* allocator,
                                DataType dtype,
                                size_t requested_size) {
  PADDLE_ENFORCE_NOT_NULL(
      allocator,
79
      phi::errors::InvalidArgument(
80 81 82 83 84 85 86
          "Required allocator shall not be nullptr, but received nullptr."));
  if (this->dtype() != dtype) {
    VLOG(10) << "change data type in mutbale_data, target dtype - " << dtype;
    meta_.dtype = dtype;
  }
  PADDLE_ENFORCE(
      valid(),
87
      phi::errors::PreconditionNotMet(
88 89 90 91 92
          "The meta data must be valid when call the mutable data function."));
  size_t bytes = numel() * SizeOf(this->dtype());
  if (requested_size) {
    PADDLE_ENFORCE_GE(requested_size,
                      bytes,
93
                      phi::errors::InvalidArgument(
94 95 96 97 98 99
                          "The reserved size %d should be enough to meet the "
                          "volume required by metadata %d.",
                          requested_size,
                          bytes));
    bytes = requested_size;
  }
100 101 102
  // 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.
103 104 105 106 107 108 109 110 111 112
  if (!holder_ || holder_->size() < bytes + meta_.offset) {
    meta_.offset = 0;
    VLOG(10) << "Allocate data with bytes: " << bytes;
    ResetHolder(allocator->Allocate(bytes));
  }

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

113 114
template <typename T>
const T* DenseTensor::data() const {
115
  check_memory_size();
H
hong 已提交
116 117 118
  PADDLE_ENFORCE_EQ(
      dtype(),
      paddle::experimental::CppTypeToDataType<T>::Type(),
119
      phi::errors::InvalidArgument(
120 121 122 123 124
          "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());
}

125 126 127 128 129
template <typename T>
T* DenseTensor::data() {
  check_memory_size();
  PADDLE_ENFORCE(
      (dtype() == paddle::experimental::CppTypeToDataType<T>::Type()),
130
      phi::errors::InvalidArgument(
131 132
          "The type of data we are trying to retrieve does not match the "
          "type of data currently contained in the container."));
133
  return static_cast<T*>(data());
134 135
}

136
void* DenseTensor::data() {
137
  check_memory_size();
138
  PADDLE_ENFORCE_NOT_NULL(
139
      holder_,
140
      phi::errors::PreconditionNotMet(
141 142
          "The storage must be valid when call the data function."));
  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(holder_->ptr()) +
143
                                 meta_.offset);
144 145
}

146
const void* DenseTensor::data() const {
147
  check_memory_size();
148
  PADDLE_ENFORCE_NOT_NULL(
149
      holder_,
150
      phi::errors::PreconditionNotMet(
151
          "The storage must be valid when call the data function."));
152
  return reinterpret_cast<const void*>(
153
      reinterpret_cast<uintptr_t>(holder_->ptr()) + meta_.offset);
154 155
}

156 157
void DenseTensor::set_meta(DenseTensorMeta&& meta) {
  PADDLE_ENFORCE(!meta_.valid(),
158
                 phi::errors::InvalidArgument(
159 160 161
                     "Only when the original attribute of Tensor is "
                     "incomplete, can it be reset."));
  meta_ = std::move(meta);
石晓伟 已提交
162 163
}

164 165 166
void DenseTensor::set_meta(const DenseTensorMeta& meta) {
  PADDLE_ENFORCE(
      meta.valid(),
167
      phi::errors::InvalidArgument(
168 169 170 171 172 173 174 175 176
          "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;
}

177 178 179 180 181 182 183 184 185 186
/* @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)
   */
187
void DenseTensor::ResizeAndAllocate(const DDim& dims) {
石晓伟 已提交
188
  meta_.dims = dims;
189 190
  if (holder_ != nullptr && place().GetType() != AllocationType::UNDEFINED) {
    mutable_data(place());
191
  }
石晓伟 已提交
192 193
}

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

196 197 198
#define DATA_MEMBER_FUNC_INSTANTIATION(dtype)      \
  template const dtype* DenseTensor::data() const; \
  template dtype* DenseTensor::data();
199 200 201 202 203 204 205 206 207 208

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);
209 210
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::bfloat16);
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::float16);
211 212
DATA_MEMBER_FUNC_INSTANTIATION(float);
DATA_MEMBER_FUNC_INSTANTIATION(double);
213 214
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::complex<float>);
DATA_MEMBER_FUNC_INSTANTIATION(::phi::dtype::complex<double>);
215 216 217

#undef DATA_MEMBER_FUNC_INSTANTIATION

218
}  // namespace phi