runtime_v2#

See also

See the migration guide for the differences between this module and the legacy runtime module.

Data types used by CUDA Runtime#

ChannelFormatDesc

Empty-initialize an instance of cudaChannelFormatDesc.

ArraySparseProperties

Empty-initialize an instance of cudaArraySparseProperties.

ArrayMemoryRequirements

Empty-initialize an instance of cudaArrayMemoryRequirements.

PitchedPtr

Empty-initialize an array of cudaPitchedPtr.

Extent

Empty-initialize an instance of cudaExtent.

Pos

Empty-initialize an instance of cudaPos.

MemCpy3dParms

Empty-initialize an instance of cudaMemcpy3DParms.

MemCpyNodeParams

Empty-initialize an instance of cudaMemcpyNodeParams.

MemCpy3dPeerParms

Empty-initialize an instance of cudaMemcpy3DPeerParms.

MemsetParams

Empty-initialize an instance of cudaMemsetParams.

MemsetParamsV2

Empty-initialize an instance of cudaMemsetParamsV2.

AccessPolicyWindow

Empty-initialize an instance of cudaAccessPolicyWindow.

HostNodeParams

Empty-initialize an instance of cudaHostNodeParams.

HostNodeParamsV2

Empty-initialize an instance of cudaHostNodeParamsV2.

ResourceDesc

Empty-initialize an instance of cudaResourceDesc.

ResourceViewDesc

Empty-initialize an instance of cudaResourceViewDesc.

PointerAttributes

Empty-initialize an instance of cudaPointerAttributes.

FuncAttributes

Empty-initialize an instance of cudaFuncAttributes.

MemLocation

Empty-initialize an array of cudaMemLocation.

MemAccessDesc

Empty-initialize an array of cudaMemAccessDesc.

MemPoolProps

Empty-initialize an instance of cudaMemPoolProps.

MemPoolPtrExportData

Empty-initialize an instance of cudaMemPoolPtrExportData.

MemAllocNodeParams

Empty-initialize an instance of cudaMemAllocNodeParams.

MemAllocNodeParamsV2

Empty-initialize an instance of cudaMemAllocNodeParamsV2.

MemFreeNodeParams

Empty-initialize an instance of cudaMemFreeNodeParams.

MemCpyAttributes

Empty-initialize an array of cudaMemcpyAttributes.

Offset3d

Empty-initialize an instance of cudaOffset3D.

MemCpy3dOperand

Empty-initialize an instance of cudaMemcpy3DOperand.

MemCpy3dBatchOp

Empty-initialize an array of cudaMemcpy3DBatchOp.

MemCpyBatchNodeParams

Empty-initialize an instance of cudaMemcpyBatchNodeParams.

Uuid

Empty-initialize an instance of cudaUUID_t.

DeviceProp

Empty-initialize an instance of cudaDeviceProp.

IpcEventHandle

Empty-initialize an instance of cudaIpcEventHandle_t.

IpcMemHandle

Empty-initialize an instance of cudaIpcMemHandle_t.

MemFabricHandle

Empty-initialize an instance of cudaMemFabricHandle_t.

ExternalMemoryHandleDesc

Empty-initialize an instance of cudaExternalMemoryHandleDesc.

ExternalMemoryBufferDesc

Empty-initialize an instance of cudaExternalMemoryBufferDesc.

ExternalMemoryMipmappedArrayDesc

Empty-initialize an instance of cudaExternalMemoryMipmappedArrayDesc.

ExternalSemaphoreHandleDesc

Empty-initialize an instance of cudaExternalSemaphoreHandleDesc.

ExternalSemaphoreSignalParams

Empty-initialize an array of cudaExternalSemaphoreSignalParams.

ExternalSemaphoreWaitParams

Empty-initialize an array of cudaExternalSemaphoreWaitParams.

DevSmResource

Empty-initialize an instance of cudaDevSmResource.

DevWorkqueueConfigResource

Empty-initialize an instance of cudaDevWorkqueueConfigResource.

DevWorkqueueResource

Empty-initialize an instance of cudaDevWorkqueueResource.

DevSmResourceGroupParams

Empty-initialize an array of cudaDevSmResourceGroupParams.

DevResource

Empty-initialize an array of cudaDevResource.

LibraryHostUniversalFunctionAndDataTable

Empty-initialize an instance of cudalibraryHostUniversalFunctionAndDataTable.

KernelNodeParams

Empty-initialize an instance of cudaKernelNodeParams.

KernelNodeParamsV2

Empty-initialize an instance of cudaKernelNodeParamsV2.

ExternalSemaphoreSignalNodeParams

Empty-initialize an instance of cudaExternalSemaphoreSignalNodeParams.

ExternalSemaphoreSignalNodeParamsV2

Empty-initialize an instance of cudaExternalSemaphoreSignalNodeParamsV2.

ExternalSemaphoreWaitNodeParams

Empty-initialize an instance of cudaExternalSemaphoreWaitNodeParams.

ExternalSemaphoreWaitNodeParamsV2

Empty-initialize an instance of cudaExternalSemaphoreWaitNodeParamsV2.

ConditionalNodeParams

Empty-initialize an instance of cudaConditionalNodeParams.

ChildGraphNodeParams

Empty-initialize an instance of cudaChildGraphNodeParams.

EventRecordNodeParams

Empty-initialize an instance of cudaEventRecordNodeParams.

EventWaitNodeParams

Empty-initialize an instance of cudaEventWaitNodeParams.

GraphNodeParams

Empty-initialize an instance of cudaGraphNodeParams.

GraphEdgeData

Empty-initialize an array of cudaGraphEdgeData.

GraphInstantiateParams

Empty-initialize an instance of cudaGraphInstantiateParams.

GraphExecUpdateResultInfo

Empty-initialize an instance of cudaGraphExecUpdateResultInfo.

GraphKernelNodeUpdate

Empty-initialize an instance of cudaGraphKernelNodeUpdate.

LaunchMemSyncDomainMap

Empty-initialize an instance of cudaLaunchMemSyncDomainMap.

LaunchAttributeValue

Empty-initialize an instance of cudaLaunchAttributeValue.

LaunchAttribute

Empty-initialize an instance of cudaLaunchAttribute.

AsyncNotificationInfo

Empty-initialize an instance of cudaAsyncNotificationInfo_t.

TextureDesc

Empty-initialize an instance of cudaTextureDesc.

EglPlaneDesc

Empty-initialize an array of cudaEglPlaneDesc.

EglFrame

Empty-initialize an instance of cudaEglFrame.

Error

CUDA error types

ChannelFormatKind

Channel format kind

MemoryType

CUDA memory types

MemCpyKind

CUDA memory copy types

AccessProperty

Specifies performance hint with cudaAccessPolicyWindow for hitProp and missProp members.

StreamCaptureStatus

Possible stream capture statuses returned by cudaStreamIsCapturing

GraphRecaptureStatus

Possible recapture statuses that can be returned to the user callback

StreamCaptureMode

Possible modes for stream capture thread interactions.

SynchronizationPolicy

See cudaSynchronizationPolicy.

ClusterSchedulingPolicy

Cluster scheduling policies.

StreamUpdateCaptureDependenciesFlags

Flags for cudaStreamUpdateCaptureDependencies

UserObjectFlags

Flags for user objects for graphs

UserObjectRetainFlags

Flags for retaining user object references for graphs

HostTaskSyncMode

Flags for host task sync mode

GraphicsRegisterFlags

CUDA graphics interop register flags

GraphicsMapFlags

CUDA graphics interop map flags

GraphicsCubeFace

CUDA graphics interop array indices for cube maps

ResourceType

CUDA resource types

ResourceViewFormat

CUDA texture resource view formats

SharedMemoryMode

Shared memory related attributes for use with cuLaunchKernelEx

FuncAttribute

CUDA function attributes that can be set using cudaFuncSetAttribute

FuncCache

CUDA function cache configurations

SharedMemConfig

CUDA shared memory configuration [Deprecated]

SharedCarveout

