rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Debug Utilities and System Information
//!
//! Collection of debugging utilities including system information gathering,
//! stack trace capture, and diagnostic helpers for deep learning operations.

use std::collections::HashMap;
use std::env;
use std::fmt;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::error::{RusTorchError, RusTorchResult};

/// System information for debugging
#[derive(Debug, Clone)]
pub struct SystemInfo {
    pub os: String,
    pub architecture: String,
    pub cpu_count: usize,
    pub available_memory_mb: usize,
    pub rust_version: String,
    pub debug_build: bool,
    pub environment_vars: HashMap<String, String>,
    pub timestamp: SystemTime,
}

impl SystemInfo {
    /// Collect current system information
    pub fn collect() -> Self {
        let cpu_count = thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1);

        // Collect relevant environment variables
        let mut env_vars = HashMap::new();
        for (key, value) in env::vars() {
            if key.starts_with("RUST")
                || key.starts_with("CARGO")
                || key.contains("CUDA")
                || key.contains("GPU")
                || key.contains("OPENCL")
            {
                env_vars.insert(key, value);
            }
        }

        Self {
            os: env::consts::OS.to_string(),
            architecture: env::consts::ARCH.to_string(),
            cpu_count,
            available_memory_mb: Self::estimate_available_memory(),
            rust_version: std::env::var("RUSTC_VERSION").unwrap_or_else(|_| "unknown".to_string()),
            debug_build: cfg!(debug_assertions),
            environment_vars: env_vars,
            timestamp: SystemTime::now(),
        }
    }

    /// Estimate available system memory (simplified)
    fn estimate_available_memory() -> usize {
        // This is a rough estimate - in a real system you'd use platform-specific APIs
        match std::env::consts::OS {
            "linux" | "macos" => 8192, // Assume 8GB default
            "windows" => 16384,        // Assume 16GB default
            _ => 4096,                 // Conservative default
        }
    }

    /// Format system info as string
    pub fn format_summary(&self) -> String {
        format!(
            "System: {} {}, {} CPUs, ~{}MB RAM, Rust {}, Debug: {}",
            self.os,
            self.architecture,
            self.cpu_count,
            self.available_memory_mb,
            self.rust_version,
            self.debug_build
        )
    }
}

/// Stack trace information (simplified)
#[derive(Debug, Clone)]
pub struct StackTrace {
    pub frames: Vec<String>,
    pub timestamp: SystemTime,
    pub thread_name: String,
}

impl StackTrace {
    /// Capture current stack trace (simplified implementation)
    pub fn capture() -> Self {
        // Note: This is a simplified implementation
        // A real implementation would use backtrace crate or similar
        let frames = vec![
            "rustorch::debug::capture_stack".to_string(),
            "rustorch::tensor::operation".to_string(),
            "rustorch::main".to_string(),
        ];

        let thread_name = thread::current().name().unwrap_or("unnamed").to_string();

        Self {
            frames,
            timestamp: SystemTime::now(),
            thread_name,
        }
    }

    /// Format stack trace as string
    pub fn format_trace(&self) -> String {
        let mut trace = format!("Stack trace (thread: {}):\n", self.thread_name);
        for (i, frame) in self.frames.iter().enumerate() {
            trace.push_str(&format!("  {}: {}\n", i, frame));
        }
        trace
    }
}

/// Performance measurement helper
#[derive(Debug, Clone)]
pub struct PerfTimer {
    name: String,
    start_time: Instant,
    checkpoints: Vec<(String, Duration)>,
}

impl PerfTimer {
    /// Start new performance timer
    pub fn start(name: String) -> Self {
        Self {
            name,
            start_time: Instant::now(),
            checkpoints: Vec::new(),
        }
    }

    /// Add checkpoint
    pub fn checkpoint(&mut self, label: &str) {
        let elapsed = self.start_time.elapsed();
        self.checkpoints.push((label.to_string(), elapsed));
    }

    /// Finish timing and get total duration
    pub fn finish(mut self) -> (Duration, Vec<(String, Duration)>) {
        let total_duration = self.start_time.elapsed();
        self.checkpoints.push(("TOTAL".to_string(), total_duration));
        (total_duration, self.checkpoints)
    }

    /// Get current elapsed time
    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Generate timing report
    pub fn generate_report(&self) -> String {
        let mut report = format!("Performance Report: {}\n", self.name);
        report.push_str("====================\n");

        for (label, duration) in &self.checkpoints {
            report.push_str(&format!(
                "{}: {:.3}ms\n",
                label,
                duration.as_secs_f64() * 1000.0
            ));
        }

        let total_elapsed = self.elapsed();
        report.push_str(&format!(
            "Current Elapsed: {:.3}ms\n",
            total_elapsed.as_secs_f64() * 1000.0
        ));

        report
    }
}

