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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! # OxiCUDA — Pure Rust CUDA Replacement
//!
//! OxiCUDA provides a complete, pure Rust replacement for NVIDIA's CUDA
//! software stack. It dynamically loads `libcuda.so` at runtime, requiring
//! no CUDA Toolkit at build time.
//!
//! ## Architecture
//!
//! ```text
//! ┌──────────────────────────────────────────────┐
//! │ COOLJAPAN Ecosystem │
//! │ SciRS2 │ oxionnx │ TrustformeRS │ ToRSh │
//! │ └────┬────┘ │ │
//! │ └───────────────────┘ │
//! │ │ │
//! │ ┌───────▼────────┐ │
//! │ │ OxiCUDA │ │
//! │ ├────────────────┤ │
//! │ │ Driver (Vol.1) │ │
//! │ │ Memory (Vol.1) │ │
//! │ │ Launch (Vol.1) │ │
//! │ │ PTX (Vol.2) │ │
//! │ │ Autotune(Vol.2)│ │
//! │ │ BLAS (Vol.3) │ │
//! │ │ DNN (Vol.4) │ │
//! │ │ FFT (Vol.5) │ │
//! │ │ Sparse (Vol.5) │ │
//! │ │ Solver (Vol.5) │ │
//! │ │ Rand (Vol.5) │ │
//! │ └───────┬────────┘ │
//! │ ┌───────▼────────┐ │
//! │ │ libcuda.so │ │
//! │ │ (NVIDIA Driver)│ │
//! │ └────────────────┘ │
//! └──────────────────────────────────────────────┘
//! ```
//!
//! ## Quick Start — portable compute (works on macOS)
//!
//! [`compute::default_backend`] probes the machine and returns the best
//! backend it can actually open, already initialized: an NVIDIA GPU through
//! CUDA, an Apple GPU through Metal (feature `metal`), and otherwise the
//! pure-Rust [`CpuBackend`](backend::CpuBackend). It never returns
//! `NotInitialized` just because there is no NVIDIA driver.
//!
//! ```
//! use oxicuda::backend::{ComputeBackend, UnaryOp};
//!
//! fn main() -> oxicuda::backend::BackendResult<()> {
//! let backend = oxicuda::compute::default_backend()?;
//! println!("computing on the {} backend", backend.name());
//!
//! let values = [-1.5f32, 0.0, 2.5, 4.0];
//! let bytes = std::mem::size_of_val(&values);
//! let host: Vec<u8> = values.iter().flat_map(|v| v.to_ne_bytes()).collect();
//!
//! let input = backend.alloc(bytes)?;
//! let output = backend.alloc(bytes)?;
//! backend.copy_htod(input, &host)?;
//! backend.unary(UnaryOp::Relu, input, output, values.len())?;
//! backend.synchronize()?;
//!
//! let mut result = vec![0u8; bytes];
//! backend.copy_dtoh(&mut result, output)?;
//! let relu: Vec<f32> = result
//! .chunks_exact(4)
//! .map(|c| f32::from_ne_bytes([c[0], c[1], c[2], c[3]]))
//! .collect();
//! assert_eq!(relu, vec![0.0, 0.0, 2.5, 4.0]);
//!
//! backend.free(input)?;
//! backend.free(output)?;
//! Ok(())
//! }
//! ```
//!
//! ## macOS
//!
//! The CUDA driver API does not exist on macOS: [`init`] and every
//! `oxicuda-driver` entry point return `Err(CudaError::NotInitialized)` there.
//! The compute-backend path above is the supported way to use a Mac's GPU:
//!
//! ```toml
//! [dependencies]
//! oxicuda = { version = "0.5", features = ["metal"] }
//! ```
//!
//! With that feature, [`compute::default_backend`] returns a
//! `MetalBackend` bound to the Apple GPU. Honest scope, as of this release:
//!
//! * **GPU-executed through Metal**: `gemm`, `batched_gemm`, the element-wise
//! `unary` / `binary` ops, and the axis `reduce` ops.
//! * **Not accelerated**: `conv2d_forward` and `attention` currently run on the
//! host inside the Metal backend, and `softmax`, `gather`, `scatter`,
//! `gemm_mixed_precision` and the `conv2d` backward passes return
//! [`BackendError::Unsupported`](backend::BackendError).
//! * **Not routed through Metal at all**: the `blas`, `dnn`, `fft`, `sparse`,
//! `solver` and `rand` features are built on the CUDA driver path, so on
//! macOS they still fail with `NotInitialized`. Use the
//! [`ComputeBackend`](backend::ComputeBackend) API for GPU work on a Mac.
//!
//! Without the `metal` feature nothing breaks — selection simply falls through
//! to the CPU backend, which computes correctly everywhere.
//!
//! ## Quick Start — CUDA driver API
//!
//! ```no_run
//! use oxicuda::prelude::*;
//!
//! fn main() -> CudaResult<()> {
//! // Initialize the CUDA driver
//! oxicuda::init()?;
//!
//! // Enumerate devices
//! let device = Device::get(0)?;
//! println!("GPU: {}", device.name()?);
//!
//! // Create context and stream
//! let ctx = Context::new(&device)?;
//! let ctx = std::sync::Arc::new(ctx);
//! let stream = Stream::new(&ctx)?;
//!
//! // Allocate device memory
//! let mut buf = DeviceBuffer::<f32>::alloc(1024)?;
//! let host_data = vec![1.0f32; 1024];
//! buf.copy_from_host(&host_data)?;
//!
//! Ok(())
//! }
//! ```
//!
//! ## Feature Flags
//!
//! | Feature | Description | Default |
//! |---------|-------------|---------|
//! | `driver` | CUDA driver API wrapper | Yes |
//! | `memory` | GPU memory management | Yes |
//! | `launch` | Kernel launch infrastructure | Yes |
//! | `ptx` | PTX code generation DSL | No |
//! | `autotune` | Autotuner engine | No |
//! | `blas` | cuBLAS equivalent | No |
//! | `dnn` | cuDNN equivalent | No |
//! | `fft` | cuFFT equivalent | No |
//! | `sparse` | cuSPARSE equivalent | No |
//! | `solver` | cuSOLVER equivalent | No |
//! | `rand` | cuRAND equivalent | No |
//! | `pool` | Stream-ordered memory pool | No |
//! | `metal` | Apple Metal compute backend (macOS GPU) | No |
//! | `webgpu` | WebGPU / `wgpu` compute backend | No |
//! | `vulkan` | Vulkan compute backend | No |
//! | `rocm` | AMD ROCm/HIP compute backend | No |
//! | `level-zero` | Intel Level Zero compute backend | No |
//! | `backend` | No-op; the [`backend`] module is always available | No |
//! | `full` | Enable all features | No |
//!
//! (C) 2026 COOLJAPAN OU (Team KitaSan)
// ─── Global initialization with device auto-selection ───────
/// Global initialization with device auto-selection.
///
/// Provides [`lazy_init`](global_init::lazy_init),
/// [`OxiCudaRuntimeBuilder`](global_init::OxiCudaRuntimeBuilder), and
/// related helpers for one-call GPU setup.
pub use ;
// ─── Profiling & tracing ────────────────────────────────────
/// Profiling and tracing hooks for kernel-level performance analysis.
///
/// Provides chrome://tracing compatible output for visualizing GPU kernel
/// execution, memory transfers, and synchronization events.
// ─── Multi-GPU device pool ─────────────────────────────────
/// Thread-safe multi-GPU device pool with workload-aware scheduling.
///
/// Provides [`MultiGpuPool`](device_pool::MultiGpuPool),
/// [`DeviceSelectionPolicy`](device_pool::DeviceSelectionPolicy),
/// [`GpuLease`](device_pool::GpuLease), and
/// [`WorkloadBalancer`](device_pool::WorkloadBalancer).
// ─── Abstract compute backend ───────────────────────────────
/// Abstract compute backend for GPU-accelerated operations.
///
/// Provides the [`ComputeBackend`](backend::ComputeBackend) trait that
/// higher-level crates use for GPU dispatch without coupling to a specific
/// GPU API, the always-available [`CpuBackend`](backend::CpuBackend), the
/// [`BackendRegistry`](backend::BackendRegistry) control plane, and the
/// concrete backends enabled by feature flags.
///
/// Always available: `oxicuda-backend` is a mandatory dependency, so the
/// abstraction costs nothing to expose. (The `backend` feature is kept as a
/// no-op for compatibility with dependants that name it.)
/// Ready-to-use backend selection: probe this machine and return the best
/// initialised [`ComputeBackend`](backend::ComputeBackend).
///
/// See [`compute::default_backend`] — the one call that turns
/// `cargo add oxicuda` into a working compute path on any platform,
/// including macOS.
/// ONNX GPU inference backend.
///
/// Provides a complete ONNX operator runtime with IR types, 60+ operators,
/// graph executor, memory planner, operator fusion, and shape inference.
/// ToRSh GPU tensor backend with autograd, optimizers, and mixed precision.
///
/// Provides [`GpuTensor`](tensor_backend::GpuTensor), an autograd tape,
/// forward/backward ops (matmul, conv2d, softmax, loss functions, etc.),
/// optimizers (SGD, Adam, AdaGrad, RMSProp, LAMB), and mixed-precision
/// training (GradScaler, Autocast).
/// TrustformeRS Transformer GPU Backend.
///
/// Provides transformer model inference infrastructure: paged KV-cache,
/// continuous batching, speculative decoding, attention dispatch,
/// token sampling, and quantized inference.
/// WASM + WebGPU compute backend for browser environments.
///
/// Wraps [`oxicuda_webgpu::WebGpuBackend`] with WASM-specific bindings,
/// making the OxiCUDA compute API usable from a browser via WebAssembly.
/// On native targets the module is still available and compiles cleanly;
/// the `#[wasm_bindgen]` exports are only emitted when targeting `wasm32`.
pub use WasmComputeBackend;
// ─── Collective communication (NCCL equivalent) ────────────
/// NCCL-equivalent collective communication primitives for multi-GPU training.
///
/// Provides AllReduce, AllGather, ReduceScatter, Broadcast, Reduce, and
/// AllToAll with ring / tree / recursive-halving algorithm support.
/// Pipeline parallelism primitives for multi-GPU model parallelism.
///
/// Provides scheduling algorithms (GPipe, 1F1B, Interleaved, ZeroBubble),
/// bubble analysis, activation checkpointing, and ASCII visualization.
/// Multi-node distributed training support (TCP/IP based).
///
/// Provides [`DistributedRuntime`](distributed::DistributedRuntime),
/// [`TcpStore`](distributed::TcpStore), [`FileStore`](distributed::FileStore),
/// [`GradientBucket`](distributed::GradientBucket), and
/// [`DistributedOptimizer`](distributed::DistributedOptimizer) for
/// coordinating training across multiple machines.
// ─── Core crates (always available) ─────────────────────────
/// CUDA Driver API wrapper.
pub use oxicuda_driver as driver;
/// GPU memory management.
pub use oxicuda_memory as memory;
/// Kernel launch infrastructure.
pub use oxicuda_launch as launch;
// ─── Optional crates (feature-gated) ────────────────────────
/// NVRTC runtime JIT compiler (CUDA-C source → PTX).
pub use oxicuda_nvrtc as nvrtc;
/// PTX code generation DSL.
pub use oxicuda_ptx as ptx;
/// Autotuner engine.
pub use oxicuda_autotune as autotune;
/// GPU-accelerated BLAS operations.
pub use oxicuda_blas as blas;
/// GPU-accelerated deep learning primitives.
pub use oxicuda_dnn as dnn;
/// GPU-accelerated FFT operations.
pub use oxicuda_fft as fft;
/// GPU-accelerated sparse matrix operations.
pub use oxicuda_sparse as sparse;
/// GPU-accelerated matrix decompositions.
pub use oxicuda_solver as solver;
/// GPU-accelerated random number generation.
pub use oxicuda_rand as rand;
/// CUB-equivalent high-performance parallel GPU primitives.
///
/// Provides PTX code generators for warp, block, and device-wide reduce, scan,
/// histogram, radix sort, and merge sort — all without any CUDA SDK dependency.
pub use oxicuda_primitives as primitives;
/// Vulkan Compute backend for cross-vendor GPU compute.
pub use oxicuda_vulkan as vulkan;
/// Apple Metal Compute backend (macOS/iOS).
pub use oxicuda_metal as metal_backend;
/// WebGPU Compute backend (cross-platform via wgpu).
pub use oxicuda_webgpu as webgpu;
/// AMD ROCm/HIP Compute backend (Linux with AMD GPU).
pub use oxicuda_rocm as rocm;
/// Intel Level Zero Compute backend (Linux/Windows with Intel GPU).
pub use oxicuda_levelzero as level_zero;
// ─── Key type re-exports ─────────────────────────────────────
// Error types
pub use ;
// Core types
pub use ;
pub use ;
// Memory types
pub use copy;
pub use ;
// Launch types
pub use ;
// Re-export the launch! macro
pub use launch;
/// Initialize the CUDA driver API.
///
/// This must be called before any other OxiCUDA function.
/// It dynamically loads `libcuda.so` (Linux), `nvcuda.dll` (Windows),
/// and initializes the CUDA driver.
///
/// Returns `Err(CudaError::NotInitialized)` on macOS or systems
/// without an NVIDIA GPU.
/// Compile-time feature availability.
// ---------------------------------------------------------------------------
// ComputeBackend auto-selection threshold
// ---------------------------------------------------------------------------
/// Auto-selection threshold for the compute backend, in bytes.
///
/// [`compute::backend_for_workload`] sends a workload whose total buffer
/// footprint is **below** this threshold to the CPU backend, and one at or
/// above it to the best GPU backend available. The 64 KiB default is tuned for
/// SciRS2 workloads, where the host↔device copies and the dispatch round-trip
/// cost more than the kernel saves for small matrices.
///
/// # Why this is a selection-time and not a per-operation decision
///
/// A device pointer belongs to the backend that allocated it: the CPU backend
/// cannot read a Metal buffer handle and vice versa. Routing individual
/// operations by size would therefore require every buffer to exist on both
/// backends and be kept in sync — far more traffic than the threshold saves.
/// So the choice is made **once**, before anything is allocated, and the whole
/// workload (buffers included) runs on the backend that was picked.
///
/// ```
/// use oxicuda::backend::{BackendKind, SelectionRequest};
///
/// // The same policy is available on any registry, not just the default one.
/// let small = SelectionRequest::any().for_workload(4096, oxicuda::AUTO_SELECT_THRESHOLD_BYTES);
/// assert_eq!(small.pin, Some(BackendKind::Cpu));
/// ```
pub const AUTO_SELECT_THRESHOLD_BYTES: usize = 64 * 1024; // 65536 bytes
// ---------------------------------------------------------------------------
// ONNX supported operator list
// ---------------------------------------------------------------------------
/// List of ONNX operators supported by the OxiCUDA ONNX backend.
///
/// This is the canonical list used both for operator dispatch and for
/// validating ONNX model compatibility.
pub const SUPPORTED_ONNX_OPS: & = &;
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
/// Convenience re-exports for common usage patterns.
///
/// ```no_run
/// use oxicuda::prelude::*;
/// ```