tvm
Loading...
Searching...
No Matches
tensor.h
Go to the documentation of this file.
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
24#ifndef TVM_RUNTIME_TENSOR_H_
25#define TVM_RUNTIME_TENSOR_H_
26
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>
33#include <tvm/runtime/base.h>
35#include <tvm/support/io.h>
37
38#include <algorithm>
39#include <atomic>
40#include <functional>
41#include <limits>
42#include <mutex>
43#include <unordered_map>
44#include <utility>
45#include <vector>
46
47namespace tvm {
48namespace runtime {
49
57TVM_RUNTIME_DLL ffi::Tensor Empty(ffi::Shape shape, DLDataType dtype, Device dev,
58 ffi::Optional<MemoryScope> mem_scope = std::nullopt);
59
64TVM_RUNTIME_DLL void CopyFromTo(ffi::TensorView source, ffi::TensorView destination,
65 TVMStreamHandle stream = nullptr);
66
71TVM_RUNTIME_DLL ffi::Tensor CopyTo(ffi::TensorView source, Device dev,
72 ffi::Optional<MemoryScope> mem_scope = std::nullopt);
73
82TVM_RUNTIME_DLL ffi::Tensor CreateView(ffi::Tensor source, ffi::Shape shape, DLDataType dtype,
83 uint64_t relative_byte_offset = 0);
84
89TVM_RUNTIME_DLL void CopyFromBytes(ffi::TensorView destination, const void* source_bytes,
90 size_t nbytes, TVMStreamHandle stream = nullptr);
91
96TVM_RUNTIME_DLL void CopyToBytes(ffi::TensorView source, void* destination_bytes, size_t nbytes,
97 TVMStreamHandle stream = nullptr);
98
100constexpr uint64_t kTVMTensorMagic = 0xDD5E40F096B4A13F;
101
107TVM_RUNTIME_DLL void SaveTensor(ffi::TensorView source, support::Stream* strm);
108
115
116class TensorMemoryPool;
117
119TVM_RUNTIME_DLL ffi::ObjectPtr<TensorMemoryPool> CreateTensorMemoryPool(DLDevice device);
120
132class TensorMemoryPool : public ffi::Object {
133 public:
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()),
137 ValueError);
138 }
139
140 virtual ~TensorMemoryPool() { Clear(); }
141
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_);
146 if (mem_scope.has_value() && *mem_scope != MemoryScope::Global()) {
147 return DeviceAPI::Get(device)->Empty(shape, dtype, device, mem_scope);
148 }
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),
152 ValueError)
153 << "Rounded tensor allocation size overflows";
154 size_t size = ((std::max<size_t>(nbytes, 1) + page_size_ - 1) / page_size_) * page_size_;
155 size_t alignment = kAllocAlignment;
156 size_t element_bytes = (static_cast<size_t>(dtype.bits) * dtype.lanes + 7) / 8;
157 while (alignment < element_bytes) alignment *= 2;
158
159 ffi::Tensor backing;
160 auto it = memory_pool_.find(size);
161 if (it != memory_pool_.end()) {
162 auto& pool = it->second;
163 bool addressable = DeviceAPI::Get(device)->SupportsDevicePtrArithmeticOnHost();
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);
168 });
169 if (candidate != pool.end()) {
170 backing = std::move(*candidate);
171 pool.erase(candidate);
172 }
173 }
174 if (!backing.defined()) {
175 // Collective backends cannot retry by unilaterally releasing cached buffers.
176 // Any allocation-pressure retry belongs to the non-collective adapter.
177 backing = AllocBacking(size, alignment, device);
178 used_memory_.fetch_add(size, std::memory_order_relaxed);
179 }
180 Lease lease{ffi::GetObjectPtr<TensorMemoryPool>(this), std::move(backing)};
181 try {
182 return ffi::Tensor::FromNDAlloc(lease, shape, dtype, device);
183 } catch (...) {
184 // Tensor metadata allocation may fail before the owning tensor exists.
185 Recycle(std::move(lease.backing));
186 throw;
187 }
188 }
189
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) {
194 auto view = runtime::CreateView(std::move(backing), std::move(shape), dtype, byte_offset);
195 if (view.device().device_type == kDLHexagon &&
196 (!mem_scope.has_value() || *mem_scope == MemoryScope::Global())) {
197 // Hexagon kernels receive the adjusted pointer rather than a byte offset.
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;
201 }
202 tensor->byte_offset = 0;
203 }
204 return view;
205 }
206
208 void Clear() {
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);
212 }
213 memory_pool_.clear();
214 }
215
217 size_t UsedMemory() const { return used_memory_.load(std::memory_order_relaxed); }
218
219 static constexpr bool _type_mutable = true;
220 TVM_FFI_DECLARE_OBJECT_INFO("runtime.TensorMemoryPool", TensorMemoryPool, ffi::Object);
221
222 protected:
229 virtual ffi::Tensor AllocBacking(size_t nbytes, size_t alignment, DLDevice device) {
230 auto allocate = [&]() {
231 auto* api = DeviceAPI::Get(device);
232 DLDataType bytes{kDLUInt, 8, 1};
233 if (alignment <= kAllocAlignment) {
234 return api->Empty({static_cast<int64_t>(nbytes)}, bytes, device);
235 }
236 // Preserve the backend's dtype alignment contract for wide vector elements.
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);
240 return runtime::CreateView(std::move(owner), {static_cast<int64_t>(nbytes)}, bytes);
241 };
242 try {
243 return allocate();
244 } catch (const ffi::Error&) {
245 // This default allocator is non-collective; release cached memory and retry.
246 Clear();
247 return allocate();
248 }
249 }
250
251 private:
252 struct Lease {
253 ffi::ObjectPtr<TensorMemoryPool> pool;
254 ffi::Tensor backing;
255
256 void AllocData(DLTensor* tensor) { tensor->data = backing.data_ptr(); }
257 void FreeData(DLTensor*) { pool->Recycle(std::move(backing)); }
258 };
259
260 void Recycle(ffi::Tensor backing) {
261 std::lock_guard<std::recursive_mutex> lock(mu_);
262 size_t size = ffi::GetDataSize(backing);
263 try {
264 memory_pool_[size].push_back(std::move(backing));
265 } catch (const std::bad_alloc&) {
266 // A cache insertion failure must not escape tensor destruction.
267 used_memory_.fetch_sub(size, std::memory_order_relaxed);
268 }
269 }
270
271 size_t page_size_;
272 std::atomic<size_t> used_memory_;
273 std::unordered_map<size_t, std::vector<ffi::Tensor>> memory_pool_;
274 std::recursive_mutex mu_;
275};
276
277} // namespace runtime
278} // namespace tvm
279
280namespace std {
281template <>
282struct hash<tvm::Device> {
283 std::size_t operator()(const tvm::Device& dev) const {
284 return ((dev.device_id << 8) | dev.device_type);
285 }
286};
287
288template <>
289struct equal_to<tvm::Device> {
290 bool operator()(const tvm::Device& lhs, const tvm::Device& rhs) const {
291 return (lhs.device_type == rhs.device_type && lhs.device_id == rhs.device_id);
292 }
293};
294} // namespace std
295
296#endif // TVM_RUNTIME_TENSOR_H_
#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.