trueno-gpu 0.4.17

Pure Rust PTX generation for NVIDIA CUDA - no LLVM, no nvcc
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! CUDA GPU Monitoring (TRUENO-SPEC-010)
//!
//! Provides native CUDA device monitoring via the CUDA Driver API.
//! This module enables accurate device information and real-time memory metrics.
//!
//! # Design Philosophy
//!
//! **Native CUDA**: Direct access via cuDeviceGetName, cuMemGetInfo provides
//! accurate information (e.g., "NVIDIA GeForce RTX 4090") compared to wgpu's
//! generic backend queries.
//!
//! # Example
//!
//! ```rust,ignore
//! use trueno_gpu::monitor::{CudaDeviceInfo, CudaMemoryInfo};
//!
//! // Query device info
//! let info = CudaDeviceInfo::query(0)?;
//! println!("GPU: {} ({} GB)", info.name, info.total_memory_gb());
//!
//! // Query memory usage
//! let mem = CudaMemoryInfo::query()?;
//! println!("Free: {} / {} MB", mem.free_mb(), mem.total_mb());
//! ```
//!
//! # References
//!
//! - NVIDIA CUDA Driver API: cuDeviceGetName, cuDeviceTotalMem, cuMemGetInfo
//! - TRUENO-SPEC-010: GPU Monitoring, Tracing, and Visualization

#[cfg(feature = "cuda")]
use crate::driver::{cuda_available, device_count, CudaContext};
use crate::GpuError;

// ============================================================================
// CUDA Device Information (TRUENO-SPEC-010 Section 3.1)
// ============================================================================

/// CUDA device information from native driver API
///
/// Provides accurate device information including:
/// - Device name (e.g., "NVIDIA GeForce RTX 4090")
/// - Total VRAM in bytes
/// - Device ordinal
#[derive(Debug, Clone)]
pub struct CudaDeviceInfo {
    /// Device ordinal (0-based index)
    pub index: u32,
    /// Device name from cuDeviceGetName
    pub name: String,
    /// Total VRAM in bytes from cuDeviceTotalMem
    pub total_memory: u64,
}

impl CudaDeviceInfo {
    /// Query device information for the specified device index
    ///
    /// # Arguments
    ///
    /// * `device_index` - Device ordinal (0 for first GPU)
    ///
    /// # Errors
    ///
    /// Returns error if device is not found or query fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let info = CudaDeviceInfo::query(0)?;
    /// println!("GPU: {}", info.name);
    /// ```
    #[cfg(feature = "cuda")]
    #[allow(clippy::cast_possible_wrap)]
    pub fn query(device_index: u32) -> Result<Self, GpuError> {
        let ctx = CudaContext::new(device_index as i32)?;
        let name = ctx.device_name()?;
        let total_memory = ctx.total_memory()? as u64;

        Ok(Self {
            index: device_index,
            name,
            total_memory,
        })
    }

    /// Query device information (non-CUDA stub)
    #[cfg(not(feature = "cuda"))]
    pub fn query(_device_index: u32) -> Result<Self, GpuError> {
        Err(GpuError::CudaNotAvailable(
            "cuda feature not enabled".to_string(),
        ))
    }

    /// Enumerate all available CUDA devices
    ///
    /// # Errors
    ///
    /// Returns error if enumeration fails.
    #[cfg(feature = "cuda")]
    pub fn enumerate() -> Result<Vec<Self>, GpuError> {
        let count = device_count()?;
        let mut devices = Vec::with_capacity(count);

        for i in 0..count {
            devices.push(Self::query(i as u32)?);
        }

        Ok(devices)
    }

    /// Enumerate devices (non-CUDA stub)
    #[cfg(not(feature = "cuda"))]
    pub fn enumerate() -> Result<Vec<Self>, GpuError> {
        Err(GpuError::CudaNotAvailable(
            "cuda feature not enabled".to_string(),
        ))
    }

    /// Get total memory in megabytes
    #[must_use]
    pub fn total_memory_mb(&self) -> u64 {
        self.total_memory / (1024 * 1024)
    }

    /// Get total memory in gigabytes
    #[must_use]
    pub fn total_memory_gb(&self) -> f64 {
        self.total_memory as f64 / (1024.0 * 1024.0 * 1024.0)
    }
}

