singe-cuda
Safe Rust wrappers for the CUDA driver and runtime APIs.
This crate provides:
- CUDA resources: devices, shared contexts, green contexts, streams, and events.
- Typed memory: device buffers and views, a pooled pinned host allocator, managed memory, stream-ordered allocations, peer copies, and virtual memory mappings.
- Kernel execution: runtime compilation with NVRTC and NVVM, module loading, JIT linking with nvJitLink, and typed launch methods through
cuda_module!. - Asynchronous work: composable operations with blocking or async completion, plus CUDA graph capture, construction, and replay.
- Sharing: interprocess memory and event handles, external memory and semaphores, and fabric multicast allocations.
- Profiling and interoperability: NVTX annotations, profiler control, and optional adapters for
cuda-coreandcudarc.
Example
Copy values to the GPU, read them back, and print the CUDA runtime version:
use ;
DeviceMemory owns the allocation and keeps its context alive.
from_slice waits for the upload, and copy_to_host_vec waits for the readback.
The unsafe forms that only enqueue work are named *_async, such as DeviceMemory::set_value_async and the launch methods cuda_module! generates.
Device information
Query the installed CUDA versions and the properties of each GPU:
use ;
println!;
for ordinal in 0..count?
device_query prints the full list of properties.
Streams and events
Split work across streams and time it with events.
use ;
let streams = ;
let start = context.create_event?;
let stop = context.create_event?;
start.record?;
streams.wait_event?;
for in streams.iter.zip
let done = context.create_event?;
done.record?;
streams.wait_event?;
stop.record?;
stop.synchronize?;
println!;
wait_event orders one stream after another without blocking the host.
sync_scope runs a closure and waits for the stream to finish before returning, even when the closure fails.
Asynchronous copies inside the closure can borrow ordinary host arrays, because the borrow checker keeps them alive and unchanged until the scope ends:
let a = ;
let b = ;
let mut a_device = zeroed?;
let mut b_device = zeroed?;
stream.sync_scope?;
let mut result = ;
stream.sync_scope?;
assert_eq!;
To run host code once a stream reaches a point, enqueue a closure with launch_host_func:
use mpsc;
let = channel;
stream.launch_host_func?;
assert_eq!;
The closure runs on a CUDA thread and must not call CUDA itself.
Asynchronous work
Compose an upload and a readback into one operation, then await it:
use ;
let upload = create?;
drop; // the upload already copied it into pinned staging memory
let output = upload.then.submit_on?.await?;
The operation owns its staging and device buffers until the result is ready.
To spread independent jobs over several streams, submit them to a StreamPool:
use StreamPool;
let pool = create?;
let mut submissions = Vecnew;
for job in 0..8_u32
// Every job is submitted before the first wait, so the streams run them concurrently.
for in submissions
CUDA graphs
Record kernel launches once and replay them with little CPU overhead.
use ;
let graph = stream.capture?;
let executable = graph.instantiate?;
for _ in 0..5
stream.synchronize?;
With cuda_module! macro, the generated _record method takes the capture scope first, then the same arguments as the _async launch without its stream.
Capturing records the work without running it.
See graph_replay for the complete program.
Memory pools
Allocate and free on a stream from a memory pool, so repeated allocations reuse the pool's memory.
Assume pool is a MemoryPool created for the device:
use ;
let mut buffer = zeroed_in_pool?;
buffer.set_value?;
assert_eq!;
buffer.release?;
The memory_pool example also creates the pool, keeps memory reserved between allocations, and trims it at the end.
Pinned host memory
Ordinary host memory is pageable. The OS may move it or swap it out, so the GPU cannot read it directly. CUDA copies pageable memory through a pinned staging buffer of its own, and an asynchronous copy from pageable memory may block the calling thread until the data is staged.
Pinned (or page-locked) memory stays in physical memory at a fixed address, so the GPU reads and writes it directly. Copies to and from it run at higher bandwidth, and an asynchronous copy returns at once, overlapping with other work. The OS can't page pinned memory, so use it for buffers that move data to and from the GPU, not for everything. Allocating it is also slower than ordinary allocation, which is why each context keeps a pool of it.
Context::pinned_host returns the allocator for that pool, a std::alloc::Allocator.
A Vec that uses it is a PinnedVec, which pinned copies accept:
use ;
let pinned = context.pinned_host;
let mut input: = Vecnew_in;
input.extend;
let mut device = zeroed?;
stream.sync_scope?;
let mut output = pinned.?;
device.copy_to_pinned?;
assert_eq!;
A PinnedVec is an ordinary Vec otherwise.
Dropping one returns its memory to the pool without a CUDA call, so short-lived buffers are cheap, and release_cached gives memory nothing uses back to CUDA.
A Vec that fails to grow aborts the process, as with any allocator.
with_capacity, from_slice, and zeroed return an error instead, so use them when the size is known up front.
The pool does not know which buffers queued GPU work still uses, so keep a buffer alive until that work finishes; sync_scope and submissions do this for you.
The pool's memory is also mapped into the device's address space.
PinnedVecExt::mapped_device_view and mapped_device_view_mut give a kernel or copy direct access to a PinnedVec, with no copy to device memory first.
Every such access crosses the bus, so a view suits data the device touches once, such as a few values a kernel reports back.
See pinned_memory for the complete program.
Typed kernels
With the macros feature, cuda_module! reads the kernel's parameter list and generates Rust methods with matching argument types.
Marking a pointer read, write, or read_write decides how the methods borrow the buffer.
cuda_module!
let x = from_slice?;
let mut y = from_slice?;
let module = create?;
let config = for_1d_grid;
// SAFETY: the kernel checks bounds, and `stream.synchronize` waits for it.
unsafe ;
stream.synchronize?;
assert_eq!;
Note; writing CUDA code like this isn't necessary, obviously.
You can write it in CUDA C++ and use cc to build and link it with your Rust crate.
Here x is borrowed immutably and y mutably, so passing a DeviceMemory<f64> or the same buffer twice fails to compile.
A write parameter also accepts uninitialized memory, such as DeviceMemory<MaybeUninit<f32>>, which cannot be read back until it is marked initialized.
Each kernel gets unsafe launch methods with the same kernel arguments: saxpy_async for a chosen stream, saxpy_record for graph capture, saxpy_node for graph construction, and saxpy_set_node_params for updating an executable graph's node.
A pointer parameter without an element type, such as void*, takes a raw pointer instead of a view.
Custom types
With the macros feature, derive the device representation traits for a #[repr(C)] struct to copy it to the GPU and pass it to kernels.
DeviceRepr fails to compile for a struct with implicit padding, and every derive requires each field to implement the same trait:
use ;
cuda_module!
let particles = ;
let mut device_particles = from_slice?;
let physics = create?;
let config = for_1d_grid;
// SAFETY: the kernel checks bounds, and `stream.synchronize` waits for it.
unsafe ;
stream.synchronize?;
assert_eq!;
The type in read_write(...) is resolved inside the generated module, hence super::.
Interoperability
Enable the interop_cuda_core or interop_cudarc feature to use singe-cuda alongside those crates.
The snippet uses both features:
// Hand a singe-cuda context and stream to cuda-core.
let device = context.to_cuda_core?;
let foreign_stream = stream.to_cuda_core?;
// Wrap a cudarc context in a singe-cuda context.
let context = from_cudarc?;
The adapters keep the original owner alive, so neither side releases a context or stream the other is still using.
Memory and safety
Every resource keeps its CUDA context alive.
Safe calls wait for their GPU work, sync_scope borrows its buffers until the stream finishes, and a submitted operation owns its buffers until its result is ready.
Nothing keeps a buffer alive for an unsafe *_async call, a generated kernel launch, or a graph launch.
The caller keeps every buffer valid, and conflicting accesses ordered, until that work finishes, including every graph replay.
Only types that implement DeviceRepr can be transferred, and its derive checks the layout of your own structs.
Raw kernel launches and external pointers are unsafe.
The caller must make sure every access stays in bounds.
Features
macros: re-exports theDeviceReprderives andcuda_module!fromsinge-cuda-macros;cuda_module!also needs the defaultnvrtc_13_4feature.interop_cuda_core: adapters between this crate's contexts and streams andcuda-core's.interop_cudarc: adapters between this crate's contexts and streams andcudarc's.
More examples
- Device query: print the driver and runtime versions and each GPU's properties.
- Vector addition: compile a kernel with
cuda_module!, add two vectors on the device, and check the result, with--features macros. - Streams and events: run work across streams and measure completion time, with
--features macros. - Graph replay: capture a kernel and replay it against the same device buffer, with
--features macros. - Owned transfers: compose an upload and readback, then await completion.
- Memory pool: reuse pool-backed allocations, free them on a stream, and trim unused memory.
- Pinned memory: fill a pinned vector, copy it through the device, and reuse the pool's memory.
- Stream pool: distribute independent jobs across streams and collect their results.