/// Memory usage snapshot
#[derive(Debug, Clone)]
pub struct MemorySnapshot {
    pub timestamp: SystemTime,
    pub component_usage: HashMap<String, usize>,
    pub total_allocated: usize,
    pub estimated_available: usize,
}

impl MemorySnapshot {
    /// Take memory snapshot (simplified)
    pub fn take(component_usage: HashMap<String, usize>) -> Self {
        let total_allocated: usize = component_usage.values().sum();

        Self {
            timestamp: SystemTime::now(),
            component_usage,
            total_allocated,
            estimated_available: SystemInfo::estimate_available_memory() * 1024 * 1024, // Convert to bytes
        }
    }

    /// Calculate memory utilization percentage
    pub fn utilization_percent(&self) -> f64 {
        if self.estimated_available > 0 {
            (self.total_allocated as f64 / self.estimated_available as f64) * 100.0
        } else {
            0.0
        }
    }

    /// Format memory snapshot
    pub fn format_summary(&self) -> String {
        let total_mb = self.total_allocated as f64 / (1024.0 * 1024.0);
        let available_mb = self.estimated_available as f64 / (1024.0 * 1024.0);

        format!(
            "Memory: {:.1}MB / {:.1}MB ({:.1}% used)",
            total_mb,
            available_mb,
            self.utilization_percent()
        )
    }
}

/// Diagnostic context for debugging
#[derive(Debug, Clone)]
pub struct DiagnosticContext {
    pub operation_name: String,
    pub parameters: HashMap<String, String>,
    pub system_info: SystemInfo,
    pub memory_snapshot: Option<MemorySnapshot>,
    pub stack_trace: Option<StackTrace>,
    pub timestamp: SystemTime,
}

impl DiagnosticContext {
    /// Create new diagnostic context
    pub fn new(operation_name: String) -> Self {
        Self {
            operation_name,
            parameters: HashMap::new(),
            system_info: SystemInfo::collect(),
            memory_snapshot: None,
            stack_trace: None,
            timestamp: SystemTime::now(),
        }
    }

    /// Add parameter
    pub fn add_parameter(&mut self, key: &str, value: &str) {
        self.parameters.insert(key.to_string(), value.to_string());
    }

    /// Set memory snapshot
    pub fn set_memory_snapshot(&mut self, snapshot: MemorySnapshot) {
        self.memory_snapshot = Some(snapshot);
    }

    /// Capture stack trace
    pub fn capture_stack_trace(&mut self) {
        self.stack_trace = Some(StackTrace::capture());
    }

    /// Generate comprehensive diagnostic report
    pub fn generate_diagnostic_report(&self) -> String {
        let mut report = String::new();

        report.push_str("🔧 Diagnostic Report\n");
        report.push_str("===================\n\n");

        report.push_str(&format!("Operation: {}\n", self.operation_name));
        report.push_str(&format!("Timestamp: {:?}\n\n", self.timestamp));

        // System information
        report.push_str("🖥️ System Information:\n");
        report.push_str(&format!("  {}\n\n", self.system_info.format_summary()));

        // Parameters
        if !self.parameters.is_empty() {
            report.push_str("📋 Parameters:\n");
            for (key, value) in &self.parameters {
                report.push_str(&format!("  {}: {}\n", key, value));
            }
            report.push('\n');
        }

        // Memory snapshot
        if let Some(snapshot) = &self.memory_snapshot {
            report.push_str("🧠 Memory Status:\n");
            report.push_str(&format!("  {}\n", snapshot.format_summary()));

            if !snapshot.component_usage.is_empty() {
                report.push_str("  Component Usage:\n");
                let mut components: Vec<_> = snapshot.component_usage.iter().collect();
                components.sort_by(|a, b| b.1.cmp(a.1));

                for (component, usage) in components.iter().take(5) {
                    let mb = **usage as f64 / (1024.0 * 1024.0);
                    report.push_str(&format!("    {}: {:.1}MB\n", component, mb));
                }
            }
            report.push('\n');
        }

        // Stack trace
        if let Some(trace) = &self.stack_trace {
            report.push_str("📚 Stack Trace:\n");
            report.push_str(&trace.format_trace());
            report.push('\n');
        }

        // Environment variables
        if !self.system_info.environment_vars.is_empty() {
            report.push_str("🌍 Relevant Environment:\n");
            for (key, value) in &self.system_info.environment_vars {
                report.push_str(&format!("  {}: {}\n", key, value));
            }
        }

        report
    }
}

/// Debug utilities collection
pub struct DebugUtils;

impl DebugUtils {
    /// Create diagnostic context for operation
    pub fn create_diagnostic_context(operation_name: &str) -> DiagnosticContext {
        DiagnosticContext::new(operation_name.to_string())
    }

