1use anyhow::Result;
7use std::collections::HashMap;
8use std::fmt::Write as FmtWrite;
9
10use super::types::*;
11
12#[derive(Debug, Clone)]
14pub struct MemorySummary {
15 pub current_memory_mb: f64,
16 pub peak_memory_mb: f64,
17 pub average_memory_mb: f64,
18 pub total_allocations: usize,
19 pub potential_leaks: usize,
20 pub active_alerts: usize,
21}
22
23impl super::profiler::MemoryProfiler {
24 pub async fn generate_report(&self) -> Result<MemoryDashboardReport> {
26 let metrics_history = self
27 .get_metrics_history()
28 .lock()
29 .map_err(|e| anyhow::anyhow!("Failed to lock metrics history: {}", e))?
30 .clone();
31 let allocations = self
32 .get_allocations()
33 .lock()
34 .map_err(|e| anyhow::anyhow!("Failed to lock allocations: {}", e))?
35 .clone();
36 let alerts = self
37 .get_alerts_internal()
38 .lock()
39 .map_err(|e| anyhow::anyhow!("Failed to lock alerts: {}", e))?
40 .clone();
41 let patterns = self
42 .get_patterns_internal()
43 .lock()
44 .map_err(|e| anyhow::anyhow!("Failed to lock patterns: {}", e))?
45 .clone();
46 let allocation_stats = self.allocation_stats()?;
47
48 let summary = if !metrics_history.is_empty() {
50 let total_metrics: Vec<_> = metrics_history.iter().map(|m| m.total_memory_mb).collect();
51 let peak_memory = total_metrics.iter().fold(0.0f64, |a, &b| a.max(b));
52 let avg_memory = total_metrics.iter().sum::<f64>() / total_metrics.len() as f64;
53
54 let efficiency_score = self.calculate_memory_efficiency(&metrics_history);
56
57 let mut alert_counts = HashMap::new();
59 for alert in &alerts {
60 let count = alert_counts.entry(alert.severity.clone()).or_insert(0);
61 *count += 1;
62 }
63
64 MemoryUsageSummary {
65 total_runtime_seconds: self
66 .get_start_time()
67 .map(|start| start.elapsed().as_secs_f64())
68 .unwrap_or(0.0),
69 peak_memory_mb: peak_memory,
70 average_memory_mb: avg_memory,
71 memory_efficiency_score: efficiency_score,
72 total_allocations: allocation_stats.allocated_objects,
73 total_deallocations: allocation_stats.deallocated_objects,
74 leaked_allocations: allocations.values().filter(|a| a.is_leaked).count() as u64,
75 fragmentation_events: metrics_history
76 .iter()
77 .filter(|m| m.memory_fragmentation_ratio > 0.3)
78 .count() as u64,
79 alert_count_by_severity: alert_counts,
80 }
81 } else {
82 MemoryUsageSummary {
83 total_runtime_seconds: 0.0,
84 peak_memory_mb: 0.0,
85 average_memory_mb: 0.0,
86 memory_efficiency_score: 0.0,
87 total_allocations: allocation_stats.allocated_objects,
88 total_deallocations: allocation_stats.deallocated_objects,
89 leaked_allocations: 0,
90 fragmentation_events: 0,
91 alert_count_by_severity: HashMap::new(),
92 }
93 };
94
95 let recommendations = self.generate_recommendations(&alerts, &patterns);
96 let system_info = self.get_system_info()?;
97
98 Ok(MemoryDashboardReport {
99 timestamp: std::time::SystemTime::now(),
100 summary,
101 metrics_over_time: metrics_history.into_iter().collect(),
102 alerts,
103 patterns,
104 recommendations,
105 system_info,
106 })
107 }
108
109 pub async fn save_report(&self, report: &MemoryDashboardReport) -> Result<()> {
111 let timestamp =
112 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
113
114 let json_filename = format!(
115 "{}/memory_report_{}.json",
116 self.get_config().output_dir,
117 timestamp
118 );
119 let html_filename = format!(
120 "{}/memory_report_{}.html",
121 self.get_config().output_dir,
122 timestamp
123 );
124
125 let json_content = serde_json::to_string_pretty(report)?;
127 std::fs::write(&json_filename, json_content)?;
128
129 let html_content = self.generate_html_report(report)?;
131 std::fs::write(&html_filename, html_content)?;
132
133 tracing::info!(
134 "Memory report saved to: {} and {}",
135 json_filename,
136 html_filename
137 );
138 Ok(())
139 }
140
141 fn generate_html_report(&self, report: &MemoryDashboardReport) -> Result<String> {
143 let mut html = String::new();
144
145 writeln!(&mut html, "<!DOCTYPE html>")?;
146 writeln!(
147 &mut html,
148 "<html><head><title>Memory Profiling Report</title>"
149 )?;
150 writeln!(&mut html, "<style>")?;
151 writeln!(
152 &mut html,
153 "body {{ font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }}"
154 )?;
155 writeln!(&mut html, ".container {{ max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}")?;
156 writeln!(&mut html, ".summary {{ background: #e8f4fd; padding: 20px; margin: 20px 0; border-radius: 6px; border-left: 4px solid #2196F3; }}")?;
157 writeln!(&mut html, ".alert {{ padding: 12px; margin: 8px 0; border-radius: 4px; border-left: 4px solid; }}")?;
158 writeln!(
159 &mut html,
160 ".info {{ background: #e3f2fd; border-color: #2196F3; }}"
161 )?;
162 writeln!(
163 &mut html,
164 ".warning {{ background: #fff3e0; border-color: #ff9800; }}"
165 )?;
166 writeln!(
167 &mut html,
168 ".error {{ background: #ffebee; border-color: #f44336; }}"
169 )?;
170 writeln!(
171 &mut html,
172 ".critical {{ background: #fce4ec; border-color: #e91e63; }}"
173 )?;
174 writeln!(
175 &mut html,
176 "table {{ border-collapse: collapse; width: 100%; margin: 20px 0; }}"
177 )?;
178 writeln!(
179 &mut html,
180 "th, td {{ border: 1px solid #e0e0e0; padding: 12px; text-align: left; }}"
181 )?;
182 writeln!(
183 &mut html,
184 "th {{ background-color: #f8f9fa; font-weight: 600; }}"
185 )?;
186 writeln!(
187 &mut html,
188 ".metric {{ display: inline-block; margin: 10px 20px 10px 0; }}"
189 )?;
190 writeln!(
191 &mut html,
192 ".metric-label {{ font-weight: bold; color: #666; }}"
193 )?;
194 writeln!(
195 &mut html,
196 ".metric-value {{ font-size: 1.2em; color: #2196F3; }}"
197 )?;
198 writeln!(
199 &mut html,
200 "h1 {{ color: #333; border-bottom: 2px solid #2196F3; padding-bottom: 10px; }}"
201 )?;
202 writeln!(&mut html, "h2 {{ color: #555; margin-top: 30px; }}")?;
203 writeln!(
204 &mut html,
205 ".recommendations {{ background: #f1f8e9; padding: 15px; border-radius: 4px; }}"
206 )?;
207 writeln!(&mut html, "</style></head><body>")?;
208
209 writeln!(&mut html, "<div class='container'>")?;
210 writeln!(&mut html, "<h1>🧠Memory Profiling Report</h1>")?;
211 writeln!(
212 &mut html,
213 "<p><strong>Generated:</strong> {:?}</p>",
214 report.timestamp
215 )?;
216 writeln!(
217 &mut html,
218 "<p><strong>Runtime:</strong> {:.1} seconds</p>",
219 report.summary.total_runtime_seconds
220 )?;
221
222 writeln!(&mut html, "<div class='summary'>")?;
224 writeln!(&mut html, "<h2>📊 Memory Usage Summary</h2>")?;
225 writeln!(&mut html, "<div class='metric'><div class='metric-label'>Peak Memory:</div><div class='metric-value'>{:.2} MB</div></div>", report.summary.peak_memory_mb)?;
226 writeln!(&mut html, "<div class='metric'><div class='metric-label'>Average Memory:</div><div class='metric-value'>{:.2} MB</div></div>", report.summary.average_memory_mb)?;
227 writeln!(&mut html, "<div class='metric'><div class='metric-label'>Efficiency Score:</div><div class='metric-value'>{:.1}%</div></div>", report.summary.memory_efficiency_score * 100.0)?;
228 writeln!(&mut html, "<div class='metric'><div class='metric-label'>Total Allocations:</div><div class='metric-value'>{}</div></div>", report.summary.total_allocations)?;
229 writeln!(&mut html, "<div class='metric'><div class='metric-label'>Leaked Allocations:</div><div class='metric-value'>{}</div></div>", report.summary.leaked_allocations)?;
230 writeln!(&mut html, "<div class='metric'><div class='metric-label'>Fragmentation Events:</div><div class='metric-value'>{}</div></div>", report.summary.fragmentation_events)?;
231 writeln!(&mut html, "</div>")?;
232
233 writeln!(&mut html, "<h2>💻 System Information</h2>")?;
235 writeln!(&mut html, "<table>")?;
236 writeln!(&mut html, "<tr><th>Property</th><th>Value</th></tr>")?;
237 writeln!(
238 &mut html,
239 "<tr><td>Total System Memory</td><td>{:.1} GB</td></tr>",
240 report.system_info.total_system_memory_gb
241 )?;
242 writeln!(
243 &mut html,
244 "<tr><td>Available Memory</td><td>{:.1} GB</td></tr>",
245 report.system_info.available_system_memory_gb
246 )?;
247 writeln!(
248 &mut html,
249 "<tr><td>CPU Count</td><td>{}</td></tr>",
250 report.system_info.cpu_count
251 )?;
252 writeln!(
253 &mut html,
254 "<tr><td>Operating System</td><td>{}</td></tr>",
255 report.system_info.os_info
256 )?;
257 writeln!(
258 &mut html,
259 "<tr><td>Rust Version</td><td>{}</td></tr>",
260 report.system_info.rust_version.as_deref().unwrap_or("unknown")
261 )?;
262 writeln!(&mut html, "</table>")?;
263
264 if !report.alerts.is_empty() {
266 writeln!(
267 &mut html,
268 "<h2>🚨 Alerts ({} total)</h2>",
269 report.alerts.len()
270 )?;
271 for alert in &report.alerts {
272 let class = match alert.severity {
273 AlertSeverity::Info => "info",
274 AlertSeverity::Warning => "warning",
275 AlertSeverity::Error => "error",
276 AlertSeverity::Critical => "critical",
277 };
278 writeln!(&mut html, "<div class='alert {}'>", class)?;
279 writeln!(
280 &mut html,
281 "<strong>{:?}:</strong> {}",
282 alert.severity, alert.message
283 )?;
284 writeln!(&mut html, "</div>")?;
285 }
286 }
287
288 if !report.patterns.is_empty() {
290 writeln!(&mut html, "<h2>📈 Memory Patterns</h2>")?;
291 writeln!(&mut html, "<table>")?;
292 writeln!(&mut html, "<tr><th>Pattern Type</th><th>Frequency</th><th>Average Size</th><th>Trend</th></tr>")?;
293 for pattern in &report.patterns {
294 writeln!(
295 &mut html,
296 "<tr><td>{:?}</td><td>{}</td><td>{:.2} MB</td><td>{:?}</td></tr>",
297 pattern.pattern_type, pattern.frequency, pattern.average_size, pattern.trend
298 )?;
299 }
300 writeln!(&mut html, "</table>")?;
301 }
302
303 if !report.recommendations.is_empty() {
305 writeln!(&mut html, "<h2>💡 Recommendations</h2>")?;
306 writeln!(&mut html, "<div class='recommendations'>")?;
307 writeln!(&mut html, "<ul>")?;
308 for rec in &report.recommendations {
309 writeln!(&mut html, "<li>{}</li>", rec)?;
310 }
311 writeln!(&mut html, "</ul>")?;
312 writeln!(&mut html, "</div>")?;
313 }
314
315 writeln!(&mut html, "</div></body></html>")?;
316 Ok(html)
317 }
318
319 fn generate_recommendations(
321 &self,
322 alerts: &[MemoryAlert],
323 patterns: &[MemoryPattern],
324 ) -> Vec<String> {
325 let mut recommendations = Vec::new();
326
327 let high_memory_alerts = alerts
329 .iter()
330 .filter(|a| matches!(a.alert_type, MemoryAlertType::HighMemoryUsage))
331 .count();
332
333 if high_memory_alerts > 5 {
334 recommendations
335 .push("Consider using gradient checkpointing to reduce memory usage".to_string());
336 recommendations.push("Try reducing the batch size".to_string());
337 recommendations
338 .push("Enable mixed precision training if not already active".to_string());
339 }
340
341 let leak_alerts = alerts
342 .iter()
343 .filter(|a| matches!(a.alert_type, MemoryAlertType::MemoryLeak))
344 .count();
345
346 if leak_alerts > 0 {
347 recommendations
348 .push("Memory leaks detected - review tensor lifecycle management".to_string());
349 recommendations.push("Use explicit cleanup for large tensors".to_string());
350 recommendations
351 .push("Consider using weak references for circular dependencies".to_string());
352 }
353
354 let large_allocation_patterns = patterns
356 .iter()
357 .filter(|p| matches!(p.pattern_type, PatternType::LargeAllocations))
358 .count();
359
360 if large_allocation_patterns > 10 {
361 recommendations
362 .push("Frequent large allocations detected - consider memory pooling".to_string());
363 recommendations
364 .push("Implement tensor reuse strategies for repeated operations".to_string());
365 }
366
367 let frequent_small_allocations = patterns
368 .iter()
369 .filter(|p| matches!(p.pattern_type, PatternType::FrequentSmallAllocations))
370 .count();
371
372 if frequent_small_allocations > 5 {
373 recommendations.push(
374 "Frequent small allocations detected - consider pre-allocating buffers".to_string(),
375 );
376 recommendations
377 .push("Use object pooling for frequently allocated small objects".to_string());
378 }
379
380 if recommendations.is_empty() {
381 recommendations.push(
382 "Memory usage appears normal - no specific recommendations at this time"
383 .to_string(),
384 );
385 recommendations
386 .push("Continue monitoring for any changes in allocation patterns".to_string());
387 }
388
389 recommendations
390 }
391
392 pub fn get_current_summary(&self) -> Option<MemorySummary> {
394 let history = self.get_metrics_history().lock().ok()?;
395 let alerts = self.get_alerts_internal().lock().ok()?;
396 let allocations = self.get_allocations().lock().ok()?;
397
398 if let Some(latest) = history.back() {
399 let total_memory: f64 = history.iter().map(|m| m.total_memory_mb).sum();
400 let avg_memory = if !history.is_empty() {
401 total_memory / history.len() as f64
402 } else {
403 latest.total_memory_mb
404 };
405
406 Some(MemorySummary {
407 current_memory_mb: latest.total_memory_mb,
408 peak_memory_mb: latest.peak_memory_mb,
409 average_memory_mb: avg_memory,
410 total_allocations: allocations.len(),
411 potential_leaks: allocations.values().filter(|a| a.is_leaked).count(),
412 active_alerts: alerts.len(),
413 })
414 } else {
415 None
416 }
417 }
418
419 fn calculate_memory_efficiency(
421 &self,
422 metrics: &std::collections::VecDeque<MemoryMetrics>,
423 ) -> f64 {
424 if metrics.is_empty() {
425 return 0.0;
426 }
427
428 let mut efficiency_factors = Vec::new();
429
430 let memory_values: Vec<f64> = metrics.iter().map(|m| m.total_memory_mb).collect();
432 let mean_memory = memory_values.iter().sum::<f64>() / memory_values.len() as f64;
433 let variance = memory_values.iter().map(|x| (x - mean_memory).powi(2)).sum::<f64>()
434 / memory_values.len() as f64;
435 let stability_score = 1.0 / (1.0 + variance / mean_memory.max(1.0));
436 efficiency_factors.push(stability_score);
437
438 let avg_fragmentation = metrics.iter().map(|m| m.memory_fragmentation_ratio).sum::<f64>()
440 / metrics.len() as f64;
441 let fragmentation_score = 1.0 - avg_fragmentation.min(1.0);
442 efficiency_factors.push(fragmentation_score);
443
444 let total_allocations: u64 = metrics.iter().map(|m| m.allocated_objects).sum();
446 let total_deallocations: u64 = metrics.iter().map(|m| m.deallocated_objects).sum();
447 let allocation_ratio = if total_allocations > 0 {
448 total_deallocations as f64 / total_allocations as f64
449 } else {
450 1.0
451 };
452 efficiency_factors.push(allocation_ratio.min(1.0));
453
454 efficiency_factors.iter().sum::<f64>() / efficiency_factors.len() as f64
456 }
457
458 fn get_system_info(&self) -> Result<SystemInfo> {
463 const BYTES_PER_GB: f64 = 1024.0 * 1024.0 * 1024.0;
464 let memory = Self::get_system_memory_info()?;
465
466 Ok(SystemInfo {
467 total_system_memory_gb: memory.total_memory as f64 / BYTES_PER_GB,
468 available_system_memory_gb: memory.available_memory as f64 / BYTES_PER_GB,
469 cpu_count: num_cpus::get(),
470 os_info: std::env::consts::OS.to_string(),
471 rust_version: option_env!("TRUSTFORMERS_RUSTC_VERSION").map(str::to_string),
474 })
475 }
476}