string_tensor.cc 6.6 KB
Newer Older
J
Jack Zhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2022 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/phi/core/string_tensor.h"
16

17 18
#include "glog/logging.h"

19
#include "paddle/phi/common/memory_utils.h"
20
#include "paddle/phi/common/pstring.h"
J
Jack Zhou 已提交
21 22 23

namespace phi {

24 25 26 27 28
template <>
const TypeInfo<phi::TensorBase>
    TypeInfoTraits<phi::TensorBase, StringTensor>::kType =
        RegisterStaticType<phi::TensorBase>(StringTensor::name());

J
Jack Zhou 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
StringTensor::StringTensor() { meta_.offset = 0; }

StringTensor::StringTensor(Allocator* a, const StringTensorMeta& meta)
    : meta_(meta), holder_(a->Allocate(SizeOf(dtype()) * numel())) {
  init_holder();
}

StringTensor::StringTensor(Allocator* a, StringTensorMeta&& meta)
    : meta_(std::move(meta)), holder_(a->Allocate(SizeOf(dtype()) * numel())) {
  init_holder();
}

StringTensor::StringTensor(const std::shared_ptr<phi::Allocation>& holder,
                           const StringTensorMeta& meta)
    : meta_(meta), holder_(holder) {}

StringTensor::StringTensor(const StringTensor& other) : meta_(other.meta()) {
  holder_ = other.holder_;
}

StringTensor& StringTensor::operator=(const StringTensor& other) {
  meta_ = other.meta();
  holder_ = other.holder_;
  return *this;
}

StringTensor& StringTensor::operator=(StringTensor&& other) {
  meta_ = std::move(other.meta_);
  std::swap(holder_, other.holder_);
  return *this;
}

int64_t StringTensor::numel() const {
  if (meta_.is_scalar) {
    return 1;
  }
  return product(meta_.dims);
}

bool StringTensor::IsSharedWith(const StringTensor& b) const {
  return holder_ && holder_ == b.holder_;
}

const Place& StringTensor::place() const {
  PADDLE_ENFORCE_NOT_NULL(
      holder_,
      phi::errors::PreconditionNotMet(
          "Tensor not initialized yet when DenseTensor::place() is called."));
  return holder_->place();
}

const dtype::pstring* StringTensor::data() const {
  PADDLE_ENFORCE_NOT_NULL(
      holder_,
      phi::errors::PreconditionNotMet(
          "The storage must be valid when call the mutable data function."));
  return reinterpret_cast<const dtype::pstring*>(
      reinterpret_cast<uintptr_t>(holder_->ptr()) + meta_.offset);
}

dtype::pstring* StringTensor::data() {
  PADDLE_ENFORCE_NOT_NULL(
      holder_,
      phi::errors::PreconditionNotMet(
          "The storage must be valid when call the mutable data function."));
  return reinterpret_cast<dtype::pstring*>(
      reinterpret_cast<uintptr_t>(holder_->ptr()) + meta_.offset);
}

void StringTensor::set_meta(const StringTensorMeta& meta) {
99
  PADDLE_ENFORCE_EQ(
J
Jack Zhou 已提交
100
      meta.valid(),
101
      true,
J
Jack Zhou 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
      phi::errors::InvalidArgument(
          "Input meta is invalid, please check the meta attribute."));
  meta_.dims = meta.dims;
  meta_.is_scalar = meta.is_scalar;
  meta_.offset = meta.offset;
}

StringTensor& StringTensor::Resize(const DDim& dims) {
  meta_.dims = dims;
  return *this;
}
// TODO(zhoushunjie): need to remove it for general space
void StringTensor::init_holder() {
  void* ptr = holder_->ptr();
  auto& place = holder_->place();
  auto bytes_size = holder_->size();
  VLOG(6) << "Init StringTensor data with bytes:" << bytes_size;
  if (place.GetType() == phi::AllocationType::CPU) {
    std::memset(ptr, 0, bytes_size);
  } else if (place.GetType() == phi::AllocationType::GPU) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
#ifdef PADDLE_WITH_HIP
    hipMemset(ptr, 0, bytes_size);
#else
    cudaMemset(ptr, 0, bytes_size);
#endif
#endif
  } else {
    // TODO(zhoushunjie): Need to support more places
    PADDLE_THROW(
        errors::Unimplemented("StringTensor can only be created in CPU or GPU "
                              "place. But now attemps to "
                              "create StringTensor on %s",
                              place.DebugString()));
  }
}

void* StringTensor::AllocateFrom(Allocator* allocator,
                                 DataType dtype,
141 142
                                 size_t requested_size,
                                 bool fake_alloc) {
J
Jack Zhou 已提交
143 144 145 146
  PADDLE_ENFORCE_NOT_NULL(
      allocator,
      errors::InvalidArgument(
          "Required allocator shall not be nullptr, but received nullptr."));
147

J
Jack Zhou 已提交
148
  size_t bytes = numel() * SizeOf(this->dtype());
149 150 151
  if (fake_alloc) {
    bytes = 0;
  } else {
152
    PADDLE_ENFORCE_EQ(
153
        valid(),
154
        true,
155 156 157 158 159 160 161 162 163 164 165 166 167
        errors::PreconditionNotMet("The meta data must be valid when call the "
                                   "mutable data function."));
    if (requested_size) {
      PADDLE_ENFORCE_GE(requested_size,
                        bytes,
                        errors::InvalidArgument(
                            "The reserved size %d should be enough to meet the "
                            "volume required by metadata %d.",
                            requested_size,
                            bytes));

      bytes = requested_size;
    }
J
Jack Zhou 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  }

  if (!holder_ || holder_->size() < bytes + meta_.offset) {
    meta_.offset = 0;
    VLOG(10) << "Allocate string data with bytes: " << bytes;
    holder_.reset();
    holder_ = allocator->Allocate(bytes);
    // Initialize the allocated bytes
    init_holder();
    meta_.offset = 0;
  }
  return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(holder_->ptr()) +
                                 meta_.offset);
}

J
Jack Zhou 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
dtype::pstring* StringTensor::mutable_data(const phi::Place& place,
                                           size_t requested_size) {
  PADDLE_ENFORCE_GE(
      numel(),
      0,
      phi::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;
  }

R
Ruibiao Chen 已提交
198
  /* some versions of paddle::variant don't have operator!= */
J
Jack Zhou 已提交
199 200 201
  if (holder_ == nullptr || !(holder_->place() == place) ||
      holder_->size() < size + meta_.offset) {
    holder_.reset();
202
    holder_ = memory_utils::AllocShared(place, size);
J
Jack Zhou 已提交
203 204 205 206 207 208 209 210
    // Initialize the allocated bytes
    init_holder();
    meta_.offset = 0;
  }
  return reinterpret_cast<dtype::pstring*>(
      reinterpret_cast<uintptr_t>(holder_->ptr()) + meta_.offset);
}

J
Jack Zhou 已提交
211
}  // namespace phi