24#ifndef TVM_RUNTIME_TENSOR_H_
25#define TVM_RUNTIME_TENSOR_H_
27#include <tvm/ffi/cast.h>
28#include <tvm/ffi/container/shape.h>
29#include <tvm/ffi/container/tensor.h>
30#include <tvm/ffi/dtype.h>
31#include <tvm/ffi/optional.h>
32#include <tvm/ffi/string.h>
43#include <unordered_map>
58 ffi::Optional<MemoryScope> mem_scope = std::nullopt);
72 ffi::Optional<MemoryScope> mem_scope = std::nullopt);
83 uint64_t relative_byte_offset = 0);
134 explicit TensorMemoryPool(
size_t page_size = 4096) : page_size_(page_size), used_memory_(0) {
135 TVM_FFI_CHECK_GT(page_size_, 0, ValueError) <<
"Pool page size must be positive";
136 TVM_FFI_CHECK_LE(page_size_,
static_cast<size_t>(std::numeric_limits<int64_t>::max()),
143 virtual ffi::Tensor
Empty(ffi::ShapeView shape, DLDataType dtype, DLDevice device,
144 ffi::Optional<MemoryScope> mem_scope = std::nullopt) {
145 std::lock_guard<std::recursive_mutex> lock(mu_);
149 size_t nbytes = ffi::GetDataSize(shape.Product(), dtype);
150 TVM_FFI_CHECK_LE(std::max<size_t>(nbytes, 1),
151 static_cast<size_t>(std::numeric_limits<int64_t>::max()) - (page_size_ - 1),
153 <<
"Rounded tensor allocation size overflows";
154 size_t size = ((std::max<size_t>(nbytes, 1) + page_size_ - 1) / page_size_) * page_size_;
156 size_t element_bytes = (
static_cast<size_t>(dtype.bits) * dtype.lanes + 7) / 8;
157 while (alignment < element_bytes) alignment *= 2;
160 auto it = memory_pool_.find(size);
161 if (it != memory_pool_.end()) {
162 auto& pool = it->second;
164 auto candidate = std::find_if(pool.begin(), pool.end(), [&](
const ffi::Tensor& tensor) {
165 return tensor.device().device_type == device.device_type &&
166 tensor.device().device_id == device.device_id &&
167 (!addressable || reinterpret_cast<uintptr_t>(tensor.data_ptr()) % alignment == 0);
169 if (candidate != pool.end()) {
170 backing = std::move(*candidate);
171 pool.erase(candidate);
174 if (!backing.defined()) {
178 used_memory_.fetch_add(size, std::memory_order_relaxed);
180 Lease lease{ffi::GetObjectPtr<TensorMemoryPool>(
this), std::move(backing)};
182 return ffi::Tensor::FromNDAlloc(lease, shape, dtype, device);
185 Recycle(std::move(lease.backing));
191 virtual ffi::Tensor
CreateView(ffi::Tensor backing, ffi::Shape shape, DLDataType dtype,
192 uint64_t byte_offset = 0,
193 ffi::Optional<MemoryScope> mem_scope = std::nullopt) {
195 if (view.device().device_type == kDLHexagon &&
198 auto* tensor =
const_cast<DLTensor*
>(view.GetDLTensorPtr());
199 if (tensor->byte_offset != 0) {
200 tensor->data =
static_cast<char*
>(tensor->data) + tensor->byte_offset;
202 tensor->byte_offset = 0;
209 std::lock_guard<std::recursive_mutex> lock(mu_);
210 for (
const auto& [size, pool] : memory_pool_) {
211 used_memory_.fetch_sub(size * pool.size(), std::memory_order_relaxed);
213 memory_pool_.clear();
217 size_t UsedMemory()
const {
return used_memory_.load(std::memory_order_relaxed); }
229 virtual ffi::Tensor
AllocBacking(
size_t nbytes,
size_t alignment, DLDevice device) {
230 auto allocate = [&]() {
232 DLDataType bytes{kDLUInt, 8, 1};
234 return api->Empty({
static_cast<int64_t
>(nbytes)}, bytes, device);
237 TVM_FFI_CHECK_LE(alignment, std::numeric_limits<uint16_t>::max(), ValueError);
238 auto owner = api->Empty({
static_cast<int64_t
>((nbytes + alignment - 1) / alignment)},
239 DLDataType{kDLUInt, 8,
static_cast<uint16_t
>(alignment)}, device);
244 }
catch (
const ffi::Error&) {
253 ffi::ObjectPtr<TensorMemoryPool> pool;
256 void AllocData(DLTensor* tensor) { tensor->data = backing.data_ptr(); }
257 void FreeData(DLTensor*) { pool->Recycle(std::move(backing)); }
260 void Recycle(ffi::Tensor backing) {
261 std::lock_guard<std::recursive_mutex> lock(mu_);
262 size_t size = ffi::GetDataSize(backing);
264 memory_pool_[size].push_back(std::move(backing));
265 }
catch (
const std::bad_alloc&) {
267 used_memory_.fetch_sub(size, std::memory_order_relaxed);
272 std::atomic<size_t> used_memory_;
273 std::unordered_map<size_t, std::vector<ffi::Tensor>> memory_pool_;
274 std::recursive_mutex mu_;
283 std::size_t operator()(
const tvm::Device& dev)
const {
284 return ((dev.device_id << 8) | dev.device_type);
291 return (lhs.device_type == rhs.device_type && lhs.device_id == rhs.device_id);
#define TVM_RUNTIME_DLL
Definition base.h:73
virtual bool SupportsDevicePtrArithmeticOnHost()
Whether pointer arithmetics on a device owned pointer may be performed on the host.
Definition device_api.h:246
static DeviceAPI * Get(Device dev, bool allow_missing=false)
Get device API based on device.
virtual ffi::Tensor Empty(ffi::ShapeView shape, DLDataType dtype, DLDevice device, ffi::Optional< MemoryScope > mem_scope=std::nullopt)=0
Create an owning, compact tensor with uninitialized contents.
static TVM_RUNTIME_DLL const MemoryScope & Global()
Return the canonical global singleton.
A cache of owning device tensors.
Definition tensor.h:132
virtual ffi::Tensor Empty(ffi::ShapeView shape, DLDataType dtype, DLDevice device, ffi::Optional< MemoryScope > mem_scope=std::nullopt)
Return an owning compact tensor in ordinary global memory.
Definition tensor.h:143
static constexpr bool _type_mutable
Definition tensor.h:219
void Clear()
Release cached backing; live tensors remain valid and may return later.
Definition tensor.h:208
TVM_FFI_DECLARE_OBJECT_INFO("runtime.TensorMemoryPool", TensorMemoryPool, ffi::Object)
virtual ffi::Tensor AllocBacking(size_t nbytes, size_t alignment, DLDevice device)
Allocate fresh owning uint8[nbytes] backing at the requested alignment.
Definition tensor.h:229
size_t UsedMemory() const
Bytes held by this pool, including checked-out backing.
Definition tensor.h:217
TensorMemoryPool(size_t page_size=4096)
Definition tensor.h:134
virtual ~TensorMemoryPool()
Definition tensor.h:140
virtual ffi::Tensor CreateView(ffi::Tensor backing, ffi::Shape shape, DLDataType dtype, uint64_t byte_offset=0, ffi::Optional< MemoryScope > mem_scope=std::nullopt)
Create a bounded owning view of a backing tensor.
Definition tensor.h:191
Abstract binary stream for serialization.
Definition io.h:57
Abstract device memory management API.
void * TVMStreamHandle
The stream that is specific to device can be NULL, which indicates the default one.
Definition device_api.h:41
Binary stream I/O interface.
TVM_RUNTIME_DLL ffi::ObjectPtr< TensorMemoryPool > CreateTensorMemoryPool(DLDevice device)
Create the default pool for a device.
TVM_RUNTIME_DLL void CopyFromTo(ffi::TensorView source, ffi::TensorView destination, TVMStreamHandle stream=nullptr)
Copy between existing tensors with exactly matching byte sizes.
TVM_RUNTIME_DLL ffi::Tensor CopyTo(ffi::TensorView source, Device dev, ffi::Optional< MemoryScope > mem_scope=std::nullopt)
Allocate a fresh tensor on dev, copy source, and synchronize the copy.
TVM_RUNTIME_DLL void SaveTensor(ffi::TensorView source, support::Stream *strm)
Save a tensor in the portable CPU tensor format.
TVM_RUNTIME_DLL ffi::Tensor Empty(ffi::Shape shape, DLDataType dtype, Device dev, ffi::Optional< MemoryScope > mem_scope=std::nullopt)
Allocate an uninitialized tensor through the runtime device allocator.
TVM_RUNTIME_DLL void CopyToBytes(ffi::TensorView source, void *destination_bytes, size_t nbytes, TVMStreamHandle stream=nullptr)
Copy a contiguous tensor into a byte buffer of exactly nbytes.
TVM_RUNTIME_DLL void CopyFromBytes(ffi::TensorView destination, const void *source_bytes, size_t nbytes, TVMStreamHandle stream=nullptr)
Copy exactly nbytes from a byte buffer into a contiguous tensor.
constexpr int kAllocAlignment
Number of bytes each allocation must align to.
Definition device_api.h:92
TVM_RUNTIME_DLL ffi::Tensor LoadTensor(support::Stream *strm)
Load a tensor from the portable format into CPU storage.
TVM_RUNTIME_DLL ffi::Tensor CreateView(ffi::Tensor source, ffi::Shape shape, DLDataType dtype, uint64_t relative_byte_offset=0)
Create a compact view retaining ownership of source.
constexpr uint64_t kTVMTensorMagic
Magic number for Tensor file.
Definition tensor.h:100
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41
DLDevice Device
Definition device_api.h:46
Serializer<T> specializations for tvm::support::Stream.