    /// Start performance measurement
    pub fn start_perf_timer(name: &str) -> PerfTimer {
        PerfTimer::start(name.to_string())
    }

    /// Collect system information
    pub fn get_system_info() -> SystemInfo {
        SystemInfo::collect()
    }

    /// Capture stack trace
    pub fn capture_stack_trace() -> StackTrace {
        StackTrace::capture()
    }

    /// Take memory snapshot
    pub fn take_memory_snapshot(component_usage: HashMap<String, usize>) -> MemorySnapshot {
        MemorySnapshot::take(component_usage)
    }

    /// Format duration for human reading
    pub fn format_duration(duration: Duration) -> String {
        let total_ms = duration.as_secs_f64() * 1000.0;

        if total_ms < 1.0 {
            format!("{:.3}μs", total_ms * 1000.0)
        } else if total_ms < 1000.0 {
            format!("{:.3}ms", total_ms)
        } else if total_ms < 60000.0 {
            format!("{:.2}s", total_ms / 1000.0)
        } else {
            let minutes = (total_ms / 60000.0) as u32;
            let seconds = (total_ms % 60000.0) / 1000.0;
            format!("{}m {:.1}s", minutes, seconds)
        }
    }

    /// Format bytes for human reading
    pub fn format_bytes(bytes: usize) -> String {
        const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
        let mut size = bytes as f64;
        let mut unit_index = 0;

        while size >= 1024.0 && unit_index < UNITS.len() - 1 {
            size /= 1024.0;
            unit_index += 1;
        }

        if unit_index == 0 {
            format!("{}B", bytes)
        } else {
            format!("{:.2}{}", size, UNITS[unit_index])
        }
    }

    /// Check if running in debug mode
    pub fn is_debug_build() -> bool {
        cfg!(debug_assertions)
    }

    /// Get current thread information
    pub fn get_thread_info() -> (String, String) {
        let current = thread::current();
        let name = current.name().unwrap_or("unnamed").to_string();
        let id = format!("{:?}", current.id());
        (name, id)
    }

    /// Generate environment report
    pub fn generate_environment_report() -> String {
        let system_info = Self::get_system_info();

        let mut report = String::new();
        report.push_str("🌍 Environment Report\n");
        report.push_str("====================\n\n");

        report.push_str(&format!("System: {}\n", system_info.format_summary()));

        let (thread_name, thread_id) = Self::get_thread_info();
        report.push_str(&format!(
            "Current Thread: {} ({})\n",
            thread_name, thread_id
        ));

        report.push_str(&format!("Debug Build: {}\n", Self::is_debug_build()));

        if !system_info.environment_vars.is_empty() {
            report.push_str("\nRelevant Environment Variables:\n");
            for (key, value) in &system_info.environment_vars {
                report.push_str(&format!("  {}: {}\n", key, value));
            }
        }

        report
    }

    /// Simple assertion with diagnostic context
    pub fn debug_assert_with_context<F>(condition: bool, context_fn: F, message: &str)
    where
        F: FnOnce() -> DiagnosticContext,
    {
        if cfg!(debug_assertions) && !condition {
            let context = context_fn();
            eprintln!("🚨 Debug Assertion Failed: {}", message);
            eprintln!("{}", context.generate_diagnostic_report());
            panic!("Debug assertion failed: {}", message);
        }
    }

    /// Conditional debugging output
    pub fn debug_print<T: fmt::Display>(value: &T, enabled: bool) {
        if enabled && cfg!(debug_assertions) {
            eprintln!("🐛 DEBUG: {}", value);
        }
    }

    /// Time a code block and return result with timing
    pub fn time_block<T, F>(name: &str, block: F) -> (T, Duration)
    where
        F: FnOnce() -> T,
    {
        let start = Instant::now();
        let result = block();
        let duration = start.elapsed();

        if cfg!(debug_assertions) {
            eprintln!("⏱️ {}: {}", name, Self::format_duration(duration));
        }

        (result, duration)
    }
}

/// Macro for easy diagnostic context creation
#[macro_export]
macro_rules! diagnostic_context {
    ($operation:expr) => {
        $crate::debug::DebugUtils::create_diagnostic_context($operation)
    };
    ($operation:expr, $($key:expr => $value:expr),*) => {{
        let mut context = $crate::debug::DebugUtils::create_diagnostic_context($operation);
        $(
            context.add_parameter($key, &$value.to_string());
        )*
        context
    }};
}

/// Macro for performance timing
#[macro_export]
macro_rules! perf_timer {
    ($name:expr) => {
        $crate::debug::DebugUtils::start_perf_timer($name)
    };
}

