oxicuda 0.1.0

OxiCUDA - Pure Rust CUDA replacement for the COOLJAPAN ecosystem (95% performance target)
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
//! Global initialization with device auto-selection.
//!
//! Provides a one-call initialization path that selects a GPU, creates a
//! context and (optionally) a default stream, then stores them in a
//! process-wide singleton accessible from any thread.
//!
//! # Quick Start
//!
//! ```no_run
//! use oxicuda::prelude::*;
//!
//! // Lazily initialize with defaults (best compute capability)
//! let rt = lazy_init()?;
//! println!("Using GPU: {}", rt.device_name());
//! # Ok::<(), oxicuda_driver::CudaError>(())
//! ```
//!
//! # Custom Configuration
//!
//! ```no_run
//! use oxicuda::global_init::*;
//!
//! let rt = OxiCudaRuntimeBuilder::new()
//!     .device(DeviceSelection::BestMemory)
//!     .with_stream(true)
//!     .build()?;
//! # Ok::<(), oxicuda_driver::CudaError>(())
//! ```

use std::fmt;
use std::sync::{Arc, OnceLock};

use oxicuda_driver::{Context, CudaError, CudaResult, Device, Stream};

// ─── DeviceSelection ────────────────────────────────────────

/// Strategy for selecting a GPU device during initialization.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum DeviceSelection {
    /// Pick the device with the highest compute capability (SM version).
    /// Ties are broken by total memory.  This is the default.
    #[default]
    BestComputeCapability,
    /// Pick the device with the most VRAM.
    /// Ties are broken by compute capability.
    BestMemory,
    /// Use the device with the given ordinal.
    Specific(i32),
    /// Always use device 0.
    First,
}

impl DeviceSelection {
    /// Apply the selection strategy and return the chosen [`Device`].
    ///
    /// Returns `Err(CudaError::NoDevice)` when the system has no CUDA devices
    /// and `Err(CudaError::InvalidDevice)` for an out-of-range ordinal in
    /// [`Specific`](DeviceSelection::Specific).
    pub fn select(&self) -> CudaResult<Device> {
        match self {
            Self::First => Device::get(0),
            Self::Specific(ordinal) => {
                let count = Device::count()?;
                if *ordinal < 0 || *ordinal >= count {
                    return Err(CudaError::InvalidDevice);
                }
                Device::get(*ordinal)
            }
            Self::BestComputeCapability => {
                let devices = oxicuda_driver::list_devices()?;
                if devices.is_empty() {
                    return Err(CudaError::NoDevice);
                }
                select_best_compute_capability(&devices)
            }
            Self::BestMemory => {
                let devices = oxicuda_driver::list_devices()?;
                if devices.is_empty() {
                    return Err(CudaError::NoDevice);
                }
                select_best_memory(&devices)
            }
        }
    }
}

/// Pick device with highest compute capability, tie-breaking on memory.
fn select_best_compute_capability(devices: &[Device]) -> CudaResult<Device> {
    let mut best = devices[0];
    let mut best_cc = best.compute_capability()?;
    let mut best_mem = best.total_memory()?;

    for dev in devices.iter().skip(1) {
        let cc = dev.compute_capability()?;
        let mem = dev.total_memory()?;
        if cc > best_cc || (cc == best_cc && mem > best_mem) {
            best = *dev;
            best_cc = cc;
            best_mem = mem;
        }
    }
    Ok(best)
}

/// Pick device with most VRAM, tie-breaking on compute capability.
fn select_best_memory(devices: &[Device]) -> CudaResult<Device> {
    let mut best = devices[0];
    let mut best_mem = best.total_memory()?;
    let mut best_cc = best.compute_capability()?;

    for dev in devices.iter().skip(1) {
        let mem = dev.total_memory()?;
        let cc = dev.compute_capability()?;
        if mem > best_mem || (mem == best_mem && cc > best_cc) {
            best = *dev;
            best_mem = mem;
            best_cc = cc;
        }
    }
    Ok(best)
}

// ─── RuntimeConfig ──────────────────────────────────────────

/// Configuration for the global OxiCUDA runtime.
#[derive(Debug, Clone)]
pub struct OxiCudaRuntimeConfig {
    /// How to pick the device (default: [`DeviceSelection::BestComputeCapability`]).
    pub device_selection: DeviceSelection,
    /// Whether to create a default stream (default: `true`).
    pub create_default_stream: bool,
}

impl Default for OxiCudaRuntimeConfig {
    fn default() -> Self {
        Self {
            device_selection: DeviceSelection::default(),
            create_default_stream: true,
        }
    }
}