Shared memory carveout configurations.

ComputeMode

CUDA device compute modes

Limit

CUDA Limits

MemoryAdvise

CUDA Memory Advise values

MemRangeAttribute

CUDA range attributes

FlushGPUDirectRDMAWritesOptions

CUDA GPUDirect RDMA flush writes APIs supported on the device

GPUDirectRDMAWritesOrdering

CUDA GPUDirect RDMA flush writes ordering features of the device

FlushGPUDirectRDMAWritesScope

CUDA GPUDirect RDMA flush writes scopes

FlushGPUDirectRDMAWritesTarget

CUDA GPUDirect RDMA flush writes targets

DeviceAttr

CUDA device attributes

MemPoolAttr

CUDA memory pool attributes

MemLocationType

Specifies the type of location

MemAccessFlags

Specifies the memory protection flags for mapping.

MemAllocationType

Defines the allocation types available

MemAllocationHandleType

Flags for specifying particular handle types

GraphMemAttributeType

Graph memory attributes

MemCpyFlags

Flags to specify for copies within a batch.

MemCpySrcAccessOrder

See cudaMemcpySrcAccessOrder.

MemCpy3dOperandType

These flags allow applications to convey the operand type for individual copies specified in cudaMemcpy3DBatchAsync.

DeviceP2PAttr

CUDA device P2P attributes

AtomicOperation

CUDA-valid Atomic Operations

AtomicOperationCapability

CUDA-valid Atomic Operation capabilities

ExternalMemoryHandleType

External memory handle types

ExternalSemaphoreHandleType

External semaphore handle types

DevSmResourceGroupFlags

Flags for a CUdevSmResource group

DevSmResourceSplitByCountFlags

See cudaDevSmResourceSplitByCount_flags.

DevResourceType

Type of resource

DevWorkqueueConfigScope

Sharing scope for workqueues

JitOption

Online compiler and linker options

LibraryOption

Library options to be specified with cudaLibraryLoadData() or cudaLibraryLoadFromFile()

JitCacheMode

Caching modes for dlcm

JitFallback

Cubin matching fallback strategies

CGScope

CUDA cooperative group scope

KernelFunctionType

CUDA Kernel Function Handle Type

GraphConditionalHandleFlags

See cudaGraphConditionalHandleFlags.

GraphConditionalNodeType

CUDA conditional node types

GraphNodeType

CUDA Graph node types

GraphChildGraphNodeOwnership

Child graph node ownership

GraphDependencyType

Type annotations that can be applied to graph edges as part of cudaGraphEdgeData.

GraphExecUpdateResult

CUDA Graph Update error types

GraphInstantiateResult

Graph instantiation results

GraphKernelNodeField

Specifies the field to update when performing multiple node updates from the device

GetDriverEntryPointFlags

Flags to specify search options to be used with cudaGetDriverEntryPoint For more details see cuGetProcAddress

DriverEntryPointQueryResult

Enum for status from obtaining driver entry points, used with cudaApiGetDriverEntryPoint

GraphDebugDotFlags

CUDA Graph debug write options

GraphInstantiateFlags

Flags for instantiating a graph

LaunchMemSyncDomain

Memory Synchronization Domain A kernel can be launched in a specified memory synchronization domain that affects all memory operations issued by that kernel.

LaunchAttributePortableClusterMode

Enum for defining applicability of portable cluster size, used with cudaLaunchKernelEx

LaunchAttributeID

Launch attributes enum; used as id field of cudaLaunchAttribute

DeviceNumaConfig

CUDA device NUMA config

AsyncNotificationType

Types of async notification that can occur

LogLevel

See cudaLogLevel.

FabricOpStatusSource

Fabric operation status source

FabricOpStatusInfo

Fabric operation status info

SurfaceBoundaryMode

CUDA Surface boundary modes

SurfaceFormatMode

CUDA Surface format modes

TextureAddressMode

CUDA texture address modes

TextureFilterMode

CUDA texture filter modes

TextureReadMode

CUDA texture read modes

EglFrameType

CUDA EglFrame type - array or pointer

EglResourceLocationFlags

Resource location flags- sysmem or vidmem For CUDA context on iGPU, since video and system memory are equivalent - these flags will not have an effect on the execution.

EglColorFormat

CUDA EGL Color Format - The different planar and multiplanar formats currently supported for CUDA_EGL interops.

ArrayFlags

Flags for malloc_array, malloc_3d_array and malloc_mipmapped_array (cudaArray*).

ArraySparsePropertiesFlags

Flags in ArraySparseProperties.flags_ (cudaArraySparseProperties*).

DataType

See cudaDataType.

DeviceFlags

Flags for set_device_flags and init_device (cudaDevice*).

Dim3

Empty-initialize an instance of dim3.

EmulationMantissaControl

Enum to configure the mantissa related parameters for floating-point emulation algorithms

EmulationSpecialValuesSupport

Enum to configure how special floating-point values will be handled by emulation algorithms

EmulationStrategy

Enum for specifying how to leverage floating-point emulation algorithms

EventFlags

Flags for event_create_with_flags (cudaEvent*).

EventRecordFlags

Flags for event_record_with_flags (cudaEventRecord*).

EventWaitFlags

Flags for stream_wait_event (cudaEventWait*).

ExternalMemoryFlags

Flags for ExternalMemoryHandleDesc.flags_ (cudaExternalMemory*).

ExternalSemaphoreSignalFlags

Flags for ExternalSemaphoreSignalParams.flags_ (cudaExternalSemaphoreSignal*).

ExternalSemaphoreWaitFlags

Flags for ExternalSemaphoreWaitParams.flags_ (cudaExternalSemaphoreWait*).

GLDeviceList

CUDA devices corresponding to the current OpenGL context

GLMapFlags

CUDA GL Map Flags

GraphKernelNodePort

Outgoing ports of a kernel node, for GraphEdgeData.from_port (cudaGraphKernelNodePort*).

GraphRecaptureCallbackData

Empty-initialize an instance of cudaGraphRecaptureCallbackData.

HostAllocFlags

Flags for host_alloc (cudaHostAlloc*).

HostRegisterFlags

Flags for host_register (cudaHostRegister*).

InitDeviceFlags

Flags for init_device (cudaInitDevice*).

IpcMemFlags

Flags for ipc_open_mem_handle (cudaIpcMem*).

KernelNodeAttrID

alias of LaunchAttributeID

KernelNodeAttrValue

alias of LaunchAttributeValue

MemAttachFlags

Flags for malloc_managed and stream_attach_mem_async (cudaMemAttach*).

MemPoolCreateUsage

Usage hints for MemPoolProps.usage (cudaMemPoolCreateUsage*).

NvSciSyncAttr

NvSciSync attribute directions (cudaNvSciSyncAttr*).

OccupancyFlags

Flags for occupancy_max_active_blocks_per_multiprocessor_with_flags (cudaOccupancy*).

PeerAccessFlags

Flags for device_enable_peer_access (cudaPeerAccess*).

RoundMode

See cudaRoundMode.

SpecialDevice

Special int device ordinals (cuda*DeviceId).

SpecialStream

Special streams, passed as a stream handle (cudaStream*).

StreamAttrID

alias of LaunchAttributeID

StreamAttrValue

alias of LaunchAttributeValue

StreamFlags

Flags for stream_create_with_flags (cudaStream*).

SurfaceType

Surface types, for ResourceDesc surfaces (cudaSurfaceType*).

TextureType

Texture types (cudaTextureType*).

Device Management#

This section describes the device management functions of the CUDA runtime application programming interface.

device_reset

Destroy all allocations and reset all state on the current device in the current process.

device_synchronize

Wait for compute device to finish.

device_set_limit

Set resource limits.

device_get_limit

Return resource limits.

device_get_texture_1d_linear_max_width

Returns the maximum number of elements allocatable in a 1D linear texture for a given element size.

device_get_cache_config

Returns the preferred cache configuration for the current device.

device_get_stream_priority_range

Returns numerical values that correspond to the least and greatest stream priorities.

