pub struct Context { /* private fields */ }Expand description
A shared CUDA driver context.
Unlike cuBLAS, cuDNN, cuFFT, and similar library handles, a CUDA context is the underlying execution environment for a device. It is intended to be shared by streams, modules, libraries, events, allocations, and higher-level library wrappers.
This type is therefore reference-counted by returning Arc<Self> from the constructors, and it remains Send + Sync.
Shared references do not mutate Rust-visible state on the Context object itself; methods such as bind update the calling thread’s current CUDA context in the driver.
Prefer one long-lived context per device and share it across dependent CUDA objects instead of creating many short-lived contexts.
Implementations§
Source§impl Context
impl Context
Sourcepub fn with_host_access<T>(
&self,
regions: &[DeviceRegion<'_>],
access: impl FnOnce() -> Result<T>,
) -> Result<T>
pub fn with_host_access<T>( &self, regions: &[DeviceRegion<'_>], access: impl FnOnce() -> Result<T>, ) -> Result<T>
Holds submitted accesses out of the supplied ranges while host code runs. Nested tracked access returns an error instead of waiting on its own host access guard.
§Errors
Returns Error::MemoryContextMismatch for a range belonging to another context, Error::ReentrantAccess for nested tracked access, or Error::LockPoisoned if tracking has failed or a tracking lock is poisoned.
Also propagates CUDA synchronization or event-query errors and errors returned by access.
The callback runs only after all required waits succeed.
Sourcepub unsafe fn with_synchronized_accesses<T, E>(
&self,
accesses: &[Access],
access: impl FnOnce() -> StdResult<T, E>,
) -> StdResult<T, E>
pub unsafe fn with_synchronized_accesses<T, E>( &self, accesses: &[Access], access: impl FnOnce() -> StdResult<T, E>, ) -> StdResult<T, E>
Waits for conflicting submitted uses and declared readiness streams, then holds these access declarations against concurrent tracked submissions while access runs.
The declarations retain context and ordering metadata, not allocation owners.
§Safety
Keep the declared storage live and obey each declaration’s access mode. Any asynchronous work using these ranges must complete before the callback returns or unwinds. Nested tracked access is rejected rather than waiting on its own guard.
§Errors
Converts tracking errors into E if a nonportable access belongs to another context, access is reentrant, tracking has failed, or a tracking lock is poisoned.
Also converts errors from synchronizing conflicting uses or readiness streams and querying completion events.
Errors returned by access pass through unchanged; the callback runs only after all required waits succeed.
Sourcepub fn enable_peer_access(
&self,
peer: &Self,
flags: PeerAccessFlags,
) -> Result<()>
pub fn enable_peer_access( &self, peer: &Self, flags: PeerAccessFlags, ) -> Result<()>
Enables this actual context to directly access peer allocations.
Already-enabled access succeeds.
The permission is unidirectional and persists until explicitly disabled or either context is destroyed.
Pool allocations additionally follow their pool’s access descriptors.
§Errors
Returns Error::OutOfRange for nondefault flags.
Also returns an error if this context cannot be bound or CUDA rejects peer access, for example because the device pair does not support it or the peer-access limit is reached.
Already-enabled access succeeds.
Sourcepub unsafe fn disable_peer_access(&self, peer: &Self) -> Result<()>
pub unsafe fn disable_peer_access(&self, peer: &Self) -> Result<()>
Disables this actual context’s direct access to peer allocations.
§Safety
Complete every access that relies on this permission, including graph replays, before disabling it. Do not use retained peer-copy objects or peer pointers again until access is re-enabled. Exclude concurrent uses.
§Errors
Returns an error if this context cannot be bound or CUDA cannot disable the permission, including when peer access is not enabled.
Sourcepub fn create() -> Result<Arc<Self>>
pub fn create() -> Result<Arc<Self>>
Retains the primary context of the calling thread’s current runtime device and makes it current.
The primary context is shared with the CUDA runtime and other libraries on the same device.
Use Self::create_dedicated for a separate execution environment.
§Errors
Propagates errors from querying the current runtime device or from Self::create_for_device.
Sourcepub fn create_dedicated(
device: Device,
flags: ContextFlags,
) -> Result<Arc<Self>>
pub fn create_dedicated( device: Device, flags: ContextFlags, ) -> Result<Arc<Self>>
Creates a new context for device with flags and makes it current on the calling thread.
The last owning wrapper destroys this context. It is a separate execution environment from the device’s primary context and from other created contexts.
§Errors
Returns an error if CUDA initialization or context creation fails, including invalid creation flags, an unavailable device, or insufficient resources.
Returns Error::NullHandle if CUDA reports success with a null context handle.
Sourcepub fn create_for_device(device: Device) -> Result<Arc<Self>>
pub fn create_for_device(device: Device) -> Result<Arc<Self>>
Retains the primary context for device and makes it current on the calling thread.
The device’s primary context is shared with the CUDA runtime. Dropping the last owning wrapper releases this retain; other native retainers may keep the context alive.
§Errors
Returns an error if CUDA initialization, retaining the primary context, or setting it current fails.
Returns Error::NullHandle if CUDA reports success with a null context handle.
Sourcepub fn bind(&self) -> Result<()>
pub fn bind(&self) -> Result<()>
Binds this CUDA context to the calling CPU thread.
The “current context” is thread-local driver state.
Calling this method does not mutate the Rust Context value itself; it makes this context current for subsequent CUDA driver and interoperating runtime calls on the current host thread.
§Errors
Returns an error if CUDA Driver cannot query or set the current context.
Sourcepub fn load_module(
self: &Arc<Self>,
image: &ModuleImage<'_>,
jit_options: JitOptions<'_>,
) -> Result<Module>
pub fn load_module( self: &Arc<Self>, image: &ModuleImage<'_>, jit_options: JitOptions<'_>, ) -> Result<Module>
Loads the corresponding module from the given image into this context with jit_options.
The image may be a cubin or fatbin as output by nvcc, or a NUL-terminated PTX string, either as output by nvcc or hand-written, or Tile IR data.
§Errors
Returns an error if the context cannot be bound, the JIT option count exceeds u32, CUDA rejects the image or JIT options, or a previous asynchronous launch reported an error.
Sourcepub fn create_graph(self: &Arc<Self>) -> Result<Graph>
pub fn create_graph(self: &Arc<Self>) -> Result<Graph>
Creates an empty CUDA graph associated with this context.
Prefer this over UnboundGraph::create for ordinary Singe code.
The returned graph carries its context association into instantiated executable graphs, allowing launches and uploads to reject streams from another context before calling CUDA.
§Errors
Returns an error if the context cannot be bound or CUDA cannot create the graph.
Sourcepub fn load_library(
self: &Arc<Self>,
image: &ModuleImage<'_>,
jit_options: JitOptions<'_>,
) -> Result<Library>
pub fn load_library( self: &Arc<Self>, image: &ModuleImage<'_>, jit_options: JitOptions<'_>, ) -> Result<Library>
Loads the corresponding library from the given image with jit_options, based on the application defined library loading mode:
- If module loading is set to EAGER by the environment variables described in “Module loading”, the library is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with
sys::cuLibraryUnload. - If the environment variables are set to LAZY, the library is not immediately loaded into existing contexts and is loaded only when a function is needed for that context, such as a kernel launch.
These environment variables are described in the CUDA programming guide under the “CUDA environment variables” section.
The code may be a cubin or fatbin emitted by nvcc, a NUL-terminated PTX string emitted by nvcc or written by hand, or Tile IR data. A fatbin must also contain relocatable code when doing separate compilation.
If the library contains managed variables and no device in the system supports them, this call returns crate::error::Status::NotSupported.
§Errors
Returns an error if the context cannot be bound, the JIT option count exceeds u32, or CUDA rejects the image, options, or required device features.
Returns Error::NullHandle if CUDA reports success with a null library handle.
CUDA may also report errors from previous asynchronous work.
Sourcepub fn load_library_from_file(self: &Arc<Self>, path: &str) -> Result<Library>
pub fn load_library_from_file(self: &Arc<Self>, path: &str) -> Result<Library>
Loads the corresponding library from the given file based on the application defined library loading mode:
- If module loading is set to EAGER by the environment variables described in “Module loading”, the library is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with
sys::cuLibraryUnload. - If the environment variables are set to LAZY, the library is not immediately loaded into existing contexts and is loaded only when a function is needed for that context, such as a kernel launch.
These environment variables are described in the CUDA programming guide under the “CUDA environment variables” section.
The file must be a cubin emitted by nvcc, a PTX file emitted by nvcc or written by hand, a fatbin emitted by nvcc or written by hand, or a Tile IR file. A fatbin must also contain relocatable code when doing separate compilation.
If the library contains managed variables and no device in the system supports them, this call returns crate::error::Status::NotSupported.
§Errors
Returns an error if this context cannot be bound, if path contains an interior NUL byte, or if CUDA Driver cannot load the library.
Sourcepub fn synchronize(&self) -> Result<()>
pub fn synchronize(&self) -> Result<()>
Blocks until the current context has completed all preceding requested tasks.
If the current context is the primary context, child contexts that have been created are also synchronized.
Context::synchronize returns an error if one of the preceding tasks failed.
If the context was created with ContextFlags::SCHEDULE_BLOCKING_SYNC, the CPU thread blocks until the GPU context has finished its work.
§Errors
Returns an error if the context cannot be bound, a preceding task failed, or a previous asynchronous launch reported an error.
Sourcepub fn flags(&self) -> Result<ContextFlags>
pub fn flags(&self) -> Result<ContextFlags>
Returns the flags of the current context.
See ContextFlags for flag values.
§Errors
Returns an error if the context cannot be bound, CUDA cannot query the flags, or a previous asynchronous launch reported an error.
Sourcepub fn limit(&self, limit: Limit) -> Result<usize>
pub fn limit(&self, limit: Limit) -> Result<usize>
Returns the current size of limit.
The supported Limit values are:
Limit::StackSize: stack size in bytes of each GPU thread.Limit::PrintfFifoSize: size in bytes of the FIFO used by theprintf()device system call.Limit::MallocHeapSize: size in bytes of the heap used by themalloc()andfree()device system calls.Limit::DevRuntimeSyncDepth: maximum grid depth at which a thread can issue the device runtime callDevice::synchronizeto wait on child grid launches to complete.Limit::DevRuntimePendingLaunchCount: maximum number of outstanding device runtime launches that can be made from this context.Limit::MaxL2FetchGranularity: L2 cache fetch granularity.Limit::PersistingL2CacheSize: persisting L2 cache size in bytes.
§Errors
Returns an error if the context cannot be bound, limit is unsupported, CUDA cannot query the limit, or a previous asynchronous launch reported an error.
Sourcepub fn set_limit(&self, limit: Limit, value: usize) -> Result<()>
pub fn set_limit(&self, limit: Limit, value: usize) -> Result<()>
Setting limit to value is a request by the application to update the current limit maintained by the context.
The driver may modify the requested value to meet hardware requirements, such as clamping to minimum or maximum values or rounding up to the nearest element size.
Use Context::limit to query the effective value.
Setting each Limit has its own restrictions.
-
Limit::StackSizecontrols the stack size in bytes of each GPU thread. The driver automatically increases the per-thread stack size for each kernel launch as needed. This size is not reset back to the original value after each launch. Setting this value will take effect immediately, and if necessary, the device will block until all preceding requested tasks are complete. -
Limit::PrintfFifoSizecontrols the size in bytes of the FIFO used by theprintf()device system call. ConfigureLimit::PrintfFifoSizebefore launching any kernel that uses theprintf()device system call; otherwisecrate::error::Status::InvalidValueis returned. -
Limit::MallocHeapSizecontrols the size in bytes of the heap used by themalloc()andfree()device system calls. ConfigureLimit::MallocHeapSizebefore launching any kernel that uses themalloc()orfree()device system calls; otherwisecrate::error::Status::InvalidValueis returned. -
Limit::DevRuntimeSyncDepthcontrols the maximum nesting depth of a grid at which a thread can safely callDevice::synchronize. Setting this limit must be performed before any launch of a kernel that uses the device runtime and callsDevice::synchronizeabove the default sync depth, two levels of grids. Calls toDevice::synchronizefail if this limit is violated. This limit can be set smaller than the default or up to the maximum launch depth of 24. Additional sync-depth levels require the driver to reserve large amounts of device memory that can no longer be used for application allocations. If these reservations of device memory fail,Context::set_limitreturnscrate::error::Status::OutOfMemory, and the limit can be reset to a lower value. This limit is only applicable to devices of compute capability < 9.0. Setting this limit on devices of other compute capability versions returnscrate::error::Status::UnsupportedLimit. -
Limit::DevRuntimePendingLaunchCountcontrols the maximum number of outstanding device runtime launches that can be made from the current context. A grid is outstanding from launch until it is known to have completed. Device runtime launches that violate this limit fail. If a module using the device runtime needs more pending launches than the default 2048 launches, this limit can be increased. Sustaining additional pending launches requires the driver to reserve larger amounts of device memory up front, which can no longer be used for allocations. If these reservations fail,Context::set_limitreturnscrate::error::Status::OutOfMemory, and the limit can be reset to a lower value. This limit is only applicable to devices of compute capability 3.5 and higher. Attempting to set this limit on devices of compute capability less than 3.5 returnscrate::error::Status::UnsupportedLimit. -
Limit::MaxL2FetchGranularitycontrols the L2 cache fetch granularity. Values can range from 0B to 128B. Performance hint that may be ignored or clamped depending on the platform. -
Limit::PersistingL2CacheSizecontrols size in bytes available for persisting L2 cache. Performance hint that may be ignored or clamped depending on the platform.
§Errors
Returns an error if the context cannot be bound, limit is unsupported, CUDA rejects the requested value, or a previous asynchronous launch reported an error.
Sourcepub const fn as_raw(&self) -> CUcontext
pub const fn as_raw(&self) -> CUcontext
Returns the borrowed native context handle.
The handle remains owned according to this wrapper’s RawContextOwnership.
Returning it does not retain the context or transfer release responsibility.
Sourcepub unsafe fn from_raw(raw: RawContext) -> Result<Arc<Self>>
pub unsafe fn from_raw(raw: RawContext) -> Result<Arc<Self>>
Takes ownership of a raw CUDA context.
§Safety
raw.handle must be a valid CUDA context for raw.device, and no other Rust wrapper may own the same release responsibility.
raw.ownership must match how the context should be released: a created context is destroyed, while a primary context has one retain released.
Borrowed contexts retain an external owner instead of acquiring release responsibility.
§Errors
Returns Error::NullHandle if raw.handle is null.
Sourcepub fn into_raw(this: Arc<Self>) -> StdResult<RawContext, Arc<Self>>
pub fn into_raw(this: Arc<Self>) -> StdResult<RawContext, Arc<Self>>
Transfers ownership of the raw CUDA context to the caller.
The caller becomes responsible for releasing the returned context according to the returned ownership mode. For borrowed contexts, keep the returned external token live while using the raw handle.
§Errors
Returns the context unchanged as Err if another clone still retains it.
Source§impl Context
impl Context
Sourcepub fn create_event(self: &Arc<Self>, flags: EventFlags) -> Result<Event>
pub fn create_event(self: &Arc<Self>, flags: EventFlags) -> Result<Event>
Creates an event in this context with the specified flags. Valid flags include:
EventFlags::DEFAULT: default event creation flag.EventFlags::BLOCKING_SYNC: the event uses blocking synchronization. A host thread that usesEvent::synchronizeto wait on an event created with this flag will block until the event actually completes.EventFlags::DISABLE_TIMING: the created event does not record timing data. Events created with this flag specified andEventFlags::BLOCKING_SYNCnot specified will provide the best performance when used withStream::wait_eventandEvent::query.EventFlags::INTERPROCESS: the created event may be shared with another process through anIpcEventHandle.EventFlags::INTERPROCESSmust be specified along withEventFlags::DISABLE_TIMING.
§Errors
Returns an error if the context cannot be bound, the flag combination is invalid, CUDA cannot create the event, or CUDA returns a null event handle.
CUDA may also report errors from previous asynchronous launches, internal runtime initialization errors such as crate::error::Status::NotInitialized, crate::error::Status::CallRequiresNewerDriver, or crate::error::Status::NoDevice, and callback diagnostics such as crate::error::Status::NotPermitted.
Source§impl Context
impl Context
Sourcepub fn from_cudarc(owner: Arc<CudaContext>) -> Result<Arc<Self>>
pub fn from_cudarc(owner: Arc<CudaContext>) -> Result<Arc<Self>>
Retains cudarc’s actual context, including independently created non-primary contexts.
§Errors
Returns an error if cudarc’s context handle is null.
Source§impl Context
impl Context
Sourcepub fn pinned_host(self: &Arc<Self>) -> PinnedHost
pub fn pinned_host(self: &Arc<Self>) -> PinnedHost
Returns the allocator for this context’s pinned host memory pool.
Source§impl Context
impl Context
Sourcepub fn default_memory_pool(self: &Arc<Self>) -> Result<MemoryPool>
pub fn default_memory_pool(self: &Arc<Self>) -> Result<MemoryPool>
Borrows the device’s default pool while retaining its CUDA context.
§Errors
Returns an error if the context cannot be bound, CUDA cannot look up the default pool, or CUDA returns a null handle.
Source§impl Context
impl Context
Sourcepub fn load_precompiled(
self: &Arc<Self>,
image: &PrecompiledImage<'_>,
) -> Result<Module>
pub fn load_precompiled( self: &Arc<Self>, image: &PrecompiledImage<'_>, ) -> Result<Module>
Loads a precompiled image while preserving producer policy and entry metadata. PTX policies requiring finalization use the existing nvJitLink integration. CUBIN and executable fatbin policies describe compilation already performed by the producer.
§Errors
Propagates context binding and module loading errors.
PTX with a nondefault compilation policy requires nvjitlink_13_4; without it, returns Error::Compiler.
With the feature enabled, device capability queries, target architecture parsing, native linker creation or finalization, and artifact-name conversion can also fail.
Source§impl Context
impl Context
Sourcepub fn load_nvrtc_module(
self: &Arc<Self>,
program: &Program,
output: OutputKind,
jit_options: JitOptions<'_>,
) -> Result<Module>
pub fn load_nvrtc_module( self: &Arc<Self>, program: &Program, output: OutputKind, jit_options: JitOptions<'_>, ) -> Result<Module>
Retrieves output from a compiled NVRTC program and loads it as a module with jit_options.
Only PTX, cubin, and Tile IR can be loaded directly.
LTO IR and OptiX IR are rejected; link LTO IR before loading it.
§Errors
Returns an error if output is LTO IR or OptiX IR, the artifact cannot be retrieved or is empty, the context cannot be bound, the JIT option count exceeds u32, CUDA rejects the image or JIT settings, or CUDA returns a null module handle.
Sourcepub fn load_nvrtc_library(
self: &Arc<Self>,
program: &Program,
output: OutputKind,
jit_options: JitOptions<'_>,
) -> Result<Library>
pub fn load_nvrtc_library( self: &Arc<Self>, program: &Program, output: OutputKind, jit_options: JitOptions<'_>, ) -> Result<Library>
Retrieves output from a compiled NVRTC program and loads it as a CUDA library with jit_options.
Only PTX, cubin, and Tile IR can be loaded directly.
LTO IR and OptiX IR are rejected; link LTO IR before loading it.
See Self::load_library for eager and lazy loading behavior.
§Errors
Returns an error if output is LTO IR or OptiX IR, the artifact cannot be retrieved or is empty, or Self::load_library fails.
Source§impl Context
impl Context
Sourcepub fn create_stream(self: &Arc<Self>, options: StreamOptions) -> Result<Stream>
pub fn create_stream(self: &Arc<Self>, options: StreamOptions) -> Result<Stream>
Creates an asynchronous stream in this context and makes this context current on the calling thread.
StreamOptions::flags sets the stream’s synchronization with the legacy default stream:
StreamFlags::DEFAULT: default stream creation behavior.StreamFlags::NON_BLOCKING: allows the created stream to run concurrently with the legacy default stream without implicit synchronization.
StreamOptions::priority sets the scheduling priority of work in the stream.
Priorities are a hint to run higher-priority work first when possible; they do not preempt running work or otherwise order execution.
Lower numbers are higher priorities, and 0 is the default priority.
Device::stream_priority_range reports the meaningful range, and CUDA clamps a priority outside it to the nearest end.
Priorities affect only compute kernels, not host-to-device or device-to-host memory operations.
§Errors
Returns an error if the context cannot be bound, CUDA cannot create the stream, CUDA returns a null stream handle, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
Source§impl Context
impl Context
Sourcepub fn synchronize_or_abort(&self)
pub fn synchronize_or_abort(&self)
Waits for all queued work in this context, or prints the error and aborts the process if the wait fails.
Cleanup code calls this before releasing borrowed storage that queued work may still access.
Trait Implementations§
impl Eq for Context
impl Send for Context
impl Sync for Context
Auto Trait Implementations§
impl !Freeze for Context
impl !RefUnwindSafe for Context
impl !UnwindSafe for Context
impl Forget for Context
impl Move for Context
impl Unpin for Context
impl UnsafeUnpin for Context
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.