impl std::fmt::Display for CudaDeviceInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "[{}] {} ({:.1} GB)",
            self.index,
            self.name,
            self.total_memory_gb()
        )
    }
}

// ============================================================================
// CUDA Memory Information (TRUENO-SPEC-010 Section 4.1.2)
// ============================================================================

/// Real-time CUDA memory information from cuMemGetInfo
///
/// Provides current memory usage on the active CUDA context.
#[derive(Debug, Clone, Copy)]
pub struct CudaMemoryInfo {
    /// Free memory in bytes
    pub free: u64,
    /// Total memory in bytes
    pub total: u64,
}

impl CudaMemoryInfo {
    /// Query current memory information
    ///
    /// Requires an active CUDA context.
    ///
    /// # Errors
    ///
    /// Returns error if no context is active or query fails.
    #[cfg(feature = "cuda")]
    pub fn query(ctx: &CudaContext) -> Result<Self, GpuError> {
        let (free, total) = ctx.memory_info()?;
        Ok(Self {
            free: free as u64,
            total: total as u64,
        })
    }

    /// Get used memory in bytes
    #[must_use]
    pub fn used(&self) -> u64 {
        self.total.saturating_sub(self.free)
    }

    /// Get free memory in megabytes
    #[must_use]
    pub fn free_mb(&self) -> u64 {
        self.free / (1024 * 1024)
    }

    /// Get total memory in megabytes
    #[must_use]
    pub fn total_mb(&self) -> u64 {
        self.total / (1024 * 1024)
    }

    /// Get used memory in megabytes
    #[must_use]
    pub fn used_mb(&self) -> u64 {
        self.used() / (1024 * 1024)
    }

    /// Get memory usage percentage (0.0 - 100.0)
    #[must_use]
    pub fn usage_percent(&self) -> f64 {
        if self.total == 0 {
            0.0
        } else {
            (self.used() as f64 / self.total as f64) * 100.0
        }
    }
}

impl std::fmt::Display for CudaMemoryInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} / {} MB ({:.1}% used)",
            self.used_mb(),
            self.total_mb(),
            self.usage_percent()
        )
    }
}

// ============================================================================
// Convenience Functions
// ============================================================================

/// Check if CUDA monitoring is available
///
/// Returns `true` if CUDA driver is installed and at least one device exists.
#[must_use]
pub fn cuda_monitoring_available() -> bool {
    #[cfg(feature = "cuda")]
    {
        cuda_available()
    }
    #[cfg(not(feature = "cuda"))]
    {
        false
    }
}

/// Get the number of CUDA devices
///
/// # Errors
///
/// Returns error if CUDA is not available.
pub fn cuda_device_count() -> Result<usize, GpuError> {
    #[cfg(feature = "cuda")]
    {
        device_count()
    }
    #[cfg(not(feature = "cuda"))]
    {
        Err(GpuError::CudaNotAvailable(
            "cuda feature not enabled".to_string(),
        ))
    }
}