device_set_cache_config

Sets the preferred cache configuration for the current device.

device_get_by_pci_bus_id

Returns a handle to a compute device.

device_get_pci_bus_id

Returns a PCI Bus Id string for the device.

ipc_get_event_handle

Gets an interprocess handle for a previously allocated event.

ipc_open_event_handle

Opens an interprocess event handle for use in the current process.

ipc_get_mem_handle

Gets an interprocess memory handle for an existing device memory allocation.

ipc_open_mem_handle

Opens an interprocess memory handle exported from another process and returns a device pointer usable in the local process.

ipc_close_mem_handle

Attempts to close memory mapped with cudaIpcOpenMemHandle.

device_flush_gpu_direct_rdma_writes

Blocks until remote writes are visible to the specified scope.

device_register_async_notification

Registers a callback function to receive async notifications.

device_unregister_async_notification

Unregisters an async notification callback.

get_device_count

Returns the number of compute-capable devices.

get_device_properties

Returns information about the compute-device.

device_get_attribute

Returns information about the device.

device_get_host_atomic_capabilities

Query atomic operation capabilities between host and device.

device_get_default_mem_pool

Returns the default mempool of a device.

device_set_mem_pool

Sets the current memory pool of a device.

device_get_mem_pool

Gets the current mempool for a device.

device_get_nv_sci_sync_attributes

Fill in NvSciSync attributes for the given CUDA device.

device_get_p2p_attribute

Queries attributes of the link between two devices.

device_get_p2p_atomic_capabilities

Query atomic operation capabilities between two devices.

choose_device

Select compute-device which best matches criteria.

init_device

Initialize device to be used for GPU executions.

set_device

Set device to be used for GPU executions.

get_device

Returns which device is currently being used.

set_device_flags

Sets flags to be used for device executions.

get_device_flags

Gets the flags for the current device.

Error Handling#

This section describes the error handling functions of the CUDA runtime application programming interface.

AddressOfConstantError

AlreadyAcquiredError

AlreadyMappedError

ApiFailureBaseError

ArrayIsMappedError

AssertError

CallRequiresNewerDriverError

CapturedEventError

CdpNotSupportedError

CdpVersionMismatchError

CompatNotSupportedOnDeviceError

ContainedError

ContextIsDestroyedError

CooperativeLaunchTooLargeError

CudaError

DeviceAlreadyInUseError

DeviceNotLicensedError

DeviceUninitializedError

DevicesUnavailableError

DuplicateSurfaceNameError

DuplicateTextureNameError

DuplicateVariableNameError

EccUncorrectableError

ExternalDeviceError

FabricNotReadyError

CudaFileNotFoundError

FunctionNotLoadedError

GraphExecUpdateFailureError

GraphRecaptureFailureError

HardwareStackError

HostMemoryAlreadyRegisteredError

HostMemoryNotRegisteredError

IllegalAddressError

IllegalInstructionError

IllegalStateError

IncompatibleDriverContextError

InitializationError

InsufficientDriverError

InsufficientLoaderVersionError

InvalidAddressSpaceError

InvalidChannelDescriptorError

InvalidClusterSizeError

InvalidConfigurationError

InvalidDeviceError

InvalidDeviceFunctionError

InvalidDevicePointerError

InvalidFilterSettingError

InvalidGraphicsContextError

InvalidHostPointerError

InvalidKernelImageError

InvalidMemcpyDirectionError

InvalidNormSettingError

InvalidPcError

InvalidPitchValueError

InvalidPtxError

InvalidResourceConfigurationError

InvalidResourceHandleError

InvalidResourceTypeError

InvalidSourceError

InvalidSurfaceError

InvalidSymbolError

InvalidTextureBindingError

InvalidTextureError

InvalidValueError

JitCompilationDisabledError

JitCompilerNotFoundError

LaunchFailureError

LaunchFileScopedSurfError

LaunchFileScopedTexError

LaunchIncompatibleTexturingError

LaunchMaxDepthExceededError

LaunchOutOfResourcesError

LaunchPendingCountExceededError

LaunchTimeoutError

LossyQueryError

MapBufferObjectFailedError

MemoryAllocationError

MemoryValueTooLargeError

MisalignedAddressError

MissingConfigurationError

MixedDeviceExecutionError

MpsClientTerminatedError

MpsConnectionFailedError

MpsMaxClientsReachedError

MpsMaxConnectionsReachedError

MpsRpcFailureError

MpsServerNotReadyError

NoDeviceError

NoKernelImageForDeviceError

NotMappedAsArrayError

NotMappedAsPointerError

NotMappedError

NotPermittedError

NotReadyError

NotSupportedError

NotYetImplementedError

NvlinkUncorrectableError

OperatingSystemError

PeerAccessAlreadyEnabledError

PeerAccessNotEnabledError

PeerAccessUnsupportedError

PriorLaunchFailureError

ProfilerAlreadyStartedError

ProfilerAlreadyStoppedError

ProfilerDisabledError

ProfilerNotInitializedError

SetOnActiveProcessError

SharedObjectInitFailedError

SharedObjectSymbolNotFoundError

SoftwareValidityNotEstablishedError

StartupFailureError

StreamCaptureImplicitError

StreamCaptureInvalidatedError

StreamCaptureIsolationError

StreamCaptureMergeError

StreamCaptureUnjoinedError

StreamCaptureUnmatchedError

StreamCaptureUnsupportedError

StreamCaptureWrongThreadError

StreamDetachedError

StubLibraryError

SymbolNotFoundError

SyncDepthExceededError

SynchronizationError

SystemDriverMismatchError

SystemNotReadyError

TensorMemoryLeakError

TextureFetchFailedError

TextureNotBoundError

CudaTimeoutError

TooManyPeersError

UnknownError

UnmapBufferObjectFailedError

UnsupportedDevSideSyncError

UnsupportedExecAffinityError

UnsupportedLimitError

UnsupportedPtxVersionError

VersionTranslationError

CudartUnloadingError

get_last_error

Returns the last error from a runtime call.

peek_at_last_error

Returns the last error from a runtime call.

get_error_name

Returns the string representation of an error code enum name.

get_error_string

Returns the description string for an error code.

Stream Management#

This section describes the stream management functions of the CUDA runtime application programming interface.

stream_create

Create an asynchronous stream.

stream_create_with_flags

Create an asynchronous stream.

stream_create_with_priority

Create an asynchronous stream with the specified priority.

stream_get_priority

Query the priority of a stream.

stream_get_flags

Query the flags of a stream.

stream_get_id

Query the Id of a stream.

stream_get_device

Query the device of a stream.

ctx_reset_persisting_l2cache

Resets all persisting lines in cache to normal status.

stream_copy_attributes

Copies attributes from source stream to destination stream.

stream_get_attribute

Queries stream attribute.

stream_set_attribute

Sets stream attribute.

stream_destroy

Destroys and cleans up an asynchronous stream.

stream_wait_event

Make a compute stream wait on an event.

stream_add_callback

Add a callback to a compute stream.

stream_synchronize

Waits for stream tasks to complete.

stream_query

Queries an asynchronous stream for completion status.

stream_query_no_raise

Queries an asynchronous stream for completion status.

stream_attach_mem_async

Attach memory to a stream asynchronously.

stream_begin_capture

Begins graph capture on a stream.

stream_begin_recapture_to_graph

Begin graph capture on a stream to an existing graph.

stream_begin_capture_to_graph

Begins graph capture on a stream to an existing graph.

thread_exchange_stream_capture_mode

Swap the stream capture interaction mode of the calling thread.

stream_end_capture

Ends capture on a stream, returning the captured graph.

stream_is_capturing

Returns a stream's capture status.

stream_get_capture_info

Query a stream's capture state.

stream_update_capture_dependencies

Update the set of dependencies in a capturing stream.

Event Management#

This section describes the event management functions of the CUDA runtime application programming interface.

event_create

Creates an event object.

event_create_with_flags

Creates an event object with the specified flags.

