tenflowers-core 0.1.1

Core tensor operations and execution engine for TenfloweRS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
99
100
101
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/// GPU Memory Metrics Exposure
///
/// This module provides public APIs for monitoring and reporting GPU memory usage,
/// allocation patterns, and pool statistics. It complements the existing internal
/// diagnostics with user-facing APIs for production monitoring.

#[cfg(feature = "gpu")]
use crate::memory::{DiagnosticMemoryPool, MemoryPool, MemoryPoolStats};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// GPU memory usage snapshot
#[derive(Debug, Clone)]
pub struct GpuMemorySnapshot {
    /// Total bytes allocated across all pools
    pub total_allocated: usize,
    /// Total bytes in use (not free)
    pub total_used: usize,
    /// Number of active allocations
    pub allocation_count: usize,
    /// Peak memory usage recorded
    pub peak_usage: usize,
    /// Number of allocation failures
    pub allocation_failures: usize,
    /// Average allocation size
    pub avg_allocation_size: usize,
    /// Fragmentation ratio (0.0 = no fragmentation, 1.0 = high fragmentation)
    pub fragmentation_ratio: f32,
}

impl Default for GpuMemorySnapshot {
    fn default() -> Self {
        Self {
            total_allocated: 0,
            total_used: 0,
            allocation_count: 0,
            peak_usage: 0,
            allocation_failures: 0,
            avg_allocation_size: 0,
            fragmentation_ratio: 0.0,
        }
    }
}

/// GPU memory metrics collector
#[derive(Debug)]
pub struct GpuMemoryMetrics {
    total_allocations: AtomicU64,
    total_deallocations: AtomicU64,
    peak_memory: AtomicU64,
    current_memory: AtomicU64,
    allocation_failures: AtomicU64,
}

impl Default for GpuMemoryMetrics {
    fn default() -> Self {
        Self::new()
    }
}

impl GpuMemoryMetrics {
    /// Create a new metrics collector
    pub fn new() -> Self {
        Self {
            total_allocations: AtomicU64::new(0),
            total_deallocations: AtomicU64::new(0),
            peak_memory: AtomicU64::new(0),
            current_memory: AtomicU64::new(0),
            allocation_failures: AtomicU64::new(0),
        }
    }

    /// Record an allocation
    pub fn record_allocation(&self, size: usize) {
        self.total_allocations.fetch_add(1, Ordering::Relaxed);
        let current = self
            .current_memory
            .fetch_add(size as u64, Ordering::Relaxed)
            + size as u64;

        // Update peak if necessary
        let mut peak = self.peak_memory.load(Ordering::Relaxed);
        while current > peak {
            match self.peak_memory.compare_exchange_weak(
                peak,
                current,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => break,
                Err(x) => peak = x,
            }
        }
    }

    /// Record a deallocation
    pub fn record_deallocation(&self, size: usize) {
        self.total_deallocations.fetch_add(1, Ordering::Relaxed);
        self.current_memory
            .fetch_sub(size as u64, Ordering::Relaxed);
    }

    /// Record an allocation failure
    pub fn record_failure(&self) {
        self.allocation_failures.fetch_add(1, Ordering::Relaxed);
    }

    /// Get current memory usage snapshot
    pub fn snapshot(&self) -> GpuMemorySnapshot {
        let total_allocs = self.total_allocations.load(Ordering::Relaxed);
        let total_deallocs = self.total_deallocations.load(Ordering::Relaxed);
        let current_memory = self.current_memory.load(Ordering::Relaxed) as usize;
        let peak_memory = self.peak_memory.load(Ordering::Relaxed) as usize;
        let allocation_count = (total_allocs.saturating_sub(total_deallocs)) as usize;

        let avg_allocation_size = current_memory.checked_div(allocation_count).unwrap_or(0);

        // Simple fragmentation estimate based on allocation count vs memory usage
        let fragmentation_ratio = if current_memory > 0 && allocation_count > 0 {
            let ideal_allocations = (current_memory / 1024).max(1); // Assume 1KB ideal size
            (allocation_count as f32 / ideal_allocations as f32).min(1.0)
        } else {
            0.0
        };

        GpuMemorySnapshot {
            total_allocated: current_memory,
            total_used: current_memory,
            allocation_count,
            peak_usage: peak_memory,
            allocation_failures: self.allocation_failures.load(Ordering::Relaxed) as usize,
            avg_allocation_size,
            fragmentation_ratio,
        }
    }