// ─── RuntimeInfo ────────────────────────────────────────────

/// Summary information about the initialized runtime.
#[derive(Debug, Clone)]
pub struct RuntimeInfo {
    /// Human-readable device name.
    pub device_name: String,
    /// Compute capability `(major, minor)`.
    pub compute_capability: (i32, i32),
    /// Zero-based device ordinal.
    pub device_ordinal: i32,
}

impl fmt::Display for RuntimeInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "OxiCUDA runtime: {} (SM {}.{}, ordinal {})",
            self.device_name,
            self.compute_capability.0,
            self.compute_capability.1,
            self.device_ordinal,
        )
    }
}

// ─── OxiCudaRuntime ─────────────────────────────────────────

/// Process-wide CUDA runtime singleton.
///
/// Holds the selected device, its primary context, and an optional default
/// stream.  Created via [`lazy_init`], [`init_with`], or
/// [`OxiCudaRuntimeBuilder`].
pub struct OxiCudaRuntime {
    device: Device,
    context: Arc<Context>,
    default_stream: Option<Stream>,
    device_name: String,
    compute_capability: (i32, i32),
}

// Manual Debug because Stream may not impl Debug.
impl fmt::Debug for OxiCudaRuntime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OxiCudaRuntime")
            .field("device_name", &self.device_name)
            .field("compute_capability", &self.compute_capability)
            .field("has_default_stream", &self.default_stream.is_some())
            .finish()
    }
}

impl OxiCudaRuntime {
    /// Build a new runtime from the given config.
    fn new(config: OxiCudaRuntimeConfig) -> CudaResult<Self> {
        // Ensure the CUDA driver is initialized.
        oxicuda_driver::init()?;

        let device = config.device_selection.select()?;
        let device_name = device.name()?;
        let compute_capability = device.compute_capability()?;
        let context = Arc::new(Context::new(&device)?);
        let default_stream = if config.create_default_stream {
            Some(Stream::new(&context)?)
        } else {
            None
        };

        Ok(Self {
            device,
            context,
            default_stream,
            device_name,
            compute_capability,
        })
    }

    // ── Accessors ───────────────────────────────────────────

    /// The selected GPU device.
    pub fn device(&self) -> &Device {
        &self.device
    }

    /// Thread-safe handle to the primary context.
    pub fn context(&self) -> &Arc<Context> {
        &self.context
    }

    /// The default stream, if one was created.
    pub fn stream(&self) -> Option<&Stream> {
        self.default_stream.as_ref()
    }

    /// Human-readable device name.
    pub fn device_name(&self) -> &str {
        &self.device_name
    }

    /// Compute capability `(major, minor)`.
    pub fn compute_capability(&self) -> (i32, i32) {
        self.compute_capability
    }

    /// Build a [`RuntimeInfo`] snapshot.
    pub fn info(&self) -> RuntimeInfo {
        RuntimeInfo {
            device_name: self.device_name.clone(),
            compute_capability: self.compute_capability,
            device_ordinal: self.device.ordinal(),
        }
    }
}

// ─── Global singleton ───────────────────────────────────────

/// The process-wide runtime instance, initialized at most once.
static RUNTIME: OnceLock<Result<OxiCudaRuntime, CudaError>> = OnceLock::new();

/// Initialize with the default configuration on the first call and return a
/// reference to the global runtime.
///
/// Subsequent calls return the same instance (even if the first call failed).
pub fn lazy_init() -> CudaResult<&'static OxiCudaRuntime> {
    let result = RUNTIME.get_or_init(|| OxiCudaRuntime::new(OxiCudaRuntimeConfig::default()));
    match result {
        Ok(rt) => Ok(rt),
        Err(e) => Err(*e),
    }
}

/// Initialize with a custom configuration.
///
/// If the runtime is already initialized (by a prior call to [`lazy_init`] or
/// [`init_with`]) the existing instance is returned and `config` is ignored.
pub fn init_with(config: OxiCudaRuntimeConfig) -> CudaResult<&'static OxiCudaRuntime> {
    let result = RUNTIME.get_or_init(|| OxiCudaRuntime::new(config));
    match result {
        Ok(rt) => Ok(rt),
        Err(e) => Err(*e),
    }
}

/// Returns `true` if the global runtime has been initialized (successfully or
/// not).
pub fn is_initialized() -> bool {
    RUNTIME.get().is_some()
}

/// Convenience: get a reference to the default device.
///
/// Calls [`lazy_init`] if the runtime has not been initialized yet.
pub fn default_device() -> CudaResult<&'static Device> {
    lazy_init().map(|rt| rt.device())
}