event_record

Records an event.

event_record_with_flags

Records an event.

event_query

Queries an event's status.

event_query_no_raise

Queries an event's status.

event_synchronize

Waits for an event to complete.

event_destroy

Destroys an event object.

event_elapsed_time

Computes the elapsed time between events.

External Resource Interoperability#

This section describes the external resource interoperability functions of the CUDA runtime application programming interface.

import_external_memory

Imports an external memory object.

external_memory_get_mapped_buffer

Maps a buffer onto an imported memory object.

external_memory_get_mapped_mipmapped_array

Maps a CUDA mipmapped array onto an external memory object.

destroy_external_memory

Destroys an external memory object.

import_external_semaphore

Imports an external semaphore.

signal_external_semaphores_async

Signals a set of external semaphore objects.

wait_external_semaphores_async

Waits on a set of external semaphore objects.

destroy_external_semaphore

Destroys an external semaphore.

Execution Control#

This section describes the execution control functions of the CUDA runtime application programming interface.

Some functions have overloaded C++ API template versions documented separately in the C++ API Routines module.

func_set_cache_config

Sets the preferred cache configuration for a device function.

func_get_attributes

Find out attributes for a given function.

func_set_attribute

Set attributes for a given function.

func_get_param_count

Returns the number of parameters used by the function.

launch_host_func

Enqueues a host function call in a stream.

launch_host_func_v2

Enqueues a host function call in a stream.

func_get_name

Returns the function name for a device entry function pointer.

func_get_param_info

Returns the offset and size of a kernel parameter in the device-side parameter layout.

Occupancy#

This section describes the occupancy calculation functions of the CUDA runtime application programming interface.

Besides the occupancy calculator functions (cudaOccupancyMaxActiveBlocksPerMultiprocessor and cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags), there are also C++ only occupancy-based launch configuration functions documented in C++ API Routines module.

See cudaOccupancyMaxPotentialBlockSize (C++ API), cudaOccupancyMaxPotentialBlockSize (C++ API), cudaOccupancyMaxPotentialBlockSizeVariableSMem (C++ API), cudaOccupancyMaxPotentialBlockSizeVariableSMem (C++ API) cudaOccupancyAvailableDynamicSMemPerBlock (C++ API),

occupancy_max_active_blocks_per_multiprocessor

Returns occupancy for a device function.

occupancy_available_dynamic_smem_per_block

Returns dynamic shared memory available per block when launching num_blocks blocks on SM.

occupancy_max_active_blocks_per_multiprocessor_with_flags

Returns occupancy for a device function with the specified flags.

Memory Management#

This section describes the memory management functions of the CUDA runtime application programming interface.

Some functions have overloaded C++ API template versions documented separately in the C++ API Routines module.

malloc_managed

Allocates memory that will be automatically managed by the Unified Memory system.

malloc

Allocate memory on the device.

malloc_host

Allocates page-locked memory on the host.

malloc_pitch

Allocates pitched memory on the device.

malloc_array

Allocate an array on the device.

free

Frees memory on the device.

free_host

Frees page-locked memory.

free_array

Frees an array on the device.

free_mipmapped_array

Frees a mipmapped array on the device.

host_alloc

Allocates page-locked memory on the host.

host_register

Registers an existing host memory range for use by CUDA.

host_unregister

Unregisters a memory range that was registered with cudaHostRegister.

host_get_device_pointer

Passes back device pointer of mapped host memory allocated by cudaHostAlloc or registered by cudaHostRegister.

host_get_flags

Passes back flags used to allocate pinned host memory allocated by cudaHostAlloc.

malloc_3d

Allocates logical 1D, 2D, or 3D memory objects on the device.

malloc_3d_array

Allocate an array on the device.

malloc_mipmapped_array

Allocate a mipmapped array on the device.

get_mipmapped_array_level

Gets a mipmap level of a CUDA mipmapped array.

memcpy_3d

Copies data between 3D objects.

memcpy_3d_peer

Copies memory between devices.

memcpy_3d_async

Copies data between 3D objects.

memcpy_3d_peer_async

Copies memory between devices asynchronously.

mem_get_info

Gets free and total device memory.

array_get_info

Gets info about the specified cudaArray.

array_get_plane

Gets a CUDA array plane from a CUDA array.

array_get_memory_requirements

Returns the memory requirements of a CUDA array.

mipmapped_array_get_memory_requirements

Returns the memory requirements of a CUDA mipmapped array.

array_get_sparse_properties

Returns the layout properties of a sparse CUDA array.

mipmapped_array_get_sparse_properties

Returns the layout properties of a sparse CUDA mipmapped array.

memcpy

Copies data between host and device.

memcpy_peer

Copies memory between two devices.

memcpy_2d

Copies data between host and device.

memcpy_2d_to_array

Copies data between host and device.

memcpy_2d_from_array

Copies data between host and device.

memcpy_2d_array_to_array

Copies data between host and device.

memcpy_async

Copies data between host and device.

memcpy_peer_async

Copies memory between two devices asynchronously.

memcpy_batch_async

Perform a batch of memory copies asynchronously.

memcpy_3d_batch_async

Performs a batch of 3D memory copies asynchronously.

memcpy_with_attributes_async

Performs asynchronous memory copy operation with the specified attributes.

memcpy_3d_with_attributes_async

Performs 3D asynchronous memory copy with the specified attributes.

memcpy_2d_async

Copies data between host and device.

memcpy_2d_to_array_async

Copies data between host and device.

memcpy_2d_from_array_async

Copies data between host and device.

memset

Initializes or sets device memory to a value.

memset_2d

Initializes or sets device memory to a value.

memset_3d

Initializes or sets device memory to a value.

memset_async

Initializes or sets device memory to a value.

memset_2d_async

Initializes or sets device memory to a value.

memset_3d_async

Initializes or sets device memory to a value.

mem_prefetch_async

Prefetches memory to the specified destination location.

mem_prefetch_batch_async

Performs a batch of memory prefetches asynchronously.

mem_discard_batch_async

Performs a batch of memory discards asynchronously.

mem_discard_and_prefetch_batch_async

Performs a batch of memory discards and prefetches asynchronously.

mem_get_location_info

Gets location information for a memory address range.

mem_advise

Advise about the usage of a given memory range.

mem_range_get_attribute

Return an attribute of a memory range.

mem_range_get_attributes

Return several attributes of a memory range, in one call.

make_pitched_ptr

Return a PitchedPtr.

make_pos

Return a Pos.

make_extent

Return an Extent.

Stream Ordered Memory Allocator#

overview

The asynchronous allocator allows the user to allocate and free in stream order. All asynchronous accesses of the allocation must happen between the stream executions of the allocation and the free. If the memory is accessed outside of the promised stream order, a use before allocation / use after free error will cause undefined behavior.

The allocator is free to reallocate the memory as long as it can guarantee that compliant memory accesses will not overlap temporally. The allocator may refer to internal stream ordering as well as inter-stream dependencies (such as CUDA events and null stream dependencies) when establishing the temporal guarantee. The allocator may also insert inter-stream dependencies to establish the temporal guarantee.

Supported Platforms

Whether or not a device supports the integrated stream ordered memory allocator may be queried by calling cudaDeviceGetAttribute() with the device attribute cudaDevAttrMemoryPoolsSupported.

malloc_async

Allocates memory with stream ordered semantics.

free_async

Frees memory with stream ordered semantics.

mem_pool_trim_to

Tries to release memory back to the OS.

mem_pool_set_attribute

Set an attribute of a memory pool.

mem_pool_get_attribute

Return an attribute of a memory pool (an int).

mem_pool_set_access

Controls visibility of pools between devices.

mem_pool_get_access

Returns the accessibility of a pool from a device.

mem_pool_create

Creates a memory pool.

mem_pool_destroy

Destroys the specified memory pool.

mem_get_default_mem_pool

Returns the default memory pool for a given location and allocation type.

mem_get_mem_pool

Gets the current memory pool for a given memory location and allocation type.