/// Macro for timed code blocks
#[macro_export]
macro_rules! time_block {
    ($name:expr, $block:block) => {
        $crate::debug::DebugUtils::time_block($name, || $block)
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration as StdDuration;

    #[test]
    fn test_system_info_collection() {
        let info = SystemInfo::collect();

        assert!(!info.os.is_empty());
        assert!(!info.architecture.is_empty());
        assert!(info.cpu_count > 0);
        assert!(info.available_memory_mb > 0);
        assert!(!info.rust_version.is_empty());

        let summary = info.format_summary();
        assert!(summary.contains(&info.os));
        assert!(summary.contains("CPUs"));
    }

    #[test]
    fn test_stack_trace_capture() {
        let trace = StackTrace::capture();

        assert!(!trace.frames.is_empty());
        assert!(!trace.thread_name.is_empty());

        let formatted = trace.format_trace();
        assert!(formatted.contains("Stack trace"));
        assert!(formatted.contains(&trace.thread_name));
    }

    #[test]
    fn test_perf_timer() {
        let mut timer = PerfTimer::start("test_operation".to_string());

        thread::sleep(StdDuration::from_millis(10));
        timer.checkpoint("checkpoint_1");

        thread::sleep(StdDuration::from_millis(10));
        timer.checkpoint("checkpoint_2");

        let (total_duration, checkpoints) = timer.finish();

        assert!(total_duration.as_millis() >= 20);
        assert_eq!(checkpoints.len(), 3); // 2 checkpoints + TOTAL

        let last_checkpoint = &checkpoints[checkpoints.len() - 1];
        assert_eq!(last_checkpoint.0, "TOTAL");
        assert_eq!(last_checkpoint.1, total_duration);
    }

    #[test]
    fn test_memory_snapshot() {
        let mut usage = HashMap::new();
        usage.insert("tensor".to_string(), 1024 * 1024); // 1MB
        usage.insert("network".to_string(), 2048 * 1024); // 2MB

        let snapshot = MemorySnapshot::take(usage);

        assert_eq!(snapshot.total_allocated, 3 * 1024 * 1024); // 3MB
        assert!(snapshot.utilization_percent() >= 0.0);

        let summary = snapshot.format_summary();
        assert!(summary.contains("Memory:"));
        assert!(summary.contains("MB"));
    }

    #[test]
    fn test_diagnostic_context() {
        let mut context = DiagnosticContext::new("test_operation".to_string());

        context.add_parameter("param1", "value1");
        context.add_parameter("param2", "value2");

        let mut usage = HashMap::new();
        usage.insert("component1".to_string(), 1024 * 1024);
        let snapshot = MemorySnapshot::take(usage);
        context.set_memory_snapshot(snapshot);

        context.capture_stack_trace();

        let report = context.generate_diagnostic_report();

        assert!(report.contains("Diagnostic Report"));
        assert!(report.contains("test_operation"));
        assert!(report.contains("param1: value1"));
        assert!(report.contains("param2: value2"));
        assert!(report.contains("Memory Status"));
        assert!(report.contains("Stack Trace"));
    }

    #[test]
    fn test_debug_utils_formatting() {
        // Test duration formatting
        let duration = Duration::from_millis(1500);
        let formatted = DebugUtils::format_duration(duration);
        assert!(formatted.contains("1.50s"));

        let micro_duration = Duration::from_nanos(500);
        let micro_formatted = DebugUtils::format_duration(micro_duration);
        assert!(micro_formatted.contains("μs"));

        // Test bytes formatting
        let bytes = DebugUtils::format_bytes(1536); // 1.5KB
        assert!(bytes.contains("1.50KB"));

        let mb_bytes = DebugUtils::format_bytes(2 * 1024 * 1024); // 2MB
        assert!(mb_bytes.contains("2.00MB"));
    }

    #[test]
    fn test_thread_info() {
        let (name, id) = DebugUtils::get_thread_info();

        // Thread name might be empty, but ID should exist
        assert!(!id.is_empty());
    }

    #[test]
    fn test_environment_report() {
        let report = DebugUtils::generate_environment_report();

        assert!(report.contains("Environment Report"));
        assert!(report.contains("System:"));
        assert!(report.contains("Current Thread:"));
        assert!(report.contains("Debug Build:"));
    }

    #[test]
    fn test_time_block_macro() {
        let (result, duration) = time_block!("test_block", {
            thread::sleep(StdDuration::from_millis(10));
            42
        });

        assert_eq!(result, 42);
        assert!(duration.as_millis() >= 10);
    }

    #[test]
    fn test_debug_print() {
        // This test just ensures the function doesn't panic
        DebugUtils::debug_print(&"test message", true);
        DebugUtils::debug_print(&"test message", false);
    }
}