Deepity
Ultra-fast, SIMD-accelerated Predictive Coding
Loading...
Searching...
No Matches
DeviceMemoryArena.h
Go to the documentation of this file.
1#pragma once
2#if defined(DEEPITY_USE_CUDA)
4#include <new>
5#include <stdexcept>
6#include <iostream>
7
34
35namespace Deep
36{
42 {
43 private:
46 IComputeBackend *backend;
48 float *base_ptr;
51 size_t capacity_bytes;
55 size_t offset_bytes;
56
57 public:
70 DeviceMemoryArena(IComputeBackend *backend, size_t total_floats)
71 : backend(backend)
72 {
73 capacity_bytes = (total_floats * sizeof(float) + 63) & ~(size_t)63;
74
75 base_ptr = backend->Allocate(capacity_bytes / sizeof(float));
76 if (!base_ptr)
77 {
78 throw std::bad_alloc();
79 }
80 offset_bytes = 0;
81 }
82
86 {
87 if (base_ptr)
88 {
89 backend->Free(base_ptr);
90 }
91 }
92
93 // Delete copy/move constructors to prevent double-free corruption
94 // -- the original version of this class had no such guard, a real
95 // gap relative to MemoryArena's own established protection.
96
103
117 float *AllocateFloats(size_t num_floats)
118 {
119 size_t allocation_size = (num_floats * sizeof(float) + 63) & ~(size_t)63;
120
121 if (offset_bytes + allocation_size > capacity_bytes)
122 {
123 throw std::runtime_error("Fatal: DeviceMemoryArena capacity exceeded during allocation.");
124 }
125
126 float *chunk = reinterpret_cast<float *>(
127 reinterpret_cast<char *>(base_ptr) + offset_bytes);
128
129 offset_bytes += allocation_size;
130 return chunk;
131 }
132
135 size_t GetUsedBytes() const { return offset_bytes; }
137 size_t GetCapacityBytes() const { return capacity_bytes; }
138 };
139}
140#endif
size_t GetUsedBytes() const
Returns how many bytes have been allocated from the arena so far.
Definition DeviceMemoryArena.h:135
DeviceMemoryArena(IComputeBackend *backend, size_t total_floats)
Allocates a single 64-byte-aligned device buffer large enough to hold total_floats floats,...
Definition DeviceMemoryArena.h:70
~DeviceMemoryArena()
Frees the underlying device buffer via the same backend it was allocated from.
Definition DeviceMemoryArena.h:85
float * AllocateFloats(size_t num_floats)
Allocates a 64-byte aligned chunk of floats from the arena.
Definition DeviceMemoryArena.h:117
DeviceMemoryArena & operator=(const DeviceMemoryArena &)=delete
Deleted: DeviceMemoryArena owns a single device allocation, so copy-assignment would risk a double-fr...
size_t GetCapacityBytes() const
Returns the arena's total capacity.
Definition DeviceMemoryArena.h:137
DeviceMemoryArena(const DeviceMemoryArena &)=delete
Deleted: DeviceMemoryArena owns a single device allocation, so copying would risk a double-free.
Device-agnostic compute backend interface: every numerical primitive a layer/network needs,...
Definition IComputeBackend.h:14
This file exists to provide both Tensor.h and IComputeBackend.h with device types without introducing...
Definition Backend.cpp:10