mem_set_mem_pool

Sets the current memory pool for a memory location and allocation type.

malloc_from_pool_async

Allocates memory from a specified pool with stream ordered semantics.

mem_pool_export_to_shareable_handle

Export a memory pool to an OS-specific shareable handle.

mem_pool_import_from_shareable_handle

imports a memory pool from a shared handle.

mem_pool_export_pointer

Export data to share a memory pool allocation between processes.

mem_pool_import_pointer

Import a memory pool allocation from another process.

Unified Addressing#

This section describes the unified addressing functions of the CUDA runtime application programming interface.

Overview

CUDA devices can share a unified address space with the host.

For these devices there is no distinction between a device pointer and a host pointer – the same pointer value may be used to access memory from the host program and from a kernel running on the device (with exceptions enumerated below).

Supported Platforms

Whether or not a device supports unified addressing may be queried by calling cudaGetDeviceProperties() with the device property cudaDeviceProp::unifiedAddressing.

Unified addressing is automatically enabled in 64-bit processes .

Looking Up Information from Pointer Values

It is possible to look up information about the memory which backs a pointer value. For instance, one may want to know if a pointer points to host or device memory. As another example, in the case of device memory, one may want to know on which CUDA device the memory resides. These properties may be queried using the function cudaPointerGetAttributes()

Since pointers are unique, it is not necessary to specify information about the pointers specified to cudaMemcpy() and other copy functions.

The copy direction cudaMemcpyDefault may be used to specify that the CUDA runtime should infer the location of the pointer from its value.

Automatic Mapping of Host Allocated Host Memory

All host memory allocated through all devices using cudaMallocHost() and cudaHostAlloc() is always directly accessible from all devices that support unified addressing. This is the case regardless of whether or not the flags cudaHostAllocPortable and cudaHostAllocMapped are specified.

The pointer value through which allocated host memory may be accessed in kernels on all devices that support unified addressing is the same as the pointer value through which that memory is accessed on the host. It is not necessary to call cudaHostGetDevicePointer() to get the device pointer for these allocations.

Note that this is not the case for memory allocated using the flag cudaHostAllocWriteCombined, as discussed below.

Direct Access of Peer Memory

Upon enabling direct access from a device that supports unified addressing to another peer device that supports unified addressing using cudaDeviceEnablePeerAccess() all memory allocated in the peer device using cudaMalloc() and cudaMallocPitch() will immediately be accessible by the current device. The device pointer value through which any peer’s memory may be accessed in the current device is the same pointer value through which that memory may be accessed from the peer device.

Exceptions, Disjoint Addressing

Not all memory may be accessed on devices through the same pointer value through which they are accessed on the host. These exceptions are host memory registered using cudaHostRegister() and host memory allocated using the flag cudaHostAllocWriteCombined. For these exceptions, there exists a distinct host and device address for the memory. The device address is guaranteed to not overlap any valid host pointer range and is guaranteed to have the same value across all devices that support unified addressing.

This device address may be queried using cudaHostGetDevicePointer() when a device using unified addressing is current. Either the host or the unified device pointer value may be used to refer to this memory in cudaMemcpy() and similar functions using the cudaMemcpyDefault memory direction.

pointer_get_attributes

Returns attributes about a specified pointer.

Peer Device Memory Access#

This section describes the peer device memory access functions of the CUDA runtime application programming interface.

device_can_access_peer

Queries if a device may directly access a peer device's memory.

device_enable_peer_access

Enables direct access to memory allocations on a peer device.

device_disable_peer_access

Disables direct access to memory allocations on a peer device.

OpenGL Interoperability#

This section describes the OpenGL interoperability functions of the CUDA runtime application programming interface. Note that mapping of OpenGL resources is performed with the graphics API agnostic, resource mapping interface described in Graphics Interopability.

cudaGLDeviceList.cudaGLDeviceListAll = <cudaGLDeviceList.cudaGLDeviceListAll: 1>#

The CUDA devices for all GPUs used by the current OpenGL context

cudaGLDeviceList.cudaGLDeviceListCurrentFrame = <cudaGLDeviceList.cudaGLDeviceListCurrentFrame: 2>#

The CUDA devices for the GPUs used by the current OpenGL context in its currently rendering frame

cudaGLDeviceList.cudaGLDeviceListNextFrame = <cudaGLDeviceList.cudaGLDeviceListNextFrame: 3>#

The CUDA devices for the GPUs to be used by the current OpenGL context in the next frame

gl_get_devices

Gets the CUDA devices associated with the current OpenGL context.

graphics_gl_register_image

Register an OpenGL texture or renderbuffer object.

graphics_gl_register_buffer

Registers an OpenGL buffer object.

VDPAU Interoperability#

This section describes the VDPAU interoperability functions of the CUDA runtime application programming interface.

vdpau_get_device

Gets the CUDA device associated with a VdpDevice.

vdpau_set_vdpau_device

Sets a CUDA device to use VDPAU interoperability.

graphics_vdpau_register_video_surface

Register a VdpVideoSurface object.

graphics_vdpau_register_output_surface

Register a VdpOutputSurface object.

EGL Interoperability#

This section describes the EGL interoperability functions of the CUDA runtime application programming interface.

graphics_egl_register_image

Registers an EGL image.

egl_stream_consumer_connect

Connect CUDA to EGLStream as a consumer.

egl_stream_consumer_connect_with_flags

Connect CUDA to EGLStream as a consumer with given flags.

egl_stream_consumer_disconnect

Disconnect CUDA as a consumer to EGLStream .

egl_stream_consumer_acquire_frame

Acquire an image frame from the EGLStream with CUDA as a consumer.

egl_stream_consumer_release_frame

Releases the last frame acquired from the EGLStream.

egl_stream_producer_connect

Connect CUDA to EGLStream as a producer.

egl_stream_producer_disconnect

Disconnect CUDA as a producer to EGLStream .

egl_stream_producer_present_frame

Present a CUDA eglFrame to the EGLStream with CUDA as a producer.

egl_stream_producer_return_frame

Return the CUDA eglFrame to the EGLStream last released by the consumer.

graphics_resource_get_mapped_egl_frame

Get an egl_frame through which to access a registered EGL graphics resource.

event_create_from_egl_sync

Creates an event from EGLSync object.

Graphics Interoperability#

This section describes the graphics interoperability functions of the CUDA runtime application programming interface.

graphics_unregister_resource

Unregisters a graphics resource for access by CUDA.

graphics_resource_set_map_flags

Set usage flags for mapping a graphics resource.

graphics_map_resources

Map graphics resources for access by CUDA.

graphics_unmap_resources

Unmap graphics resources.

graphics_resource_get_mapped_pointer

Get an device pointer through which to access a mapped graphics resource.

graphics_sub_resource_get_mapped_array

Get an array through which to access a subresource of a mapped graphics resource.

graphics_resource_get_mapped_mipmapped_array

Get a mipmapped array through which to access a mapped graphics resource.

Texture Object Management#

This section describes the low level texture object management functions of the CUDA runtime application programming interface. The texture object API is only supported on devices of compute capability 3.0 or higher.

get_channel_desc

Get the channel descriptor of an array.

create_channel_desc

Return a channel format descriptor.

create_texture_object

Creates a texture object.

destroy_texture_object

Destroys a texture object.

get_texture_object_resource_desc

Returns a texture object's resource descriptor.

get_texture_object_texture_desc

Returns a texture object's texture descriptor.

get_texture_object_resource_view_desc

Returns a texture object's resource view descriptor.

Surface Object Management#

This section describes the low level texture object management functions of the CUDA runtime application programming interface. The surface object API is only supported on devices of compute capability 3.0 or higher.

create_surface_object

Creates a surface object.

destroy_surface_object

Destroys a surface object.

get_surface_object_resource_desc

Returns a surface object's resource descriptor Returns the resource descriptor for the surface object specified by surf_object.

Version Management#

driver_get_version

Returns the latest version of CUDA supported by the driver.

runtime_get_version

Returns the CUDA Runtime version.