/// Convenience: get an `Arc<Context>` for the default device.
///
/// Calls [`lazy_init`] if the runtime has not been initialized yet.
pub fn default_context() -> CudaResult<&'static Arc<Context>> {
    lazy_init().map(|rt| rt.context())
}

/// Convenience: get the default stream.
///
/// Returns `Err(CudaError::NotInitialized)` if the runtime was created
/// without a default stream.
///
/// Calls [`lazy_init`] if the runtime has not been initialized yet.
pub fn default_stream() -> CudaResult<&'static Stream> {
    let rt = lazy_init()?;
    rt.stream().ok_or(CudaError::NotInitialized)
}

/// Convenience: get a [`RuntimeInfo`] summary.
///
/// Calls [`lazy_init`] if the runtime has not been initialized yet.
pub fn runtime_info() -> CudaResult<RuntimeInfo> {
    lazy_init().map(|rt| rt.info())
}

// ─── Builder ────────────────────────────────────────────────

/// Fluent builder for configuring and initializing the global runtime.
///
/// ```no_run
/// use oxicuda::global_init::*;
///
/// let rt = OxiCudaRuntimeBuilder::new()
///     .device(DeviceSelection::Specific(1))
///     .with_stream(false)
///     .build()?;
/// # Ok::<(), oxicuda_driver::CudaError>(())
/// ```
#[derive(Debug, Clone)]
pub struct OxiCudaRuntimeBuilder {
    config: OxiCudaRuntimeConfig,
}

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

impl OxiCudaRuntimeBuilder {
    /// Create a builder with default settings.
    pub fn new() -> Self {
        Self {
            config: OxiCudaRuntimeConfig::default(),
        }
    }

    /// Set the device selection strategy.
    pub fn device(mut self, selection: DeviceSelection) -> Self {
        self.config.device_selection = selection;
        self
    }

    /// Enable or disable creation of a default stream.
    pub fn with_stream(mut self, enabled: bool) -> Self {
        self.config.create_default_stream = enabled;
        self
    }

    /// Consume the builder and initialize the global runtime.
    ///
    /// If the runtime is already initialized the existing instance is returned
    /// and this builder's configuration is ignored.
    pub fn build(self) -> CudaResult<&'static OxiCudaRuntime> {
        init_with(self.config)
    }
}

