Skip to content

Commit 335c82b

Browse files
voidstackloopclaude
andcommitted
memory: allocator statistics (live/peak bytes, buffer counts) via tracked storage
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 5d35c41 commit 335c82b

3 files changed

Lines changed: 111 additions & 8 deletions

File tree

‎crates/oxideon-core/src/backend/mod.rs‎

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -131,27 +131,57 @@ pub enum StorageInner {
131131

132132
/// Shared, interior-mutable handle to device storage so views share the same allocation.
133133
#[derive(Clone, Debug)]
134-
pub struct Storage(Arc<RwLock<StorageInner>>);
134+
pub struct Storage(Arc<Tracked>);
135+
136+
/// The lock around a buffer plus the byte count it contributed to [`crate::memory`] (taken back when the last handle drops).
137+
#[derive(Debug)]
138+
pub struct Tracked {
139+
lock: RwLock<StorageInner>,
140+
bytes: usize,
141+
}
142+
143+
impl std::ops::Deref for Tracked {
144+
type Target = RwLock<StorageInner>;
145+
fn deref(&self) -> &Self::Target {
146+
&self.lock
147+
}
148+
}
149+
150+
impl Tracked {
151+
fn new(inner: StorageInner) -> Arc<Self> {
152+
let bytes = match &inner {
153+
StorageInner::Cpu(s) | StorageInner::Accelerator { storage: s, .. } => s.len() * s.dtype().size_in_bytes(),
154+
#[cfg(feature = "wgpu")]
155+
StorageInner::Wgpu(s) => s.len() * s.dtype().size_in_bytes(),
156+
StorageInner::Meta { .. } => 0,
157+
};
158+
crate::memory::on_alloc(bytes);
159+
Arc::new(Self { lock: RwLock::new(inner), bytes })
160+
}
161+
}
162+
163+
impl Drop for Tracked {
164+
fn drop(&mut self) {
165+
crate::memory::on_free(self.bytes);
166+
}
167+
}
135168

136169
impl Storage {
137170
pub fn new_cpu(s: CpuStorage) -> Self {
138-
Self(Arc::new(RwLock::new(StorageInner::Cpu(s))))
171+
Self(Tracked::new(StorageInner::Cpu(s)))
139172
}
140173

141174
#[cfg(feature = "wgpu")]
142175
pub fn new_wgpu(s: WgpuStorage) -> Self {
143-
Self(Arc::new(RwLock::new(StorageInner::Wgpu(s))))
176+
Self(Tracked::new(StorageInner::Wgpu(s)))
144177
}
145178

146179
pub fn new_accelerator(device: Device, storage: CpuStorage) -> Self {
147-
Self(Arc::new(RwLock::new(StorageInner::Accelerator {
148-
device,
149-
storage,
150-
})))
180+
Self(Tracked::new(StorageInner::Accelerator { device, storage }))
151181
}
152182

153183
pub fn new_meta(dtype: DType, len: usize) -> Self {
154-
Self(Arc::new(RwLock::new(StorageInner::Meta { dtype, len })))
184+
Self(Tracked::new(StorageInner::Meta { dtype, len }))
155185
}
156186

157187
pub fn read(&self) -> RwLockReadGuard<'_, StorageInner> {

‎crates/oxideon-core/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ pub mod structured;
114114
pub mod checkpoint;
115115
pub mod hub;
116116
pub mod loader;
117+
pub mod memory;
117118
pub mod train_loop;
118119
pub mod profiler;
119120
pub mod summary_writer;

‎crates/oxideon-core/src/memory.rs‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
//! Allocator statistics: bytes of tensor storage currently alive, the peak since the last reset, and allocation counts
2+
//! (the CPU analogue of `torch.cuda.memory_allocated` / `max_memory_allocated`). Views share their base storage, so only
3+
//! real buffers count; a buffer's bytes are returned when its last handle is dropped.
4+
5+
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
6+
7+
static LIVE: AtomicUsize = AtomicUsize::new(0);
8+
static PEAK: AtomicUsize = AtomicUsize::new(0);
9+
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
10+
static LIVE_BUFFERS: AtomicUsize = AtomicUsize::new(0);
11+
12+
pub(crate) fn on_alloc(bytes: usize) {
13+
let now = LIVE.fetch_add(bytes, Relaxed) + bytes;
14+
PEAK.fetch_max(now, Relaxed);
15+
ALLOCS.fetch_add(1, Relaxed);
16+
LIVE_BUFFERS.fetch_add(1, Relaxed);
17+
}
18+
19+
pub(crate) fn on_free(bytes: usize) {
20+
LIVE.fetch_sub(bytes, Relaxed);
21+
LIVE_BUFFERS.fetch_sub(1, Relaxed);
22+
}
23+
24+
/// A snapshot of the counters.
25+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26+
pub struct MemoryStats {
27+
pub allocated_bytes: usize,
28+
pub peak_bytes: usize,
29+
pub live_buffers: usize,
30+
pub total_allocations: usize,
31+
}
32+
33+
pub fn stats() -> MemoryStats {
34+
MemoryStats { allocated_bytes: LIVE.load(Relaxed), peak_bytes: PEAK.load(Relaxed), live_buffers: LIVE_BUFFERS.load(Relaxed), total_allocations: ALLOCS.load(Relaxed) }
35+
}
36+
37+
/// Bytes of tensor storage alive right now.
38+
pub fn allocated_bytes() -> usize {
39+
LIVE.load(Relaxed)
40+
}
41+
42+
/// Highest [`allocated_bytes`] since startup or the last [`reset_peak`].
43+
pub fn peak_bytes() -> usize {
44+
PEAK.load(Relaxed)
45+
}
46+
47+
/// Restarts peak tracking from the current usage.
48+
pub fn reset_peak() {
49+
PEAK.store(LIVE.load(Relaxed), Relaxed);
50+
}
51+
52+
#[cfg(test)]
53+
mod tests {
54+
use crate::tensor::Tensor;
55+
56+
// global counters: other tests allocate concurrently, so compare with inequalities on a large buffer
57+
#[test]
58+
fn a_large_tensor_raises_live_bytes_and_peak_and_releases_them_on_drop() {
59+
let big = 8 << 20; // 8 MiB of f32 = 2M elements
60+
let before = super::stats();
61+
let t = Tensor::zeros(&[big / 4], crate::dtype::DType::F32, &crate::device::Device::Cpu).unwrap();
62+
let view = t.reshape(&[2, big / 8]).unwrap(); // a view adds no buffer
63+
let during = super::stats();
64+
assert!(during.allocated_bytes >= before.allocated_bytes + big - (1 << 20) || during.peak_bytes >= big);
65+
assert!(during.peak_bytes >= big);
66+
drop(view);
67+
drop(t);
68+
std::thread::sleep(std::time::Duration::from_millis(1));
69+
assert!(super::allocated_bytes() < during.allocated_bytes || during.allocated_bytes < big);
70+
assert!(super::stats().total_allocations > before.total_allocations);
71+
}
72+
}

0 commit comments

Comments
 (0)