get_local_runtime_version

Return the version of the CUDA runtime this module was loaded against.

Error Log Management Functions#

This section describes the error log management functions of the CUDA runtime application programming interface. The Error Log Management interface will operate on both the CUDA Driver and CUDA Runtime.

logs_register_callback

Register a callback function to receive error log messages.

logs_unregister_callback

Unregister a log message callback.

logs_current

Sets log iterator to point to the end of log buffer, where the next message would be written.

logs_dump_to_file

Dump the runtime's error log buffer to a file.

logs_dump_to_memory

Dump accumulated driver logs into a buffer.

Graph Management#

This section describes the graph management functions of CUDA runtime application programming interface.

graph_create

Creates a graph.

graph_add_kernel_node

Creates a kernel execution node and adds it to a graph.

graph_kernel_node_get_params

Returns a kernel node's parameters.

graph_kernel_node_set_params

Sets a kernel node's parameters.

graph_kernel_node_copy_attributes

Copies attributes from source node to destination node.

graph_kernel_node_get_attribute

Queries node attribute.

graph_kernel_node_set_attribute

Sets node attribute.

graph_add_memcpy_node

Creates a memcpy node and adds it to a graph.

graph_add_memcpy_node_1d

Creates a 1D memcpy node and adds it to a graph.

graph_memcpy_node_get_params

Returns a memcpy node's parameters.

graph_memcpy_node_set_params

Sets a memcpy node's parameters.

graph_memcpy_node_set_params_1d

Sets a memcpy node's parameters to perform a 1-dimensional copy.

graph_add_memset_node

Creates a memset node and adds it to a graph.

graph_memset_node_get_params

Returns a memset node's parameters.

graph_memset_node_set_params

Sets a memset node's parameters.

graph_add_host_node

Creates a host execution node and adds it to a graph.

graph_host_node_get_params

Returns a host node's parameters.

graph_host_node_set_params

Sets a host node's parameters.

graph_add_child_graph_node

Creates a child graph node and adds it to a graph.

graph_child_graph_node_get_graph

Gets a handle to the embedded graph of a child graph node.

graph_add_empty_node

Creates an empty node and adds it to a graph.

graph_add_event_record_node

Creates an event record node and adds it to a graph.

graph_event_record_node_get_event

Returns the event associated with an event record node.

graph_event_record_node_set_event

Sets an event record node's event.

graph_add_event_wait_node

Creates an event wait node and adds it to a graph.

graph_event_wait_node_get_event

Returns the event associated with an event wait node.

graph_event_wait_node_set_event

Sets an event wait node's event.

graph_add_external_semaphores_signal_node

Creates an external semaphore signal node and adds it to a graph.

graph_external_semaphores_signal_node_get_params

Returns an external semaphore signal node's parameters.

graph_external_semaphores_signal_node_set_params

Sets an external semaphore signal node's parameters.

graph_add_external_semaphores_wait_node

Creates an external semaphore wait node and adds it to a graph.

graph_external_semaphores_wait_node_get_params

Returns an external semaphore wait node's parameters.

graph_external_semaphores_wait_node_set_params

Sets an external semaphore wait node's parameters.

graph_add_mem_alloc_node

Creates an allocation node and adds it to a graph.

graph_mem_alloc_node_get_params

Returns a memory alloc node's parameters.

graph_add_mem_free_node

Creates a memory free node and adds it to a graph.

graph_mem_free_node_get_params

Return the device address freed by a memory free node.

device_graph_mem_trim

Free unused memory that was cached on the specified device for use with graphs back to the OS.

device_get_graph_mem_attribute

Return a graph memory attribute of a device, in bytes.

device_set_graph_mem_attribute

Set a graph memory attribute of a device.

graph_clone

Clones a graph.

graph_node_find_in_clone

Finds a cloned version of a node.

graph_node_get_type

Returns a node's type.

graph_node_get_containing_graph

Returns the graph that contains a given graph node.

graph_node_get_local_id

Returns the node id of a given graph node.

graph_node_get_tools_id

Returns an id used by tools to identify a given node.

graph_get_id

Returns the id of a given graph.

graph_exec_get_id

Returns the id of a given graph exec.

graph_get_nodes

Returns a graph's nodes.

graph_get_root_nodes

Returns a graph's root nodes.

graph_get_edges

Returns a graph's dependency edges.

graph_node_get_dependencies

Returns a node's dependencies.

graph_node_get_dependent_nodes

Returns a node's dependent nodes.

graph_add_dependencies

Adds dependency edges to a graph.

graph_remove_dependencies

Removes dependency edges from a graph.

graph_destroy_node

Remove a node from the graph.

graph_instantiate

Creates an executable graph from a graph.

graph_instantiate_with_flags

Creates an executable graph from a graph.

graph_instantiate_with_params

Creates an executable graph from a graph.

graph_exec_get_flags

Query the instantiation flags of an executable graph.

graph_exec_kernel_node_set_params

Sets the parameters for a kernel node in the given graphExec.

graph_exec_memcpy_node_set_params

Sets the parameters for a memcpy node in the given graphExec.

graph_exec_memcpy_node_set_params_1d

Sets the parameters for a memcpy node in the given graphExec to perform a 1-dimensional copy.

graph_exec_memset_node_set_params

Sets the parameters for a memset node in the given graphExec.

graph_exec_host_node_set_params

Sets the parameters for a host node in the given graphExec.

graph_exec_child_graph_node_set_params

Updates node parameters in the child graph node in the given graphExec.

graph_exec_event_record_node_set_event

Sets the event for an event record node in the given graphExec.

graph_exec_event_wait_node_set_event

Sets the event for an event wait node in the given graphExec.

graph_exec_external_semaphores_signal_node_set_params

Sets the parameters for an external semaphore signal node in the given graphExec.

graph_exec_external_semaphores_wait_node_set_params

Sets the parameters for an external semaphore wait node in the given graphExec.

graph_node_set_enabled

Enables or disables the specified node in the given graphExec.

graph_node_get_enabled

Query whether a node in the given graphExec is enabled.

graph_exec_update

Check whether an executable graph can be updated with a graph and perform the update if possible.

graph_upload

Uploads an executable graph in a stream.

graph_launch

Launches an executable graph in a stream.

graph_exec_destroy

Destroys an executable graph.

graph_destroy

Destroys a graph.

graph_debug_dot_print

Write a DOT file describing graph structure.

user_object_create

Create a user object.

user_object_retain

Retain a reference to a user object.

user_object_release

Release a reference to a user object.

graph_retain_user_object

Retain a reference to a user object from a graph.

graph_release_user_object

Release a user object reference from a graph.

graph_add_node

Adds a node of arbitrary type to a graph.

graph_node_set_params

Update a graph node's parameters.

graph_node_get_params

Returns a graph node's parameters.

graph_exec_node_set_params

Update a graph node's parameters in an instantiated graph.

graph_conditional_handle_create

Create a conditional handle.

graph_conditional_handle_create_v2

Create a conditional handle.

Driver Entry Point Access#

This section describes the driver entry point access functions of CUDA runtime application programming interface.

get_driver_entry_point

Returns the requested driver API function pointer.

get_driver_entry_point_by_version

Returns the requested driver API function pointer by CUDA version.

get_export_table

Gets an internal export table.

Library Management#

This section describes the library management functions of the CUDA runtime application programming interface.

library_load_data

Load a library with specified code and options.

library_load_from_file

Load a library with specified file and options.

library_unload

Unloads a library.

library_get_kernel

Returns a kernel handle.

library_get_global

Returns a global device pointer.

library_get_managed

Returns a pointer to managed memory.

library_get_unified_function

Returns a pointer to a unified function.

library_get_kernel_count

Returns the number of kernels within a library.

library_enumerate_kernels

Retrieve the kernel handles within a library.

kernel_set_attribute_for_device

Sets information about a kernel.

Execution Context Management#

This section describes the execution context management functions of the CUDA runtime application programming interface.

Overview