    /// Reset all metrics (useful for testing/benchmarking)
    pub fn reset(&self) {
        self.total_allocations.store(0, Ordering::Relaxed);
        self.total_deallocations.store(0, Ordering::Relaxed);
        self.peak_memory.store(0, Ordering::Relaxed);
        self.current_memory.store(0, Ordering::Relaxed);
        self.allocation_failures.store(0, Ordering::Relaxed);
    }

    /// Get total number of allocations
    pub fn total_allocations(&self) -> u64 {
        self.total_allocations.load(Ordering::Relaxed)
    }

    /// Get total number of deallocations
    pub fn total_deallocations(&self) -> u64 {
        self.total_deallocations.load(Ordering::Relaxed)
    }

    /// Get current memory usage in bytes
    pub fn current_usage(&self) -> usize {
        self.current_memory.load(Ordering::Relaxed) as usize
    }

    /// Get peak memory usage in bytes
    pub fn peak_usage(&self) -> usize {
        self.peak_memory.load(Ordering::Relaxed) as usize
    }

    /// Get number of allocation failures
    pub fn allocation_failures(&self) -> usize {
        self.allocation_failures.load(Ordering::Relaxed) as usize
    }
}

/// Global GPU memory metrics instance
lazy_static::lazy_static! {
    pub static ref GPU_MEMORY_METRICS: Arc<GpuMemoryMetrics> = Arc::new(GpuMemoryMetrics::new());
}

/// Get current GPU memory usage
pub fn get_gpu_memory_usage() -> usize {
    GPU_MEMORY_METRICS.current_usage()
}

/// Get peak GPU memory usage
pub fn get_gpu_peak_memory() -> usize {
    GPU_MEMORY_METRICS.peak_usage()
}

/// Get GPU memory snapshot
pub fn get_gpu_memory_snapshot() -> GpuMemorySnapshot {
    GPU_MEMORY_METRICS.snapshot()
}

/// Reset GPU memory metrics (for testing/benchmarking)
pub fn reset_gpu_memory_metrics() {
    GPU_MEMORY_METRICS.reset();
}

/// GPU memory statistics report
#[derive(Debug, Clone)]
pub struct GpuMemoryReport {
    /// Current snapshot
    pub snapshot: GpuMemorySnapshot,
    /// Memory utilization percentage (0-100)
    pub utilization: f32,
    /// Allocation efficiency (deallocations / allocations)
    pub efficiency: f32,
    /// Recommendations for optimization
    pub recommendations: Vec<String>,
}

/// Generate a comprehensive GPU memory report
pub fn generate_memory_report() -> GpuMemoryReport {
    let snapshot = get_gpu_memory_snapshot();

    let total_ops =
        GPU_MEMORY_METRICS.total_allocations() + GPU_MEMORY_METRICS.total_deallocations();
    let efficiency = if total_ops > 0 {
        (GPU_MEMORY_METRICS.total_deallocations() as f32
            / GPU_MEMORY_METRICS.total_allocations() as f32)
            * 100.0
    } else {
        100.0
    };

    // Calculate utilization based on peak vs current
    let utilization = if snapshot.peak_usage > 0 {
        (snapshot.total_used as f32 / snapshot.peak_usage as f32) * 100.0
    } else {
        0.0
    };

    let mut recommendations = Vec::new();

    // Add recommendations based on metrics
    if snapshot.allocation_failures > 0 {
        recommendations.push(format!(
            "High allocation failure rate detected ({} failures). Consider increasing memory pool size.",
            snapshot.allocation_failures
        ));
    }

    if snapshot.fragmentation_ratio > 0.5 {
        recommendations.push(format!(
            "High memory fragmentation detected ({:.1}%). Consider enabling memory compaction.",
            snapshot.fragmentation_ratio * 100.0
        ));
    }

    if snapshot.allocation_count > 10000 {
        recommendations.push(format!(
            "Large number of active allocations ({}) detected. Consider batch processing to reduce overhead.",
            snapshot.allocation_count
        ));
    }

    if snapshot.avg_allocation_size < 1024 {
        recommendations.push(format!(
            "Small average allocation size ({} bytes). Consider allocation coalescing.",
            snapshot.avg_allocation_size
        ));
    }

    if efficiency < 80.0 {
        recommendations.push(format!(
            "Memory efficiency is low ({:.1}%). Check for memory leaks.",
            efficiency
        ));
    }

    GpuMemoryReport {
        snapshot,
        utilization,
        efficiency,
        recommendations,
    }
}

