trustformers_models/memory_profiling/
profiler.rs1use anyhow::{Context, Result};
7use std::collections::{HashMap, VecDeque};
8use std::sync::{
9 atomic::{AtomicBool, AtomicU64, Ordering},
10 Arc, Mutex,
11};
12use std::time::{Duration, Instant};
13use uuid::Uuid;
14
15use super::analytics::*;
16use super::types::*;
17
18pub struct MemoryProfiler {
20 config: ProfilerConfig,
21 metrics_history: Arc<Mutex<VecDeque<MemoryMetrics>>>,
22 allocations: Arc<Mutex<HashMap<Uuid, AllocationInfo>>>,
23 alerts: Arc<Mutex<Vec<MemoryAlert>>>,
24 patterns: Arc<Mutex<Vec<MemoryPattern>>>,
25 is_monitoring: Arc<AtomicBool>,
26 start_time: Option<Instant>,
27 cached_recommendations: AlertRecommendations,
29 adaptive_thresholds: Arc<Mutex<AdaptiveThresholds>>,
31 leak_detection: Arc<Mutex<LeakDetectionHeuristics>>,
32 memory_predictor: Arc<Mutex<MemoryPredictor>>,
33 monitoring_overhead_us: Arc<AtomicU64>,
35 total_collections: Arc<AtomicU64>,
36 allocated_objects: Arc<AtomicU64>,
38 deallocated_objects: Arc<AtomicU64>,
39}
40
41impl MemoryProfiler {
42 pub fn new(config: ProfilerConfig) -> Result<Self> {
44 std::fs::create_dir_all(&config.output_dir).context("Failed to create output directory")?;
46
47 Ok(Self {
48 config,
49 metrics_history: Arc::new(Mutex::new(VecDeque::new())),
50 allocations: Arc::new(Mutex::new(HashMap::new())),
51 alerts: Arc::new(Mutex::new(Vec::new())),
52 patterns: Arc::new(Mutex::new(Vec::new())),
53 is_monitoring: Arc::new(AtomicBool::new(false)),
54 start_time: None,
55 cached_recommendations: AlertRecommendations::new(),
56 adaptive_thresholds: Arc::new(Mutex::new(AdaptiveThresholds::default())),
57 leak_detection: Arc::new(Mutex::new(LeakDetectionHeuristics::default())),
58 memory_predictor: Arc::new(Mutex::new(MemoryPredictor::default())),
59 monitoring_overhead_us: Arc::new(AtomicU64::new(0)),
60 total_collections: Arc::new(AtomicU64::new(0)),
61 allocated_objects: Arc::new(AtomicU64::new(0)),
62 deallocated_objects: Arc::new(AtomicU64::new(0)),
63 })
64 }
65
66 pub async fn start_monitoring(&mut self) -> Result<()> {
68 if self
70 .is_monitoring
71 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
72 .is_err()
73 {
74 return Ok(());
75 }
76
77 self.start_time = Some(Instant::now());
78
79 let metrics_history = self.metrics_history.clone();
80 let allocations = self.allocations.clone();
81 let allocated_objects = self.allocated_objects.clone();
82 let deallocated_objects = self.deallocated_objects.clone();
83 let alerts = self.alerts.clone();
84 let patterns = self.patterns.clone();
85 let config = self.config.clone();
86 let is_monitoring = self.is_monitoring.clone();
87 let cached_recommendations = self.cached_recommendations.clone();
88 let adaptive_thresholds = self.adaptive_thresholds.clone();
89 let leak_detection = self.leak_detection.clone();
90 let memory_predictor = self.memory_predictor.clone();
91 let monitoring_overhead_us = self.monitoring_overhead_us.clone();
92 let total_collections = self.total_collections.clone();
93
94 tokio::spawn(async move {
96 let mut interval =
97 tokio::time::interval(Duration::from_millis(config.collection_interval_ms));
98 let mut previous_metrics: Option<MemoryMetrics> = None;
99
100 while is_monitoring.load(Ordering::Relaxed) {
101 interval.tick().await;
102
103 let monitoring_start = Instant::now();
105 total_collections.fetch_add(1, Ordering::Relaxed);
106
107 let tracked = Self::snapshot_allocation_stats(
109 &allocations,
110 &allocated_objects,
111 &deallocated_objects,
112 );
113 let current_metrics = match Self::collect_memory_metrics(tracked).await {
114 Ok(metrics) => metrics,
115 Err(e) => {
116 tracing::warn!("Failed to collect memory metrics: {}", e);
117 continue;
118 },
119 };
120
121 let growth_rate = if let Some(ref prev) = previous_metrics {
123 let time_diff = current_metrics
124 .timestamp
125 .duration_since(prev.timestamp)
126 .unwrap_or_default()
127 .as_secs_f64();
128
129 if time_diff > 0.0 {
130 (current_metrics.total_memory_mb - prev.total_memory_mb) / time_diff
131 } else {
132 0.0
133 }
134 } else {
135 0.0
136 };
137
138 let mut final_metrics = current_metrics;
139 final_metrics.memory_growth_rate_mb_per_sec = growth_rate;
140
141 {
143 let mut history = match metrics_history.lock() {
144 Ok(guard) => guard,
145 Err(_) => continue, };
147 history.push_back(final_metrics.clone());
148
149 while history.len() > config.max_data_points {
151 history.pop_front();
152 }
153 }
154
155 Self::update_adaptive_thresholds(&final_metrics, &adaptive_thresholds).await;
157
158 if config.enable_leak_detection {
160 Self::detect_memory_leaks(
161 &final_metrics,
162 &previous_metrics,
163 &leak_detection,
164 &alerts,
165 &cached_recommendations,
166 )
167 .await;
168 }
169
170 Self::update_memory_prediction(&final_metrics, &memory_predictor, &metrics_history)
172 .await;
173
174 Self::analyze_for_alerts_adaptive(
176 &final_metrics,
177 &previous_metrics,
178 &alerts,
179 &config,
180 &cached_recommendations,
181 &adaptive_thresholds,
182 )
183 .await;
184
185 if config.enable_pattern_analysis {
187 Self::update_patterns(&final_metrics, &patterns).await;
188 }
189
190 let monitoring_duration = monitoring_start.elapsed();
192 monitoring_overhead_us
193 .store(monitoring_duration.as_micros() as u64, Ordering::Relaxed);
194
195 previous_metrics = Some(final_metrics);
196 }
197 });
198
199 Ok(())
200 }
201
202 pub fn record_allocation(&self, info: AllocationInfo) -> Result<Uuid> {
210 let id = info.id;
211 let mut allocations = self
212 .allocations
213 .lock()
214 .map_err(|e| anyhow::anyhow!("Failed to lock allocations: {}", e))?;
215 allocations.insert(id, info);
216 drop(allocations);
217 self.allocated_objects.fetch_add(1, Ordering::Relaxed);
218 Ok(id)
219 }
220
221 pub fn record_deallocation(&self, id: Uuid) -> Result<bool> {
226 let mut allocations = self
227 .allocations
228 .lock()
229 .map_err(|e| anyhow::anyhow!("Failed to lock allocations: {}", e))?;
230 let removed = allocations.remove(&id).is_some();
231 drop(allocations);
232 if removed {
233 self.deallocated_objects.fetch_add(1, Ordering::Relaxed);
234 }
235 Ok(removed)
236 }
237
238 pub fn allocation_stats(&self) -> Result<super::system::TrackedAllocationStats> {
240 Ok(Self::snapshot_allocation_stats(
241 &self.allocations,
242 &self.allocated_objects,
243 &self.deallocated_objects,
244 ))
245 }
246
247 fn snapshot_allocation_stats(
248 allocations: &Arc<Mutex<HashMap<Uuid, AllocationInfo>>>,
249 allocated: &Arc<AtomicU64>,
250 deallocated: &Arc<AtomicU64>,
251 ) -> super::system::TrackedAllocationStats {
252 let (active_allocations, active_bytes) = match allocations.lock() {
253 Ok(guard) => (
254 guard.len() as u64,
255 guard.values().map(|info| info.size_bytes as u64).sum(),
256 ),
257 Err(_) => (0, 0),
258 };
259
260 super::system::TrackedAllocationStats {
261 allocated_objects: allocated.load(Ordering::Relaxed),
262 deallocated_objects: deallocated.load(Ordering::Relaxed),
263 active_allocations,
264 active_bytes,
265 }
266 }
267
268 pub async fn stop_monitoring(&self) -> Result<()> {
270 self.is_monitoring.store(false, Ordering::SeqCst);
271 Ok(())
272 }
273
274 pub async fn get_current_metrics(&self) -> Result<Option<MemoryMetrics>> {
276 let history = self
277 .metrics_history
278 .lock()
279 .map_err(|e| anyhow::anyhow!("Failed to lock metrics history: {}", e))?;
280 Ok(history.back().cloned())
281 }
282
283 pub async fn get_alerts(&self) -> Result<Vec<MemoryAlert>> {
285 let alerts = self
286 .alerts
287 .lock()
288 .map_err(|e| anyhow::anyhow!("Failed to lock alerts: {}", e))?;
289 Ok(alerts.clone())
290 }
291
292 pub async fn get_patterns(&self) -> Result<Vec<MemoryPattern>> {
294 let patterns = self
295 .patterns
296 .lock()
297 .map_err(|e| anyhow::anyhow!("Failed to lock patterns: {}", e))?;
298 Ok(patterns.clone())
299 }
300
301 pub async fn get_adaptive_thresholds(&self) -> Result<AdaptiveThresholds> {
303 let thresholds = self
304 .adaptive_thresholds
305 .lock()
306 .map_err(|e| anyhow::anyhow!("Failed to lock adaptive thresholds: {}", e))?;
307 Ok(thresholds.clone())
308 }
309
310 pub async fn get_monitoring_stats(&self) -> Result<MonitoringStats> {
312 let total_collections = self.total_collections.load(Ordering::Relaxed);
313 let overhead_us = self.monitoring_overhead_us.load(Ordering::Relaxed);
314
315 let average_overhead_us = overhead_us.checked_div(total_collections).unwrap_or(0);
316
317 let uptime_secs = self.start_time.map(|start| start.elapsed().as_secs()).unwrap_or(0);
318
319 Ok(MonitoringStats {
320 total_collections,
321 average_overhead_us,
322 uptime_secs,
323 })
324 }
325
326 pub async fn configure_leak_detection(&self, config: LeakDetectionConfig) -> Result<()> {
328 let mut detection = self
329 .leak_detection
330 .lock()
331 .map_err(|e| anyhow::anyhow!("Failed to lock leak detection: {}", e))?;
332 *detection = LeakDetectionHeuristics {
333 sustained_growth_threshold: config.growth_threshold,
334 growth_duration_threshold: Duration::from_secs(config.duration_secs),
335 allocation_pattern_threshold: config.allocation_threshold,
336 false_positive_filter: config.confidence_threshold,
337 };
338 Ok(())
339 }
340
341 pub async fn get_leak_detection_config(&self) -> Result<LeakDetectionConfig> {
343 let detection = self
344 .leak_detection
345 .lock()
346 .map_err(|e| anyhow::anyhow!("Failed to lock leak detection: {}", e))?;
347 Ok(LeakDetectionConfig {
348 growth_threshold: detection.sustained_growth_threshold,
349 duration_secs: detection.growth_duration_threshold.as_secs(),
350 allocation_threshold: detection.allocation_pattern_threshold,
351 confidence_threshold: detection.false_positive_filter,
352 })
353 }
354
355 pub async fn predict_memory_usage(
357 &self,
358 horizon_secs: u64,
359 ) -> Result<Option<MemoryPrediction>> {
360 let metrics_history = self
361 .metrics_history
362 .lock()
363 .map_err(|e| anyhow::anyhow!("Failed to lock metrics history: {}", e))?;
364 let metrics: Vec<MemoryMetrics> = metrics_history.iter().cloned().collect();
365 drop(metrics_history);
366
367 let mut predictor = self
368 .memory_predictor
369 .lock()
370 .map_err(|e| anyhow::anyhow!("Failed to lock memory predictor: {}", e))?;
371 Ok(predictor.predict_memory_usage(&metrics, Some(horizon_secs)))
372 }
373
374 pub async fn get_analytics_summary(&self) -> Result<AnalyticsSummary> {
376 let thresholds = self.get_adaptive_thresholds().await?;
377 let prediction = self.predict_memory_usage(300).await?; let monitoring_stats = self.get_monitoring_stats().await?;
379 let leak_config = self.get_leak_detection_config().await?;
380
381 Ok(AnalyticsSummary {
382 adaptive_thresholds: thresholds,
383 memory_prediction: prediction,
384 monitoring_stats,
385 leak_detection_config: leak_config,
386 })
387 }
388
389 pub(crate) fn get_metrics_history(
391 &self,
392 ) -> &Arc<Mutex<std::collections::VecDeque<super::types::MemoryMetrics>>> {
393 &self.metrics_history
394 }
395
396 pub(crate) fn get_allocations(
398 &self,
399 ) -> &Arc<Mutex<HashMap<uuid::Uuid, super::types::AllocationInfo>>> {
400 &self.allocations
401 }
402
403 pub(crate) fn get_alerts_internal(&self) -> &Arc<Mutex<Vec<super::types::MemoryAlert>>> {
405 &self.alerts
406 }
407
408 pub(crate) fn get_patterns_internal(&self) -> &Arc<Mutex<Vec<super::types::MemoryPattern>>> {
410 &self.patterns
411 }
412
413 pub(crate) fn get_start_time(&self) -> Option<std::time::Instant> {
415 self.start_time
416 }
417
418 pub(crate) fn get_config(&self) -> &super::types::ProfilerConfig {
420 &self.config
421 }
422
423 #[cfg(test)]
425 pub fn is_monitoring(&self) -> bool {
426 self.is_monitoring.load(std::sync::atomic::Ordering::Relaxed)
427 }
428
429 #[cfg(test)]
431 pub fn get_cached_recommendations(&self) -> &super::analytics::AlertRecommendations {
432 &self.cached_recommendations
433 }
434
435 #[cfg(test)]
437 pub fn get_adaptive_thresholds_internal(
438 &self,
439 ) -> &Arc<Mutex<super::analytics::AdaptiveThresholds>> {
440 &self.adaptive_thresholds
441 }
442
443 #[cfg(test)]
445 pub fn get_memory_predictor_internal(&self) -> &Arc<Mutex<super::analytics::MemoryPredictor>> {
446 &self.memory_predictor
447 }
448}
449
450#[derive(Debug, Clone)]
451pub struct MonitoringStats {
452 pub total_collections: u64,
453 pub average_overhead_us: u64,
454 pub uptime_secs: u64,
455}
456
457#[derive(Debug, Clone)]
458pub struct LeakDetectionConfig {
459 pub growth_threshold: f64,
460 pub duration_secs: u64,
461 pub allocation_threshold: usize,
462 pub confidence_threshold: f64,
463}
464
465#[derive(Debug, Clone)]
466pub struct AnalyticsSummary {
467 pub adaptive_thresholds: AdaptiveThresholds,
468 pub memory_prediction: Option<MemoryPrediction>,
469 pub monitoring_stats: MonitoringStats,
470 pub leak_detection_config: LeakDetectionConfig,
471}