A CUDA execution context cudaExecutionContext_t serves as an abstraction for the contexts exposed by the CUDA Runtime, specifically green contexts and the primary context, and provides a unified programming model and API interface for contexts in the Runtime.

There are two primary ways today to obtain an execution context:

  • cudaDeviceGetExecutionCtx: Returns the execution context that corresponds to the primary context of the specified device.

  • cudaGreenCtxCreate: Creates a green context with the specified resources and returns an execution context.

Once you have an execution context at hand, you can perform context-level operations via the CUDA Runtime APIs. This includes:

  • Submitting work via streams created with cudaExecutionCtxStreamCreate.

  • Querying context via cudaExecutionCtxGetDevResource, cudaExecutionCtxGetDevice, etc.

  • Synchronizing and tracking context-level operations via cudaExecutionCtxSynchronize, cudaExecutionCtxRecordEvent, cudaExecutionCtxWaitEvent.

  • Performing context-level graph node operations via cudaGraphAddNode by specifying the context in nodeParams. Note that individual node creation APIs, such as cudaGraphAddKernelNode, do not support specifying an execution context.

Note: The above APIs take in an explicit cudaExecutionContext_t handle and ignores the context that is current to the calling thread. This enables explicit context-based programming without relying on thread-local state. If no context is specified, the APIs return cudaErrorInvalidValue.

Note: Developers should treat cudaExecutionContext_t as an opaque handle and avoid assumptions about its underlying representation. The CUDA Runtime does not provide a way to convert this handle into driver-level contexts, such as ::CUcontext or ::CUgreenCtx.

Lifetime of CUDA Resources

The lifetime of CUDA resources (memory, streams, events, modules, etc) is not tied to the lifetime of the execution context. Their lifetime is tied to the device against which they were created. As such, usage of cudaDeviceReset() should be avoided to persist the lifetime of these resources.

APIs Operating on Current Context

The CUDA runtime does not provide a way to set an execution context as current. Since, the majority of the runtime APIs operate on the current context, we document below how the developer can work with these APIs.

APIs Operating on Device Resources

To work with these APIs (for example, cudaMalloc, cudaEventCreate, etc), developers are expected to call cudaSetDevice() prior to invoking them. Doing so does not impact functional correctness as these APIs operate on resources that are device-wide. If users have a context handle at hand, they can get the device handle from the context handle using cudaExecutionCtxGetDevice().

APIs Operating on Context Resources

These APIs (for example, cudaLaunchKernel, cudaMemcpyAsync, cudaMemsetAsync, etc) take in a stream and resources are inferred from the context bound to the stream at creation. See cudaExecutionCtxStreamCreate for more details. Developers are expected to use the stream-based APIs for context awareness and always pass an explicit stream handle to ensure context-awareness, and avoid reliance on the default NULL stream, which implicitly binds to the current context.

Green Contexts

Green contexts are a lightweight alternative to traditional contexts, that can be used to select a subset of device resources. This allows the developer to, for example, select SMs from distinct spatial partitions of the GPU and target them via CUDA stream operations, kernel launches, etc.

Here are the broad initial steps to follow to get started:

    1. Start with an initial set of resources. For SM resources, they can be fetched via cudaDeviceGetDevResource. In case of workqueues, a new configuration can be used or an existing one queried via the cudaDeviceGetDevResource API.

    1. Modify these resources by either partitioning them (in case of SMs) or changing the configuration (in case of workqueues). To partition SMs, we recommend cudaDevSmResourceSplit. Changing the workqueue configuration can be done directly in place.

    1. Finalize the specification of resources by creating a descriptor via cudaDevResourceGenerateDesc.

    1. Create a green context via cudaGreenCtxCreate. This provisions the resource, such as workqueues (until this step it was only a configuration specification).

    1. Create a stream via cudaExecutionCtxStreamCreate, and use it throughout your application.

SMs

There are two possible partition operations - with cudaDevSmResourceSplitByCount the partitions created have to follow default SM count granularity requirements, so it will often be rounded up and aligned to a default value. On the other hand, cudaDevSmResourceSplit is explicit and allows for creation of non-equal groups. It will not round up automatically - instead it is the developer’s responsibility to query and set the correct values. These requirements can be queried with cudaDeviceGetDevResource to determine the alignment granularity (sm.smCoscheduledAlignment). A general guideline on the default values for each compute architecture:

  • On Compute Architecture 7.X, 8.X, and all Tegra SoC:

    • The smCount must be a multiple of 2.

    • The alignment (and default value of coscheduledSmCount) is 2.

  • On Compute Architecture 9.0+:

    • The smCount must be a multiple of 8, or coscheduledSmCount if provided.

    • The alignment (and default value of coscheduledSmCount) is 8. While the maximum value for coscheduled SM count is 32 on all Compute Architecture 9.0+, it’s recommended to follow cluster size requirements. The portable cluster size and the max cluster size should be used in order to benefit from this co-scheduling.

Workqueues

For cudaDevResourceTypeWorkqueueConfig, the resource specifies the expected maximum number of concurrent stream-ordered workloads via the wqConcurrencyLimit field. The sharingScope field determines how workqueue resources are shared:

  • cudaDevWorkqueueConfigScopeDeviceCtx: Use all shared workqueue resources across all contexts (default driver behavior).

  • cudaDevWorkqueueConfigScopeGreenCtxBalanced: When possible, use non-overlapping workqueue resources with other balanced green contexts.

The maximum concurrency limit depends on ::CUDA_DEVICE_MAX_CONNECTIONS and can be queried from the device via cudaDeviceGetDevResource. Configurations may exceed this concurrency limit, but the driver will not guarantee that work submission remains non-overlapping.

For cudaDevResourceTypeWorkqueue, the resource represents a pre-existing workqueue that can be retrieved from existing execution contexts. This allows reusing workqueue resources across different execution contexts.

On Concurrency

Even if the green contexts have disjoint SM partitions, it is not guaranteed that the kernels launched in them will run concurrently or have forward progress guarantees. This is due to other resources that could cause a dependency. Using a combination of disjoint SMs and cudaDevWorkqueueConfigScopeGreenCtxBalanced workqueue configurations can provide the best chance of avoiding interference. More resources will be added in the future to provide stronger guarantees.

Additionally, there are two known scenarios, where its possible for the workload to run on more SMs than was provisioned (but never less).

  • On Volta+ MPS: When CUDA_MPS_ACTIVE_THREAD_PERCENTAGE is used, the set of SMs that are used for running kernels can be scaled up to the value of SMs used for the MPS client.

  • On Compute Architecture 9.x: When a module with dynamic parallelism (CDP) is loaded, all future kernels running under green contexts may use and share an additional set of 2 SMs.

Memory Copy Operations

Green context restrictions apply to memory copy operations only when the copy is performed using a green context. For cross-device copies, green context restrictions may not be applied.

device_get_dev_resource

Get device resources.

dev_sm_resource_split_by_count

Splits cudaDevResourceTypeSm resources.

dev_sm_resource_split

Splits a cudaDevResourceTypeSm resource into structured groups.

dev_resource_generate_desc

Generate a resource descriptor.

green_ctx_create

Creates a green context with a specified set of resources.

execution_ctx_destroy

Destroy a execution context.

execution_ctx_get_dev_resource

Get context resources.

execution_ctx_get_device

Returns the device handle for the execution context.

execution_ctx_get_id

Returns the unique Id associated with the execution context supplied.

execution_ctx_stream_create

Creates a stream and initializes it for the given execution context.

execution_ctx_synchronize

Block for the specified execution context's tasks to complete.

stream_get_dev_resource

Get stream resources.

execution_ctx_record_event

Records an event for the specified execution context.

execution_ctx_wait_event

Make an execution context wait on an event.

device_get_execution_ctx

Returns the execution context for a device.

Interactions with the CUDA Driver API#

This section describes the interactions between the CUDA Driver API and the CUDA Runtime API

Execution Contexts

The CUDA Runtime provides cudaExecutionContext_t as an abstraction over driver-level contexts—specifically, green contexts and the primary context.