/// Print GPU memory report to stdout
pub fn print_memory_report() {
    let report = generate_memory_report();

    println!("\n=== GPU Memory Report ===");
    println!(
        "Total Allocated: {} bytes ({:.2} MB)",
        report.snapshot.total_allocated,
        report.snapshot.total_allocated as f32 / 1024.0 / 1024.0
    );
    println!(
        "Peak Usage: {} bytes ({:.2} MB)",
        report.snapshot.peak_usage,
        report.snapshot.peak_usage as f32 / 1024.0 / 1024.0
    );
    println!("Active Allocations: {}", report.snapshot.allocation_count);
    println!(
        "Average Allocation Size: {} bytes",
        report.snapshot.avg_allocation_size
    );
    println!(
        "Fragmentation: {:.1}%",
        report.snapshot.fragmentation_ratio * 100.0
    );
    println!("Utilization: {:.1}%", report.utilization);
    println!("Efficiency: {:.1}%", report.efficiency);

    if !report.recommendations.is_empty() {
        println!("\nRecommendations:");
        for (i, rec) in report.recommendations.iter().enumerate() {
            println!("  {}. {}", i + 1, rec);
        }
    }

    println!("========================\n");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_metrics_creation() {
        let metrics = GpuMemoryMetrics::new();
        assert_eq!(metrics.current_usage(), 0);
        assert_eq!(metrics.peak_usage(), 0);
        assert_eq!(metrics.total_allocations(), 0);
    }

    #[test]
    fn test_allocation_tracking() {
        let metrics = GpuMemoryMetrics::new();

        metrics.record_allocation(1024);
        assert_eq!(metrics.current_usage(), 1024);
        assert_eq!(metrics.peak_usage(), 1024);
        assert_eq!(metrics.total_allocations(), 1);

        metrics.record_allocation(2048);
        assert_eq!(metrics.current_usage(), 3072);
        assert_eq!(metrics.peak_usage(), 3072);
        assert_eq!(metrics.total_allocations(), 2);
    }

    #[test]
    fn test_deallocation_tracking() {
        let metrics = GpuMemoryMetrics::new();

        metrics.record_allocation(2048);
        metrics.record_deallocation(1024);

        assert_eq!(metrics.current_usage(), 1024);
        assert_eq!(metrics.peak_usage(), 2048);
        assert_eq!(metrics.total_deallocations(), 1);
    }

    #[test]
    fn test_snapshot() {
        let metrics = GpuMemoryMetrics::new();

        metrics.record_allocation(1024);
        metrics.record_allocation(2048);
        metrics.record_deallocation(512);

        let snapshot = metrics.snapshot();

        assert_eq!(snapshot.total_allocated, 2560); // 1024 + 2048 - 512
        assert_eq!(snapshot.allocation_count, 1); // 2 - 1
        assert_eq!(snapshot.peak_usage, 3072); // Peak before dealloc
    }

    #[test]
    fn test_failure_tracking() {
        let metrics = GpuMemoryMetrics::new();

        metrics.record_failure();
        metrics.record_failure();

        assert_eq!(metrics.allocation_failures(), 2);
    }

    #[test]
    fn test_reset() {
        let metrics = GpuMemoryMetrics::new();

        metrics.record_allocation(1024);
        metrics.record_failure();

        metrics.reset();

        assert_eq!(metrics.current_usage(), 0);
        assert_eq!(metrics.peak_usage(), 0);
        assert_eq!(metrics.total_allocations(), 0);
        assert_eq!(metrics.allocation_failures(), 0);
    }

    #[test]
    fn test_report_generation() {
        reset_gpu_memory_metrics();

        GPU_MEMORY_METRICS.record_allocation(1024);
        GPU_MEMORY_METRICS.record_allocation(2048);

        let report = generate_memory_report();

        assert!(report.snapshot.total_allocated > 0);
        assert!(report.utilization >= 0.0);
        assert!(report.efficiency >= 0.0);
    }
}