// ============================================================================
// Tests (EXTREME TDD)
// ============================================================================

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

    // =========================================================================
    // Hâ‚€-CUDA-MON-01: CudaDeviceInfo unit tests
    // =========================================================================

    #[test]
    fn h0_cuda_mon_01_device_info_display() {
        let info = CudaDeviceInfo {
            index: 0,
            name: "Test GPU".to_string(),
            total_memory: 24 * 1024 * 1024 * 1024, // 24 GB
        };

        let display = format!("{}", info);
        assert!(display.contains("Test GPU"));
        assert!(display.contains("24.0"));
    }

    #[test]
    fn h0_cuda_mon_02_device_info_memory_helpers() {
        let info = CudaDeviceInfo {
            index: 0,
            name: "Test".to_string(),
            total_memory: 24 * 1024 * 1024 * 1024, // 24 GB
        };

        assert_eq!(info.total_memory_mb(), 24 * 1024);
        assert!((info.total_memory_gb() - 24.0).abs() < 0.01);
    }

    // =========================================================================
    // Hâ‚€-CUDA-MON-10: CudaMemoryInfo unit tests
    // =========================================================================

    #[test]
    fn h0_cuda_mon_10_memory_info_used() {
        let mem = CudaMemoryInfo {
            free: 16 * 1024 * 1024 * 1024,  // 16 GB free
            total: 24 * 1024 * 1024 * 1024, // 24 GB total
        };

        assert_eq!(mem.used(), 8 * 1024 * 1024 * 1024); // 8 GB used
    }

    #[test]
    fn h0_cuda_mon_11_memory_info_mb_helpers() {
        let mem = CudaMemoryInfo {
            free: 16 * 1024 * 1024 * 1024,
            total: 24 * 1024 * 1024 * 1024,
        };

        assert_eq!(mem.free_mb(), 16 * 1024);
        assert_eq!(mem.total_mb(), 24 * 1024);
        assert_eq!(mem.used_mb(), 8 * 1024);
    }

    #[test]
    fn h0_cuda_mon_12_memory_info_usage_percent() {
        let mem = CudaMemoryInfo {
            free: 12 * 1024 * 1024 * 1024,  // 12 GB free
            total: 24 * 1024 * 1024 * 1024, // 24 GB total
        };

        // 50% used
        assert!((mem.usage_percent() - 50.0).abs() < 0.01);
    }

    #[test]
    fn h0_cuda_mon_13_memory_info_usage_percent_zero_total() {
        let mem = CudaMemoryInfo { free: 0, total: 0 };

        assert!((mem.usage_percent() - 0.0).abs() < 0.01);
    }

    #[test]
    fn h0_cuda_mon_14_memory_info_display() {
        let mem = CudaMemoryInfo {
            free: 16 * 1024 * 1024 * 1024,
            total: 24 * 1024 * 1024 * 1024,
        };

        let display = format!("{}", mem);
        assert!(display.contains("8192")); // 8 GB used
        assert!(display.contains("24576")); // 24 GB total
        assert!(display.contains("33.3")); // ~33% used
    }

    // =========================================================================
    // Hâ‚€-CUDA-MON-20: Integration tests (require CUDA feature)
    // =========================================================================

    #[test]
    #[cfg(feature = "cuda")]
    fn h0_cuda_mon_20_query_device_info() {
        match CudaDeviceInfo::query(0) {
            Ok(info) => {
                assert!(!info.name.is_empty());
                assert!(info.total_memory > 0);
                println!("CUDA Device: {}", info);
            }
            Err(e) => {
                // No CUDA device is OK for CI
                println!("No CUDA device (expected in CI): {}", e);
            }
        }
    }

    #[test]
    #[cfg(feature = "cuda")]
    fn h0_cuda_mon_21_enumerate_devices() {
        match CudaDeviceInfo::enumerate() {
            Ok(devices) => {
                for dev in &devices {
                    println!("Found: {}", dev);
                }
            }
            Err(e) => {
                println!("CUDA enumeration failed (expected in CI): {}", e);
            }
        }
    }

    #[test]
    #[cfg(feature = "cuda")]
    fn h0_cuda_mon_22_query_memory_info() {
        use crate::driver::CudaContext;

        match CudaDeviceInfo::query(0) {
            Ok(_) => {
                // Context was created by query, but we need a fresh one for memory_info
                if let Ok(ctx) = CudaContext::new(0) {
                    match CudaMemoryInfo::query(&ctx) {
                        Ok(mem) => {
                            assert!(mem.total > 0);
                            assert!(mem.free <= mem.total);
                            println!("CUDA Memory: {}", mem);
                        }
                        Err(e) => {
                            println!("Memory query failed: {}", e);
                        }
                    }
                }
            }
            Err(e) => {
                println!("No CUDA device (expected in CI): {}", e);
            }
        }
    }

    #[test]
    #[cfg(not(feature = "cuda"))]
    fn h0_cuda_mon_30_no_cuda_feature() {
        // Without cuda feature, queries should return error
        assert!(CudaDeviceInfo::query(0).is_err());
        assert!(CudaDeviceInfo::enumerate().is_err());
    }

    // =========================================================================
    // H0-CUDA-MON-40: Convenience function tests
    // =========================================================================

    #[test]
    fn h0_cuda_mon_40_cuda_monitoring_available() {
        // Test the convenience function - it should return a boolean
        let available = cuda_monitoring_available();
        // Without the cuda feature, this should be false
        #[cfg(not(feature = "cuda"))]
        assert!(
            !available,
            "Without CUDA feature, monitoring should not be available"
        );
        // With cuda feature but possibly no hardware, it might be true or false
        #[cfg(feature = "cuda")]
        {
            // Just verify it returns a boolean (no panic)
            let _ = available;
        }
    }

    #[test]
    fn h0_cuda_mon_41_cuda_device_count() {
        // Test the device count function
        let result = cuda_device_count();
        #[cfg(not(feature = "cuda"))]
        {
            assert!(
                result.is_err(),
                "Without CUDA feature, device count should error"
            );
            if let Err(e) = result {
                let err_msg = format!("{:?}", e);
                assert!(
                    err_msg.contains("cuda") || err_msg.contains("Cuda"),
                    "Error should mention CUDA"
                );
            }
        }
        #[cfg(feature = "cuda")]
        {
            // With cuda feature, it should return Ok or Err based on hardware
            match result {
                Ok(count) => {
                    // Count should be a reasonable number
                    assert!(count <= 16, "Device count should be reasonable");
                }
                Err(_) => {
                    // No CUDA hardware is OK for CI
                }
            }
        }
    }

    // =========================================================================
    // H0-CUDA-MON-50: Derive trait tests (Clone, Debug, Copy)
    // =========================================================================

    #[test]
    fn h0_cuda_mon_50_device_info_clone() {
        let info = CudaDeviceInfo {
            index: 1,
            name: "Cloneable GPU".to_string(),
            total_memory: 8 * 1024 * 1024 * 1024,
        };

        let cloned = info.clone();
        assert_eq!(cloned.index, info.index);
        assert_eq!(cloned.name, info.name);
        assert_eq!(cloned.total_memory, info.total_memory);
    }

    #[test]
    fn h0_cuda_mon_51_device_info_debug() {
        let info = CudaDeviceInfo {
            index: 2,
            name: "Debug GPU".to_string(),
            total_memory: 16 * 1024 * 1024 * 1024,
        };

        let debug_str = format!("{:?}", info);
        assert!(debug_str.contains("CudaDeviceInfo"));
        assert!(debug_str.contains("Debug GPU"));
        // 16 GB = 17179869184 bytes - check for index
        assert!(debug_str.contains("2"), "Should contain the index value");
    }

    #[test]
    fn h0_cuda_mon_52_memory_info_clone() {
        let mem = CudaMemoryInfo {
            free: 4 * 1024 * 1024 * 1024,
            total: 8 * 1024 * 1024 * 1024,
        };

        let cloned = mem.clone();
        assert_eq!(cloned.free, mem.free);
        assert_eq!(cloned.total, mem.total);
    }

    #[test]
    fn h0_cuda_mon_53_memory_info_copy() {
        let mem = CudaMemoryInfo {
            free: 2 * 1024 * 1024 * 1024,
            total: 4 * 1024 * 1024 * 1024,
        };

        // Test Copy trait by assigning to another variable
        let copied = mem;
        assert_eq!(copied.free, 2 * 1024 * 1024 * 1024);
        assert_eq!(copied.total, 4 * 1024 * 1024 * 1024);

        // Original should still be usable (Copy semantics)
        assert_eq!(mem.free, 2 * 1024 * 1024 * 1024);
    }

    #[test]
    fn h0_cuda_mon_54_memory_info_debug() {
        let mem = CudaMemoryInfo {
            free: 1024 * 1024 * 1024,
            total: 2 * 1024 * 1024 * 1024,
        };

        let debug_str = format!("{:?}", mem);
        assert!(debug_str.contains("CudaMemoryInfo"));
        assert!(debug_str.contains("free"));
        assert!(debug_str.contains("total"));
    }

    // =========================================================================
    // H0-CUDA-MON-60: Edge case tests
    // =========================================================================

    #[test]
    fn h0_cuda_mon_60_memory_info_used_saturating() {
        // Test saturating_sub edge case where free > total (shouldn't happen but be safe)
        let mem = CudaMemoryInfo {
            free: 10 * 1024 * 1024 * 1024, // 10 GB free (impossible: more than total)
            total: 8 * 1024 * 1024 * 1024, // 8 GB total
        };

        // saturating_sub should return 0, not underflow
        assert_eq!(mem.used(), 0);
        assert_eq!(mem.used_mb(), 0);
    }

    #[test]
    fn h0_cuda_mon_61_device_info_display_index_format() {
        // Test Display formatting with different index values
        let info = CudaDeviceInfo {
            index: 7,
            name: "GPU Seven".to_string(),
            total_memory: 12 * 1024 * 1024 * 1024,
        };

        let display = format!("{}", info);
        assert!(
            display.contains("[7]"),
            "Display should show index in brackets"
        );
        assert!(display.contains("GPU Seven"));
        assert!(display.contains("12.0"));
    }

    #[test]
    fn h0_cuda_mon_62_memory_info_display_formatting() {
        // Test Display with specific values to verify format
        let mem = CudaMemoryInfo {
            free: 0,                   // 0 bytes free
            total: 1024 * 1024 * 1024, // 1 GB total
        };

        let display = format!("{}", mem);
        assert!(display.contains("1024")); // 1024 MB total
        assert!(display.contains("100")); // 100% used
    }

    #[test]
    fn h0_cuda_mon_63_small_memory_values() {
        // Test with small memory values (less than 1 MB)
        let mem = CudaMemoryInfo {
            free: 512 * 1024,   // 512 KB
            total: 1024 * 1024, // 1 MB
        };

        assert_eq!(mem.free_mb(), 0); // Less than 1 MB
        assert_eq!(mem.total_mb(), 1);
        assert_eq!(mem.used_mb(), 0); // 512 KB used
        assert!((mem.usage_percent() - 50.0).abs() < 0.01);
    }

    #[test]
    fn h0_cuda_mon_64_device_info_empty_name() {
        // Test with empty device name
        let info = CudaDeviceInfo {
            index: 0,
            name: String::new(),
            total_memory: 1024,
        };

        let display = format!("{}", info);
        assert!(display.contains("[0]"));
        // Should handle empty name gracefully
    }

    #[test]
    fn h0_cuda_mon_65_device_info_zero_memory() {
        // Test with zero total memory
        let info = CudaDeviceInfo {
            index: 0,
            name: "Zero Memory GPU".to_string(),
            total_memory: 0,
        };

        assert_eq!(info.total_memory_mb(), 0);
        assert!((info.total_memory_gb() - 0.0).abs() < 0.001);

        let display = format!("{}", info);
        assert!(display.contains("0.0 GB"));
    }

    #[test]
    fn h0_cuda_mon_66_memory_info_full_usage() {
        // Test with 100% memory usage
        let mem = CudaMemoryInfo {
            free: 0,
            total: 16 * 1024 * 1024 * 1024,
        };

        assert_eq!(mem.used(), 16 * 1024 * 1024 * 1024);
        assert!((mem.usage_percent() - 100.0).abs() < 0.001);
    }

    #[test]
    fn h0_cuda_mon_67_memory_info_no_usage() {
        // Test with 0% memory usage (all free)
        let mem = CudaMemoryInfo {
            free: 8 * 1024 * 1024 * 1024,
            total: 8 * 1024 * 1024 * 1024,
        };

        assert_eq!(mem.used(), 0);
        assert!((mem.usage_percent() - 0.0).abs() < 0.001);
    }

    // =========================================================================
    // H0-CUDA-MON-70: Error message validation (non-CUDA feature)
    // =========================================================================

    #[test]
    #[cfg(not(feature = "cuda"))]
    fn h0_cuda_mon_70_query_error_message() {
        let result = CudaDeviceInfo::query(0);
        assert!(result.is_err());

        if let Err(e) = result {
            let err_str = format!("{:?}", e);
            assert!(
                err_str.contains("cuda") || err_str.contains("Cuda") || err_str.contains("CUDA"),
                "Error should mention CUDA: got {}",
                err_str
            );
        }
    }

    #[test]
    #[cfg(not(feature = "cuda"))]
    fn h0_cuda_mon_71_enumerate_error_message() {
        let result = CudaDeviceInfo::enumerate();
        assert!(result.is_err());

        if let Err(e) = result {
            let err_str = format!("{:?}", e);
            assert!(
                err_str.contains("cuda") || err_str.contains("Cuda") || err_str.contains("CUDA"),
                "Error should mention CUDA: got {}",
                err_str
            );
        }
    }
}