There are two primary ways to obtain an execution context:

  • cudaDeviceGetExecutionCtx: Returns the execution context that corresponds to the primary context of the specified device.

  • cudaGreenCtxCreate: Creates a green context with the specified resources and returns an execution context.

Note: Developers should treat cudaExecutionContext_t as an opaque handle and avoid assumptions about its underlying representation. The CUDA Runtime does not provide a way to convert this handle into a ::CUcontext or ::CUgreenCtx.

Primary Context (aka Device Execution Context)

The primary context is the default execution context associated with a device in the Runtime. It can be obtained via a call to cudaDeviceGetExecutionCtx(). There is a one-to-one mapping between CUDA devices in the runtime and their primary contexts within a process.

From the CUDA Runtime’s perspective, a device and its primary context are functionally synonymous.

Unless explicitly overridden, either by making a different context current via the Driver API (e.g., ::cuCtxSetCurrent()) or by using an explicit execution context handle, the Runtime will implicitly initialize and use the primary context for API calls as needed.

Initialization and Tear-Down

Unless an explicit execution context is specified (see “Execution Context Management” for APIs), CUDA Runtime API calls operate on the CUDA Driver ::CUcontext which is current to the calling host thread. If no ::CUcontext is current to the calling thread when a CUDA Runtime API call which requires an active context is made, then the primary context (device execution context) for a device will be selected, made current to the calling thread, and initialized. The context will be initialized using the parameters specified by the CUDA Runtime API functions cudaSetDeviceFlags(), ::cudaD3D9SetDirect3DDevice(), ::cudaD3D10SetDirect3DDevice(), ::cudaD3D11SetDirect3DDevice(), cudaGLSetGLDevice(), and cudaVDPAUSetVDPAUDevice(). Note that these functions will fail with cudaErrorSetOnActiveProcess if they are called when the primary context for the specified device has already been initialized, except for cudaSetDeviceFlags() which will simply overwrite the previous settings.

The function cudaInitDevice() ensures that the primary context is initialized for the requested device but does not make it current to the calling thread.

The function cudaSetDevice() initializes the primary context for the specified device and makes it current to the calling thread by calling ::cuCtxSetCurrent().

Primary contexts will remain active until they are explicitly deinitialized using cudaDeviceReset(). The function cudaDeviceReset() will deinitialize the primary context for the calling thread’s current device immediately. The context will remain current to all of the threads that it was current to. The next CUDA Runtime API call on any thread which requires an active context will trigger the reinitialization of that device’s primary context.

Note that primary contexts are shared resources. It is recommended that the primary context not be reset except just before exit or to recover from an unspecified launch failure.

CUcontext Interoperability

Note that the use of multiple ::CUcontext s per device within a single process will substantially degrade performance and is strongly discouraged. Instead, it is highly recommended to either use execution contexts cudaExecutionContext_t or the implicit one-to-one device-to-primary context mapping for the process provided by the CUDA Runtime API.

If a non-primary ::CUcontext created by the CUDA Driver API is current to a thread then the CUDA Runtime API calls to that thread will operate on that ::CUcontext, with some exceptions listed below. Interoperability between data types is discussed in the following sections.

The function cudaDeviceEnablePeerAccess() and the rest of the peer access API may not be called when a non-primary CUcontext is current. To use the peer access APIs with a context created using the CUDA Driver API, it is necessary that the CUDA Driver API be used to access these features.

All CUDA Runtime API state (e.g, global variables’ addresses and values) travels with its underlying ::CUcontext. In particular, if a ::CUcontext is moved from one thread to another then all CUDA Runtime API state will move to that thread as well.

Please note that attaching to legacy CUcontext (those with a version of 3010 as returned by ::cuCtxGetApiVersion()) is not possible. The CUDA Runtime will return cudaErrorIncompatibleDriverContext in such cases.

Interactions between CUstream and cudaStream_t

The types ::CUstream and cudaStream_t are identical and may be used interchangeably.

Interactions between CUevent and cudaEvent_t

The types ::CUevent and cudaEvent_t are identical and may be used interchangeably.

Interactions between CUarray and cudaArray_t

The types ::CUarray and struct ::cudaArray * represent the same data type and may be used interchangeably by casting the two types between each other.

In order to use a ::CUarray in a CUDA Runtime API function which takes a struct ::cudaArray *, it is necessary to explicitly cast the ::CUarray to a struct ::cudaArray *.

In order to use a struct ::cudaArray * in a CUDA Driver API function which takes a ::CUarray, it is necessary to explicitly cast the struct ::cudaArray * to a ::CUarray .

Interactions between CUgraphicsResource and cudaGraphicsResource_t

The types ::CUgraphicsResource and cudaGraphicsResource_t represent the same data type and may be used interchangeably by casting the two types between each other.

In order to use a ::CUgraphicsResource in a CUDA Runtime API function which takes a cudaGraphicsResource_t, it is necessary to explicitly cast the ::CUgraphicsResource to a cudaGraphicsResource_t.

In order to use a cudaGraphicsResource_t in a CUDA Driver API function which takes a ::CUgraphicsResource, it is necessary to explicitly cast the cudaGraphicsResource_t to a ::CUgraphicsResource.

Interactions between CUtexObject and cudaTextureObject_t

The types ::CUtexObject and cudaTextureObject_t represent the same data type and may be used interchangeably by casting the two types between each other.

In order to use a ::CUtexObject in a CUDA Runtime API function which takes a cudaTextureObject_t, it is necessary to explicitly cast the ::CUtexObject to a cudaTextureObject_t.

In order to use a cudaTextureObject_t in a CUDA Driver API function which takes a ::CUtexObject, it is necessary to explicitly cast the cudaTextureObject_t to a ::CUtexObject.

Interactions between CUsurfObject and cudaSurfaceObject_t

The types ::CUsurfObject and cudaSurfaceObject_t represent the same data type and may be used interchangeably by casting the two types between each other.

In order to use a ::CUsurfObject in a CUDA Runtime API function which takes a cudaSurfaceObject_t, it is necessary to explicitly cast the ::CUsurfObject to a cudaSurfaceObject_t.

In order to use a cudaSurfaceObject_t in a CUDA Driver API function which takes a ::CUsurfObject, it is necessary to explicitly cast the cudaSurfaceObject_t to a ::CUsurfObject.

Interactions between CUfunction and cudaFunction_t

The types ::CUfunction and cudaFunction_t represent the same data type and may be used interchangeably by casting the two types between each other.

In order to use a cudaFunction_t in a CUDA Driver API function which takes a ::CUfunction, it is necessary to explicitly cast the cudaFunction_t to a ::CUfunction.

Interactions between CUkernel and cudaKernel_t

The types ::CUkernel and cudaKernel_t represent the same data type and may be used interchangeably by casting the two types between each other.

In order to use a cudaKernel_t in a CUDA Driver API function which takes a ::CUkernel, it is necessary to explicitly cast the cudaKernel_t to a ::CUkernel.

get_kernel

Get pointer to device kernel that matches entry function entry_func_addr.

Profiler Control#

This section describes the profiler control functions of the CUDA runtime application programming interface.

profiler_start

Enable profiling.

profiler_stop

Disable profiling.

Deprecated Device Management#

This section describes the deprecated device management functions of the CUDA runtime application programming interface.

device_get_shared_mem_config

Returns the shared memory configuration for the current device.

device_set_shared_mem_config

Sets the shared memory configuration for the current device.

Deprecated Execution Control#

This section describes the deprecated execution control functions of the CUDA runtime application programming interface.

func_set_shared_mem_config

Sets the shared memory configuration for a device function.

Deprecated Memory Management#

This section describes the deprecated memory management functions of the CUDA runtime application programming interface.

memcpy_to_array

Copies data between host and device.

memcpy_to_array_async

Copies data between host and device.

memcpy_from_array

Copies data between host and device.

memcpy_from_array_async

Copies data between host and device.

memcpy_array_to_array

Copies data between host and device.