// ─── Tests ──────────────────────────────────────────────────

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

    // ── DeviceSelection unit tests ─────────────────────────

    #[test]
    fn device_selection_default_is_best_compute_capability() {
        assert_eq!(
            DeviceSelection::default(),
            DeviceSelection::BestComputeCapability
        );
    }

    #[test]
    fn device_selection_eq() {
        assert_eq!(DeviceSelection::First, DeviceSelection::First);
        assert_eq!(DeviceSelection::BestMemory, DeviceSelection::BestMemory);
        assert_eq!(DeviceSelection::Specific(0), DeviceSelection::Specific(0));
        assert_ne!(DeviceSelection::Specific(0), DeviceSelection::Specific(1));
        assert_ne!(DeviceSelection::First, DeviceSelection::BestMemory);
    }

    #[test]
    fn device_selection_debug() {
        let s = format!("{:?}", DeviceSelection::BestComputeCapability);
        assert!(s.contains("BestComputeCapability"));
    }

    #[test]
    fn device_selection_clone() {
        let a = DeviceSelection::Specific(42);
        let b = a.clone();
        assert_eq!(a, b);
    }

    // ── OxiCudaRuntimeConfig tests ─────────────────────────

    #[test]
    fn config_default_values() {
        let cfg = OxiCudaRuntimeConfig::default();
        assert_eq!(cfg.device_selection, DeviceSelection::BestComputeCapability);
        assert!(cfg.create_default_stream);
    }

    #[test]
    fn config_custom_values() {
        let cfg = OxiCudaRuntimeConfig {
            device_selection: DeviceSelection::BestMemory,
            create_default_stream: false,
        };
        assert_eq!(cfg.device_selection, DeviceSelection::BestMemory);
        assert!(!cfg.create_default_stream);
    }

    #[test]
    fn config_debug() {
        let cfg = OxiCudaRuntimeConfig::default();
        let s = format!("{:?}", cfg);
        assert!(s.contains("BestComputeCapability"));
        assert!(s.contains("true"));
    }

    // ── RuntimeInfo tests ──────────────────────────────────

    #[test]
    fn runtime_info_display() {
        let info = RuntimeInfo {
            device_name: "Test GPU".to_string(),
            compute_capability: (8, 6),
            device_ordinal: 0,
        };
        let s = format!("{info}");
        assert!(s.contains("Test GPU"));
        assert!(s.contains("SM 8.6"));
        assert!(s.contains("ordinal 0"));
    }

    #[test]
    fn runtime_info_debug() {
        let info = RuntimeInfo {
            device_name: "RTX 4090".to_string(),
            compute_capability: (9, 0),
            device_ordinal: 1,
        };
        let s = format!("{info:?}");
        assert!(s.contains("RTX 4090"));
        assert!(s.contains("(9, 0)"));
    }

    #[test]
    fn runtime_info_clone() {
        let info = RuntimeInfo {
            device_name: "A100".to_string(),
            compute_capability: (8, 0),
            device_ordinal: 0,
        };
        let cloned = info.clone();
        assert_eq!(cloned.device_name, "A100");
        assert_eq!(cloned.compute_capability, (8, 0));
        assert_eq!(cloned.device_ordinal, 0);
    }

    // ── Builder tests ──────────────────────────────────────

    #[test]
    fn builder_default_config() {
        let builder = OxiCudaRuntimeBuilder::new();
        assert_eq!(
            builder.config.device_selection,
            DeviceSelection::BestComputeCapability
        );
        assert!(builder.config.create_default_stream);
    }

    #[test]
    fn builder_chained() {
        let builder = OxiCudaRuntimeBuilder::new()
            .device(DeviceSelection::Specific(2))
            .with_stream(false);
        assert_eq!(
            builder.config.device_selection,
            DeviceSelection::Specific(2)
        );
        assert!(!builder.config.create_default_stream);
    }

    #[test]
    fn builder_default_trait() {
        let builder = OxiCudaRuntimeBuilder::default();
        assert_eq!(
            builder.config.device_selection,
            DeviceSelection::BestComputeCapability
        );
    }

    #[test]
    fn builder_clone() {
        let a = OxiCudaRuntimeBuilder::new().device(DeviceSelection::BestMemory);
        let b = a.clone();
        assert_eq!(b.config.device_selection, DeviceSelection::BestMemory);
    }

    #[test]
    fn builder_debug() {
        let builder = OxiCudaRuntimeBuilder::new();
        let s = format!("{builder:?}");
        assert!(s.contains("OxiCudaRuntimeBuilder"));
    }

    // ── is_initialized (static state) ──────────────────────

    // Note: Because OnceLock is process-wide and tests run in the same
    // process, we can only reliably test the *type* of `is_initialized`.
    // On macOS (no GPU) the init will fail, but the lock will still be set.
    #[test]
    fn is_initialized_returns_bool() {
        // Just verify the function compiles and returns a bool.
        let _val: bool = is_initialized();
    }

    // ── select logic (negative ordinal) ────────────────────

    #[test]
    fn specific_negative_ordinal_without_gpu() {
        // Without a GPU, Device::count() itself will fail, which is fine.
        // We just verify that the code path doesn't panic.
        let sel = DeviceSelection::Specific(-1);
        let _result = sel.select(); // may be Err on any platform
    }

    // ── GPU-gated tests ────────────────────────────────────

    #[cfg(feature = "gpu-tests")]
    mod gpu {
        use super::super::*;

        /// Returns true if a GPU is actually available on this system.
        fn gpu_available() -> bool {
            oxicuda_driver::init().is_ok() && Device::count().unwrap_or(0) > 0
        }

        #[test]
        fn select_first_device() {
            if !gpu_available() {
                return; // skip on macOS / systems without NVIDIA GPU
            }
            let dev = DeviceSelection::First.select();
            assert!(dev.is_ok());
        }

        #[test]
        fn select_specific_zero() {
            if !gpu_available() {
                return;
            }
            let dev = DeviceSelection::Specific(0).select();
            assert!(dev.is_ok());
        }

        #[test]
        fn select_best_cc() {
            if !gpu_available() {
                return;
            }
            let dev = DeviceSelection::BestComputeCapability.select();
            assert!(dev.is_ok());
        }

        #[test]
        fn select_best_memory() {
            if !gpu_available() {
                return;
            }
            let dev = DeviceSelection::BestMemory.select();
            assert!(dev.is_ok());
        }

        #[test]
        fn specific_out_of_range() {
            if !gpu_available() {
                return;
            }
            let count = Device::count().unwrap_or(0);
            let dev = DeviceSelection::Specific(count + 10).select();
            assert!(dev.is_err());
        }
    }
}