cudart#
Profiler Control#
This section describes the profiler control functions of the CUDA runtime application programming interface.
- cuda.cudart.cudaProfilerStart()#
Enable profiling.
Enables profile collection by the active profiling tool for the current context. If profiling is already enabled, then
cudaProfilerStart()
has no effect.cudaProfilerStart and cudaProfilerStop APIs are used to programmatically control the profiling granularity by allowing profiling to be done only on selective pieces of code.
- Returns:
- Return type:
See also
- cuda.cudart.cudaProfilerStop()#
Disable profiling.
Disables profile collection by the active profiling tool for the current context. If profiling is already disabled, then
cudaProfilerStop()
has no effect.cudaProfilerStart and cudaProfilerStop APIs are used to programmatically control the profiling granularity by allowing profiling to be done only on selective pieces of code.
- Returns:
- Return type:
See also
Device Management#
impl_private This section describes the device management functions of the CUDA runtime application programming interface.
- cuda.cudart.cudaDeviceReset()#
Destroy all allocations and reset all state on the current device in the current process.
Explicitly destroys and cleans up all resources associated with the current device in the current process. It is the caller’s responsibility to ensure that the resources are not accessed or passed in subsequent API calls and doing so will result in undefined behavior. These resources include CUDA types such as
cudaStream_t
,cudaEvent_t
,cudaArray_t
,cudaMipmappedArray_t
,cudaTextureObject_t
,cudaSurfaceObject_t
,textureReference
,surfaceReference
,cudaExternalMemory_t
,cudaExternalSemaphore_t
andcudaGraphicsResource_t
. Any subsequent API call to this device will reinitialize the device.Note that this function will reset the device immediately. It is the caller’s responsibility to ensure that the device is not being accessed by any other host threads from the process when this function is called.
- Returns:
- Return type:
See also
- cuda.cudart.cudaDeviceSynchronize()#
Wait for compute device to finish.
Blocks until the device has completed all preceding requested tasks.
cudaDeviceSynchronize()
returns an error if one of the preceding tasks has failed. If thecudaDeviceScheduleBlockingSync
flag was set for this device, the host thread will block until the device has finished its work.- Returns:
- Return type:
See also
- cuda.cudart.cudaDeviceSetLimit(limit: cudaLimit, size_t value)#
Set resource limits.
Setting limit to value is a request by the application to update the current limit maintained by the device. The driver is free to modify the requested value to meet h/w requirements (this could be clamping to minimum or maximum values, rounding up to nearest element size, etc). The application can use
cudaDeviceGetLimit()
to find out exactly what the limit has been set to.Setting each
cudaLimit
has its own specific restrictions, so each is discussed here.cudaLimitStackSize
controls the stack size in bytes of each GPU thread.cudaLimitPrintfFifoSize
controls the size in bytes of the shared FIFO used by theprintf()
device system call. SettingcudaLimitPrintfFifoSize
must not be performed after launching any kernel that uses theprintf()
device system call - in such casecudaErrorInvalidValue
will be returned.cudaLimitMallocHeapSize
controls the size in bytes of the heap used by themalloc()
andfree()
device system calls. SettingcudaLimitMallocHeapSize
must not be performed after launching any kernel that uses themalloc()
orfree()
device system calls - in such casecudaErrorInvalidValue
will be returned.cudaLimitDevRuntimeSyncDepth
controls the maximum nesting depth of a grid at which a thread can safely callcudaDeviceSynchronize()
. Setting this limit must be performed before any launch of a kernel that uses the device runtime and callscudaDeviceSynchronize()
above the default sync depth, two levels of grids. Calls tocudaDeviceSynchronize()
will fail with error codecudaErrorSyncDepthExceeded
if the limitation is violated. This limit can be set smaller than the default or up the maximum launch depth of 24. When setting this limit, keep in mind that additional levels of sync depth require the runtime to reserve large amounts of device memory which can no longer be used for user allocations. If these reservations of device memory fail,cudaDeviceSetLimit
will returncudaErrorMemoryAllocation
, and the limit can be reset to a lower value. This limit is only applicable to devices of compute capability < 9.0. Attempting to set this limit on devices of other compute capability will results in errorcudaErrorUnsupportedLimit
being returned.cudaLimitDevRuntimePendingLaunchCount
controls the maximum number of outstanding device runtime launches that can be made from the current device. A grid is outstanding from the point of launch up until the grid is known to have been completed. Device runtime launches which violate this limitation fail and returncudaErrorLaunchPendingCountExceeded
whencudaGetLastError()
is called after launch. If more pending launches than the default (2048 launches) are needed for a module using the device runtime, this limit can be increased. Keep in mind that being able to sustain additional pending launches will require the runtime to reserve larger amounts of device memory upfront which can no longer be used for allocations. If these reservations fail,cudaDeviceSetLimit
will returncudaErrorMemoryAllocation
, 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 will result in the errorcudaErrorUnsupportedLimit
being returned.cudaLimitMaxL2FetchGranularity
controls the L2 cache fetch granularity. Values can range from 0B to 128B. This is purely a performance hint and it can be ignored or clamped depending on the platform.cudaLimitPersistingL2CacheSize
controls size in bytes available for persisting L2 cache. This is purely a performance hint and it can be ignored or clamped depending on the platform.
- Parameters:
limit (
cudaLimit
) – Limit to setvalue (size_t) – Size of limit
- Returns:
cudaSuccess
,cudaErrorUnsupportedLimit
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
- Return type:
See also
- cuda.cudart.cudaDeviceGetLimit(limit: cudaLimit)#
Return resource limits.
Returns in *pValue the current size of limit. The following
cudaLimit
values are supported.cudaLimitStackSize
is the stack size in bytes of each GPU thread.cudaLimitPrintfFifoSize
is the size in bytes of the shared FIFO used by theprintf()
device system call.cudaLimitMallocHeapSize
is the size in bytes of the heap used by themalloc()
andfree()
device system calls.cudaLimitDevRuntimeSyncDepth
is the maximum grid depth at which a thread can isssue the device runtime callcudaDeviceSynchronize()
to wait on child grid launches to complete. This functionality is removed for devices of compute capability >= 9.0, and hence will return errorcudaErrorUnsupportedLimit
on such devices.cudaLimitDevRuntimePendingLaunchCount
is the maximum number of outstanding device runtime launches.cudaLimitMaxL2FetchGranularity
is the L2 cache fetch granularity.cudaLimitPersistingL2CacheSize
is the persisting L2 cache size in bytes.
- Parameters:
limit (
cudaLimit
) – Limit to query- Returns:
cudaError_t –
cudaSuccess
,cudaErrorUnsupportedLimit
,cudaErrorInvalidValue
pValue (int) – Returned size of the limit
See also
- cuda.cudart.cudaDeviceGetTexture1DLinearMaxWidth(cudaChannelFormatDesc fmtDesc: cudaChannelFormatDesc, int device)#
Returns the maximum number of elements allocatable in a 1D linear texture for a given element size.
Returns in maxWidthInElements the maximum number of elements allocatable in a 1D linear texture for given format descriptor fmtDesc.
- Parameters:
fmtDesc (
cudaChannelFormatDesc
) – Texture format description.None (int) – None
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorUnsupportedLimit
,cudaErrorInvalidValue
maxWidthInElements (int) – Returns maximum number of texture elements allocatable for given fmtDesc.
See also
- cuda.cudart.cudaDeviceGetCacheConfig()#
Returns the preferred cache configuration for the current device.
On devices where the L1 cache and shared memory use the same hardware resources, this returns through pCacheConfig the preferred cache configuration for the current device. This is only a preference. The runtime will use the requested configuration if possible, but it is free to choose a different configuration if required to execute functions.
This will return a pCacheConfig of
cudaFuncCachePreferNone
on devices where the size of the L1 cache and shared memory are fixed.The supported cache configurations are:
cudaFuncCachePreferNone
: no preference for shared memory or L1 (default)cudaFuncCachePreferShared
: prefer larger shared memory and smaller L1 cachecudaFuncCachePreferL1
: prefer larger L1 cache and smaller shared memorycudaFuncCachePreferEqual
: prefer equal size L1 cache and shared memory
- Returns:
cudaError_t –
cudaSuccess
pCacheConfig (
cudaFuncCache
) – Returned cache configuration
See also
cudaDeviceSetCacheConfig
,cudaFuncSetCacheConfig (C API)
, cudaFuncSetCacheConfig (C++ API),cuCtxGetCacheConfig
- cuda.cudart.cudaDeviceGetStreamPriorityRange()#
Returns numerical values that correspond to the least and greatest stream priorities.
Returns in *leastPriority and *greatestPriority the numerical values that correspond to the least and greatest stream priorities respectively. Stream priorities follow a convention where lower numbers imply greater priorities. The range of meaningful stream priorities is given by [*greatestPriority, *leastPriority]. If the user attempts to create a stream with a priority value that is outside the the meaningful range as specified by this API, the priority is automatically clamped down or up to either *leastPriority or *greatestPriority respectively. See
cudaStreamCreateWithPriority
for details on creating a priority stream. A NULL may be passed in for *leastPriority or *greatestPriority if the value is not desired.This function will return ‘0’ in both *leastPriority and *greatestPriority if the current context’s device does not support stream priorities (see
cudaDeviceGetAttribute
).- Returns:
cudaError_t –
cudaSuccess
leastPriority (int) – Pointer to an int in which the numerical value for least stream priority is returned
greatestPriority (int) – Pointer to an int in which the numerical value for greatest stream priority is returned
- cuda.cudart.cudaDeviceSetCacheConfig(cacheConfig: cudaFuncCache)#
Sets the preferred cache configuration for the current device.
On devices where the L1 cache and shared memory use the same hardware resources, this sets through cacheConfig the preferred cache configuration for the current device. This is only a preference. The runtime will use the requested configuration if possible, but it is free to choose a different configuration if required to execute the function. Any function preference set via
cudaFuncSetCacheConfig (C API)
or cudaFuncSetCacheConfig (C++ API) will be preferred over this device-wide setting. Setting the device-wide cache configuration tocudaFuncCachePreferNone
will cause subsequent kernel launches to prefer to not change the cache configuration unless required to launch the kernel.This setting does nothing on devices where the size of the L1 cache and shared memory are fixed.
Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point.
The supported cache configurations are:
cudaFuncCachePreferNone
: no preference for shared memory or L1 (default)cudaFuncCachePreferShared
: prefer larger shared memory and smaller L1 cachecudaFuncCachePreferL1
: prefer larger L1 cache and smaller shared memorycudaFuncCachePreferEqual
: prefer equal size L1 cache and shared memory
- Parameters:
cacheConfig (
cudaFuncCache
) – Requested cache configuration- Returns:
- Return type:
See also
cudaDeviceGetCacheConfig
,cudaFuncSetCacheConfig (C API)
, cudaFuncSetCacheConfig (C++ API),cuCtxSetCacheConfig
Returns the shared memory configuration for the current device.
This function will return in pConfig the current size of shared memory banks on the current device. On devices with configurable shared memory banks,
cudaDeviceSetSharedMemConfig
can be used to change this setting, so that all subsequent kernel launches will by default use the new bank size. WhencudaDeviceGetSharedMemConfig
is called on devices without configurable shared memory, it will return the fixed bank size of the hardware.The returned bank configurations can be either:
cudaSharedMemBankSizeFourByte
- shared memory bank width is four bytes.cudaSharedMemBankSizeEightByte
- shared memory bank width is eight bytes.
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
pConfig (
cudaSharedMemConfig
) – Returned cache configuration
Sets the shared memory configuration for the current device.
On devices with configurable shared memory banks, this function will set the shared memory bank size which is used for all subsequent kernel launches. Any per-function setting of shared memory set via
cudaFuncSetSharedMemConfig
will override the device wide setting.Changing the shared memory configuration between launches may introduce a device side synchronization point.
Changing the shared memory bank size will not increase shared memory usage or affect occupancy of kernels, but may have major effects on performance. Larger bank sizes will allow for greater potential bandwidth to shared memory, but will change what kinds of accesses to shared memory will result in bank conflicts.
This function will do nothing on devices with fixed shared memory bank size.
The supported bank configurations are:
cudaSharedMemBankSizeDefault
: set bank width the device default (currently, four bytes)cudaSharedMemBankSizeFourByte
: set shared memory bank width to be four bytes natively.cudaSharedMemBankSizeEightByte
: set shared memory bank width to be eight bytes natively.
- Parameters:
config (
cudaSharedMemConfig
) – Requested cache configuration- Returns:
- Return type:
- cuda.cudart.cudaDeviceGetByPCIBusId(char *pciBusId)#
Returns a handle to a compute device.
Returns in *device a device ordinal given a PCI bus ID string.
where domain, bus, device, and function are all hexadecimal values
- Parameters:
pciBusId (bytes) – String in one of the following forms:
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidDevice
device (int) – Returned device ordinal
See also
- cuda.cudart.cudaDeviceGetPCIBusId(int length, int device)#
Returns a PCI Bus Id string for the device.
Returns an ASCII string identifying the device dev in the NULL- terminated string pointed to by pciBusId. length specifies the maximum length of the string that may be returned.
where domain, bus, device, and function are all hexadecimal values. pciBusId should be large enough to store 13 characters including the NULL-terminator.
- Parameters:
length (int) – Maximum length of string to store in name
device (int) – Device to get identifier string for
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidDevice
pciBusId (bytes) – Returned identifier string for the device in the following format
See also
- cuda.cudart.cudaIpcGetEventHandle(event)#
Gets an interprocess handle for a previously allocated event.
Takes as input a previously allocated event. This event must have been created with the
cudaEventInterprocess
andcudaEventDisableTiming
flags set. This opaque handle may be copied into other processes and opened withcudaIpcOpenEventHandle
to allow efficient hardware synchronization between GPU work in different processes.After the event has been been opened in the importing process,
cudaEventRecord
,cudaEventSynchronize
,cudaStreamWaitEvent
andcudaEventQuery
may be used in either process. Performing operations on the imported event after the exported event has been freed withcudaEventDestroy
will result in undefined behavior.IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is restricted to GPUs in TCC mode. Users can test their device for IPC functionality by calling
cudaDeviceGetAttribute
withcudaDevAttrIpcEventSupport
- Parameters:
event (
CUevent
orcudaEvent_t
) – Event allocated withcudaEventInterprocess
andcudaEventDisableTiming
flags.- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidResourceHandle
,cudaErrorMemoryAllocation
,cudaErrorMapBufferObjectFailed
,cudaErrorNotSupported
,cudaErrorInvalidValue
handle (
cudaIpcEventHandle_t
) – Pointer to a user allocated cudaIpcEventHandle in which to return the opaque event handle
- cuda.cudart.cudaIpcOpenEventHandle(cudaIpcEventHandle_t handle: cudaIpcEventHandle_t)#
Opens an interprocess event handle for use in the current process.
Opens an interprocess event handle exported from another process with
cudaIpcGetEventHandle
. This function returns acudaEvent_t
that behaves like a locally created event with thecudaEventDisableTiming
flag specified. This event must be freed withcudaEventDestroy
.Performing operations on the imported event after the exported event has been freed with
cudaEventDestroy
will result in undefined behavior.IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is restricted to GPUs in TCC mode. Users can test their device for IPC functionality by calling
cudaDeviceGetAttribute
withcudaDevAttrIpcEventSupport
- Parameters:
handle (
cudaIpcEventHandle_t
) – Interprocess handle to open- Returns:
cudaError_t –
cudaSuccess
,cudaErrorMapBufferObjectFailed
,cudaErrorNotSupported
,cudaErrorInvalidValue
,cudaErrorDeviceUninitialized
event (
cudaEvent_t
) – Returns the imported event
- cuda.cudart.cudaIpcGetMemHandle(devPtr)#
Gets an interprocess memory handle for an existing device memory allocation.
Takes a pointer to the base of an existing device memory allocation created with
cudaMalloc
and exports it for use in another process. This is a lightweight operation and may be called multiple times on an allocation without adverse effects.If a region of memory is freed with
cudaFree
and a subsequent call tocudaMalloc
returns memory with the same device address,cudaIpcGetMemHandle
will return a unique handle for the new memory.IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is restricted to GPUs in TCC mode. Users can test their device for IPC functionality by calling
cudaDeviceGetAttribute
withcudaDevAttrIpcEventSupport
- Parameters:
devPtr (Any) – Base pointer to previously allocated device memory
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorMemoryAllocation
,cudaErrorMapBufferObjectFailed
,cudaErrorNotSupported
,cudaErrorInvalidValue
handle (
cudaIpcMemHandle_t
) – Pointer to user allocatedcudaIpcMemHandle
to return the handle in.
- cuda.cudart.cudaIpcOpenMemHandle(cudaIpcMemHandle_t handle: cudaIpcMemHandle_t, unsigned int flags)#
Opens an interprocess memory handle exported from another process and returns a device pointer usable in the local process.
Maps memory exported from another process with
cudaIpcGetMemHandle
into the current device address space. For contexts on different devicescudaIpcOpenMemHandle
can attempt to enable peer access between the devices as if the user calledcudaDeviceEnablePeerAccess
. This behavior is controlled by thecudaIpcMemLazyEnablePeerAccess
flag.cudaDeviceCanAccessPeer
can determine if a mapping is possible.cudaIpcOpenMemHandle
can open handles to devices that may not be visible in the process calling the API.Contexts that may open
cudaIpcMemHandles
are restricted in the following way.cudaIpcMemHandles
from each device in a given process may only be opened by one context per device per other process.If the memory handle has already been opened by the current context, the reference count on the handle is incremented by 1 and the existing device pointer is returned.
Memory returned from
cudaIpcOpenMemHandle
must be freed withcudaIpcCloseMemHandle
.Calling
cudaFree
on an exported memory region before callingcudaIpcCloseMemHandle
in the importing context will result in undefined behavior.IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is restricted to GPUs in TCC mode. Users can test their device for IPC functionality by calling
cudaDeviceGetAttribute
withcudaDevAttrIpcEventSupport
- Parameters:
handle (
cudaIpcMemHandle_t
) –cudaIpcMemHandle
to openflags (unsigned int) – Flags for this operation. Must be specified as
cudaIpcMemLazyEnablePeerAccess
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorMapBufferObjectFailed
,cudaErrorInvalidResourceHandle
,cudaErrorDeviceUninitialized
,cudaErrorTooManyPeers
,cudaErrorNotSupported
,cudaErrorInvalidValue
devPtr (Any) – Returned device pointer
See also
cudaMalloc
,cudaFree
,cudaIpcGetEventHandle
,cudaIpcOpenEventHandle
,cudaIpcGetMemHandle
,cudaIpcCloseMemHandle
,cudaDeviceEnablePeerAccess
,cudaDeviceCanAccessPeer
,cuIpcOpenMemHandle
Notes
- No guarantees are made about the address returned in *devPtr.
In particular, multiple processes may not receive the same address for the same handle.
- cuda.cudart.cudaIpcCloseMemHandle(devPtr)#
Attempts to close memory mapped with cudaIpcOpenMemHandle.
Decrements the reference count of the memory returnd by
cudaIpcOpenMemHandle
by 1. When the reference count reaches 0, this API unmaps the memory. The original allocation in the exporting process as well as imported mappings in other processes will be unaffected.Any resources used to enable peer access will be freed if this is the last mapping using them.
IPC functionality is restricted to devices with support for unified addressing on Linux and Windows operating systems. IPC functionality on Windows is restricted to GPUs in TCC mode. Users can test their device for IPC functionality by calling
cudaDeviceGetAttribute
withcudaDevAttrIpcEventSupport
- Parameters:
devPtr (Any) – Device pointer returned by
cudaIpcOpenMemHandle
- Returns:
cudaSuccess
,cudaErrorMapBufferObjectFailed
,cudaErrorNotSupported
,cudaErrorInvalidValue
- Return type:
- cuda.cudart.cudaDeviceFlushGPUDirectRDMAWrites(target: cudaFlushGPUDirectRDMAWritesTarget, scope: cudaFlushGPUDirectRDMAWritesScope)#
Blocks until remote writes are visible to the specified scope.
Blocks until remote writes to the target context via mappings created through GPUDirect RDMA APIs, like nvidia_p2p_get_pages (see https://docs.nvidia.com/cuda/gpudirect-rdma for more information), are visible to the specified scope.
If the scope equals or lies within the scope indicated by
cudaDevAttrGPUDirectRDMAWritesOrdering
, the call will be a no-op and can be safely omitted for performance. This can be determined by comparing the numerical values between the two enums, with smaller scopes having smaller values.Users may query support for this API via
cudaDevAttrGPUDirectRDMAFlushWritesOptions
.- Parameters:
target (
cudaFlushGPUDirectRDMAWritesTarget
) – The target of the operation, see cudaFlushGPUDirectRDMAWritesTargetscope (
cudaFlushGPUDirectRDMAWritesScope
) – The scope of the operation, see cudaFlushGPUDirectRDMAWritesScope
- Returns:
- Return type:
See also
- cuda.cudart.cudaGetDeviceCount()#
Returns the number of compute-capable devices.
Returns in *count the number of devices with compute capability greater or equal to 2.0 that are available for execution.
- Returns:
cudaError_t –
cudaSuccess
count (int) – Returns the number of devices with compute capability greater or equal to 2.0
- cuda.cudart.cudaGetDeviceProperties(int device)#
Returns information about the compute-device.
Returns in *prop the properties of device dev. The
cudaDeviceProp
structure is defined as:View CUDA Toolkit Documentation for a C++ code example
where:
name[256]
is an ASCII string identifying the device.uuid
is a 16-byte unique identifier.totalGlobalMem
is the total amount of global memory available on the device in bytes.sharedMemPerBlock
is the maximum amount of shared memory available to a thread block in bytes.regsPerBlock
is the maximum number of 32-bit registers available to a thread block.warpSize
is the warp size in threads.memPitch
is the maximum pitch in bytes allowed by the memory copy functions that involve memory regions allocated throughcudaMallocPitch()
.maxThreadsPerBlock
is the maximum number of threads per block.maxThreadsDim[3]
contains the maximum size of each dimension of a block.maxGridSize[3]
contains the maximum size of each dimension of a grid.clockRate
is the clock frequency in kilohertz.totalConstMem
is the total amount of constant memory available on the device in bytes.major
,minor
are the major and minor revision numbers defining the device’s compute capability.textureAlignment
is the alignment requirement; texture base addresses that are aligned totextureAlignment
bytes do not need an offset applied to texture fetches.texturePitchAlignment
is the pitch alignment requirement for 2D texture references that are bound to pitched memory.deviceOverlap
is 1 if the device can concurrently copy memory between host and device while executing a kernel, or 0 if not. Deprecated, use instead asyncEngineCount.multiProcessorCount
is the number of multiprocessors on the device.kernelExecTimeoutEnabled
is 1 if there is a run time limit for kernels executed on the device, or 0 if not.integrated
is 1 if the device is an integrated (motherboard) GPU and 0 if it is a discrete (card) component.canMapHostMemory
is 1 if the device can map host memory into the CUDA address space for use withcudaHostAlloc()
/cudaHostGetDevicePointer()
, or 0 if not.computeMode
is the compute mode that the device is currently in. Available modes are as follows:cudaComputeModeDefault: Default mode - Device is not restricted and multiple threads can use
cudaSetDevice()
with this device.cudaComputeModeProhibited: Compute-prohibited mode - No threads can use
cudaSetDevice()
with this device.cudaComputeModeExclusiveProcess: Compute-exclusive-process mode - Many threads in one process will be able to use
cudaSetDevice()
with this device. When an occupied exclusive mode device is chosen withcudaSetDevice
, all subsequent non-device management runtime functions will returncudaErrorDevicesUnavailable
.
maxTexture1D
is the maximum 1D texture size.maxTexture1DMipmap
is the maximum 1D mipmapped texture texture size.maxTexture1DLinear
is the maximum 1D texture size for textures bound to linear memory.maxTexture2D[2]
contains the maximum 2D texture dimensions.maxTexture2DMipmap[2]
contains the maximum 2D mipmapped texture dimensions.maxTexture2DLinear[3]
contains the maximum 2D texture dimensions for 2D textures bound to pitch linear memory.maxTexture2DGather[2]
contains the maximum 2D texture dimensions if texture gather operations have to be performed.maxTexture3D[3]
contains the maximum 3D texture dimensions.maxTexture3DAlt[3]
contains the maximum alternate 3D texture dimensions.maxTextureCubemap
is the maximum cubemap texture width or height.maxTexture1DLayered[2]
contains the maximum 1D layered texture dimensions.maxTexture2DLayered[3]
contains the maximum 2D layered texture dimensions.maxTextureCubemapLayered[2]
contains the maximum cubemap layered texture dimensions.maxSurface1D
is the maximum 1D surface size.maxSurface2D[2]
contains the maximum 2D surface dimensions.maxSurface3D[3]
contains the maximum 3D surface dimensions.maxSurface1DLayered[2]
contains the maximum 1D layered surface dimensions.maxSurface2DLayered[3]
contains the maximum 2D layered surface dimensions.maxSurfaceCubemap
is the maximum cubemap surface width or height.maxSurfaceCubemapLayered[2]
contains the maximum cubemap layered surface dimensions.surfaceAlignment
specifies the alignment requirements for surfaces.concurrentKernels
is 1 if the device supports executing multiple kernels within the same context simultaneously, or 0 if not. It is not guaranteed that multiple kernels will be resident on the device concurrently so this feature should not be relied upon for correctness.ECCEnabled
is 1 if the device has ECC support turned on, or 0 if not.pciBusID
is the PCI bus identifier of the device.pciDeviceID
is the PCI device (sometimes called slot) identifier of the device.pciDomainID
is the PCI domain identifier of the device.tccDriver
is 1 if the device is using a TCC driver or 0 if not.asyncEngineCount
is 1 when the device can concurrently copy memory between host and device while executing a kernel. It is 2 when the device can concurrently copy memory between host and device in both directions and execute a kernel at the same time. It is 0 if neither of these is supported.unifiedAddressing
is 1 if the device shares a unified address space with the host and 0 otherwise.memoryClockRate
is the peak memory clock frequency in kilohertz.memoryBusWidth
is the memory bus width in bits.l2CacheSize
is L2 cache size in bytes.persistingL2CacheMaxSize
is L2 cache’s maximum persisting lines size in bytes.maxThreadsPerMultiProcessor
is the number of maximum resident threads per multiprocessor.streamPrioritiesSupported
is 1 if the device supports stream priorities, or 0 if it is not supported.globalL1CacheSupported
is 1 if the device supports caching of globals in L1 cache, or 0 if it is not supported.localL1CacheSupported
is 1 if the device supports caching of locals in L1 cache, or 0 if it is not supported.sharedMemPerMultiprocessor
is the maximum amount of shared memory available to a multiprocessor in bytes; this amount is shared by all thread blocks simultaneously resident on a multiprocessor.regsPerMultiprocessor
is the maximum number of 32-bit registers available to a multiprocessor; this number is shared by all thread blocks simultaneously resident on a multiprocessor.managedMemory
is 1 if the device supports allocating managed memory on this system, or 0 if it is not supported.isMultiGpuBoard
is 1 if the device is on a multi-GPU board (e.g. Gemini cards), and 0 if not;multiGpuBoardGroupID
is a unique identifier for a group of devices associated with the same board. Devices on the same multi- GPU board will share the same identifier.hostNativeAtomicSupported
is 1 if the link between the device and the host supports native atomic operations, or 0 if it is not supported.singleToDoublePrecisionPerfRatio
is the ratio of single precision performance (in floating-point operations per second) to double precision performance.pageableMemoryAccess
is 1 if the device supports coherently accessing pageable memory without calling cudaHostRegister on it, and 0 otherwise.concurrentManagedAccess
is 1 if the device can coherently access managed memory concurrently with the CPU, and 0 otherwise.computePreemptionSupported
is 1 if the device supports Compute Preemption, and 0 otherwise.canUseHostPointerForRegisteredMem
is 1 if the device can access host registered memory at the same virtual address as the CPU, and 0 otherwise.cooperativeLaunch
is 1 if the device supports launching cooperative kernels viacudaLaunchCooperativeKernel
, and 0 otherwise.cooperativeMultiDeviceLaunch
is 1 if the device supports launching cooperative kernels viacudaLaunchCooperativeKernelMultiDevice
, and 0 otherwise.sharedMemPerBlockOptin
is the per device maximum shared memory per block usable by special opt inpageableMemoryAccessUsesHostPageTables
is 1 if the device accesses pageable memory via the host’s page tables, and 0 otherwise.directManagedMemAccessFromHost
is 1 if the host can directly access managed memory on the device without migration, and 0 otherwise.maxBlocksPerMultiProcessor
is the maximum number of thread blocks that can reside on a multiprocessor.accessPolicyMaxWindowSize
is the maximum value ofnum_bytes
.reservedSharedMemPerBlock
is the shared memory reserved by CUDA driver per block in byteshostRegisterSupported
is 1 if the device supports host memory registration viacudaHostRegister
, and 0 otherwise.sparseCudaArraySupported
is 1 if the device supports sparse CUDA arrays and sparse CUDA mipmapped arrays, 0 otherwisehostRegisterReadOnlySupported
is 1 if the device supports using thecudaHostRegister
flag cudaHostRegisterReadOnly to register memory that must be mapped as read-only to the GPUtimelineSemaphoreInteropSupported
is 1 if external timeline semaphore interop is supported on the device, 0 otherwisememoryPoolsSupported
is 1 if the device supports using the cudaMallocAsync and cudaMemPool family of APIs, 0 otherwisegpuDirectRDMASupported
is 1 if the device supports GPUDirect RDMA APIs, 0 otherwisegpuDirectRDMAFlushWritesOptions
is a bitmask to be interpreted according to thecudaFlushGPUDirectRDMAWritesOptions
enumgpuDirectRDMAWritesOrdering
See thecudaGPUDirectRDMAWritesOrdering
enum for numerical valuesmemoryPoolSupportedHandleTypes
is a bitmask of handle types supported with mempool-based IPCdeferredMappingCudaArraySupported
is 1 if the device supports deferred mapping CUDA arrays and CUDA mipmapped arraysipcEventSupported
is 1 if the device supports IPC Events, and 0 otherwiseunifiedFunctionPointers
is 1 if the device support unified pointers, and 0 otherwise
- Parameters:
device (int) – Device number to get properties for
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
prop (
cudaDeviceProp
) – Properties for the specified device
- cuda.cudart.cudaDeviceGetAttribute(attr: cudaDeviceAttr, int device)#
Returns information about the device.
Returns in *value the integer value of the attribute attr on device device. The supported attributes are:
cudaDevAttrMaxThreadsPerBlock
: Maximum number of threads per blockcudaDevAttrMaxBlockDimX
: Maximum x-dimension of a blockcudaDevAttrMaxBlockDimY
: Maximum y-dimension of a blockcudaDevAttrMaxBlockDimZ
: Maximum z-dimension of a blockcudaDevAttrMaxGridDimX
: Maximum x-dimension of a gridcudaDevAttrMaxGridDimY
: Maximum y-dimension of a gridcudaDevAttrMaxGridDimZ
: Maximum z-dimension of a gridcudaDevAttrMaxSharedMemoryPerBlock
: Maximum amount of shared memory available to a thread block in bytescudaDevAttrTotalConstantMemory
: Memory available on device for constant variables in a CUDA C kernel in bytescudaDevAttrWarpSize
: Warp size in threadscudaDevAttrMaxPitch
: Maximum pitch in bytes allowed by the memory copy functions that involve memory regions allocated throughcudaMallocPitch()
cudaDevAttrMaxTexture1DWidth
: Maximum 1D texture widthcudaDevAttrMaxTexture1DLinearWidth
: Maximum width for a 1D texture bound to linear memorycudaDevAttrMaxTexture1DMipmappedWidth
: Maximum mipmapped 1D texture widthcudaDevAttrMaxTexture2DWidth
: Maximum 2D texture widthcudaDevAttrMaxTexture2DHeight
: Maximum 2D texture heightcudaDevAttrMaxTexture2DLinearWidth
: Maximum width for a 2D texture bound to linear memorycudaDevAttrMaxTexture2DLinearHeight
: Maximum height for a 2D texture bound to linear memorycudaDevAttrMaxTexture2DLinearPitch
: Maximum pitch in bytes for a 2D texture bound to linear memorycudaDevAttrMaxTexture2DMipmappedWidth
: Maximum mipmapped 2D texture widthcudaDevAttrMaxTexture2DMipmappedHeight
: Maximum mipmapped 2D texture heightcudaDevAttrMaxTexture3DWidth
: Maximum 3D texture widthcudaDevAttrMaxTexture3DHeight
: Maximum 3D texture heightcudaDevAttrMaxTexture3DDepth
: Maximum 3D texture depthcudaDevAttrMaxTexture3DWidthAlt
: Alternate maximum 3D texture width, 0 if no alternate maximum 3D texture size is supportedcudaDevAttrMaxTexture3DHeightAlt
: Alternate maximum 3D texture height, 0 if no alternate maximum 3D texture size is supportedcudaDevAttrMaxTexture3DDepthAlt
: Alternate maximum 3D texture depth, 0 if no alternate maximum 3D texture size is supportedcudaDevAttrMaxTextureCubemapWidth
: Maximum cubemap texture width or heightcudaDevAttrMaxTexture1DLayeredWidth
: Maximum 1D layered texture widthcudaDevAttrMaxTexture1DLayeredLayers
: Maximum layers in a 1D layered texturecudaDevAttrMaxTexture2DLayeredWidth
: Maximum 2D layered texture widthcudaDevAttrMaxTexture2DLayeredHeight
: Maximum 2D layered texture heightcudaDevAttrMaxTexture2DLayeredLayers
: Maximum layers in a 2D layered texturecudaDevAttrMaxTextureCubemapLayeredWidth
: Maximum cubemap layered texture width or heightcudaDevAttrMaxTextureCubemapLayeredLayers
: Maximum layers in a cubemap layered texturecudaDevAttrMaxSurface1DWidth
: Maximum 1D surface widthcudaDevAttrMaxSurface2DWidth
: Maximum 2D surface widthcudaDevAttrMaxSurface2DHeight
: Maximum 2D surface heightcudaDevAttrMaxSurface3DWidth
: Maximum 3D surface widthcudaDevAttrMaxSurface3DHeight
: Maximum 3D surface heightcudaDevAttrMaxSurface3DDepth
: Maximum 3D surface depthcudaDevAttrMaxSurface1DLayeredWidth
: Maximum 1D layered surface widthcudaDevAttrMaxSurface1DLayeredLayers
: Maximum layers in a 1D layered surfacecudaDevAttrMaxSurface2DLayeredWidth
: Maximum 2D layered surface widthcudaDevAttrMaxSurface2DLayeredHeight
: Maximum 2D layered surface heightcudaDevAttrMaxSurface2DLayeredLayers
: Maximum layers in a 2D layered surfacecudaDevAttrMaxSurfaceCubemapWidth
: Maximum cubemap surface widthcudaDevAttrMaxSurfaceCubemapLayeredWidth
: Maximum cubemap layered surface widthcudaDevAttrMaxSurfaceCubemapLayeredLayers
: Maximum layers in a cubemap layered surfacecudaDevAttrMaxRegistersPerBlock
: Maximum number of 32-bit registers available to a thread blockcudaDevAttrClockRate
: Peak clock frequency in kilohertzcudaDevAttrTextureAlignment
: Alignment requirement; texture base addresses aligned totextureAlign
bytes do not need an offset applied to texture fetchescudaDevAttrTexturePitchAlignment
: Pitch alignment requirement for 2D texture references bound to pitched memorycudaDevAttrGpuOverlap
: 1 if the device can concurrently copy memory between host and device while executing a kernel, or 0 if notcudaDevAttrMultiProcessorCount
: Number of multiprocessors on the devicecudaDevAttrKernelExecTimeout
: 1 if there is a run time limit for kernels executed on the device, or 0 if notcudaDevAttrIntegrated
: 1 if the device is integrated with the memory subsystem, or 0 if notcudaDevAttrCanMapHostMemory
: 1 if the device can map host memory into the CUDA address space, or 0 if notcudaDevAttrComputeMode
: Compute mode is the compute mode that the device is currently in. Available modes are as follows:cudaComputeModeDefault
: Default mode - Device is not restricted and multiple threads can usecudaSetDevice()
with this device.cudaComputeModeProhibited
: Compute-prohibited mode - No threads can usecudaSetDevice()
with this device.cudaComputeModeExclusiveProcess
: Compute-exclusive- process mode - Many threads in one process will be able to usecudaSetDevice()
with this device.
cudaDevAttrConcurrentKernels
: 1 if the device supports executing multiple kernels within the same context simultaneously, or 0 if not. It is not guaranteed that multiple kernels will be resident on the device concurrently so this feature should not be relied upon for correctness.cudaDevAttrEccEnabled
: 1 if error correction is enabled on the device, 0 if error correction is disabled or not supported by the devicecudaDevAttrPciBusId
: PCI bus identifier of the devicecudaDevAttrPciDeviceId
: PCI device (also known as slot) identifier of the devicecudaDevAttrTccDriver
: 1 if the device is using a TCC driver. TCC is only available on Tesla hardware running Windows Vista or later.cudaDevAttrMemoryClockRate
: Peak memory clock frequency in kilohertzcudaDevAttrGlobalMemoryBusWidth
: Global memory bus width in bitscudaDevAttrL2CacheSize
: Size of L2 cache in bytes. 0 if the device doesn’t have L2 cache.cudaDevAttrMaxThreadsPerMultiProcessor
: Maximum resident threads per multiprocessorcudaDevAttrUnifiedAddressing
: 1 if the device shares a unified address space with the host, or 0 if notcudaDevAttrComputeCapabilityMajor
: Major compute capability version numbercudaDevAttrComputeCapabilityMinor
: Minor compute capability version numbercudaDevAttrStreamPrioritiesSupported
: 1 if the device supports stream priorities, or 0 if notcudaDevAttrGlobalL1CacheSupported
: 1 if device supports caching globals in L1 cache, 0 if notcudaDevAttrLocalL1CacheSupported
: 1 if device supports caching locals in L1 cache, 0 if notcudaDevAttrMaxSharedMemoryPerMultiprocessor
: Maximum amount of shared memory available to a multiprocessor in bytes; this amount is shared by all thread blocks simultaneously resident on a multiprocessorcudaDevAttrMaxRegistersPerMultiprocessor
: Maximum number of 32-bit registers available to a multiprocessor; this number is shared by all thread blocks simultaneously resident on a multiprocessorcudaDevAttrManagedMemory
: 1 if device supports allocating managed memory, 0 if notcudaDevAttrIsMultiGpuBoard
: 1 if device is on a multi-GPU board, 0 if notcudaDevAttrMultiGpuBoardGroupID
: Unique identifier for a group of devices on the same multi-GPU boardcudaDevAttrHostNativeAtomicSupported
: 1 if the link between the device and the host supports native atomic operationscudaDevAttrSingleToDoublePrecisionPerfRatio
: Ratio of single precision performance (in floating-point operations per second) to double precision performancecudaDevAttrPageableMemoryAccess
: 1 if the device supports coherently accessing pageable memory without calling cudaHostRegister on it, and 0 otherwisecudaDevAttrConcurrentManagedAccess
: 1 if the device can coherently access managed memory concurrently with the CPU, and 0 otherwisecudaDevAttrComputePreemptionSupported
: 1 if the device supports Compute Preemption, 0 if notcudaDevAttrCanUseHostPointerForRegisteredMem
: 1 if the device can access host registered memory at the same virtual address as the CPU, and 0 otherwisecudaDevAttrCooperativeLaunch
: 1 if the device supports launching cooperative kernels viacudaLaunchCooperativeKernel
, and 0 otherwisecudaDevAttrCooperativeMultiDeviceLaunch
: 1 if the device supports launching cooperative kernels viacudaLaunchCooperativeKernelMultiDevice
, and 0 otherwisecudaDevAttrCanFlushRemoteWrites
: 1 if the device supports flushing of outstanding remote writes, and 0 otherwisecudaDevAttrHostRegisterSupported
: 1 if the device supports host memory registration viacudaHostRegister
, and 0 otherwisecudaDevAttrPageableMemoryAccessUsesHostPageTables
: 1 if the device accesses pageable memory via the host’s page tables, and 0 otherwisecudaDevAttrDirectManagedMemAccessFromHost
: 1 if the host can directly access managed memory on the device without migration, and 0 otherwisecudaDevAttrMaxSharedMemoryPerBlockOptin
: Maximum per block shared memory size on the device. This value can be opted into when usingcudaFuncSetAttribute
cudaDevAttrMaxBlocksPerMultiprocessor
: Maximum number of thread blocks that can reside on a multiprocessorcudaDevAttrMaxPersistingL2CacheSize
: Maximum L2 persisting lines capacity setting in bytescudaDevAttrMaxAccessPolicyWindowSize
: Maximum value ofnum_bytes
cudaDevAttrReservedSharedMemoryPerBlock
: Shared memory reserved by CUDA driver per block in bytescudaDevAttrSparseCudaArraySupported
: 1 if the device supports sparse CUDA arrays and sparse CUDA mipmapped arrays.cudaDevAttrHostRegisterReadOnlySupported
: Device supports using thecudaHostRegister
flag cudaHostRegisterReadOnly to register memory that must be mapped as read-only to the GPUcudaDevAttrMemoryPoolsSupported
: 1 if the device supports using the cudaMallocAsync and cudaMemPool family of APIs, and 0 otherwisecudaDevAttrGPUDirectRDMASupported
: 1 if the device supports GPUDirect RDMA APIs, and 0 otherwisecudaDevAttrGPUDirectRDMAFlushWritesOptions
: bitmask to be interpreted according to thecudaFlushGPUDirectRDMAWritesOptions
enumcudaDevAttrGPUDirectRDMAWritesOrdering
: see thecudaGPUDirectRDMAWritesOrdering
enum for numerical valuescudaDevAttrMemoryPoolSupportedHandleTypes
: Bitmask of handle types supported with mempool based IPCcudaDevAttrDeferredMappingCudaArraySupported
: 1 if the device supports deferred mapping CUDA arrays and CUDA mipmapped arrays.cudaDevAttrIpcEventSupport
: 1 if the device supports IPC Events.
- Parameters:
attr (
cudaDeviceAttr
) – Device attribute to querydevice (int) – Device number to query
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
,cudaErrorInvalidValue
value (int) – Returned device attribute value
- cuda.cudart.cudaDeviceGetDefaultMemPool(int device)#
Returns the default mempool of a device.
The default mempool of a device contains device memory from that device.
- Parameters:
device (int) – None
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
,cudaErrorInvalidValue
cudaErrorNotSupported
memPool (
cudaMemPool_t
) – None
- cuda.cudart.cudaDeviceSetMemPool(int device, memPool)#
Sets the current memory pool of a device.
The memory pool must be local to the specified device. Unless a mempool is specified in the
cudaMallocAsync
call,cudaMallocAsync
allocates from the current mempool of the provided stream’s device. By default, a device’s current memory pool is its default memory pool.- Parameters:
device (int) – None
memPool (
CUmemoryPool
orcudaMemPool_t
) – None
- Returns:
cudaSuccess
,cudaErrorInvalidValue
cudaErrorInvalidDevice
cudaErrorNotSupported
- Return type:
See also
cuDeviceSetMemPool
,cudaDeviceGetMemPool
,cudaDeviceGetDefaultMemPool
,cudaMemPoolCreate
,cudaMemPoolDestroy
,cudaMallocFromPoolAsync
Notes
Use
cudaMallocFromPoolAsync
to specify asynchronous allocations from a device different than the one the stream runs on.
- cuda.cudart.cudaDeviceGetMemPool(int device)#
Gets the current mempool for a device.
Returns the last pool provided to
cudaDeviceSetMemPool
for this device or the device’s default memory pool ifcudaDeviceSetMemPool
has never been called. By default the current mempool is the default mempool for a device, otherwise the returned pool must have been set withcuDeviceSetMemPool
orcudaDeviceSetMemPool
.- Parameters:
device (int) – None
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
cudaErrorNotSupported
memPool (
cudaMemPool_t
) – None
- cuda.cudart.cudaDeviceGetNvSciSyncAttributes(nvSciSyncAttrList, int device, int flags)#
Return NvSciSync attributes that this device can support.
Returns in nvSciSyncAttrList, the properties of NvSciSync that this CUDA device, dev can support. The returned nvSciSyncAttrList can be used to create an NvSciSync that matches this device’s capabilities.
If NvSciSyncAttrKey_RequiredPerm field in nvSciSyncAttrList is already set this API will return
cudaErrorInvalidValue
.The applications should set nvSciSyncAttrList to a valid NvSciSyncAttrList failing which this API will return
cudaErrorInvalidHandle
.The flags controls how applications intends to use the NvSciSync created from the nvSciSyncAttrList. The valid flags are:
cudaNvSciSyncAttrSignal
, specifies that the applications intends to signal an NvSciSync on this CUDA device.cudaNvSciSyncAttrWait
, specifies that the applications intends to wait on an NvSciSync on this CUDA device.
At least one of these flags must be set, failing which the API returns
cudaErrorInvalidValue
. Both the flags are orthogonal to one another: a developer may set both these flags that allows to set both wait and signal specific attributes in the same nvSciSyncAttrList.Note that this API updates the input nvSciSyncAttrList with values equivalent to the following public attribute key-values: NvSciSyncAttrKey_RequiredPerm is set to
NvSciSyncAccessPerm_SignalOnly if
cudaNvSciSyncAttrSignal
is set in flags.NvSciSyncAccessPerm_WaitOnly if
cudaNvSciSyncAttrWait
is set in flags.NvSciSyncAccessPerm_WaitSignal if both
cudaNvSciSyncAttrWait
andcudaNvSciSyncAttrSignal
are set in flags. NvSciSyncAttrKey_PrimitiveInfo is set toNvSciSyncAttrValPrimitiveType_SysmemSemaphore on any valid device.
NvSciSyncAttrValPrimitiveType_Syncpoint if device is a Tegra device.
NvSciSyncAttrValPrimitiveType_SysmemSemaphorePayload64b if device is GA10X+. NvSciSyncAttrKey_GpuId is set to the same UUID that is returned in None from
cudaDeviceGetProperties
for this device.
cudaSuccess
,cudaErrorDeviceUninitialized
,cudaErrorInvalidValue
,cudaErrorInvalidHandle
,cudaErrorInvalidDevice
,cudaErrorNotSupported
,cudaErrorMemoryAllocation
- Parameters:
nvSciSyncAttrList (Any) – Return NvSciSync attributes supported.
device (int) – Valid Cuda Device to get NvSciSync attributes for.
flags (int) – flags describing NvSciSync usage.
- Return type:
- cuda.cudart.cudaDeviceGetP2PAttribute(attr: cudaDeviceP2PAttr, int srcDevice, int dstDevice)#
Queries attributes of the link between two devices.
Returns in *value the value of the requested attribute attrib of the link between srcDevice and dstDevice. The supported attributes are:
cudaDevP2PAttrPerformanceRank
: A relative value indicating the performance of the link between two devices. Lower value means better performance (0 being the value used for most performant link).cudaDevP2PAttrAccessSupported
: 1 if peer access is enabled.cudaDevP2PAttrNativeAtomicSupported
: 1 if native atomic operations over the link are supported.cudaDevP2PAttrCudaArrayAccessSupported
: 1 if accessing CUDA arrays over the link is supported.
Returns
cudaErrorInvalidDevice
if srcDevice or dstDevice are not valid or if they represent the same device.Returns
cudaErrorInvalidValue
if attrib is not valid or if value is a null pointer.- Parameters:
attrib (
cudaDeviceP2PAttr
) – The requested attribute of the link between srcDevice and dstDevice.srcDevice (int) – The source device of the target link.
dstDevice (int) – The destination device of the target link.
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
,cudaErrorInvalidValue
value (int) – Returned value of the requested attribute
- cuda.cudart.cudaChooseDevice(cudaDeviceProp prop: cudaDeviceProp)#
Select compute-device which best matches criteria.
Returns in *device the device which has properties that best match *prop.
- Parameters:
prop (
cudaDeviceProp
) – Desired device properties- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
device (int) – Device with best match
- cuda.cudart.cudaInitDevice(int device, unsigned int deviceFlags, unsigned int flags)#
Initialize device to be used for GPU executions.
This function will initialize the CUDA Runtime structures and primary context on device when called, but the context will not be made current to device.
When
cudaInitDeviceFlagsAreValid
is set in flags, deviceFlags are applied to the requested device. The values of deviceFlags match those of the flags parameters incudaSetDeviceFlags
. The effect may be verified bycudaGetDeviceFlags
.This function will return an error if the device is in
cudaComputeModeExclusiveProcess
and is occupied by another process or if the device is incudaComputeModeProhibited
.- Parameters:
device (int) – Device on which the runtime will initialize itself.
deviceFlags (unsigned int) – Parameters for device operation.
flags (unsigned int) – Flags for controlling the device initialization.
- Returns:
- Return type:
- cuda.cudart.cudaSetDevice(int device)#
Set device to be used for GPU executions.
Sets device as the current device for the calling host thread. Valid device id’s are 0 to (
cudaGetDeviceCount()
- 1).Any device memory subsequently allocated from this host thread using
cudaMalloc()
,cudaMallocPitch()
orcudaMallocArray()
will be physically resident on device. Any host memory allocated from this host thread usingcudaMallocHost()
orcudaHostAlloc()
orcudaHostRegister()
will have its lifetime associated with device. Any streams or events created from this host thread will be associated with device. Any kernels launched from this host thread using the <<<>>> operator orcudaLaunchKernel()
will be executed on device.This call may be made from any host thread, to any device, and at any time. This function will do no synchronization with the previous or new device, and should only take significant time when it initializes the runtime’s context state. This call will bind the primary context of the specified device to the calling thread and all the subsequent memory allocations, stream and event creations, and kernel launches will be associated with the primary context. This function will also immediately initialize the runtime state on the primary context, and the context will be current on device immediately. This function will return an error if the device is in
cudaComputeModeExclusiveProcess
and is occupied by another process or if the device is incudaComputeModeProhibited
.It is not required to call
cudaInitDevice
before using this function.- Parameters:
device (int) – Device on which the active host thread should execute the device code.
- Returns:
cudaSuccess
,cudaErrorInvalidDevice
,cudaErrorDeviceUnavailable
,- Return type:
- cuda.cudart.cudaGetDevice()#
Returns which device is currently being used.
Returns in *device the current device for the calling host thread.
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorDeviceUnavailable
,device (int) – Returns the device on which the active host thread executes the device code.
- cuda.cudart.cudaSetDeviceFlags(unsigned int flags)#
Sets flags to be used for device executions.
Records flags as the flags for the current device. If the current device has been set and that device has already been initialized, the previous flags are overwritten. If the current device has not been initialized, it is initialized with the provided flags. If no device has been made current to the calling thread, a default device is selected and initialized with the provided flags.
The two LSBs of the flags parameter can be used to control how the CPU thread interacts with the OS scheduler when waiting for results from the device.
cudaDeviceScheduleAuto
: The default value if the flags parameter is zero, uses a heuristic based on the number of active CUDA contexts in the process C and the number of logical processors in the system P. If C > P, then CUDA will yield to other OS threads when waiting for the device, otherwise CUDA will not yield while waiting for results and actively spin on the processor. Additionally, on Tegra devices,cudaDeviceScheduleAuto
uses a heuristic based on the power profile of the platform and may choosecudaDeviceScheduleBlockingSync
for low-powered devices.cudaDeviceScheduleSpin
: Instruct CUDA to actively spin when waiting for results from the device. This can decrease latency when waiting for the device, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread.cudaDeviceScheduleYield
: Instruct CUDA to yield its thread when waiting for results from the device. This can increase latency when waiting for the device, but can increase the performance of CPU threads performing work in parallel with the device.cudaDeviceScheduleBlockingSync
: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the device to finish work.cudaDeviceBlockingSync
: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the device to finish work.Deprecated:
This flag was deprecated as of CUDA 4.0 and replaced withcudaDeviceScheduleBlockingSync
.cudaDeviceMapHost
: This flag enables allocating pinned host memory that is accessible to the device. It is implicit for the runtime but may be absent if a context is created using the driver API. If this flag is not set,cudaHostGetDevicePointer()
will always return a failure code.cudaDeviceLmemResizeToMax
: Instruct CUDA to not reduce local memory after resizing local memory for a kernel. This can prevent thrashing by local memory allocations when launching many kernels with high local memory usage at the cost of potentially increased memory usage.Deprecated:
This flag is deprecated and the behavior enabled by this flag is now the default and cannot be disabled.
- Parameters:
flags (unsigned int) – Parameters for device operation
- Returns:
- Return type:
See also
cudaGetDeviceFlags
,cudaGetDeviceCount
,cudaGetDevice
,cudaGetDeviceProperties
,cudaSetDevice
,cudaSetValidDevices
,cudaInitDevice
,cudaChooseDevice
,cuDevicePrimaryCtxSetFlags
- cuda.cudart.cudaGetDeviceFlags()#
Gets the flags for the current device.
Returns in flags the flags for the current device. If there is a current device for the calling thread, the flags for the device are returned. If there is no current device, the flags for the first device are returned, which may be the default flags. Compare to the behavior of
cudaSetDeviceFlags
.Typically, the flags returned should match the behavior that will be seen if the calling thread uses a device after this call, without any change to the flags or current device inbetween by this or another thread. Note that if the device is not initialized, it is possible for another thread to change the flags for the current device before it is initialized. Additionally, when using exclusive mode, if this thread has not requested a specific device, it may use a device other than the first device, contrary to the assumption made by this function.
If a context has been created via the driver API and is current to the calling thread, the flags for that context are always returned.
Flags returned by this function may specifically include
cudaDeviceMapHost
even though it is not accepted bycudaSetDeviceFlags
because it is implicit in runtime API flags. The reason for this is that the current context may have been created via the driver API in which case the flag is not implicit and may be unset.- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
flags (unsigned int) – Pointer to store the device flags
Error Handling#
This section describes the error handling functions of the CUDA runtime application programming interface.
- cuda.cudart.cudaGetLastError()#
Returns the last error from a runtime call.
Returns the last error that has been produced by any of the runtime calls in the same instance of the CUDA Runtime library in the host thread and resets it to
cudaSuccess
.Note: Multiple instances of the CUDA Runtime library can be present in an application when using a library that statically links the CUDA Runtime.
- Returns:
cudaSuccess
,cudaErrorMissingConfiguration
,cudaErrorMemoryAllocation
,cudaErrorInitializationError
,cudaErrorLaunchFailure
,cudaErrorLaunchTimeout
,cudaErrorLaunchOutOfResources
,cudaErrorInvalidDeviceFunction
,cudaErrorInvalidConfiguration
,cudaErrorInvalidDevice
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidSymbol
,cudaErrorUnmapBufferObjectFailed
,cudaErrorInvalidDevicePointer
,cudaErrorInvalidTexture
,cudaErrorInvalidTextureBinding
,cudaErrorInvalidChannelDescriptor
,cudaErrorInvalidMemcpyDirection
,cudaErrorInvalidFilterSetting
,cudaErrorInvalidNormSetting
,cudaErrorUnknown
,cudaErrorInvalidResourceHandle
,cudaErrorInsufficientDriver
,cudaErrorNoDevice
,cudaErrorSetOnActiveProcess
,cudaErrorStartupFailure
,cudaErrorInvalidPtx
,cudaErrorUnsupportedPtxVersion
,cudaErrorNoKernelImageForDevice
,cudaErrorJitCompilerNotFound
,cudaErrorJitCompilationDisabled
- Return type:
See also
cudaPeekAtLastError
,cudaGetErrorName
,cudaGetErrorString
,cudaError
- cuda.cudart.cudaPeekAtLastError()#
Returns the last error from a runtime call.
Returns the last error that has been produced by any of the runtime calls in the same instance of the CUDA Runtime library in the host thread. This call does not reset the error to
cudaSuccess
likecudaGetLastError()
.Note: Multiple instances of the CUDA Runtime library can be present in an application when using a library that statically links the CUDA Runtime.
- Returns:
cudaSuccess
,cudaErrorMissingConfiguration
,cudaErrorMemoryAllocation
,cudaErrorInitializationError
,cudaErrorLaunchFailure
,cudaErrorLaunchTimeout
,cudaErrorLaunchOutOfResources
,cudaErrorInvalidDeviceFunction
,cudaErrorInvalidConfiguration
,cudaErrorInvalidDevice
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidSymbol
,cudaErrorUnmapBufferObjectFailed
,cudaErrorInvalidDevicePointer
,cudaErrorInvalidTexture
,cudaErrorInvalidTextureBinding
,cudaErrorInvalidChannelDescriptor
,cudaErrorInvalidMemcpyDirection
,cudaErrorInvalidFilterSetting
,cudaErrorInvalidNormSetting
,cudaErrorUnknown
,cudaErrorInvalidResourceHandle
,cudaErrorInsufficientDriver
,cudaErrorNoDevice
,cudaErrorSetOnActiveProcess
,cudaErrorStartupFailure
,cudaErrorInvalidPtx
,cudaErrorUnsupportedPtxVersion
,cudaErrorNoKernelImageForDevice
,cudaErrorJitCompilerNotFound
,cudaErrorJitCompilationDisabled
- Return type:
See also
cudaGetLastError
,cudaGetErrorName
,cudaGetErrorString
,cudaError
- cuda.cudart.cudaGetErrorName(error: cudaError_t)#
Returns the string representation of an error code enum name.
Returns a string containing the name of an error code in the enum. If the error code is not recognized, “unrecognized error code” is returned.
- Parameters:
error (
cudaError_t
) – Error code to convert to string- Returns:
cudaError_t.cudaSuccess – cudaError_t.cudaSuccess
bytes – char* pointer to a NULL-terminated string
See also
cudaGetErrorString
,cudaGetLastError
,cudaPeekAtLastError
,cudaError
,cuGetErrorName
- cuda.cudart.cudaGetErrorString(error: cudaError_t)#
Returns the description string for an error code.
Returns the description string for an error code. If the error code is not recognized, “unrecognized error code” is returned.
- Parameters:
error (
cudaError_t
) – Error code to convert to string- Returns:
cudaError_t.cudaSuccess – cudaError_t.cudaSuccess
bytes – char* pointer to a NULL-terminated string
See also
cudaGetErrorName
,cudaGetLastError
,cudaPeekAtLastError
,cudaError
,cuGetErrorString
Stream Management#
This section describes the stream management functions of the CUDA runtime application programming interface.
- class cuda.cudart.cudaStreamCallback_t(*args, **kwargs)#
- getPtr()#
Get memory address of class instance
- cuda.cudart.cudaStreamCreate()#
Create an asynchronous stream.
Creates a new asynchronous stream.
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
pStream (
cudaStream_t
) – Pointer to new stream identifier
- cuda.cudart.cudaStreamCreateWithFlags(unsigned int flags)#
Create an asynchronous stream.
Creates a new asynchronous stream. The flags argument determines the behaviors of the stream. Valid values for flags are
cudaStreamDefault
: Default stream creation flag.cudaStreamNonBlocking
: Specifies that work running in the created stream may run concurrently with work in stream 0 (the NULL stream), and that the created stream should perform no implicit synchronization with stream 0.
- Parameters:
flags (unsigned int) – Parameters for stream creation
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
pStream (
cudaStream_t
) – Pointer to new stream identifier
- cuda.cudart.cudaStreamCreateWithPriority(unsigned int flags, int priority)#
Create an asynchronous stream with the specified priority.
Creates a stream with the specified priority and returns a handle in pStream. This API alters the scheduler priority of work in the stream. Work in a higher priority stream may preempt work already executing in a low priority stream.
priority follows a convention where lower numbers represent higher priorities. ‘0’ represents default priority. The range of meaningful numerical priorities can be queried using
cudaDeviceGetStreamPriorityRange
. If the specified priority is outside the numerical range returned bycudaDeviceGetStreamPriorityRange
, it will automatically be clamped to the lowest or the highest number in the range.- Parameters:
flags (unsigned int) – Flags for stream creation. See
cudaStreamCreateWithFlags
for a list of valid flags that can be passedpriority (int) – Priority of the stream. Lower numbers represent higher priorities. See
cudaDeviceGetStreamPriorityRange
for more information about the meaningful stream priorities that can be passed.
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
pStream (
cudaStream_t
) – Pointer to new stream identifier
See also
cudaStreamCreate
,cudaStreamCreateWithFlags
,cudaDeviceGetStreamPriorityRange
,cudaStreamGetPriority
,cudaStreamQuery
,cudaStreamWaitEvent
,cudaStreamAddCallback
,cudaStreamSynchronize
,cudaStreamDestroy
,cuStreamCreateWithPriority
Notes
Stream priorities are supported only on GPUs with compute capability 3.5 or higher.
In the current implementation, only compute kernels launched in priority streams are affected by the stream’s priority. Stream priorities have no effect on host-to-device and device-to-host memory operations.
- cuda.cudart.cudaStreamGetPriority(hStream)#
Query the priority of a stream.
Query the priority of a stream. The priority is returned in in priority. Note that if the stream was created with a priority outside the meaningful numerical range returned by
cudaDeviceGetStreamPriorityRange
, this function returns the clamped priority. SeecudaStreamCreateWithPriority
for details about priority clamping.- Parameters:
hStream (
CUstream
orcudaStream_t
) – Handle to the stream to be queried- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
priority (int) – Pointer to a signed integer in which the stream’s priority is returned
- cuda.cudart.cudaStreamGetFlags(hStream)#
Query the flags of a stream.
Query the flags of a stream. The flags are returned in flags. See
cudaStreamCreateWithFlags
for a list of valid flags.- Parameters:
hStream (
CUstream
orcudaStream_t
) – Handle to the stream to be queried- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
flags (unsigned int) – Pointer to an unsigned integer in which the stream’s flags are returned
- cuda.cudart.cudaStreamGetId(hStream)#
Query the Id of a stream.
Query the Id of a stream. The Id is returned in streamId. The Id is unique for the life of the program.
The stream handle hStream can refer to any of the following:
a stream created via any of the CUDA runtime APIs such as
cudaStreamCreate
,cudaStreamCreateWithFlags
andcudaStreamCreateWithPriority
, or their driver API equivalents such ascuStreamCreate
orcuStreamCreateWithPriority
. Passing an invalid handle will result in undefined behavior.any of the special streams such as the NULL stream,
cudaStreamLegacy
andcudaStreamPerThread
respectively. The driver API equivalents of these are also accepted which are NULL,CU_STREAM_LEGACY
andCU_STREAM_PER_THREAD
.
- Parameters:
hStream (
CUstream
orcudaStream_t
) – Handle to the stream to be queried- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
streamId (unsigned long long) – Pointer to an unsigned long long in which the stream Id is returned
- cuda.cudart.cudaCtxResetPersistingL2Cache()#
Resets all persisting lines in cache to normal status.
Resets all persisting lines in cache to normal status. Takes effect on function return.
- Returns:
- Return type:
See also
- cuda.cudart.cudaStreamCopyAttributes(dst, src)#
Copies attributes from source stream to destination stream.
Copies attributes from source stream src to destination stream dst. Both streams must have the same context.
- Parameters:
dst (
CUstream
orcudaStream_t
) – Destination streamsrc (
CUstream
orcudaStream_t
) – Source stream For attributes seecudaStreamAttrID
- Returns:
- Return type:
See also
- cuda.cudart.cudaStreamGetAttribute(hStream, attr: cudaStreamAttrID)#
Queries stream attribute.
Queries attribute attr from hStream and stores it in corresponding member of value_out.
- Parameters:
hStream (
CUstream
orcudaStream_t
) –attr (
cudaStreamAttrID
) –
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
value_out (
cudaStreamAttrValue
)
See also
- cuda.cudart.cudaStreamSetAttribute(hStream, attr: cudaStreamAttrID, cudaStreamAttrValue value: cudaStreamAttrValue)#
Sets stream attribute.
Sets attribute attr on hStream from corresponding attribute of value. The updated attribute will be applied to subsequent work submitted to the stream. It will not affect previously submitted work.
- Parameters:
hStream (
CUstream
orcudaStream_t
) –attr (
cudaStreamAttrID
) –value (
cudaStreamAttrValue
) –
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
- Return type:
See also
- cuda.cudart.cudaStreamDestroy(stream)#
Destroys and cleans up an asynchronous stream.
Destroys and cleans up the asynchronous stream specified by stream.
In case the device is still doing work in the stream stream when
cudaStreamDestroy()
is called, the function will return immediately and the resources associated with stream will be released automatically once the device has completed all work in stream.- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream identifier- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
- Return type:
- cuda.cudart.cudaStreamWaitEvent(stream, event, unsigned int flags)#
Make a compute stream wait on an event.
Makes all future work submitted to stream wait for all work captured in event. See
cudaEventRecord()
for details on what is captured by an event. The synchronization will be performed efficiently on the device when applicable. event may be from a different device than stream.flags include:
cudaEventWaitDefault
: Default event creation flag.cudaEventWaitExternal
: Event is captured in the graph as an external event node when performing stream capture.
- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream to waitevent (
CUevent
orcudaEvent_t
) – Event to wait onflags (unsigned int) – Parameters for the operation(See above)
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
- Return type:
- cuda.cudart.cudaStreamAddCallback(stream, callback, userData, unsigned int flags)#
Add a callback to a compute stream.
Adds a callback to be called on the host after all currently enqueued items in the stream have completed. For each cudaStreamAddCallback call, a callback will be executed exactly once. The callback will block later work in the stream until it is finished.
The callback may be passed
cudaSuccess
or an error code. In the event of a device error, all subsequently executed callbacks will receive an appropriatecudaError_t
.Callbacks must not make any CUDA API calls. Attempting to use CUDA APIs may result in
cudaErrorNotPermitted
. Callbacks must not perform any synchronization that may depend on outstanding device work or other callbacks that are not mandated to run earlier. Callbacks without a mandated order (in independent streams) execute in undefined order and may be serialized.For the purposes of Unified Memory, callback execution makes a number of guarantees:
The callback stream is considered idle for the duration of the callback. Thus, for example, a callback may always use memory attached to the callback stream.
The start of execution of a callback has the same effect as synchronizing an event recorded in the same stream immediately prior to the callback. It thus synchronizes streams which have been “joined” prior to the callback.
Adding device work to any stream does not have the effect of making the stream active until all preceding callbacks have executed. Thus, for example, a callback might use global attached memory even if work has been added to another stream, if it has been properly ordered with an event.
Completion of a callback does not cause a stream to become active except as described above. The callback stream will remain idle if no device work follows the callback, and will remain idle across consecutive callbacks without device work in between. Thus, for example, stream synchronization can be done by signaling from a callback at the end of the stream.
- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream to add callback tocallback (
cudaStreamCallback_t
) – The function to call once preceding stream operations are completeuserData (Any) – User specified data to be passed to the callback function
flags (unsigned int) – Reserved for future use, must be 0
- Returns:
cudaSuccess
,cudaErrorInvalidResourceHandle
,cudaErrorInvalidValue
,cudaErrorNotSupported
- Return type:
See also
cudaStreamCreate
,cudaStreamCreateWithFlags
,cudaStreamQuery
,cudaStreamSynchronize
,cudaStreamWaitEvent
,cudaStreamDestroy
,cudaMallocManaged
,cudaStreamAttachMemAsync
,cudaLaunchHostFunc
,cuStreamAddCallback
Notes
This function is slated for eventual deprecation and removal. If you do not require the callback to execute in case of a device error, consider using
cudaLaunchHostFunc
. Additionally, this function is not supported withcudaStreamBeginCapture
andcudaStreamEndCapture
, unlikecudaLaunchHostFunc
.
- cuda.cudart.cudaStreamSynchronize(stream)#
Waits for stream tasks to complete.
Blocks until stream has completed all operations. If the
cudaDeviceScheduleBlockingSync
flag was set for this device, the host thread will block until the stream is finished with all of its tasks.- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream identifier- Returns:
- Return type:
- cuda.cudart.cudaStreamQuery(stream)#
Queries an asynchronous stream for completion status.
Returns
cudaSuccess
if all operations in stream have completed, orcudaErrorNotReady
if not.For the purposes of Unified Memory, a return value of
cudaSuccess
is equivalent to having calledcudaStreamSynchronize()
.- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream identifier- Returns:
cudaSuccess
,cudaErrorNotReady
,cudaErrorInvalidResourceHandle
- Return type:
- cuda.cudart.cudaStreamAttachMemAsync(stream, devPtr, size_t length, unsigned int flags)#
Attach memory to a stream asynchronously.
Enqueues an operation in stream to specify stream association of length bytes of memory starting from devPtr. This function is a stream-ordered operation, meaning that it is dependent on, and will only take effect when, previous work in stream has completed. Any previous association is automatically replaced.
devPtr must point to an one of the following types of memories:
managed memory declared using the managed keyword or allocated with
cudaMallocManaged
.a valid host-accessible region of system-allocated pageable memory. This type of memory may only be specified if the device associated with the stream reports a non-zero value for the device attribute
cudaDevAttrPageableMemoryAccess
.
For managed allocations, length must be either zero or the entire allocation’s size. Both indicate that the entire allocation’s stream association is being changed. Currently, it is not possible to change stream association for a portion of a managed allocation.
For pageable allocations, length must be non-zero.
The stream association is specified using flags which must be one of
cudaMemAttachGlobal
,cudaMemAttachHost
orcudaMemAttachSingle
. The default value for flags iscudaMemAttachSingle
If thecudaMemAttachGlobal
flag is specified, the memory can be accessed by any stream on any device. If thecudaMemAttachHost
flag is specified, the program makes a guarantee that it won’t access the memory on the device from any stream on a device that has a zero value for the device attributecudaDevAttrConcurrentManagedAccess
. If thecudaMemAttachSingle
flag is specified and stream is associated with a device that has a zero value for the device attributecudaDevAttrConcurrentManagedAccess
, the program makes a guarantee that it will only access the memory on the device from stream. It is illegal to attach singly to the NULL stream, because the NULL stream is a virtual global stream and not a specific stream. An error will be returned in this case.When memory is associated with a single stream, the Unified Memory system will allow CPU access to this memory region so long as all operations in stream have completed, regardless of whether other streams are active. In effect, this constrains exclusive ownership of the managed memory region by an active GPU to per-stream activity instead of whole-GPU activity.
Accessing memory on the device from streams that are not associated with it will produce undefined results. No error checking is performed by the Unified Memory system to ensure that kernels launched into other streams do not access this region.
It is a program’s responsibility to order calls to
cudaStreamAttachMemAsync
via events, synchronization or other means to ensure legal access to memory at all times. Data visibility and coherency will be changed appropriately for all kernels which follow a stream-association change.If stream is destroyed while data is associated with it, the association is removed and the association reverts to the default visibility of the allocation as specified at
cudaMallocManaged
. For managed variables, the default association is alwayscudaMemAttachGlobal
. Note that destroying a stream is an asynchronous operation, and as a result, the change to default association won’t happen until all work in the stream has completed.- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream in which to enqueue the attach operationdevPtr (Any) – Pointer to memory (must be a pointer to managed memory or to a valid host-accessible region of system-allocated memory)
length (size_t) – Length of memory (defaults to zero)
flags (unsigned int) – Must be one of
cudaMemAttachGlobal
,cudaMemAttachHost
orcudaMemAttachSingle
(defaults tocudaMemAttachSingle
)
- Returns:
cudaSuccess
,cudaErrorNotReady
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
- Return type:
- cuda.cudart.cudaStreamBeginCapture(stream, mode: cudaStreamCaptureMode)#
Begins graph capture on a stream.
Begin graph capture on stream. When a stream is in capture mode, all operations pushed into the stream will not be executed, but will instead be captured into a graph, which will be returned via
cudaStreamEndCapture
. Capture may not be initiated if stream iscudaStreamLegacy
. Capture must be ended on the same stream in which it was initiated, and it may only be initiated if the stream is not already in capture mode. The capture mode may be queried viacudaStreamIsCapturing
. A unique id representing the capture sequence may be queried viacudaStreamGetCaptureInfo
.If mode is not
cudaStreamCaptureModeRelaxed
,cudaStreamEndCapture
must be called on this stream from the same thread.- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream in which to initiate capturemode (
cudaStreamCaptureMode
) – Controls the interaction of this capture sequence with other API calls that are potentially unsafe. For more details seecudaThreadExchangeStreamCaptureMode
.
- Returns:
- Return type:
See also
cudaStreamCreate
,cudaStreamIsCapturing
,cudaStreamEndCapture
,cudaThreadExchangeStreamCaptureMode
Notes
Kernels captured using this API must not use texture and surface references. Reading or writing through any texture or surface reference is undefined behavior. This restriction does not apply to texture and surface objects.
- cuda.cudart.cudaThreadExchangeStreamCaptureMode(mode: cudaStreamCaptureMode)#
Swaps the stream capture interaction mode for a thread.
Sets the calling thread’s stream capture interaction mode to the value contained in *mode, and overwrites *mode with the previous mode for the thread. To facilitate deterministic behavior across function or module boundaries, callers are encouraged to use this API in a push-pop fashion:
View CUDA Toolkit Documentation for a C++ code example
During stream capture (see
cudaStreamBeginCapture
), some actions, such as a call tocudaMalloc
, may be unsafe. In the case ofcudaMalloc
, the operation is not enqueued asynchronously to a stream, and is not observed by stream capture. Therefore, if the sequence of operations captured viacudaStreamBeginCapture
depended on the allocation being replayed whenever the graph is launched, the captured graph would be invalid.Therefore, stream capture places restrictions on API calls that can be made within or concurrently to a
cudaStreamBeginCapture
-cudaStreamEndCapture
sequence. This behavior can be controlled via this API and flags tocudaStreamBeginCapture
.A thread’s mode is one of the following:
cudaStreamCaptureModeGlobal: This is the default mode. If the local thread has an ongoing capture sequence that was not initiated with cudaStreamCaptureModeRelaxed at cuStreamBeginCapture, or if any other thread has a concurrent capture sequence initiated with cudaStreamCaptureModeGlobal, this thread is prohibited from potentially unsafe API calls.
cudaStreamCaptureModeThreadLocal: If the local thread has an ongoing capture sequence not initiated with cudaStreamCaptureModeRelaxed, it is prohibited from potentially unsafe API calls. Concurrent capture sequences in other threads are ignored.
cudaStreamCaptureModeRelaxed: The local thread is not prohibited from potentially unsafe API calls. Note that the thread is still prohibited from API calls which necessarily conflict with stream capture, for example, attempting
cudaEventQuery
on an event that was last recorded inside a capture sequence.
- Parameters:
mode (
cudaStreamCaptureMode
) – Pointer to mode value to swap with the current mode- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
mode (
cudaStreamCaptureMode
) – Pointer to mode value to swap with the current mode
See also
- cuda.cudart.cudaStreamEndCapture(stream)#
Ends capture on a stream, returning the captured graph.
End capture on stream, returning the captured graph via pGraph. Capture must have been initiated on stream via a call to
cudaStreamBeginCapture
. If capture was invalidated, due to a violation of the rules of stream capture, then a NULL graph will be returned.If the mode argument to
cudaStreamBeginCapture
was notcudaStreamCaptureModeRelaxed
, this call must be from the same thread ascudaStreamBeginCapture
.- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream to query- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorStreamCaptureWrongThread
pGraph (
cudaGraph_t
) – The captured graph
- cuda.cudart.cudaStreamIsCapturing(stream)#
Returns a stream’s capture status.
Return the capture status of stream via pCaptureStatus. After a successful call, *pCaptureStatus will contain one of the following:
cudaStreamCaptureStatusNone
: The stream is not capturing.cudaStreamCaptureStatusActive
: The stream is capturing.cudaStreamCaptureStatusInvalidated
: The stream was capturing but an error has invalidated the capture sequence. The capture sequence must be terminated withcudaStreamEndCapture
on the stream where it was initiated in order to continue using stream.
Note that, if this is called on
cudaStreamLegacy
(the “null stream”) while a blocking stream on the same device is capturing, it will returncudaErrorStreamCaptureImplicit
and *pCaptureStatus is unspecified after the call. The blocking stream capture is not invalidated.When a blocking stream is capturing, the legacy stream is in an unusable state until the blocking stream capture is terminated. The legacy stream is not supported for stream capture, but attempted use would have an implicit dependency on the capturing stream(s).
- Parameters:
stream (
CUstream
orcudaStream_t
) – Stream to query- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorStreamCaptureImplicit
pCaptureStatus (
cudaStreamCaptureStatus
) – Returns the stream’s capture status
- cuda.cudart.cudaStreamGetCaptureInfo(stream)#
Query a stream’s capture state.
Query stream state related to stream capture.
If called on
cudaStreamLegacy
(the “null stream”) while a stream not created withcudaStreamNonBlocking
is capturing, returnscudaErrorStreamCaptureImplicit
.Valid data (other than capture status) is returned only if both of the following are true:
the call returns cudaSuccess
the returned capture status is
cudaStreamCaptureStatusActive
- Parameters:
stream (
CUstream
orcudaStream_t
) – The stream to query- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorStreamCaptureImplicit
captureStatus_out (
cudaStreamCaptureStatus
) – Location to return the capture status of the stream; requiredid_out (unsigned long long) – Optional location to return an id for the capture sequence, which is unique over the lifetime of the process
graph_out (
cudaGraph_t
) – Optional location to return the graph being captured into. All operations other than destroy and node removal are permitted on the graph while the capture sequence is in progress. This API does not transfer ownership of the graph, which is transferred or destroyed atcudaStreamEndCapture
. Note that the graph handle may be invalidated before end of capture for certain errors. Nodes that are or become unreachable from the original stream atcudaStreamEndCapture
due to direct actions on the graph do not triggercudaErrorStreamCaptureUnjoined
.dependencies_out (List[
cudaGraphNode_t
]) – Optional location to store a pointer to an array of nodes. The next node to be captured in the stream will depend on this set of nodes, absent operations such as event wait which modify this set. The array pointer is valid until the next API call which operates on the stream or until end of capture. The node handles may be copied out and are valid until they or the graph is destroyed. The driver- owned array may also be passed directly to APIs that operate on the graph (not the stream) without copying.numDependencies_out (int) – Optional location to store the size of the array returned in dependencies_out.
- cuda.cudart.cudaStreamUpdateCaptureDependencies(stream, dependencies: List[cudaGraphNode_t], size_t numDependencies, unsigned int flags)#
Update the set of dependencies in a capturing stream (11.3+)
Modifies the dependency set of a capturing stream. The dependency set is the set of nodes that the next captured node in the stream will depend on.
Valid flags are
cudaStreamAddCaptureDependencies
andcudaStreamSetCaptureDependencies
. These control whether the set passed to the API is added to the existing set or replaces it. A flags value of 0 defaults tocudaStreamAddCaptureDependencies
.Nodes that are removed from the dependency set via this API do not result in
cudaErrorStreamCaptureUnjoined
if they are unreachable from the stream atcudaStreamEndCapture
.Returns
cudaErrorIllegalState
if the stream is not capturing.This API is new in CUDA 11.3. Developers requiring compatibility across minor versions of the CUDA driver to 11.0 should not use this API or provide a fallback.
- Parameters:
stream (
CUstream
orcudaStream_t
) – Nonedependencies (List[
cudaGraphNode_t
]) – NonenumDependencies (size_t) – None
flags (unsigned int) – None
- Returns:
- Return type:
Event Management#
This section describes the event management functions of the CUDA runtime application programming interface.
- cuda.cudart.cudaEventCreate()#
Creates an event object.
Creates an event object for the current device using
cudaEventDefault
.- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorLaunchFailure
,cudaErrorMemoryAllocation
event (
cudaEvent_t
) – Newly created event
- cuda.cudart.cudaEventCreateWithFlags(unsigned int flags)#
Creates an event object with the specified flags.
Creates an event object for the current device with the specified flags. Valid flags include:
cudaEventDefault
: Default event creation flag.cudaEventBlockingSync
: Specifies that event should use blocking synchronization. A host thread that usescudaEventSynchronize()
to wait on an event created with this flag will block until the event actually completes.cudaEventDisableTiming
: Specifies that the created event does not need to record timing data. Events created with this flag specified and thecudaEventBlockingSync
flag not specified will provide the best performance when used withcudaStreamWaitEvent()
andcudaEventQuery()
.cudaEventInterprocess
: Specifies that the created event may be used as an interprocess event bycudaIpcGetEventHandle()
.cudaEventInterprocess
must be specified along withcudaEventDisableTiming
.
- Parameters:
flags (unsigned int) – Flags for new event
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorLaunchFailure
,cudaErrorMemoryAllocation
event (
cudaEvent_t
) – Newly created event
See also
cudaEventCreate (C API)
,cudaEventSynchronize
,cudaEventDestroy
,cudaEventElapsedTime
,cudaStreamWaitEvent
,cuEventCreate
- cuda.cudart.cudaEventRecord(event, stream)#
Records an event.
Captures in event the contents of stream at the time of this call. event and stream must be on the same CUDA context. Calls such as
cudaEventQuery()
orcudaStreamWaitEvent()
will then examine or wait for completion of the work that was captured. Uses of stream after this call do not modify event. See note on default stream behavior for what is captured in the default case.cudaEventRecord()
can be called multiple times on the same event and will overwrite the previously captured state. Other APIs such ascudaStreamWaitEvent()
use the most recently captured state at the time of the API call, and are not affected by later calls tocudaEventRecord()
. Before the first call tocudaEventRecord()
, an event represents an empty set of work, so for examplecudaEventQuery()
would returncudaSuccess
.- Parameters:
event (
CUevent
orcudaEvent_t
) – Event to recordstream (
CUstream
orcudaStream_t
) – Stream in which to record event
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
,cudaErrorLaunchFailure
- Return type:
See also
cudaEventCreate (C API)
,cudaEventCreateWithFlags
,cudaEventQuery
,cudaEventSynchronize
,cudaEventDestroy
,cudaEventElapsedTime
,cudaStreamWaitEvent
,cudaEventRecordWithFlags
,cuEventRecord
- cuda.cudart.cudaEventRecordWithFlags(event, stream, unsigned int flags)#
Records an event.
Captures in event the contents of stream at the time of this call. event and stream must be on the same CUDA context. Calls such as
cudaEventQuery()
orcudaStreamWaitEvent()
will then examine or wait for completion of the work that was captured. Uses of stream after this call do not modify event. See note on default stream behavior for what is captured in the default case.cudaEventRecordWithFlags()
can be called multiple times on the same event and will overwrite the previously captured state. Other APIs such ascudaStreamWaitEvent()
use the most recently captured state at the time of the API call, and are not affected by later calls tocudaEventRecordWithFlags()
. Before the first call tocudaEventRecordWithFlags()
, an event represents an empty set of work, so for examplecudaEventQuery()
would returncudaSuccess
.flags include:
cudaEventRecordDefault
: Default event creation flag.cudaEventRecordExternal
: Event is captured in the graph as an external event node when performing stream capture.
- Parameters:
event (
CUevent
orcudaEvent_t
) – Event to recordstream (
CUstream
orcudaStream_t
) – Stream in which to record eventflags (unsigned int) – Parameters for the operation(See above)
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
,cudaErrorLaunchFailure
- Return type:
See also
cudaEventCreate (C API)
,cudaEventCreateWithFlags
,cudaEventQuery
,cudaEventSynchronize
,cudaEventDestroy
,cudaEventElapsedTime
,cudaStreamWaitEvent
,cudaEventRecord
,cuEventRecord
,
- cuda.cudart.cudaEventQuery(event)#
Queries an event’s status.
Queries the status of all work currently captured by event. See
cudaEventRecord()
for details on what is captured by an event.Returns
cudaSuccess
if all captured work has been completed, orcudaErrorNotReady
if any captured work is incomplete.For the purposes of Unified Memory, a return value of
cudaSuccess
is equivalent to having calledcudaEventSynchronize()
.- Parameters:
event (
CUevent
orcudaEvent_t
) – Event to query- Returns:
cudaSuccess
,cudaErrorNotReady
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
,cudaErrorLaunchFailure
- Return type:
See also
cudaEventCreate (C API)
,cudaEventCreateWithFlags
,cudaEventRecord
,cudaEventSynchronize
,cudaEventDestroy
,cudaEventElapsedTime
,cuEventQuery
- cuda.cudart.cudaEventSynchronize(event)#
Waits for an event to complete.
Waits until the completion of all work currently captured in event. See
cudaEventRecord()
for details on what is captured by an event.Waiting for an event that was created with the
cudaEventBlockingSync
flag will cause the calling CPU thread to block until the event has been completed by the device. If thecudaEventBlockingSync
flag has not been set, then the CPU thread will busy-wait until the event has been completed by the device.- Parameters:
event (
CUevent
orcudaEvent_t
) – Event to wait for- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
,cudaErrorLaunchFailure
- Return type:
See also
cudaEventCreate (C API)
,cudaEventCreateWithFlags
,cudaEventRecord
,cudaEventQuery
,cudaEventDestroy
,cudaEventElapsedTime
,cuEventSynchronize
- cuda.cudart.cudaEventDestroy(event)#
Destroys an event object.
Destroys the event specified by event.
An event may be destroyed before it is complete (i.e., while
cudaEventQuery()
would returncudaErrorNotReady
). In this case, the call does not block on completion of the event, and any associated resources will automatically be released asynchronously at completion.- Parameters:
event (
CUevent
orcudaEvent_t
) – Event to destroy- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
,cudaErrorLaunchFailure
- Return type:
See also
cudaEventCreate (C API)
,cudaEventCreateWithFlags
,cudaEventQuery
,cudaEventSynchronize
,cudaEventRecord
,cudaEventElapsedTime
,cuEventDestroy
- cuda.cudart.cudaEventElapsedTime(start, end)#
Computes the elapsed time between events.
Computes the elapsed time between two events (in milliseconds with a resolution of around 0.5 microseconds).
If either event was last recorded in a non-NULL stream, the resulting time may be greater than expected (even if both used the same stream handle). This happens because the
cudaEventRecord()
operation takes place asynchronously and there is no guarantee that the measured latency is actually just between the two events. Any number of other different stream operations could execute in between the two measured events, thus altering the timing in a significant way.If
cudaEventRecord()
has not been called on either event, thencudaErrorInvalidResourceHandle
is returned. IfcudaEventRecord()
has been called on both events but one or both of them has not yet been completed (that is,cudaEventQuery()
would returncudaErrorNotReady
on at least one of the events),cudaErrorNotReady
is returned. If either event was created with thecudaEventDisableTiming
flag, then this function will returncudaErrorInvalidResourceHandle
.- Parameters:
start (
CUevent
orcudaEvent_t
) – Starting eventend (
CUevent
orcudaEvent_t
) – Ending event
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorNotReady
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
,cudaErrorLaunchFailure
,cudaErrorUnknown
ms (float) – Time between start and end in ms
See also
cudaEventCreate (C API)
,cudaEventCreateWithFlags
,cudaEventQuery
,cudaEventSynchronize
,cudaEventDestroy
,cudaEventRecord
,cuEventElapsedTime
External Resource Interoperability#
This section describes the external resource interoperability functions of the CUDA runtime application programming interface.
- cuda.cudart.cudaImportExternalMemory(cudaExternalMemoryHandleDesc memHandleDesc: cudaExternalMemoryHandleDesc)#
Imports an external memory object.
Imports an externally allocated memory object and returns a handle to that in extMem_out.
The properties of the handle being imported must be described in memHandleDesc. The
cudaExternalMemoryHandleDesc
structure is defined as follows:View CUDA Toolkit Documentation for a C++ code example
where
type
specifies the type of handle being imported.cudaExternalMemoryHandleType
is defined as:View CUDA Toolkit Documentation for a C++ code example
If
type
iscudaExternalMemoryHandleTypeOpaqueFd
, thencudaExternalMemoryHandleDesc
::handle::fd must be a valid file descriptor referencing a memory object. Ownership of the file descriptor is transferred to the CUDA driver when the handle is imported successfully. Performing any operations on the file descriptor after it is imported results in undefined behavior.If
type
iscudaExternalMemoryHandleTypeOpaqueWin32
, then exactly one ofcudaExternalMemoryHandleDesc
::handle::win32::handle andcudaExternalMemoryHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalMemoryHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that references a memory object. Ownership of this handle is not transferred to CUDA after the import operation, so the application must release the handle using the appropriate system call. IfcudaExternalMemoryHandleDesc
::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a memory object.If
type
iscudaExternalMemoryHandleTypeOpaqueWin32Kmt
, thencudaExternalMemoryHandleDesc
::handle::win32::handle must be non-NULL andcudaExternalMemoryHandleDesc
::handle::win32::name must be NULL. The handle specified must be a globally shared KMT handle. This handle does not hold a reference to the underlying object, and thus will be invalid when all references to the memory object are destroyed.If
type
iscudaExternalMemoryHandleTypeD3D12Heap
, then exactly one ofcudaExternalMemoryHandleDesc
::handle::win32::handle andcudaExternalMemoryHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalMemoryHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by ID3D12Device::CreateSharedHandle when referring to a ID3D12Heap object. This handle holds a reference to the underlying object. IfcudaExternalMemoryHandleDesc
::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a ID3D12Heap object.If
type
iscudaExternalMemoryHandleTypeD3D12Resource
, then exactly one ofcudaExternalMemoryHandleDesc
::handle::win32::handle andcudaExternalMemoryHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalMemoryHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by ID3D12Device::CreateSharedHandle when referring to a ID3D12Resource object. This handle holds a reference to the underlying object. IfcudaExternalMemoryHandleDesc
::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a ID3D12Resource object.If
type
iscudaExternalMemoryHandleTypeD3D11Resource
,then exactly one ofcudaExternalMemoryHandleDesc
::handle::win32::handle andcudaExternalMemoryHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalMemoryHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by IDXGIResource1::CreateSharedHandle when referring to a ID3D11Resource object. IfcudaExternalMemoryHandleDesc
::handle::win32::name is not NULL, then it must point to a NULL-terminated array of UTF-16 characters that refers to a ID3D11Resource object.If
type
iscudaExternalMemoryHandleTypeD3D11ResourceKmt
, thencudaExternalMemoryHandleDesc
::handle::win32::handle must be non-NULL andcudaExternalMemoryHandleDesc
::handle::win32::name must be NULL. The handle specified must be a valid shared KMT handle that is returned by IDXGIResource::GetSharedHandle when referring to a ID3D11Resource object.If
type
iscudaExternalMemoryHandleTypeNvSciBuf
, thencudaExternalMemoryHandleDesc
::handle::nvSciBufObject must be NON-NULL and reference a valid NvSciBuf object. If the NvSciBuf object imported into CUDA is also mapped by other drivers, then the application must usecudaWaitExternalSemaphoresAsync
orcudaSignalExternalSemaphoresAsync
as approprriate barriers to maintain coherence between CUDA and the other drivers. SeecudaExternalSemaphoreWaitSkipNvSciBufMemSync
andcudaExternalSemaphoreSignalSkipNvSciBufMemSync
for memory synchronization.The size of the memory object must be specified in
size
.Specifying the flag
cudaExternalMemoryDedicated
inflags
indicates that the resource is a dedicated resource. The definition of what a dedicated resource is outside the scope of this extension. This flag must be set iftype
is one of the following:cudaExternalMemoryHandleTypeD3D12Resource
cudaExternalMemoryHandleTypeD3D11Resource
cudaExternalMemoryHandleTypeD3D11ResourceKmt
- Parameters:
memHandleDesc (
cudaExternalMemoryHandleDesc
) – Memory import handle descriptor- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
,cudaErrorOperatingSystem
extMem_out (
cudaExternalMemory_t
) – Returned handle to an external memory object
See also
cudaDestroyExternalMemory
,cudaExternalMemoryGetMappedBuffer
,cudaExternalMemoryGetMappedMipmappedArray
Notes
If the Vulkan memory imported into CUDA is mapped on the CPU then the application must use vkInvalidateMappedMemoryRanges/vkFlushMappedMemoryRanges as well as appropriate Vulkan pipeline barriers to maintain coherence between CPU and GPU. For more information on these APIs, please refer to “Synchronization and Cache Control” chapter from Vulkan specification.
- cuda.cudart.cudaExternalMemoryGetMappedBuffer(extMem, cudaExternalMemoryBufferDesc bufferDesc: cudaExternalMemoryBufferDesc)#
Maps a buffer onto an imported memory object.
Maps a buffer onto an imported memory object and returns a device pointer in devPtr.
The properties of the buffer being mapped must be described in bufferDesc. The
cudaExternalMemoryBufferDesc
structure is defined as follows:View CUDA Toolkit Documentation for a C++ code example
where
offset
is the offset in the memory object where the buffer’s base address is.size
is the size of the buffer.flags
must be zero.The offset and size have to be suitably aligned to match the requirements of the external API. Mapping two buffers whose ranges overlap may or may not result in the same virtual address being returned for the overlapped portion. In such cases, the application must ensure that all accesses to that region from the GPU are volatile. Otherwise writes made via one address are not guaranteed to be visible via the other address, even if they’re issued by the same thread. It is recommended that applications map the combined range instead of mapping separate buffers and then apply the appropriate offsets to the returned pointer to derive the individual buffers.
The returned pointer devPtr must be freed using
cudaFree
.- Parameters:
extMem (
cudaExternalMemory_t
) – Handle to external memory objectbufferDesc (
cudaExternalMemoryBufferDesc
) – Buffer descriptor
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
devPtr (Any) – Returned device pointer to buffer
- cuda.cudart.cudaExternalMemoryGetMappedMipmappedArray(extMem, cudaExternalMemoryMipmappedArrayDesc mipmapDesc: cudaExternalMemoryMipmappedArrayDesc)#
Maps a CUDA mipmapped array onto an external memory object.
Maps a CUDA mipmapped array onto an external object and returns a handle to it in mipmap.
The properties of the CUDA mipmapped array being mapped must be described in mipmapDesc. The structure
cudaExternalMemoryMipmappedArrayDesc
is defined as follows:View CUDA Toolkit Documentation for a C++ code example
where
offset
is the offset in the memory object where the base level of the mipmap chain is.formatDesc
describes the format of the data.extent
specifies the dimensions of the base level of the mipmap chain.flags
are flags associated with CUDA mipmapped arrays. For further details, please refer to the documentation forcudaMalloc3DArray
. Note that if the mipmapped array is bound as a color target in the graphics API, then the flagcudaArrayColorAttachment
must be specified inflags
.numLevels
specifies the total number of levels in the mipmap chain.The returned CUDA mipmapped array must be freed using
cudaFreeMipmappedArray
.- Parameters:
extMem (
cudaExternalMemory_t
) – Handle to external memory objectmipmapDesc (
cudaExternalMemoryMipmappedArrayDesc
) – CUDA array descriptor
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidResourceHandle
mipmap (
cudaMipmappedArray_t
) – Returned CUDA mipmapped array
Notes
If
type
iscudaExternalMemoryHandleTypeNvSciBuf
, thennumLevels
must not be greater than 1.
- cuda.cudart.cudaDestroyExternalMemory(extMem)#
Destroys an external memory object.
Destroys the specified external memory object. Any existing buffers and CUDA mipmapped arrays mapped onto this object must no longer be used and must be explicitly freed using
cudaFree
andcudaFreeMipmappedArray
respectively.- Parameters:
extMem (
cudaExternalMemory_t
) – External memory object to be destroyed- Returns:
- Return type:
- cuda.cudart.cudaImportExternalSemaphore(cudaExternalSemaphoreHandleDesc semHandleDesc: cudaExternalSemaphoreHandleDesc)#
Imports an external semaphore.
Imports an externally allocated synchronization object and returns a handle to that in extSem_out.
The properties of the handle being imported must be described in semHandleDesc. The
cudaExternalSemaphoreHandleDesc
is defined as follows:View CUDA Toolkit Documentation for a C++ code example
where
type
specifies the type of handle being imported.cudaExternalSemaphoreHandleType
is defined as:View CUDA Toolkit Documentation for a C++ code example
If
type
iscudaExternalSemaphoreHandleTypeOpaqueFd
, thencudaExternalSemaphoreHandleDesc
::handle::fd must be a valid file descriptor referencing a synchronization object. Ownership of the file descriptor is transferred to the CUDA driver when the handle is imported successfully. Performing any operations on the file descriptor after it is imported results in undefined behavior.If
type
iscudaExternalSemaphoreHandleTypeOpaqueWin32
, then exactly one ofcudaExternalSemaphoreHandleDesc
::handle::win32::handle andcudaExternalSemaphoreHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalSemaphoreHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that references a synchronization object. Ownership of this handle is not transferred to CUDA after the import operation, so the application must release the handle using the appropriate system call. IfcudaExternalSemaphoreHandleDesc
::handle::win32::name is not NULL, then it must name a valid synchronization object.If
type
iscudaExternalSemaphoreHandleTypeOpaqueWin32Kmt
, thencudaExternalSemaphoreHandleDesc
::handle::win32::handle must be non-NULL andcudaExternalSemaphoreHandleDesc
::handle::win32::name must be NULL. The handle specified must be a globally shared KMT handle. This handle does not hold a reference to the underlying object, and thus will be invalid when all references to the synchronization object are destroyed.If
type
iscudaExternalSemaphoreHandleTypeD3D12Fence
, then exactly one ofcudaExternalSemaphoreHandleDesc
::handle::win32::handle andcudaExternalSemaphoreHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalSemaphoreHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by ID3D12Device::CreateSharedHandle when referring to a ID3D12Fence object. This handle holds a reference to the underlying object. IfcudaExternalSemaphoreHandleDesc
::handle::win32::name is not NULL, then it must name a valid synchronization object that refers to a valid ID3D12Fence object.If
type
iscudaExternalSemaphoreHandleTypeD3D11Fence
, then exactly one ofcudaExternalSemaphoreHandleDesc
::handle::win32::handle andcudaExternalSemaphoreHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalSemaphoreHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that is returned by ID3D11Fence::CreateSharedHandle. IfcudaExternalSemaphoreHandleDesc
::handle::win32::name is not NULL, then it must name a valid synchronization object that refers to a valid ID3D11Fence object.If
type
iscudaExternalSemaphoreHandleTypeNvSciSync
, thencudaExternalSemaphoreHandleDesc
::handle::nvSciSyncObj represents a valid NvSciSyncObj.cudaExternalSemaphoreHandleTypeKeyedMutex
, then exactly one ofcudaExternalSemaphoreHandleDesc
::handle::win32::handle andcudaExternalSemaphoreHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalSemaphoreHandleDesc
::handle::win32::handle is not NULL, then it represent a valid shared NT handle that is returned by IDXGIResource1::CreateSharedHandle when referring to a IDXGIKeyedMutex object.If
type
iscudaExternalSemaphoreHandleTypeKeyedMutexKmt
, thencudaExternalSemaphoreHandleDesc
::handle::win32::handle must be non-NULL andcudaExternalSemaphoreHandleDesc
::handle::win32::name must be NULL. The handle specified must represent a valid KMT handle that is returned by IDXGIResource::GetSharedHandle when referring to a IDXGIKeyedMutex object.If
type
iscudaExternalSemaphoreHandleTypeTimelineSemaphoreFd
, thencudaExternalSemaphoreHandleDesc
::handle::fd must be a valid file descriptor referencing a synchronization object. Ownership of the file descriptor is transferred to the CUDA driver when the handle is imported successfully. Performing any operations on the file descriptor after it is imported results in undefined behavior.If
type
iscudaExternalSemaphoreHandleTypeTimelineSemaphoreWin32
, then exactly one ofcudaExternalSemaphoreHandleDesc
::handle::win32::handle andcudaExternalSemaphoreHandleDesc
::handle::win32::name must not be NULL. IfcudaExternalSemaphoreHandleDesc
::handle::win32::handle is not NULL, then it must represent a valid shared NT handle that references a synchronization object. Ownership of this handle is not transferred to CUDA after the import operation, so the application must release the handle using the appropriate system call. IfcudaExternalSemaphoreHandleDesc
::handle::win32::name is not NULL, then it must name a valid synchronization object.- Parameters:
semHandleDesc (
cudaExternalSemaphoreHandleDesc
) – Semaphore import handle descriptor- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidResourceHandle
,cudaErrorOperatingSystem
extSem_out (
cudaExternalSemaphore_t
) – Returned handle to an external semaphore
- cuda.cudart.cudaSignalExternalSemaphoresAsync(extSemArray: List[cudaExternalSemaphore_t], paramsArray: List[cudaExternalSemaphoreSignalParams], unsigned int numExtSems, stream)#
Signals a set of external semaphore objects.
Enqueues a signal operation on a set of externally allocated semaphore object in the specified stream. The operations will be executed when all prior operations in the stream complete.
The exact semantics of signaling a semaphore depends on the type of the object.
If the semaphore object is any one of the following types:
cudaExternalSemaphoreHandleTypeOpaqueFd
,cudaExternalSemaphoreHandleTypeOpaqueWin32
,cudaExternalSemaphoreHandleTypeOpaqueWin32Kmt
then signaling the semaphore will set it to the signaled state.If the semaphore object is any one of the following types:
cudaExternalSemaphoreHandleTypeD3D12Fence
,cudaExternalSemaphoreHandleTypeD3D11Fence
,cudaExternalSemaphoreHandleTypeTimelineSemaphoreFd
,cudaExternalSemaphoreHandleTypeTimelineSemaphoreWin32
then the semaphore will be set to the value specified incudaExternalSemaphoreSignalParams
::params::fence::value.If the semaphore object is of the type
cudaExternalSemaphoreHandleTypeNvSciSync
this API setscudaExternalSemaphoreSignalParams
::params::nvSciSync::fence to a value that can be used by subsequent waiters of the same NvSciSync object to order operations with those currently submitted in stream. Such an update will overwrite previous contents ofcudaExternalSemaphoreSignalParams
::params::nvSciSync::fence. By default, signaling such an external semaphore object causes appropriate memory synchronization operations to be performed over all the external memory objects that are imported ascudaExternalMemoryHandleTypeNvSciBuf
. This ensures that any subsequent accesses made by other importers of the same set of NvSciBuf memory object(s) are coherent. These operations can be skipped by specifying the flagcudaExternalSemaphoreSignalSkipNvSciBufMemSync
, which can be used as a performance optimization when data coherency is not required. But specifying this flag in scenarios where data coherency is required results in undefined behavior. Also, for semaphore object of the typecudaExternalSemaphoreHandleTypeNvSciSync
, if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags incudaDeviceGetNvSciSyncAttributes
to cudaNvSciSyncAttrSignal, this API will return cudaErrorNotSupported.cudaExternalSemaphoreSignalParams
::params::nvSciSync::fence associated with semaphore object of the typecudaExternalSemaphoreHandleTypeNvSciSync
can be deterministic. For this the NvSciSyncAttrList used to create the semaphore object must have value of NvSciSyncAttrKey_RequireDeterministicFences key set to true. Deterministic fences allow users to enqueue a wait over the semaphore object even before corresponding signal is enqueued. For such a semaphore object, CUDA guarantees that each signal operation will increment the fence value by ‘1’. Users are expected to track count of signals enqueued on the semaphore object and insert waits accordingly. When such a semaphore object is signaled from multiple streams, due to concurrent stream execution, it is possible that the order in which the semaphore gets signaled is indeterministic. This could lead to waiters of the semaphore getting unblocked incorrectly. Users are expected to handle such situations, either by not using the same semaphore object with deterministic fence support enabled in different streams or by adding explicit dependency amongst such streams so that the semaphore is signaled in order.If the semaphore object is any one of the following types:
cudaExternalSemaphoreHandleTypeKeyedMutex
,cudaExternalSemaphoreHandleTypeKeyedMutexKmt
, then the keyed mutex will be released with the key specified incudaExternalSemaphoreSignalParams
::params::keyedmutex::key.- Parameters:
extSemArray (List[
cudaExternalSemaphore_t
]) – Set of external semaphores to be signaledparamsArray (List[
cudaExternalSemaphoreSignalParams
]) – Array of semaphore parametersnumExtSems (unsigned int) – Number of semaphores to signal
stream (
CUstream
orcudaStream_t
) – Stream to enqueue the signal operations in
- Returns:
- Return type:
- cuda.cudart.cudaWaitExternalSemaphoresAsync(extSemArray: List[cudaExternalSemaphore_t], paramsArray: List[cudaExternalSemaphoreWaitParams], unsigned int numExtSems, stream)#
Waits on a set of external semaphore objects.
Enqueues a wait operation on a set of externally allocated semaphore object in the specified stream. The operations will be executed when all prior operations in the stream complete.
The exact semantics of waiting on a semaphore depends on the type of the object.
If the semaphore object is any one of the following types:
cudaExternalSemaphoreHandleTypeOpaqueFd
,cudaExternalSemaphoreHandleTypeOpaqueWin32
,cudaExternalSemaphoreHandleTypeOpaqueWin32Kmt
then waiting on the semaphore will wait until the semaphore reaches the signaled state. The semaphore will then be reset to the unsignaled state. Therefore for every signal operation, there can only be one wait operation.If the semaphore object is any one of the following types:
cudaExternalSemaphoreHandleTypeD3D12Fence
,cudaExternalSemaphoreHandleTypeD3D11Fence
,cudaExternalSemaphoreHandleTypeTimelineSemaphoreFd
,cudaExternalSemaphoreHandleTypeTimelineSemaphoreWin32
then waiting on the semaphore will wait until the value of the semaphore is greater than or equal tocudaExternalSemaphoreWaitParams
::params::fence::value.If the semaphore object is of the type
cudaExternalSemaphoreHandleTypeNvSciSync
then, waiting on the semaphore will wait until thecudaExternalSemaphoreSignalParams
::params::nvSciSync::fence is signaled by the signaler of the NvSciSyncObj that was associated with this semaphore object. By default, waiting on such an external semaphore object causes appropriate memory synchronization operations to be performed over all external memory objects that are imported ascudaExternalMemoryHandleTypeNvSciBuf
. This ensures that any subsequent accesses made by other importers of the same set of NvSciBuf memory object(s) are coherent. These operations can be skipped by specifying the flagcudaExternalSemaphoreWaitSkipNvSciBufMemSync
, which can be used as a performance optimization when data coherency is not required. But specifying this flag in scenarios where data coherency is required results in undefined behavior. Also, for semaphore object of the typecudaExternalSemaphoreHandleTypeNvSciSync
, if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags incudaDeviceGetNvSciSyncAttributes
to cudaNvSciSyncAttrWait, this API will return cudaErrorNotSupported.If the semaphore object is any one of the following types:
cudaExternalSemaphoreHandleTypeKeyedMutex
,cudaExternalSemaphoreHandleTypeKeyedMutexKmt
, then the keyed mutex will be acquired when it is released with the key specified incudaExternalSemaphoreSignalParams
::params::keyedmutex::key or until the timeout specified bycudaExternalSemaphoreSignalParams
::params::keyedmutex::timeoutMs has lapsed. The timeout interval can either be a finite value specified in milliseconds or an infinite value. In case an infinite value is specified the timeout never elapses. The windows INFINITE macro must be used to specify infinite timeout- Parameters:
extSemArray (List[
cudaExternalSemaphore_t
]) – External semaphores to be waited onparamsArray (List[
cudaExternalSemaphoreWaitParams
]) – Array of semaphore parametersnumExtSems (unsigned int) – Number of semaphores to wait on
stream (
CUstream
orcudaStream_t
) – Stream to enqueue the wait operations in
- Returns:
cudaSuccess
,cudaErrorInvalidResourceHandle
cudaErrorTimeout
- Return type:
- cuda.cudart.cudaDestroyExternalSemaphore(extSem)#
Destroys an external semaphore.
Destroys an external semaphore object and releases any references to the underlying resource. Any outstanding signals or waits must have completed before the semaphore is destroyed.
- Parameters:
extSem (
cudaExternalSemaphore_t
) – External semaphore to be destroyed- Returns:
- Return type:
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.
- cuda.cudart.cudaFuncSetCacheConfig(func, cacheConfig: cudaFuncCache)#
Sets the preferred cache configuration for a device function.
On devices where the L1 cache and shared memory use the same hardware resources, this sets through cacheConfig the preferred cache configuration for the function specified via func. This is only a preference. The runtime will use the requested configuration if possible, but it is free to choose a different configuration if required to execute func.
func is a device function symbol and must be declared as a None function. If the specified function does not exist, then
cudaErrorInvalidDeviceFunction
is returned. For templated functions, pass the function symbol as follows: func_name<template_arg_0,…,template_arg_N>This setting does nothing on devices where the size of the L1 cache and shared memory are fixed.
Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point.
The supported cache configurations are:
cudaFuncCachePreferNone
: no preference for shared memory or L1 (default)cudaFuncCachePreferShared
: prefer larger shared memory and smaller L1 cachecudaFuncCachePreferL1
: prefer larger L1 cache and smaller shared memorycudaFuncCachePreferEqual
: prefer equal size L1 cache and shared memory
- Parameters:
func (Any) – Device function symbol
cacheConfig (
cudaFuncCache
) – Requested cache configuration
- Returns:
cudaSuccess
, :py:obj:`~.cudaErrorInvalidDeviceFunction`2- Return type:
See also
cudaFuncSetCacheConfig (C++ API),
cudaFuncGetAttributes (C API)
,cudaLaunchKernel (C API)
,cuFuncSetCacheConfig
Sets the shared memory configuration for a device function.
On devices with configurable shared memory banks, this function will force all subsequent launches of the specified device function to have the given shared memory bank size configuration. On any given launch of the function, the shared memory configuration of the device will be temporarily changed if needed to suit the function’s preferred configuration. Changes in shared memory configuration between subsequent launches of functions, may introduce a device side synchronization point.
Any per-function setting of shared memory bank size set via
cudaFuncSetSharedMemConfig
will override the device wide setting set bycudaDeviceSetSharedMemConfig
.Changing the shared memory bank size will not increase shared memory usage or affect occupancy of kernels, but may have major effects on performance. Larger bank sizes will allow for greater potential bandwidth to shared memory, but will change what kinds of accesses to shared memory will result in bank conflicts.
This function will do nothing on devices with fixed shared memory bank size.
For templated functions, pass the function symbol as follows: func_name<template_arg_0,…,template_arg_N>
The supported bank configurations are:
cudaSharedMemBankSizeDefault
: use the device’s shared memory configuration when launching this function.cudaSharedMemBankSizeFourByte
: set shared memory bank width to be four bytes natively when launching this function.cudaSharedMemBankSizeEightByte
: set shared memory bank width to be eight bytes natively when launching this function.
- Parameters:
func (Any) – Device function symbol
config (
cudaSharedMemConfig
) – Requested shared memory configuration
- Returns:
cudaSuccess
,cudaErrorInvalidDeviceFunction
,cudaErrorInvalidValue
,2- Return type:
- cuda.cudart.cudaFuncGetAttributes(func)#
Find out attributes for a given function.
This function obtains the attributes of a function specified via func. func is a device function symbol and must be declared as a None function. The fetched attributes are placed in attr. If the specified function does not exist, then
cudaErrorInvalidDeviceFunction
is returned. For templated functions, pass the function symbol as follows: func_name<template_arg_0,…,template_arg_N>Note that some function attributes such as
maxThreadsPerBlock
may vary based on the device that is currently being used.- Parameters:
func (Any) – Device function symbol
- Returns:
cudaError_t –
cudaSuccess
, :py:obj:`~.cudaErrorInvalidDeviceFunction`2attr (
cudaFuncAttributes
) – Return pointer to function’s attributes
See also
cudaFuncSetCacheConfig (C API)
, cudaFuncGetAttributes (C++ API),cudaLaunchKernel (C API)
,cuFuncGetAttribute
- cuda.cudart.cudaFuncSetAttribute(func, attr: cudaFuncAttribute, int value)#
Set attributes for a given function.
This function sets the attributes of a function specified via func. The parameter func must be a pointer to a function that executes on the device. The parameter specified by func must be declared as a None function. The enumeration defined by attr is set to the value defined by value. If the specified function does not exist, then
cudaErrorInvalidDeviceFunction
is returned. If the specified attribute cannot be written, or if the value is incorrect, thencudaErrorInvalidValue
is returned.Valid values for attr are:
cudaFuncAttributeMaxDynamicSharedMemorySize
- The requested maximum size in bytes of dynamically-allocated shared memory. The sum of this value and the function attributesharedSizeBytes
cannot exceed the device attributecudaDevAttrMaxSharedMemoryPerBlockOptin
. The maximal size of requestable dynamic shared memory may differ by GPU architecture.cudaFuncAttributePreferredSharedMemoryCarveout
- On devices where the L1 cache and shared memory use the same hardware resources, this sets the shared memory carveout preference, in percent of the total shared memory. SeecudaDevAttrMaxSharedMemoryPerMultiprocessor
. This is only a hint, and the driver can choose a different ratio if required to execute the function.
cudaLaunchKernel (C++ API), cudaFuncSetCacheConfig (C++ API),
cudaFuncGetAttributes (C API)
,- Parameters:
func (Any) – Function to get attributes of
attr (
cudaFuncAttribute
) – Attribute to setvalue (int) – Value to set
- Returns:
cudaSuccess
,cudaErrorInvalidDeviceFunction
,cudaErrorInvalidValue
- Return type:
- cuda.cudart.cudaLaunchHostFunc(stream, fn, userData)#
Enqueues a host function call in a stream.
Enqueues a host function to run in a stream. The function will be called after currently enqueued work and will block work added after it.
The host function must not make any CUDA API calls. Attempting to use a CUDA API may result in
cudaErrorNotPermitted
, but this is not required. The host function must not perform any synchronization that may depend on outstanding CUDA work not mandated to run earlier. Host functions without a mandated order (such as in independent streams) execute in undefined order and may be serialized.For the purposes of Unified Memory, execution makes a number of guarantees:
The stream is considered idle for the duration of the function’s execution. Thus, for example, the function may always use memory attached to the stream it was enqueued in.
The start of execution of the function has the same effect as synchronizing an event recorded in the same stream immediately prior to the function. It thus synchronizes streams which have been “joined” prior to the function.
Adding device work to any stream does not have the effect of making the stream active until all preceding host functions and stream callbacks have executed. Thus, for example, a function might use global attached memory even if work has been added to another stream, if the work has been ordered behind the function call with an event.
Completion of the function does not cause a stream to become active except as described above. The stream will remain idle if no device work follows the function, and will remain idle across consecutive host functions or stream callbacks without device work in between. Thus, for example, stream synchronization can be done by signaling from a host function at the end of the stream.
Note that, in constrast to
cuStreamAddCallback
, the function will not be called in the event of an error in the CUDA context.- Parameters:
hStream (
CUstream
orcudaStream_t
) – Stream to enqueue function call infn (
cudaHostFn_t
) – The function to call once preceding stream operations are completeuserData (Any) – User-specified data to be passed to the function
- Returns:
cudaSuccess
,cudaErrorInvalidResourceHandle
,cudaErrorInvalidValue
,cudaErrorNotSupported
- Return type:
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),
- cuda.cudart.cudaOccupancyMaxActiveBlocksPerMultiprocessor(func, int blockSize, size_t dynamicSMemSize)#
Returns occupancy for a device function.
Returns in *numBlocks the maximum number of active blocks per streaming multiprocessor for the device function.
- Parameters:
func (Any) – Kernel function for which occupancy is calculated
blockSize (int) – Block size the kernel is intended to be launched with
dynamicSMemSize (size_t) – Per-block dynamic shared memory usage intended, in bytes
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
,cudaErrorInvalidDeviceFunction
,cudaErrorInvalidValue
,cudaErrorUnknown
,numBlocks (int) – Returned occupancy
See also
cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags
,cudaOccupancyMaxPotentialBlockSize
,cudaOccupancyMaxPotentialBlockSizeWithFlags
,cudaOccupancyMaxPotentialBlockSizeVariableSMem
,cudaOccupancyMaxPotentialBlockSizeVariableSMemWithFlags
,cudaOccupancyAvailableDynamicSMemPerBlock
,cuOccupancyMaxActiveBlocksPerMultiprocessor
- cuda.cudart.cudaOccupancyAvailableDynamicSMemPerBlock(func, int numBlocks, int blockSize)#
Returns dynamic shared memory available per block when launching numBlocks blocks on SM.
Returns in *dynamicSmemSize the maximum size of dynamic shared memory to allow numBlocks blocks per SM.
- Parameters:
func (Any) – Kernel function for which occupancy is calculated
numBlocks (int) – Number of blocks to fit on SM
blockSize (int) – Size of the block
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
,cudaErrorInvalidDeviceFunction
,cudaErrorInvalidValue
,cudaErrorUnknown
,dynamicSmemSize (int) – Returned maximum dynamic shared memory
See also
cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags
,cudaOccupancyMaxPotentialBlockSize
,cudaOccupancyMaxPotentialBlockSizeWithFlags
,cudaOccupancyMaxPotentialBlockSizeVariableSMem
,cudaOccupancyMaxPotentialBlockSizeVariableSMemWithFlags
,cudaOccupancyAvailableDynamicSMemPerBlock
- cuda.cudart.cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(func, int blockSize, size_t dynamicSMemSize, unsigned int flags)#
Returns occupancy for a device function with the specified flags.
Returns in *numBlocks the maximum number of active blocks per streaming multiprocessor for the device function.
The flags parameter controls how special cases are handled. Valid flags include:
cudaOccupancyDefault
: keeps the default behavior ascudaOccupancyMaxActiveBlocksPerMultiprocessor
cudaOccupancyDisableCachingOverride
: This flag suppresses the default behavior on platform where global caching affects occupancy. On such platforms, if caching is enabled, but per-block SM resource usage would result in zero occupancy, the occupancy calculator will calculate the occupancy as if caching is disabled. Setting this flag makes the occupancy calculator to return 0 in such cases. More information can be found about this feature in the “Unified L1/Texture Cache” section of the Maxwell tuning guide.
- Parameters:
func (Any) – Kernel function for which occupancy is calculated
blockSize (int) – Block size the kernel is intended to be launched with
dynamicSMemSize (size_t) – Per-block dynamic shared memory usage intended, in bytes
flags (unsigned int) – Requested behavior for the occupancy calculator
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidDevice
,cudaErrorInvalidDeviceFunction
,cudaErrorInvalidValue
,cudaErrorUnknown
,numBlocks (int) – Returned occupancy
See also
cudaOccupancyMaxActiveBlocksPerMultiprocessor
,cudaOccupancyMaxPotentialBlockSize
,cudaOccupancyMaxPotentialBlockSizeWithFlags
,cudaOccupancyMaxPotentialBlockSizeVariableSMem
,cudaOccupancyMaxPotentialBlockSizeVariableSMemWithFlags
,cudaOccupancyAvailableDynamicSMemPerBlock
,cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags
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.
- cuda.cudart.cudaMallocManaged(size_t size, unsigned int flags)#
Allocates memory that will be automatically managed by the Unified Memory system.
Allocates size bytes of managed memory on the device and returns in *devPtr a pointer to the allocated memory. If the device doesn’t support allocating managed memory,
cudaErrorNotSupported
is returned. Support for managed memory can be queried using the device attributecudaDevAttrManagedMemory
. The allocated memory is suitably aligned for any kind of variable. The memory is not cleared. If size is 0,cudaMallocManaged
returnscudaErrorInvalidValue
. The pointer is valid on the CPU and on all GPUs in the system that support managed memory. All accesses to this pointer must obey the Unified Memory programming model.flags specifies the default stream association for this allocation. flags must be one of
cudaMemAttachGlobal
orcudaMemAttachHost
. The default value for flags iscudaMemAttachGlobal
. IfcudaMemAttachGlobal
is specified, then this memory is accessible from any stream on any device. IfcudaMemAttachHost
is specified, then the allocation should not be accessed from devices that have a zero value for the device attributecudaDevAttrConcurrentManagedAccess
; an explicit call tocudaStreamAttachMemAsync
will be required to enable access on such devices.If the association is later changed via
cudaStreamAttachMemAsync
to a single stream, the default association, as specifed duringcudaMallocManaged
, is restored when that stream is destroyed. For managed variables, the default association is alwayscudaMemAttachGlobal
. Note that destroying a stream is an asynchronous operation, and as a result, the change to default association won’t happen until all work in the stream has completed.Memory allocated with
cudaMallocManaged
should be released withcudaFree
.Device memory oversubscription is possible for GPUs that have a non- zero value for the device attribute
cudaDevAttrConcurrentManagedAccess
. Managed memory on such GPUs may be evicted from device memory to host memory at any time by the Unified Memory driver in order to make room for other allocations.In a multi-GPU system where all GPUs have a non-zero value for the device attribute
cudaDevAttrConcurrentManagedAccess
, managed memory may not be populated when this API returns and instead may be populated on access. In such systems, managed memory can migrate to any processor’s memory at any time. The Unified Memory driver will employ heuristics to maintain data locality and prevent excessive page faults to the extent possible. The application can also guide the driver about memory usage patterns viacudaMemAdvise
. The application can also explicitly migrate memory to a desired processor’s memory viacudaMemPrefetchAsync
.In a multi-GPU system where all of the GPUs have a zero value for the device attribute
cudaDevAttrConcurrentManagedAccess
and all the GPUs have peer-to-peer support with each other, the physical storage for managed memory is created on the GPU which is active at the timecudaMallocManaged
is called. All other GPUs will reference the data at reduced bandwidth via peer mappings over the PCIe bus. The Unified Memory driver does not migrate memory among such GPUs.In a multi-GPU system where not all GPUs have peer-to-peer support with each other and where the value of the device attribute
cudaDevAttrConcurrentManagedAccess
is zero for at least one of those GPUs, the location chosen for physical storage of managed memory is system-dependent.On Linux, the location chosen will be device memory as long as the current set of active contexts are on devices that either have peer- to-peer support with each other or have a non-zero value for the device attribute
cudaDevAttrConcurrentManagedAccess
. If there is an active context on a GPU that does not have a non-zero value for that device attribute and it does not have peer-to-peer support with the other devices that have active contexts on them, then the location for physical storage will be ‘zero-copy’ or host memory. Note that this means that managed memory that is located in device memory is migrated to host memory if a new context is created on a GPU that doesn’t have a non-zero value for the device attribute and does not support peer-to-peer with at least one of the other devices that has an active context. This in turn implies that context creation may fail if there is insufficient host memory to migrate all managed allocations.On Windows, the physical storage is always created in ‘zero-copy’ or host memory. All GPUs will reference the data at reduced bandwidth over the PCIe bus. In these circumstances, use of the environment variable CUDA_VISIBLE_DEVICES is recommended to restrict CUDA to only use those GPUs that have peer-to-peer support. Alternatively, users can also set CUDA_MANAGED_FORCE_DEVICE_ALLOC to a non-zero value to force the driver to always use device memory for physical storage. When this environment variable is set to a non-zero value, all devices used in that process that support managed memory have to be peer-to-peer compatible with each other. The error
cudaErrorInvalidDevice
will be returned if a device that supports managed memory is used and it is not peer-to-peer compatible with any of the other managed memory supporting devices that were previously used in that process, even ifcudaDeviceReset
has been called on those devices. These environment variables are described in the CUDA programming guide under the “CUDA environment variables” section.
- Parameters:
size (size_t) – Requested allocation size in bytes
flags (unsigned int) – Must be either
cudaMemAttachGlobal
orcudaMemAttachHost
(defaults tocudaMemAttachGlobal
)
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorMemoryAllocation
,cudaErrorNotSupported
,cudaErrorInvalidValue
devPtr (Any) – Pointer to allocated device memory
See also
cudaMallocPitch
,cudaFree
,cudaMallocArray
,cudaFreeArray
,cudaMalloc3D
,cudaMalloc3DArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,cudaDeviceGetAttribute
,cudaStreamAttachMemAsync
,cuMemAllocManaged
- cuda.cudart.cudaMalloc(size_t size)#
Allocate memory on the device.
Allocates size bytes of linear memory on the device and returns in *devPtr a pointer to the allocated memory. The allocated memory is suitably aligned for any kind of variable. The memory is not cleared.
cudaMalloc()
returnscudaErrorMemoryAllocation
in case of failure.The device version of
cudaFree
cannot be used with a *devPtr allocated using the host API, and vice versa.- Parameters:
size (size_t) – Requested allocation size in bytes
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
devPtr (Any) – Pointer to allocated device memory
See also
cudaMallocPitch
,cudaFree
,cudaMallocArray
,cudaFreeArray
,cudaMalloc3D
,cudaMalloc3DArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,cuMemAlloc
- cuda.cudart.cudaMallocHost(size_t size)#
Allocates page-locked memory on the host.
Allocates size bytes of host memory that is page-locked and accessible to the device. The driver tracks the virtual memory ranges allocated with this function and automatically accelerates calls to functions such as
malloc()
. Allocating excessive amounts of memory withcudaMallocHost()
may degrade system performance, since it reduces the amount of memory available to the system for paging. As a result, this function is best used sparingly to allocate staging areas for data exchange between host and device.- Parameters:
size (size_t) – Requested allocation size in bytes
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
ptr (Any) – Pointer to allocated host memory
- cuda.cudart.cudaMallocPitch(size_t width, size_t height)#
Allocates pitched memory on the device.
Allocates at least width (in bytes) * height bytes of linear memory on the device and returns in *devPtr a pointer to the allocated memory. The function may pad the allocation to ensure that corresponding pointers in any given row will continue to meet the alignment requirements for coalescing as the address is updated from row to row. The pitch returned in *pitch by
cudaMallocPitch()
is the width in bytes of the allocation. The intended usage of pitch is as a separate parameter of the allocation, used to compute addresses within the 2D array. Given the row and column of an array element of type T, the address is computed as:View CUDA Toolkit Documentation for a C++ code example
For allocations of 2D arrays, it is recommended that programmers consider performing pitch allocations using
cudaMallocPitch()
. Due to pitch alignment restrictions in the hardware, this is especially true if the application will be performing 2D memory copies between different regions of device memory (whether linear memory or CUDA arrays).- Parameters:
width (size_t) – Requested pitched allocation width (in bytes)
height (size_t) – Requested pitched allocation height
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
devPtr (Any) – Pointer to allocated pitched device memory
pitch (int) – Pitch for allocation
See also
cudaMalloc
,cudaFree
,cudaMallocArray
,cudaFreeArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaMalloc3D
,cudaMalloc3DArray
,cudaHostAlloc
,cuMemAllocPitch
- cuda.cudart.cudaMallocArray(cudaChannelFormatDesc desc: cudaChannelFormatDesc, size_t width, size_t height, unsigned int flags)#
Allocate an array on the device.
Allocates a CUDA array according to the
cudaChannelFormatDesc
structure desc and returns a handle to the new CUDA array in *array.The
cudaChannelFormatDesc
is defined as:View CUDA Toolkit Documentation for a C++ code example
where
cudaChannelFormatKind
is one ofcudaChannelFormatKindSigned
,cudaChannelFormatKindUnsigned
, orcudaChannelFormatKindFloat
.The flags parameter enables different options to be specified that affect the allocation, as follows.
cudaArrayDefault
: This flag’s value is defined to be 0 and provides default array allocationcudaArraySurfaceLoadStore
: Allocates an array that can be read from or written to using a surface referencecudaArrayTextureGather
: This flag indicates that texture gather operations will be performed on the array.cudaArraySparse
: Allocates a CUDA array without physical backing memory. The subregions within this sparse array can later be mapped onto a physical memory allocation by callingcuMemMapArrayAsync
. The physical backing memory must be allocated viacuMemCreate
.cudaArrayDeferredMapping
: Allocates a CUDA array without physical backing memory. The entire array can later be mapped onto a physical memory allocation by callingcuMemMapArrayAsync
. The physical backing memory must be allocated viacuMemCreate
.
width and height must meet certain size requirements. See
cudaMalloc3DArray()
for more details.- Parameters:
desc (
cudaChannelFormatDesc
) – Requested channel formatwidth (size_t) – Requested array allocation width
height (size_t) – Requested array allocation height
flags (unsigned int) – Requested properties of allocated array
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
array (
cudaArray_t
) – Pointer to allocated array in device memory
See also
cudaMalloc
,cudaMallocPitch
,cudaFree
,cudaFreeArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaMalloc3D
,cudaMalloc3DArray
,cudaHostAlloc
,cuArrayCreate
- cuda.cudart.cudaFree(devPtr)#
Frees memory on the device.
Frees the memory space pointed to by devPtr, which must have been returned by a previous call to one of the following memory allocation APIs -
cudaMalloc()
,cudaMallocPitch()
,cudaMallocManaged()
,cudaMallocAsync()
,cudaMallocFromPoolAsync()
.Note - This API will not perform any implicit synchronization when the pointer was allocated with
cudaMallocAsync
orcudaMallocFromPoolAsync
. Callers must ensure that all accesses to the pointer have completed before invokingcudaFree
. For best performance and memory reuse, users should usecudaFreeAsync
to free memory allocated via the stream ordered memory allocator.If
cudaFree`(`devPtr
) has already been called before, an error is returned. If devPtr is 0, no operation is performed.cudaFree()
returnscudaErrorValue
in case of failure.The device version of
cudaFree
cannot be used with a *devPtr allocated using the host API, and vice versa.- Parameters:
devPtr (Any) – Device pointer to memory to free
- Returns:
- Return type:
- cuda.cudart.cudaFreeHost(ptr)#
Frees page-locked memory.
Frees the memory space pointed to by hostPtr, which must have been returned by a previous call to
cudaMallocHost()
orcudaHostAlloc()
.- Parameters:
ptr (Any) – Pointer to memory to free
- Returns:
- Return type:
See also
cudaMalloc
,cudaMallocPitch
,cudaFree
,cudaMallocArray
,cudaFreeArray
,cudaMallocHost (C API)
,cudaMalloc3D
,cudaMalloc3DArray
,cudaHostAlloc
,cuMemFreeHost
- cuda.cudart.cudaFreeArray(array)#
Frees an array on the device.
Frees the CUDA array array, which must have been returned by a previous call to
cudaMallocArray()
. If devPtr is 0, no operation is performed.- Parameters:
array (
cudaArray_t
) – Pointer to array to free- Returns:
- Return type:
See also
cudaMalloc
,cudaMallocPitch
,cudaFree
,cudaMallocArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,cuArrayDestroy
- cuda.cudart.cudaFreeMipmappedArray(mipmappedArray)#
Frees a mipmapped array on the device.
Frees the CUDA mipmapped array mipmappedArray, which must have been returned by a previous call to
cudaMallocMipmappedArray()
. If devPtr is 0, no operation is performed.- Parameters:
mipmappedArray (
cudaMipmappedArray_t
) – Pointer to mipmapped array to free- Returns:
- Return type:
See also
cudaMalloc
,cudaMallocPitch
,cudaFree
,cudaMallocArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,cuMipmappedArrayDestroy
- cuda.cudart.cudaHostAlloc(size_t size, unsigned int flags)#
Allocates page-locked memory on the host.
Allocates size bytes of host memory that is page-locked and accessible to the device. The driver tracks the virtual memory ranges allocated with this function and automatically accelerates calls to functions such as
cudaMemcpy()
. Since the memory can be accessed directly by the device, it can be read or written with much higher bandwidth than pageable memory obtained with functions such asmalloc()
. Allocating excessive amounts of pinned memory may degrade system performance, since it reduces the amount of memory available to the system for paging. As a result, this function is best used sparingly to allocate staging areas for data exchange between host and device.The flags parameter enables different options to be specified that affect the allocation, as follows.
cudaHostAllocDefault
: This flag’s value is defined to be 0 and causescudaHostAlloc()
to emulatecudaMallocHost()
.cudaHostAllocPortable
: The memory returned by this call will be considered as pinned memory by all CUDA contexts, not just the one that performed the allocation.cudaHostAllocMapped
: Maps the allocation into the CUDA address space. The device pointer to the memory may be obtained by callingcudaHostGetDevicePointer()
.cudaHostAllocWriteCombined
: Allocates the memory as write-combined (WC). WC memory can be transferred across the PCI Express bus more quickly on some system configurations, but cannot be read efficiently by most CPUs. WC memory is a good option for buffers that will be written by the CPU and read by the device via mapped pinned memory or host->device transfers.
All of these flags are orthogonal to one another: a developer may allocate memory that is portable, mapped and/or write-combined with no restrictions.
In order for the
cudaHostAllocMapped
flag to have any effect, the CUDA context must support thecudaDeviceMapHost
flag, which can be checked viacudaGetDeviceFlags()
. ThecudaDeviceMapHost
flag is implicitly set for contexts created via the runtime API.The
cudaHostAllocMapped
flag may be specified on CUDA contexts for devices that do not support mapped pinned memory. The failure is deferred tocudaHostGetDevicePointer()
because the memory may be mapped into other CUDA contexts via thecudaHostAllocPortable
flag.Memory allocated by this function must be freed with
cudaFreeHost()
.- Parameters:
size (size_t) – Requested allocation size in bytes
flags (unsigned int) – Requested properties of allocated memory
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
pHost (Any) – Device pointer to allocated memory
See also
cudaSetDeviceFlags
,cudaMallocHost (C API)
,cudaFreeHost
,cudaGetDeviceFlags
,cuMemHostAlloc
- cuda.cudart.cudaHostRegister(ptr, size_t size, unsigned int flags)#
Registers an existing host memory range for use by CUDA.
Page-locks the memory range specified by ptr and size and maps it for the device(s) as specified by flags. This memory range also is added to the same tracking mechanism as
cudaHostAlloc()
to automatically accelerate calls to functions such ascudaMemcpy()
. Since the memory can be accessed directly by the device, it can be read or written with much higher bandwidth than pageable memory that has not been registered. Page-locking excessive amounts of memory may degrade system performance, since it reduces the amount of memory available to the system for paging. As a result, this function is best used sparingly to register staging areas for data exchange between host and device.On systems where
pageableMemoryAccessUsesHostPageTables
is true,cudaHostRegister
will not page-lock the memory range specified by ptr but only populate unpopulated pages.cudaHostRegister
is supported only on I/O coherent devices that have a non-zero value for the device attributecudaDevAttrHostRegisterSupported
.The flags parameter enables different options to be specified that affect the allocation, as follows.
cudaHostRegisterDefault
: On a system with unified virtual addressing, the memory will be both mapped and portable. On a system with no unified virtual addressing, the memory will be neither mapped nor portable.cudaHostRegisterPortable
: The memory returned by this call will be considered as pinned memory by all CUDA contexts, not just the one that performed the allocation.cudaHostRegisterMapped
: Maps the allocation into the CUDA address space. The device pointer to the memory may be obtained by callingcudaHostGetDevicePointer()
.cudaHostRegisterIoMemory
: The passed memory pointer is treated as pointing to some memory-mapped I/O space, e.g. belonging to a third-party PCIe device, and it will marked as non cache- coherent and contiguous.cudaHostRegisterReadOnly
: The passed memory pointer is treated as pointing to memory that is considered read-only by the device. On platforms withoutcudaDevAttrPageableMemoryAccessUsesHostPageTables
, this flag is required in order to register memory mapped to the CPU as read-only. Support for the use of this flag can be queried from the device attribute cudaDeviceAttrReadOnlyHostRegisterSupported. Using this flag with a current context associated with a device that does not have this attribute set will causecudaHostRegister
to error with cudaErrorNotSupported.
All of these flags are orthogonal to one another: a developer may page- lock memory that is portable or mapped with no restrictions.
The CUDA context must have been created with the
cudaMapHost
flag in order for thecudaHostRegisterMapped
flag to have any effect.The
cudaHostRegisterMapped
flag may be specified on CUDA contexts for devices that do not support mapped pinned memory. The failure is deferred tocudaHostGetDevicePointer()
because the memory may be mapped into other CUDA contexts via thecudaHostRegisterPortable
flag.For devices that have a non-zero value for the device attribute
cudaDevAttrCanUseHostPointerForRegisteredMem
, the memory can also be accessed from the device using the host pointer ptr. The device pointer returned bycudaHostGetDevicePointer()
may or may not match the original host pointer ptr and depends on the devices visible to the application. If all devices visible to the application have a non-zero value for the device attribute, the device pointer returned bycudaHostGetDevicePointer()
will match the original pointer ptr. If any device visible to the application has a zero value for the device attribute, the device pointer returned bycudaHostGetDevicePointer()
will not match the original host pointer ptr, but it will be suitable for use on all devices provided Unified Virtual Addressing is enabled. In such systems, it is valid to access the memory using either pointer on devices that have a non-zero value for the device attribute. Note however that such devices should access the memory using only of the two pointers and not both.The memory page-locked by this function must be unregistered with
cudaHostUnregister()
.- Parameters:
ptr (Any) – Host pointer to memory to page-lock
size (size_t) – Size in bytes of the address range to page-lock in bytes
flags (unsigned int) – Flags for allocation request
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
,cudaErrorHostMemoryAlreadyRegistered
,cudaErrorNotSupported
- Return type:
- cuda.cudart.cudaHostUnregister(ptr)#
Unregisters a memory range that was registered with cudaHostRegister.
Unmaps the memory range whose base address is specified by ptr, and makes it pageable again.
The base address must be the same one specified to
cudaHostRegister()
.- Parameters:
ptr (Any) – Host pointer to memory to unregister
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorHostMemoryNotRegistered
- Return type:
See also
- cuda.cudart.cudaHostGetDevicePointer(pHost, unsigned int flags)#
Passes back device pointer of mapped host memory allocated by cudaHostAlloc or registered by cudaHostRegister.
Passes back the device pointer corresponding to the mapped, pinned host buffer allocated by
cudaHostAlloc()
or registered bycudaHostRegister()
.cudaHostGetDevicePointer()
will fail if thecudaDeviceMapHost
flag was not specified before deferred context creation occurred, or if called on a device that does not support mapped, pinned memory.For devices that have a non-zero value for the device attribute
cudaDevAttrCanUseHostPointerForRegisteredMem
, the memory can also be accessed from the device using the host pointer pHost. The device pointer returned bycudaHostGetDevicePointer()
may or may not match the original host pointer pHost and depends on the devices visible to the application. If all devices visible to the application have a non-zero value for the device attribute, the device pointer returned bycudaHostGetDevicePointer()
will match the original pointer pHost. If any device visible to the application has a zero value for the device attribute, the device pointer returned bycudaHostGetDevicePointer()
will not match the original host pointer pHost, but it will be suitable for use on all devices provided Unified Virtual Addressing is enabled. In such systems, it is valid to access the memory using either pointer on devices that have a non-zero value for the device attribute. Note however that such devices should access the memory using only of the two pointers and not both.flags provides for future releases. For now, it must be set to 0.
- Parameters:
pHost (Any) – Requested host pointer mapping
flags (unsigned int) – Flags for extensions (must be 0 for now)
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
pDevice (Any) – Returned device pointer for mapped memory
- cuda.cudart.cudaHostGetFlags(pHost)#
Passes back flags used to allocate pinned host memory allocated by cudaHostAlloc.
cudaHostGetFlags()
will fail if the input pointer does not reside in an address range allocated bycudaHostAlloc()
.- Parameters:
pHost (Any) – Host pointer
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
pFlags (unsigned int) – Returned flags word
See also
- cuda.cudart.cudaMalloc3D(cudaExtent extent: cudaExtent)#
Allocates logical 1D, 2D, or 3D memory objects on the device.
Allocates at least width * height * depth bytes of linear memory on the device and returns a
cudaPitchedPtr
in which ptr is a pointer to the allocated memory. The function may pad the allocation to ensure hardware alignment requirements are met. The pitch returned in the pitch field of pitchedDevPtr is the width in bytes of the allocation.The returned
cudaPitchedPtr
contains additional fields xsize and ysize, the logical width and height of the allocation, which are equivalent to the width and height extent parameters provided by the programmer during allocation.For allocations of 2D and 3D objects, it is highly recommended that programmers perform allocations using
cudaMalloc3D()
orcudaMallocPitch()
. Due to alignment restrictions in the hardware, this is especially true if the application will be performing memory copies involving 2D or 3D objects (whether linear memory or CUDA arrays).- Parameters:
extent (
cudaExtent
) – Requested allocation size (width field in bytes)- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
pitchedDevPtr (
cudaPitchedPtr
) – Pointer to allocated pitched device memory
See also
cudaMallocPitch
,cudaFree
,cudaMemcpy3D
,cudaMemset3D
,cudaMalloc3DArray
,cudaMallocArray
,cudaFreeArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,make_cudaPitchedPtr
,make_cudaExtent
,cuMemAllocPitch
- cuda.cudart.cudaMalloc3DArray(cudaChannelFormatDesc desc: cudaChannelFormatDesc, cudaExtent extent: cudaExtent, unsigned int flags)#
Allocate an array on the device.
Allocates a CUDA array according to the
cudaChannelFormatDesc
structure desc and returns a handle to the new CUDA array in *array.The
cudaChannelFormatDesc
is defined as:View CUDA Toolkit Documentation for a C++ code example
where
cudaChannelFormatKind
is one ofcudaChannelFormatKindSigned
,cudaChannelFormatKindUnsigned
, orcudaChannelFormatKindFloat
.cudaMalloc3DArray()
can allocate the following:A 1D array is allocated if the height and depth extents are both zero.
A 2D array is allocated if only the depth extent is zero.
A 3D array is allocated if all three extents are non-zero.
A 1D layered CUDA array is allocated if only the height extent is zero and the cudaArrayLayered flag is set. Each layer is a 1D array. The number of layers is determined by the depth extent.
A 2D layered CUDA array is allocated if all three extents are non- zero and the cudaArrayLayered flag is set. Each layer is a 2D array. The number of layers is determined by the depth extent.
A cubemap CUDA array is allocated if all three extents are non-zero and the cudaArrayCubemap flag is set. Width must be equal to height, and depth must be six. A cubemap is a special type of 2D layered CUDA array, where the six layers represent the six faces of a cube. The order of the six layers in memory is the same as that listed in
cudaGraphicsCubeFace
.A cubemap layered CUDA array is allocated if all three extents are non-zero, and both, cudaArrayCubemap and cudaArrayLayered flags are set. Width must be equal to height, and depth must be a multiple of six. A cubemap layered CUDA array is a special type of 2D layered CUDA array that consists of a collection of cubemaps. The first six layers represent the first cubemap, the next six layers form the second cubemap, and so on.
The flags parameter enables different options to be specified that affect the allocation, as follows.
cudaArrayDefault
: This flag’s value is defined to be 0 and provides default array allocationcudaArrayLayered
: Allocates a layered CUDA array, with the depth extent indicating the number of layerscudaArrayCubemap
: Allocates a cubemap CUDA array. Width must be equal to height, and depth must be six. If the cudaArrayLayered flag is also set, depth must be a multiple of six.cudaArraySurfaceLoadStore
: Allocates a CUDA array that could be read from or written to using a surface reference.cudaArrayTextureGather
: This flag indicates that texture gather operations will be performed on the CUDA array. Texture gather can only be performed on 2D CUDA arrays.cudaArraySparse
: Allocates a CUDA array without physical backing memory. The subregions within this sparse array can later be mapped onto a physical memory allocation by callingcuMemMapArrayAsync
. This flag can only be used for creating 2D, 3D or 2D layered sparse CUDA arrays. The physical backing memory must be allocated viacuMemCreate
.cudaArrayDeferredMapping
: Allocates a CUDA array without physical backing memory. The entire array can later be mapped onto a physical memory allocation by callingcuMemMapArrayAsync
. The physical backing memory must be allocated viacuMemCreate
.
The width, height and depth extents must meet certain size requirements as listed in the following table. All values are specified in elements.
Note that 2D CUDA arrays have different size requirements if the
cudaArrayTextureGather
flag is set. In that case, the valid range for (width, height, depth) is ((1,maxTexture2DGather[0]), (1,maxTexture2DGather[1]), 0).View CUDA Toolkit Documentation for a table example
- Parameters:
desc (
cudaChannelFormatDesc
) – Requested channel formatextent (
cudaExtent
) – Requested allocation size (width field in elements)flags (unsigned int) – Flags for extensions
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
array (
cudaArray_t
) – Pointer to allocated array in device memory
See also
cudaMalloc3D
,cudaMalloc
,cudaMallocPitch
,cudaFree
,cudaFreeArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,make_cudaExtent
,cuArray3DCreate
- cuda.cudart.cudaMallocMipmappedArray(cudaChannelFormatDesc desc: cudaChannelFormatDesc, cudaExtent extent: cudaExtent, unsigned int numLevels, unsigned int flags)#
Allocate a mipmapped array on the device.
Allocates a CUDA mipmapped array according to the
cudaChannelFormatDesc
structure desc and returns a handle to the new CUDA mipmapped array in *mipmappedArray. numLevels specifies the number of mipmap levels to be allocated. This value is clamped to the range [1, 1 + floor(log2(max(width, height, depth)))].The
cudaChannelFormatDesc
is defined as:View CUDA Toolkit Documentation for a C++ code example
where
cudaChannelFormatKind
is one ofcudaChannelFormatKindSigned
,cudaChannelFormatKindUnsigned
, orcudaChannelFormatKindFloat
.cudaMallocMipmappedArray()
can allocate the following:A 1D mipmapped array is allocated if the height and depth extents are both zero.
A 2D mipmapped array is allocated if only the depth extent is zero.
A 3D mipmapped array is allocated if all three extents are non-zero.
A 1D layered CUDA mipmapped array is allocated if only the height extent is zero and the cudaArrayLayered flag is set. Each layer is a 1D mipmapped array. The number of layers is determined by the depth extent.
A 2D layered CUDA mipmapped array is allocated if all three extents are non-zero and the cudaArrayLayered flag is set. Each layer is a 2D mipmapped array. The number of layers is determined by the depth extent.
A cubemap CUDA mipmapped array is allocated if all three extents are non-zero and the cudaArrayCubemap flag is set. Width must be equal to height, and depth must be six. The order of the six layers in memory is the same as that listed in
cudaGraphicsCubeFace
.A cubemap layered CUDA mipmapped array is allocated if all three extents are non-zero, and both, cudaArrayCubemap and cudaArrayLayered flags are set. Width must be equal to height, and depth must be a multiple of six. A cubemap layered CUDA mipmapped array is a special type of 2D layered CUDA mipmapped array that consists of a collection of cubemap mipmapped arrays. The first six layers represent the first cubemap mipmapped array, the next six layers form the second cubemap mipmapped array, and so on.
The flags parameter enables different options to be specified that affect the allocation, as follows.
cudaArrayDefault
: This flag’s value is defined to be 0 and provides default mipmapped array allocationcudaArrayLayered
: Allocates a layered CUDA mipmapped array, with the depth extent indicating the number of layerscudaArrayCubemap
: Allocates a cubemap CUDA mipmapped array. Width must be equal to height, and depth must be six. If the cudaArrayLayered flag is also set, depth must be a multiple of six.cudaArraySurfaceLoadStore
: This flag indicates that individual mipmap levels of the CUDA mipmapped array will be read from or written to using a surface reference.cudaArrayTextureGather
: This flag indicates that texture gather operations will be performed on the CUDA array. Texture gather can only be performed on 2D CUDA mipmapped arrays, and the gather operations are performed only on the most detailed mipmap level.cudaArraySparse
: Allocates a CUDA mipmapped array without physical backing memory. The subregions within this sparse array can later be mapped onto a physical memory allocation by callingcuMemMapArrayAsync
. This flag can only be used for creating 2D, 3D or 2D layered sparse CUDA mipmapped arrays. The physical backing memory must be allocated viacuMemCreate
.cudaArrayDeferredMapping
: Allocates a CUDA mipmapped array without physical backing memory. The entire array can later be mapped onto a physical memory allocation by callingcuMemMapArrayAsync
. The physical backing memory must be allocated viacuMemCreate
.
The width, height and depth extents must meet certain size requirements as listed in the following table. All values are specified in elements.
View CUDA Toolkit Documentation for a table example
- Parameters:
desc (
cudaChannelFormatDesc
) – Requested channel formatextent (
cudaExtent
) – Requested allocation size (width field in elements)numLevels (unsigned int) – Number of mipmap levels to allocate
flags (unsigned int) – Flags for extensions
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorMemoryAllocation
mipmappedArray (
cudaMipmappedArray_t
) – Pointer to allocated mipmapped array in device memory
See also
cudaMalloc3D
,cudaMalloc
,cudaMallocPitch
,cudaFree
,cudaFreeArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,make_cudaExtent
,cuMipmappedArrayCreate
- cuda.cudart.cudaGetMipmappedArrayLevel(mipmappedArray, unsigned int level)#
Gets a mipmap level of a CUDA mipmapped array.
Returns in *levelArray a CUDA array that represents a single mipmap level of the CUDA mipmapped array mipmappedArray.
If level is greater than the maximum number of levels in this mipmapped array,
cudaErrorInvalidValue
is returned.If mipmappedArray is NULL,
cudaErrorInvalidResourceHandle
is returned.- Parameters:
mipmappedArray (
cudaMipmappedArray_const_t
) – CUDA mipmapped arraylevel (unsigned int) – Mipmap level
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
cudaErrorInvalidResourceHandle
levelArray (
cudaArray_t
) – Returned mipmap level CUDA array
See also
cudaMalloc3D
,cudaMalloc
,cudaMallocPitch
,cudaFree
,cudaFreeArray
,cudaMallocHost (C API)
,cudaFreeHost
,cudaHostAlloc
,make_cudaExtent
,cuMipmappedArrayGetLevel
- cuda.cudart.cudaMemcpy3D(cudaMemcpy3DParms p: cudaMemcpy3DParms)#
Copies data between 3D objects.
View CUDA Toolkit Documentation for a C++ code example
cudaMemcpy3D()
copies data betwen two 3D objects. The source and destination objects may be in either host memory, device memory, or a CUDA array. The source, destination, extent, and kind of copy performed is specified by thecudaMemcpy3DParms
struct which should be initialized to zero before use:View CUDA Toolkit Documentation for a C++ code example
The struct passed to
cudaMemcpy3D()
must specify one of srcArray or srcPtr and one of dstArray or dstPtr. Passing more than one non-zero source or destination will causecudaMemcpy3D()
to return an error.The srcPos and dstPos fields are optional offsets into the source and destination objects and are defined in units of each object’s elements. The element for a host or device pointer is assumed to be unsigned char.
The extent field defines the dimensions of the transferred area in elements. If a CUDA array is participating in the copy, the extent is defined in terms of that array’s elements. If no CUDA array is participating in the copy then the extents are defined in elements of unsigned char.
The kind field defines the direction of the copy. It must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. ForcudaMemcpyHostToHost
orcudaMemcpyHostToDevice
orcudaMemcpyDeviceToHost
passed as kind and cudaArray type passed as source or destination, if the kind implies cudaArray type to be present on the host,cudaMemcpy3D()
will disregard that implication and silently correct the kind based on the fact that cudaArray type can only be present on the device.If the source and destination are both arrays,
cudaMemcpy3D()
will return an error if they do not have the same element size.The source and destination object may not overlap. If overlapping source and destination objects are specified, undefined behavior will result.
The source object must entirely contain the region defined by srcPos and extent. The destination object must entirely contain the region defined by dstPos and extent.
cudaMemcpy3D()
returns an error if the pitch of srcPtr or dstPtr exceeds the maximum allowed. The pitch of acudaPitchedPtr
allocated withcudaMalloc3D()
will always be valid.- Parameters:
p (
cudaMemcpy3DParms
) – 3D memory copy parameters- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMalloc3D
,cudaMalloc3DArray
,cudaMemset3D
,cudaMemcpy3DAsync
,cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,make_cudaExtent
,make_cudaPos
,cuMemcpy3D
- cuda.cudart.cudaMemcpy3DPeer(cudaMemcpy3DPeerParms p: cudaMemcpy3DPeerParms)#
Copies memory between devices.
Perform a 3D memory copy according to the parameters specified in p. See the definition of the
cudaMemcpy3DPeerParms
structure for documentation of its parameters.Note that this function is synchronous with respect to the host only if the source or destination of the transfer is host memory. Note also that this copy is serialized with respect to all pending and future asynchronous work in to the current device, the copy’s source device, and the copy’s destination device (use
cudaMemcpy3DPeerAsync
to avoid this synchronization).- Parameters:
p (
cudaMemcpy3DPeerParms
) – Parameters for the memory copy- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidDevice
,cudaErrorInvalidPitchValue
- Return type:
- cuda.cudart.cudaMemcpy3DAsync(cudaMemcpy3DParms p: cudaMemcpy3DParms, stream)#
Copies data between 3D objects.
View CUDA Toolkit Documentation for a C++ code example
cudaMemcpy3DAsync()
copies data betwen two 3D objects. The source and destination objects may be in either host memory, device memory, or a CUDA array. The source, destination, extent, and kind of copy performed is specified by thecudaMemcpy3DParms
struct which should be initialized to zero before use:View CUDA Toolkit Documentation for a C++ code example
The struct passed to
cudaMemcpy3DAsync()
must specify one of srcArray or srcPtr and one of dstArray or dstPtr. Passing more than one non-zero source or destination will causecudaMemcpy3DAsync()
to return an error.The srcPos and dstPos fields are optional offsets into the source and destination objects and are defined in units of each object’s elements. The element for a host or device pointer is assumed to be unsigned char. For CUDA arrays, positions must be in the range [0, 2048) for any dimension.
The extent field defines the dimensions of the transferred area in elements. If a CUDA array is participating in the copy, the extent is defined in terms of that array’s elements. If no CUDA array is participating in the copy then the extents are defined in elements of unsigned char.
The kind field defines the direction of the copy. It must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. ForcudaMemcpyHostToHost
orcudaMemcpyHostToDevice
orcudaMemcpyDeviceToHost
passed as kind and cudaArray type passed as source or destination, if the kind implies cudaArray type to be present on the host,cudaMemcpy3DAsync()
will disregard that implication and silently correct the kind based on the fact that cudaArray type can only be present on the device.If the source and destination are both arrays,
cudaMemcpy3DAsync()
will return an error if they do not have the same element size.The source and destination object may not overlap. If overlapping source and destination objects are specified, undefined behavior will result.
The source object must lie entirely within the region defined by srcPos and extent. The destination object must lie entirely within the region defined by dstPos and extent.
cudaMemcpy3DAsync()
returns an error if the pitch of srcPtr or dstPtr exceeds the maximum allowed. The pitch of acudaPitchedPtr
allocated withcudaMalloc3D()
will always be valid.cudaMemcpy3DAsync()
is asynchronous with respect to the host, so the call may return before the copy is complete. The copy can optionally be associated to a stream by passing a non-zero stream argument. If kind iscudaMemcpyHostToDevice
orcudaMemcpyDeviceToHost
and stream is non-zero, the copy may overlap with operations in other streams.The device version of this function only handles device to device copies and cannot be given local or shared pointers.
- Parameters:
p (
cudaMemcpy3DParms
) – 3D memory copy parametersstream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMalloc3D
,cudaMalloc3DArray
,cudaMemset3D
,cudaMemcpy3D
,cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
, :::cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,make_cudaExtent
,make_cudaPos
,cuMemcpy3DAsync
- cuda.cudart.cudaMemcpy3DPeerAsync(cudaMemcpy3DPeerParms p: cudaMemcpy3DPeerParms, stream)#
Copies memory between devices asynchronously.
Perform a 3D memory copy according to the parameters specified in p. See the definition of the
cudaMemcpy3DPeerParms
structure for documentation of its parameters.- Parameters:
p (
cudaMemcpy3DPeerParms
) – Parameters for the memory copystream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidDevice
,cudaErrorInvalidPitchValue
- Return type:
- cuda.cudart.cudaMemGetInfo()#
Gets free and total device memory.
Returns in *total the total amount of memory available to the the current context. Returns in *free the amount of memory on the device that is free according to the OS. CUDA is not guaranteed to be able to allocate all of the memory that the OS reports as free. In a multi- tenet situation, free estimate returned is prone to race condition where a new allocation/free done by a different process or a different thread in the same process between the time when free memory was estimated and reported, will result in deviation in free value reported and actual free memory.
The integrated GPU on Tegra shares memory with CPU and other component of the SoC. The free and total values returned by the API excludes the SWAP memory space maintained by the OS on some platforms. The OS may move some of the memory pages into swap area as the GPU or CPU allocate or access memory. See Tegra app note on how to calculate total and free memory on Tegra.
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorLaunchFailure
free (int) – Returned free memory in bytes
total (int) – Returned total memory in bytes
See also
- cuda.cudart.cudaArrayGetInfo(array)#
Gets info about the specified cudaArray.
Returns in *desc, *extent and *flags respectively, the type, shape and flags of array.
Any of *desc, *extent and *flags may be specified as NULL.
- Parameters:
array (
cudaArray_t
) – ThecudaArray
to get info for- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
desc (
cudaChannelFormatDesc
) – Returned array typeextent (
cudaExtent
) – Returned array shape. 2D arrays will have depth of zeroflags (unsigned int) – Returned array flags
See also
- cuda.cudart.cudaArrayGetPlane(hArray, unsigned int planeIdx)#
Gets a CUDA array plane from a CUDA array.
Returns in pPlaneArray a CUDA array that represents a single format plane of the CUDA array hArray.
If planeIdx is greater than the maximum number of planes in this array or if the array does not have a multi-planar format e.g:
cudaChannelFormatKindNV12
, thencudaErrorInvalidValue
is returned.Note that if the hArray has format
cudaChannelFormatKindNV12
, then passing in 0 for planeIdx returns a CUDA array of the same size as hArray but with one 8-bit channel andcudaChannelFormatKindUnsigned
as its format kind. If 1 is passed for planeIdx, then the returned CUDA array has half the height and width of hArray with two 8-bit channels andcudaChannelFormatKindUnsigned
as its format kind.- Parameters:
hArray (
cudaArray_t
) – CUDA arrayplaneIdx (unsigned int) – Plane index
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
cudaErrorInvalidResourceHandle
pPlaneArray (
cudaArray_t
) – Returned CUDA array referenced by the planeIdx
See also
- cuda.cudart.cudaArrayGetMemoryRequirements(array, int device)#
Returns the memory requirements of a CUDA array.
Returns the memory requirements of a CUDA array in memoryRequirements If the CUDA array is not allocated with flag
cudaArrayDeferredMapping
cudaErrorInvalidValue
will be returned.The returned value in
size
represents the total size of the CUDA array. The returned value inalignment
represents the alignment necessary for mapping the CUDA array.- Parameters:
array (
cudaArray_t
) – CUDA array to get the memory requirements ofdevice (int) – Device to get the memory requirements for
- Returns:
cudaError_t –
cudaSuccess
cudaErrorInvalidValue
memoryRequirements (
cudaArrayMemoryRequirements
) – Pointer tocudaArrayMemoryRequirements
- cuda.cudart.cudaMipmappedArrayGetMemoryRequirements(mipmap, int device)#
Returns the memory requirements of a CUDA mipmapped array.
Returns the memory requirements of a CUDA mipmapped array in memoryRequirements If the CUDA mipmapped array is not allocated with flag
cudaArrayDeferredMapping
cudaErrorInvalidValue
will be returned.The returned value in
size
represents the total size of the CUDA mipmapped array. The returned value inalignment
represents the alignment necessary for mapping the CUDA mipmapped array.- Parameters:
mipmap (
cudaMipmappedArray_t
) – CUDA mipmapped array to get the memory requirements ofdevice (int) – Device to get the memory requirements for
- Returns:
cudaError_t –
cudaSuccess
cudaErrorInvalidValue
memoryRequirements (
cudaArrayMemoryRequirements
) – Pointer tocudaArrayMemoryRequirements
See also
- cuda.cudart.cudaArrayGetSparseProperties(array)#
Returns the layout properties of a sparse CUDA array.
Returns the layout properties of a sparse CUDA array in sparseProperties. If the CUDA array is not allocated with flag
cudaArraySparse
cudaErrorInvalidValue
will be returned.If the returned value in
flags
containscudaArraySparsePropertiesSingleMipTail
, thenmiptailSize
represents the total size of the array. Otherwise, it will be zero. Also, the returned value inmiptailFirstLevel
is always zero. Note that the array must have been allocated usingcudaMallocArray
orcudaMalloc3DArray
. For CUDA arrays obtained usingcudaMipmappedArrayGetLevel
,cudaErrorInvalidValue
will be returned. Instead,cudaMipmappedArrayGetSparseProperties
must be used to obtain the sparse properties of the entire CUDA mipmapped array to which array belongs to.- Parameters:
array (
cudaArray_t
) – The CUDA array to get the sparse properties of- Returns:
cudaError_t –
cudaSuccess
cudaErrorInvalidValue
sparseProperties (
cudaArraySparseProperties
) – Pointer to return thecudaArraySparseProperties
- cuda.cudart.cudaMipmappedArrayGetSparseProperties(mipmap)#
Returns the layout properties of a sparse CUDA mipmapped array.
Returns the sparse array layout properties in sparseProperties. If the CUDA mipmapped array is not allocated with flag
cudaArraySparse
cudaErrorInvalidValue
will be returned.For non-layered CUDA mipmapped arrays,
miptailSize
returns the size of the mip tail region. The mip tail region includes all mip levels whose width, height or depth is less than that of the tile. For layered CUDA mipmapped arrays, ifflags
containscudaArraySparsePropertiesSingleMipTail
, thenmiptailSize
specifies the size of the mip tail of all layers combined. Otherwise,miptailSize
specifies mip tail size per layer. The returned value ofmiptailFirstLevel
is valid only ifmiptailSize
is non-zero.- Parameters:
mipmap (
cudaMipmappedArray_t
) – The CUDA mipmapped array to get the sparse properties of- Returns:
cudaError_t –
cudaSuccess
cudaErrorInvalidValue
sparseProperties (
cudaArraySparseProperties
) – Pointer to returncudaArraySparseProperties
- cuda.cudart.cudaMemcpy(dst, src, size_t count, kind: cudaMemcpyKind)#
Copies data between host and device.
Copies count bytes from the memory area pointed to by src to the memory area pointed to by dst, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. CallingcudaMemcpy()
with dst and src pointers that do not match the direction of the copy results in an undefined behavior.ote_sync
- dstAny
Destination memory address
- srcAny
Source memory address
- countsize_t
Size in bytes to copy
- kind
cudaMemcpyKind
Type of transfer
cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpyDtoH
,cuMemcpyHtoD
,cuMemcpyDtoD
,cuMemcpy
- cuda.cudart.cudaMemcpyPeer(dst, int dstDevice, src, int srcDevice, size_t count)#
Copies memory between two devices.
Copies memory from one device to memory on another device. dst is the base device pointer of the destination memory and dstDevice is the destination device. src is the base device pointer of the source memory and srcDevice is the source device. count specifies the number of bytes to copy.
Note that this function is asynchronous with respect to the host, but serialized with respect all pending and future asynchronous work in to the current device, srcDevice, and dstDevice (use
cudaMemcpyPeerAsync
to avoid this synchronization).- Parameters:
dst (Any) – Destination device pointer
dstDevice (int) – Destination device
src (Any) – Source device pointer
srcDevice (int) – Source device
count (size_t) – Size of memory copy in bytes
- Returns:
- Return type:
- cuda.cudart.cudaMemcpy2D(dst, size_t dpitch, src, size_t spitch, size_t width, size_t height, kind: cudaMemcpyKind)#
Copies data between host and device.
Copies a matrix (height rows of width bytes each) from the memory area pointed to by src to the memory area pointed to by dst, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. dpitch and spitch are the widths in memory in bytes of the 2D arrays pointed to by dst and src, including any padding added to the end of each row. The memory areas may not overlap. width must not exceed either dpitch or spitch. CallingcudaMemcpy2D()
with dst and src pointers that do not match the direction of the copy results in an undefined behavior.cudaMemcpy2D()
returns an error if dpitch or spitch exceeds the maximum allowed.- Parameters:
dst (Any) – Destination memory address
dpitch (size_t) – Pitch of destination memory
src (Any) – Source memory address
spitch (size_t) – Pitch of source memory
width (size_t) – Width of matrix transfer (columns in bytes)
height (size_t) – Height of matrix transfer (rows)
kind (
cudaMemcpyKind
) – Type of transfer
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpy2D
,cuMemcpy2DUnaligned
- cuda.cudart.cudaMemcpy2DToArray(dst, size_t wOffset, size_t hOffset, src, size_t spitch, size_t width, size_t height, kind: cudaMemcpyKind)#
Copies data between host and device.
Copies a matrix (height rows of width bytes each) from the memory area pointed to by src to the CUDA array dst starting at hOffset rows and wOffset bytes from the upper left corner, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. spitch is the width in memory in bytes of the 2D array pointed to by src, including any padding added to the end of each row. wOffset + width must not exceed the width of the CUDA array dst. width must not exceed spitch.cudaMemcpy2DToArray()
returns an error if spitch exceeds the maximum allowed.- Parameters:
dst (
cudaArray_t
) – Destination memory addresswOffset (size_t) – Destination starting X offset (columns in bytes)
hOffset (size_t) – Destination starting Y offset (rows)
src (Any) – Source memory address
spitch (size_t) – Pitch of source memory
width (size_t) – Width of matrix transfer (columns in bytes)
height (size_t) – Height of matrix transfer (rows)
kind (
cudaMemcpyKind
) – Type of transfer
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpy2D
,cuMemcpy2DUnaligned
- cuda.cudart.cudaMemcpy2DFromArray(dst, size_t dpitch, src, size_t wOffset, size_t hOffset, size_t width, size_t height, kind: cudaMemcpyKind)#
Copies data between host and device.
Copies a matrix (height rows of width bytes each) from the CUDA array src starting at hOffset rows and wOffset bytes from the upper left corner to the memory area pointed to by dst, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. dpitch is the width in memory in bytes of the 2D array pointed to by dst, including any padding added to the end of each row. wOffset + width must not exceed the width of the CUDA array src. width must not exceed dpitch.cudaMemcpy2DFromArray()
returns an error if dpitch exceeds the maximum allowed.- Parameters:
dst (Any) – Destination memory address
dpitch (size_t) – Pitch of destination memory
src (
cudaArray_const_t
) – Source memory addresswOffset (size_t) – Source starting X offset (columns in bytes)
hOffset (size_t) – Source starting Y offset (rows)
width (size_t) – Width of matrix transfer (columns in bytes)
height (size_t) – Height of matrix transfer (rows)
kind (
cudaMemcpyKind
) – Type of transfer
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpy2D
,cuMemcpy2DUnaligned
- cuda.cudart.cudaMemcpy2DArrayToArray(dst, size_t wOffsetDst, size_t hOffsetDst, src, size_t wOffsetSrc, size_t hOffsetSrc, size_t width, size_t height, kind: cudaMemcpyKind)#
Copies data between host and device.
Copies a matrix (height rows of width bytes each) from the CUDA array src starting at hOffsetSrc rows and wOffsetSrc bytes from the upper left corner to the CUDA array dst starting at hOffsetDst rows and wOffsetDst bytes from the upper left corner, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. wOffsetDst + width must not exceed the width of the CUDA array dst. wOffsetSrc + width must not exceed the width of the CUDA array src.- Parameters:
dst (
cudaArray_t
) – Destination memory addresswOffsetDst (size_t) – Destination starting X offset (columns in bytes)
hOffsetDst (size_t) – Destination starting Y offset (rows)
src (
cudaArray_const_t
) – Source memory addresswOffsetSrc (size_t) – Source starting X offset (columns in bytes)
hOffsetSrc (size_t) – Source starting Y offset (rows)
width (size_t) – Width of matrix transfer (columns in bytes)
height (size_t) – Height of matrix transfer (rows)
kind (
cudaMemcpyKind
) – Type of transfer
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpy2D
,cuMemcpy2DUnaligned
- cuda.cudart.cudaMemcpyAsync(dst, src, size_t count, kind: cudaMemcpyKind, stream)#
Copies data between host and device.
Copies count bytes from the memory area pointed to by src to the memory area pointed to by dst, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing.The memory areas may not overlap. Calling
cudaMemcpyAsync()
with dst and src pointers that do not match the direction of the copy results in an undefined behavior.cudaMemcpyAsync()
is asynchronous with respect to the host, so the call may return before the copy is complete. The copy can optionally be associated to a stream by passing a non-zero stream argument. If kind iscudaMemcpyHostToDevice
orcudaMemcpyDeviceToHost
and the stream is non-zero, the copy may overlap with operations in other streams.The device version of this function only handles device to device copies and cannot be given local or shared pointers.
- Parameters:
dst (Any) – Destination memory address
src (Any) – Source memory address
count (size_t) – Size in bytes to copy
kind (
cudaMemcpyKind
) – Type of transferstream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpyAsync
,cuMemcpyDtoHAsync
,cuMemcpyHtoDAsync
,cuMemcpyDtoDAsync
- cuda.cudart.cudaMemcpyPeerAsync(dst, int dstDevice, src, int srcDevice, size_t count, stream)#
Copies memory between two devices asynchronously.
Copies memory from one device to memory on another device. dst is the base device pointer of the destination memory and dstDevice is the destination device. src is the base device pointer of the source memory and srcDevice is the source device. count specifies the number of bytes to copy.
Note that this function is asynchronous with respect to the host and all work on other devices.
- Parameters:
dst (Any) – Destination device pointer
dstDevice (int) – Destination device
src (Any) – Source device pointer
srcDevice (int) – Source device
count (size_t) – Size of memory copy in bytes
stream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
- Return type:
- cuda.cudart.cudaMemcpy2DAsync(dst, size_t dpitch, src, size_t spitch, size_t width, size_t height, kind: cudaMemcpyKind, stream)#
Copies data between host and device.
Copies a matrix (height rows of width bytes each) from the memory area pointed to by src to the memory area pointed to by dst, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. dpitch and spitch are the widths in memory in bytes of the 2D arrays pointed to by dst and src, including any padding added to the end of each row. The memory areas may not overlap. width must not exceed either dpitch or spitch.Calling
cudaMemcpy2DAsync()
with dst and src pointers that do not match the direction of the copy results in an undefined behavior.cudaMemcpy2DAsync()
returns an error if dpitch or spitch is greater than the maximum allowed.cudaMemcpy2DAsync()
is asynchronous with respect to the host, so the call may return before the copy is complete. The copy can optionally be associated to a stream by passing a non-zero stream argument. If kind iscudaMemcpyHostToDevice
orcudaMemcpyDeviceToHost
and stream is non-zero, the copy may overlap with operations in other streams.The device version of this function only handles device to device copies and cannot be given local or shared pointers.
- Parameters:
dst (Any) – Destination memory address
dpitch (size_t) – Pitch of destination memory
src (Any) – Source memory address
spitch (size_t) – Pitch of source memory
width (size_t) – Width of matrix transfer (columns in bytes)
height (size_t) – Height of matrix transfer (rows)
kind (
cudaMemcpyKind
) – Type of transferstream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DToArrayAsync
,cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpy2DAsync
- cuda.cudart.cudaMemcpy2DToArrayAsync(dst, size_t wOffset, size_t hOffset, src, size_t spitch, size_t width, size_t height, kind: cudaMemcpyKind, stream)#
Copies data between host and device.
Copies a matrix (height rows of width bytes each) from the memory area pointed to by src to the CUDA array dst starting at hOffset rows and wOffset bytes from the upper left corner, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. spitch is the width in memory in bytes of the 2D array pointed to by src, including any padding added to the end of each row. wOffset + width must not exceed the width of the CUDA array dst. width must not exceed spitch.cudaMemcpy2DToArrayAsync()
returns an error if spitch exceeds the maximum allowed.cudaMemcpy2DToArrayAsync()
is asynchronous with respect to the host, so the call may return before the copy is complete. The copy can optionally be associated to a stream by passing a non-zero stream argument. If kind iscudaMemcpyHostToDevice
orcudaMemcpyDeviceToHost
and stream is non-zero, the copy may overlap with operations in other streams.cudaMemcpy2DFromArrayAsync
,cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpy2DAsync
- Parameters:
dst (
cudaArray_t
) – Destination memory addresswOffset (size_t) – Destination starting X offset (columns in bytes)
hOffset (size_t) – Destination starting Y offset (rows)
src (Any) – Source memory address
spitch (size_t) – Pitch of source memory
width (size_t) – Width of matrix transfer (columns in bytes)
height (size_t) – Height of matrix transfer (rows)
kind (
cudaMemcpyKind
) – Type of transferstream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
- cuda.cudart.cudaMemcpy2DFromArrayAsync(dst, size_t dpitch, src, size_t wOffset, size_t hOffset, size_t width, size_t height, kind: cudaMemcpyKind, stream)#
Copies data between host and device.
Copies a matrix (height rows of width bytes each) from the CUDA array src starting at hOffset rows and wOffset bytes from the upper left corner to the memory area pointed to by dst, where kind specifies the direction of the copy, and must be one of
cudaMemcpyHostToHost
,cudaMemcpyHostToDevice
,cudaMemcpyDeviceToHost
,cudaMemcpyDeviceToDevice
, orcudaMemcpyDefault
. PassingcudaMemcpyDefault
is recommended, in which case the type of transfer is inferred from the pointer values. However,cudaMemcpyDefault
is only allowed on systems that support unified virtual addressing. dpitch is the width in memory in bytes of the 2D array pointed to by dst, including any padding added to the end of each row. wOffset + width must not exceed the width of the CUDA array src. width must not exceed dpitch.cudaMemcpy2DFromArrayAsync()
returns an error if dpitch exceeds the maximum allowed.cudaMemcpy2DFromArrayAsync()
is asynchronous with respect to the host, so the call may return before the copy is complete. The copy can optionally be associated to a stream by passing a non-zero stream argument. If kind iscudaMemcpyHostToDevice
orcudaMemcpyDeviceToHost
and stream is non-zero, the copy may overlap with operations in other streams.cudaMemcpyToSymbolAsync
,cudaMemcpyFromSymbolAsync
,cuMemcpy2DAsync
- Parameters:
dst (Any) – Destination memory address
dpitch (size_t) – Pitch of destination memory
src (
cudaArray_const_t
) – Source memory addresswOffset (size_t) – Source starting X offset (columns in bytes)
hOffset (size_t) – Source starting Y offset (rows)
width (size_t) – Width of matrix transfer (columns in bytes)
height (size_t) – Height of matrix transfer (rows)
kind (
cudaMemcpyKind
) – Type of transferstream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorInvalidPitchValue
,cudaErrorInvalidMemcpyDirection
- Return type:
See also
cudaMemcpy
,cudaMemcpy2D
,cudaMemcpy2DToArray
,cudaMemcpy2DFromArray
,cudaMemcpy2DArrayToArray
,cudaMemcpyToSymbol
,cudaMemcpyFromSymbol
,cudaMemcpyAsync
,cudaMemcpy2DAsync
,cudaMemcpy2DToArrayAsync
- cuda.cudart.cudaMemset(devPtr, int value, size_t count)#
Initializes or sets device memory to a value.
Fills the first count bytes of the memory area pointed to by devPtr with the constant byte value value.
Note that this function is asynchronous with respect to the host unless devPtr refers to pinned host memory.
- Parameters:
devPtr (Any) – Pointer to device memory
value (int) – Value to set for each byte of specified memory
count (size_t) – Size in bytes to set
- Returns:
- Return type:
See also
- cuda.cudart.cudaMemset2D(devPtr, size_t pitch, int value, size_t width, size_t height)#
Initializes or sets device memory to a value.
Sets to the specified value value a matrix (height rows of width bytes each) pointed to by dstPtr. pitch is the width in bytes of the 2D array pointed to by dstPtr, including any padding added to the end of each row. This function performs fastest when the pitch is one that has been passed back by
cudaMallocPitch()
.Note that this function is asynchronous with respect to the host unless devPtr refers to pinned host memory.
- Parameters:
devPtr (Any) – Pointer to 2D device memory
pitch (size_t) – Pitch in bytes of 2D device memory(Unused if height is 1)
value (int) – Value to set for each byte of specified memory
width (size_t) – Width of matrix set (columns in bytes)
height (size_t) – Height of matrix set (rows)
- Returns:
- Return type:
- cuda.cudart.cudaMemset3D(cudaPitchedPtr pitchedDevPtr: cudaPitchedPtr, int value, cudaExtent extent: cudaExtent)#
Initializes or sets device memory to a value.
Initializes each element of a 3D array to the specified value value. The object to initialize is defined by pitchedDevPtr. The pitch field of pitchedDevPtr is the width in memory in bytes of the 3D array pointed to by pitchedDevPtr, including any padding added to the end of each row. The xsize field specifies the logical width of each row in bytes, while the ysize field specifies the height of each 2D slice in rows. The pitch field of pitchedDevPtr is ignored when height and depth are both equal to 1.
The extents of the initialized region are specified as a width in bytes, a height in rows, and a depth in slices.
Extents with width greater than or equal to the xsize of pitchedDevPtr may perform significantly faster than extents narrower than the xsize. Secondarily, extents with height equal to the ysize of pitchedDevPtr will perform faster than when the height is shorter than the ysize.
This function performs fastest when the pitchedDevPtr has been allocated by
cudaMalloc3D()
.Note that this function is asynchronous with respect to the host unless pitchedDevPtr refers to pinned host memory.
- Parameters:
pitchedDevPtr (
cudaPitchedPtr
) – Pointer to pitched device memoryvalue (int) – Value to set for each byte of specified memory
extent (
cudaExtent
) – Size parameters for where to set device memory (width field in bytes)
- Returns:
- Return type:
- cuda.cudart.cudaMemsetAsync(devPtr, int value, size_t count, stream)#
Initializes or sets device memory to a value.
Fills the first count bytes of the memory area pointed to by devPtr with the constant byte value value.
cudaMemsetAsync()
is asynchronous with respect to the host, so the call may return before the memset is complete. The operation can optionally be associated to a stream by passing a non-zero stream argument. If stream is non-zero, the operation may overlap with operations in other streams.The device version of this function only handles device to device copies and cannot be given local or shared pointers.
- Parameters:
devPtr (Any) – Pointer to device memory
value (int) – Value to set for each byte of specified memory
count (size_t) – Size in bytes to set
stream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
- Return type:
- cuda.cudart.cudaMemset2DAsync(devPtr, size_t pitch, int value, size_t width, size_t height, stream)#
Initializes or sets device memory to a value.
Sets to the specified value value a matrix (height rows of width bytes each) pointed to by dstPtr. pitch is the width in bytes of the 2D array pointed to by dstPtr, including any padding added to the end of each row. This function performs fastest when the pitch is one that has been passed back by
cudaMallocPitch()
.cudaMemset2DAsync()
is asynchronous with respect to the host, so the call may return before the memset is complete. The operation can optionally be associated to a stream by passing a non- zero stream argument. If stream is non-zero, the operation may overlap with operations in other streams.The device version of this function only handles device to device copies and cannot be given local or shared pointers.
- Parameters:
devPtr (Any) – Pointer to 2D device memory
pitch (size_t) – Pitch in bytes of 2D device memory(Unused if height is 1)
value (int) – Value to set for each byte of specified memory
width (size_t) – Width of matrix set (columns in bytes)
height (size_t) – Height of matrix set (rows)
stream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
- Return type:
- cuda.cudart.cudaMemset3DAsync(cudaPitchedPtr pitchedDevPtr: cudaPitchedPtr, int value, cudaExtent extent: cudaExtent, stream)#
Initializes or sets device memory to a value.
Initializes each element of a 3D array to the specified value value. The object to initialize is defined by pitchedDevPtr. The pitch field of pitchedDevPtr is the width in memory in bytes of the 3D array pointed to by pitchedDevPtr, including any padding added to the end of each row. The xsize field specifies the logical width of each row in bytes, while the ysize field specifies the height of each 2D slice in rows. The pitch field of pitchedDevPtr is ignored when height and depth are both equal to 1.
The extents of the initialized region are specified as a width in bytes, a height in rows, and a depth in slices.
Extents with width greater than or equal to the xsize of pitchedDevPtr may perform significantly faster than extents narrower than the xsize. Secondarily, extents with height equal to the ysize of pitchedDevPtr will perform faster than when the height is shorter than the ysize.
This function performs fastest when the pitchedDevPtr has been allocated by
cudaMalloc3D()
.cudaMemset3DAsync()
is asynchronous with respect to the host, so the call may return before the memset is complete. The operation can optionally be associated to a stream by passing a non- zero stream argument. If stream is non-zero, the operation may overlap with operations in other streams.The device version of this function only handles device to device copies and cannot be given local or shared pointers.
- Parameters:
pitchedDevPtr (
cudaPitchedPtr
) – Pointer to pitched device memoryvalue (int) – Value to set for each byte of specified memory
extent (
cudaExtent
) – Size parameters for where to set device memory (width field in bytes)stream (
CUstream
orcudaStream_t
) – Stream identifier
- Returns:
- Return type:
- cuda.cudart.cudaMemPrefetchAsync(devPtr, size_t count, int dstDevice, stream)#
Prefetches memory to the specified destination device.
Prefetches memory to the specified destination device. devPtr is the base device pointer of the memory to be prefetched and dstDevice is the destination device. count specifies the number of bytes to copy. stream is the stream in which the operation is enqueued. The memory range must refer to managed memory allocated via
cudaMallocManaged
or declared via managed variables.Passing in cudaCpuDeviceId for dstDevice will prefetch the data to host memory. If dstDevice is a GPU, then the device attribute
cudaDevAttrConcurrentManagedAccess
must be non-zero. Additionally, stream must be associated with a device that has a non- zero value for the device attributecudaDevAttrConcurrentManagedAccess
.The start address and end address of the memory range will be rounded down and rounded up respectively to be aligned to CPU page size before the prefetch operation is enqueued in the stream.
If no physical memory has been allocated for this region, then this memory region will be populated and mapped on the destination device. If there’s insufficient memory to prefetch the desired region, the Unified Memory driver may evict pages from other
cudaMallocManaged
allocations to host memory in order to make room. Device memory allocated usingcudaMalloc
orcudaMallocArray
will not be evicted.By default, any mappings to the previous location of the migrated pages are removed and mappings for the new location are only setup on dstDevice. The exact behavior however also depends on the settings applied to this memory range via
cudaMemAdvise
as described below:If
cudaMemAdviseSetReadMostly
was set on any subset of this memory range, then that subset will create a read-only copy of the pages on dstDevice.If
cudaMemAdviseSetPreferredLocation
was called on any subset of this memory range, then the pages will be migrated to dstDevice even if dstDevice is not the preferred location of any pages in the memory range.If
cudaMemAdviseSetAccessedBy
was called on any subset of this memory range, then mappings to those pages from all the appropriate processors are updated to refer to the new location if establishing such a mapping is possible. Otherwise, those mappings are cleared.Note that this API is not required for functionality and only serves to improve performance by allowing the application to migrate data to a suitable location before it is accessed. Memory accesses to this range are always coherent and are allowed even when the data is actively being migrated.
Note that this function is asynchronous with respect to the host and all work on other devices.
- Parameters:
devPtr (Any) – Pointer to be prefetched
count (size_t) – Size in bytes
dstDevice (int) – Destination device to prefetch to
stream (
CUstream
orcudaStream_t
) – Stream to enqueue prefetch operation
- Returns:
- Return type:
- cuda.cudart.cudaMemAdvise(devPtr, size_t count, advice: cudaMemoryAdvise, int device)#
Advise about the usage of a given memory range.
Advise the Unified Memory subsystem about the usage pattern for the memory range starting at devPtr with a size of count bytes. The start address and end address of the memory range will be rounded down and rounded up respectively to be aligned to CPU page size before the advice is applied. The memory range must refer to managed memory allocated via
cudaMallocManaged
or declared via managed variables. The memory range could also refer to system-allocated pageable memory provided it represents a valid, host-accessible region of memory and all additional constraints imposed by advice as outlined below are also satisfied. Specifying an invalid system- allocated pageable memory range results in an error being returned.The advice parameter can take the following values:
cudaMemAdviseSetReadMostly
: This implies that the data is mostly going to be read from and only occasionally written to. Any read accesses from any processor to this region will create a read- only copy of at least the accessed pages in that processor’s memory. Additionally, ifcudaMemPrefetchAsync
is called on this region, it will create a read-only copy of the data on the destination processor. If any processor writes to this region, all copies of the corresponding page will be invalidated except for the one where the write occurred. The device argument is ignored for this advice. Note that for a page to be read-duplicated, the accessing processor must either be the CPU or a GPU that has a non- zero value for the device attributecudaDevAttrConcurrentManagedAccess
. Also, if a context is created on a device that does not have the device attributecudaDevAttrConcurrentManagedAccess
set, then read- duplication will not occur until all such contexts are destroyed. If the memory region refers to valid system-allocated pageable memory, then the accessing device must have a non-zero value for the device attributecudaDevAttrPageableMemoryAccess
for a read-only copy to be created on that device. Note however that if the accessing device also has a non-zero value for the device attributecudaDevAttrPageableMemoryAccessUsesHostPageTables
, then setting this advice will not create a read-only copy when that device accesses this memory region.cudaMemAdviceUnsetReadMostly
: Undoes the effect ofcudaMemAdviceReadMostly
and also prevents the Unified Memory driver from attempting heuristic read-duplication on the memory range. Any read-duplicated copies of the data will be collapsed into a single copy. The location for the collapsed copy will be the preferred location if the page has a preferred location and one of the read-duplicated copies was resident at that location. Otherwise, the location chosen is arbitrary.cudaMemAdviseSetPreferredLocation
: This advice sets the preferred location for the data to be the memory belonging to device. Passing in cudaCpuDeviceId for device sets the preferred location as host memory. If device is a GPU, then it must have a non-zero value for the device attributecudaDevAttrConcurrentManagedAccess
. Setting the preferred location does not cause data to migrate to that location immediately. Instead, it guides the migration policy when a fault occurs on that memory region. If the data is already in its preferred location and the faulting processor can establish a mapping without requiring the data to be migrated, then data migration will be avoided. On the other hand, if the data is not in its preferred location or if a direct mapping cannot be established, then it will be migrated to the processor accessing it. It is important to note that setting the preferred location does not prevent data prefetching done usingcudaMemPrefetchAsync
. Having a preferred location can override the page thrash detection and resolution logic in the Unified Memory driver. Normally, if a page is detected to be constantly thrashing between for example host and device memory, the page may eventually be pinned to host memory by the Unified Memory driver. But if the preferred location is set as device memory, then the page will continue to thrash indefinitely. IfcudaMemAdviseSetReadMostly
is also set on this memory region or any subset of it, then the policies associated with that advice will override the policies of this advice, unless read accesses from device will not result in a read-only copy being created on that device as outlined in description for the advicecudaMemAdviseSetReadMostly
. If the memory region refers to valid system-allocated pageable memory, then device must have a non-zero value for the device attributecudaDevAttrPageableMemoryAccess
. Additionally, if device has a non-zero value for the device attributecudaDevAttrPageableMemoryAccessUsesHostPageTables
, then this call has no effect. Note however that this behavior may change in the future.cudaMemAdviseUnsetPreferredLocation
: Undoes the effect ofcudaMemAdviseSetPreferredLocation
and changes the preferred location to none.cudaMemAdviseSetAccessedBy
: This advice implies that the data will be accessed by device. Passing incudaCpuDeviceId
for device will set the advice for the CPU. If device is a GPU, then the device attributecudaDevAttrConcurrentManagedAccess
must be non-zero. This advice does not cause data migration and has no impact on the location of the data per se. Instead, it causes the data to always be mapped in the specified processor’s page tables, as long as the location of the data permits a mapping to be established. If the data gets migrated for any reason, the mappings are updated accordingly. This advice is recommended in scenarios where data locality is not important, but avoiding faults is. Consider for example a system containing multiple GPUs with peer-to-peer access enabled, where the data located on one GPU is occasionally accessed by peer GPUs. In such scenarios, migrating data over to the other GPUs is not as important because the accesses are infrequent and the overhead of migration may be too high. But preventing faults can still help improve performance, and so having a mapping set up in advance is useful. Note that on CPU access of this data, the data may be migrated to host memory because the CPU typically cannot access device memory directly. Any GPU that had thecudaMemAdviceSetAccessedBy
flag set for this data will now have its mapping updated to point to the page in host memory. IfcudaMemAdviseSetReadMostly
is also set on this memory region or any subset of it, then the policies associated with that advice will override the policies of this advice. Additionally, if the preferred location of this memory region or any subset of it is also device, then the policies associated withcudaMemAdviseSetPreferredLocation
will override the policies of this advice. If the memory region refers to valid system- allocated pageable memory, then device must have a non-zero value for the device attributecudaDevAttrPageableMemoryAccess
. Additionally, if device has a non-zero value for the device attributecudaDevAttrPageableMemoryAccessUsesHostPageTables
, then this call has no effect.cudaMemAdviseUnsetAccessedBy
: Undoes the effect ofcudaMemAdviseSetAccessedBy
. Any mappings to the data from device may be removed at any time causing accesses to result in non-fatal page faults. If the memory region refers to valid system- allocated pageable memory, then device must have a non-zero value for the device attributecudaDevAttrPageableMemoryAccess
. Additionally, if device has a non-zero value for the device attributecudaDevAttrPageableMemoryAccessUsesHostPageTables
, then this call has no effect.
- Parameters:
devPtr (Any) – Pointer to memory to set the advice for
count (size_t) – Size in bytes of the memory range
advice (
cudaMemoryAdvise
) – Advice to be applied for the specified memory rangedevice (int) – Device to apply the advice for
- Returns:
- Return type:
- cuda.cudart.cudaMemRangeGetAttribute(size_t dataSize, attribute: cudaMemRangeAttribute, devPtr, size_t count)#
Query an attribute of a given memory range.
Query an attribute about the memory range starting at devPtr with a size of count bytes. The memory range must refer to managed memory allocated via
cudaMallocManaged
or declared via managed variables.The attribute parameter can take the following values:
cudaMemRangeAttributeReadMostly
: If this attribute is specified, data will be interpreted as a 32-bit integer, and dataSize must be 4. The result returned will be 1 if all pages in the given memory range have read-duplication enabled, or 0 otherwise.cudaMemRangeAttributePreferredLocation
: If this attribute is specified, data will be interpreted as a 32-bit integer, and dataSize must be 4. The result returned will be a GPU device id if all pages in the memory range have that GPU as their preferred location, or it will be cudaCpuDeviceId if all pages in the memory range have the CPU as their preferred location, or it will be cudaInvalidDeviceId if either all the pages don’t have the same preferred location or some of the pages don’t have a preferred location at all. Note that the actual location of the pages in the memory range at the time of the query may be different from the preferred location.cudaMemRangeAttributeAccessedBy
: If this attribute is specified, data will be interpreted as an array of 32-bit integers, and dataSize must be a non-zero multiple of 4. The result returned will be a list of device ids that hadcudaMemAdviceSetAccessedBy
set for that entire memory range. If any device does not have that advice set for the entire memory range, that device will not be included. If data is larger than the number of devices that have that advice set for that memory range, cudaInvalidDeviceId will be returned in all the extra space provided. For ex., if dataSize is 12 (i.e. data has 3 elements) and only device 0 has the advice set, then the result returned will be { 0, cudaInvalidDeviceId, cudaInvalidDeviceId }. If data is smaller than the number of devices that have that advice set, then only as many devices will be returned as can fit in the array. There is no guarantee on which specific devices will be returned, however.cudaMemRangeAttributeLastPrefetchLocation
: If this attribute is specified, data will be interpreted as a 32-bit integer, and dataSize must be 4. The result returned will be the last location to which all pages in the memory range were prefetched explicitly viacudaMemPrefetchAsync
. This will either be a GPU id or cudaCpuDeviceId depending on whether the last location for prefetch was a GPU or the CPU respectively. If any page in the memory range was never explicitly prefetched or if all pages were not prefetched to the same location, cudaInvalidDeviceId will be returned. Note that this simply returns the last location that the applicaton requested to prefetch the memory range to. It gives no indication as to whether the prefetch operation to that location has completed or even begun.
- Parameters:
dataSize (size_t) – Array containing the size of data
attribute (
cudaMemRangeAttribute
) – The attribute to querydevPtr (Any) – Start of the range to query
count (size_t) – Size of the range to query
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
data (Any) – A pointers to a memory location where the result of each attribute query will be written to.
- cuda.cudart.cudaMemRangeGetAttributes(dataSizes: List[int], attributes: List[cudaMemRangeAttribute], size_t numAttributes, devPtr, size_t count)#
Query attributes of a given memory range.
Query attributes of the memory range starting at devPtr with a size of count bytes. The memory range must refer to managed memory allocated via
cudaMallocManaged
or declared via managed variables. The attributes array will be interpreted to have numAttributes entries. The dataSizes array will also be interpreted to have numAttributes entries. The results of the query will be stored in data.The list of supported attributes are given below. Please refer to
cudaMemRangeGetAttribute
for attribute descriptions and restrictions.- Parameters:
dataSizes (List[int]) – Array containing the sizes of each result
attributes (List[
cudaMemRangeAttribute
]) – An array of attributes to query (numAttributes and the number of attributes in this array should match)numAttributes (size_t) – Number of attributes to query
devPtr (Any) – Start of the range to query
count (size_t) – Size of the range to query
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
data (List[Any]) – A two-dimensional array containing pointers to memory locations where the result of each attribute query will be written to.
- cuda.cudart.make_cudaPitchedPtr(d, size_t p, size_t xsz, size_t ysz)#
Returns a
cudaPitchedPtr
based on input parameters.Returns a
cudaPitchedPtr
based on the specified input parameters d, p, xsz, and ysz.- Parameters:
d (Any) – Pointer to allocated memory
p (size_t) – Pitch of allocated memory in bytes
xsz (size_t) – Logical width of allocation in elements
ysz (size_t) – Logical height of allocation in elements
- Returns:
cudaError_t.cudaSuccess – cudaError_t.cudaSuccess
cudaPitchedPtr
–cudaPitchedPtr
specified by d, p, xsz, and ysz
See also
- cuda.cudart.make_cudaPos(size_t x, size_t y, size_t z)#
Returns a
cudaPos
based on input parameters.Returns a
cudaPos
based on the specified input parameters x, y, and z.- Parameters:
x (size_t) – X position
y (size_t) – Y position
z (size_t) – Z position
- Returns:
See also
- cuda.cudart.make_cudaExtent(size_t w, size_t h, size_t d)#
Returns a
cudaExtent
based on input parameters.Returns a
cudaExtent
based on the specified input parameters w, h, and d.- Parameters:
w (size_t) – Width in elements when referring to array memory, in bytes when referring to linear memory
h (size_t) – Height in elements
d (size_t) – Depth in elements
- Returns:
cudaError_t.cudaSuccess – cudaError_t.cudaSuccess
cudaExtent
–cudaExtent
specified by w, h, and d
See also
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.
- cuda.cudart.cudaMallocAsync(size_t size, hStream)#
Allocates memory with stream ordered semantics.
Inserts an allocation operation into hStream. A pointer to the allocated memory is returned immediately in *dptr. The allocation must not be accessed until the the allocation operation completes. The allocation comes from the memory pool associated with the stream’s device.
- Parameters:
size (size_t) – Number of bytes to allocate
hStream (
CUstream
orcudaStream_t
) – The stream establishing the stream ordering contract and the memory pool to allocate from
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorNotSupported
,cudaErrorOutOfMemory
,devPtr (Any) – Returned device pointer
See also
cuMemAllocAsync
,cudaMallocAsync
,cudaMallocFromPoolAsync
,cudaFreeAsync
,cudaDeviceSetMemPool
,cudaDeviceGetDefaultMemPool
,cudaDeviceGetMemPool
,cudaMemPoolSetAccess
,cudaMemPoolSetAttribute
,cudaMemPoolGetAttribute
Notes
The default memory pool of a device contains device memory from that device.
Basic stream ordering allows future work submitted into the same stream to use the allocation. Stream query, stream synchronize, and CUDA events can be used to guarantee that the allocation operation completes before work submitted in a separate stream runs.
During stream capture, this function results in the creation of an allocation node. In this case, the allocation is owned by the graph instead of the memory pool. The memory pool’s properties are used to set the node’s creation parameters.
- cuda.cudart.cudaFreeAsync(devPtr, hStream)#
Frees memory with stream ordered semantics.
Inserts a free operation into hStream. The allocation must not be accessed after stream execution reaches the free. After this API returns, accessing the memory from any subsequent work launched on the GPU or querying its pointer attributes results in undefined behavior.
- Parameters:
dptr (Any) – memory to free
hStream (
CUstream
orcudaStream_t
) – The stream establishing the stream ordering promise
- Returns:
- Return type:
See also
Notes
During stream capture, this function results in the creation of a free node and must therefore be passed the address of a graph allocation.
- cuda.cudart.cudaMemPoolTrimTo(memPool, size_t minBytesToKeep)#
Tries to release memory back to the OS.
Releases memory back to the OS until the pool contains fewer than minBytesToKeep reserved bytes, or there is no more memory that the allocator can safely release. The allocator cannot release OS allocations that back outstanding asynchronous allocations. The OS allocations may happen at different granularity from the user allocations.
- Parameters:
pool (
CUmemoryPool
orcudaMemPool_t
) – The memory pool to trimminBytesToKeep (size_t) – If the pool has less than minBytesToKeep reserved, the TrimTo operation is a no-op. Otherwise the pool will be guaranteed to have at least minBytesToKeep bytes reserved after the operation.
- Returns:
- Return type:
See also
cuMemPoolTrimTo
,cudaMallocAsync
,cudaFreeAsync
,cudaDeviceGetDefaultMemPool
,cudaDeviceGetMemPool
,cudaMemPoolCreate
Notes
: Allocations that have not been freed count as outstanding.
: Allocations that have been asynchronously freed but whose completion has not been observed on the host (eg. by a synchronize) can count as outstanding.
- cuda.cudart.cudaMemPoolSetAttribute(memPool, attr: cudaMemPoolAttr, value)#
Sets attributes of a memory pool.
Supported attributes are:
cudaMemPoolAttrReleaseThreshold
: (value type = cuuint64_t) Amount of reserved memory in bytes to hold onto before trying to release memory back to the OS. When more than the release threshold bytes of memory are held by the memory pool, the allocator will try to release memory back to the OS on the next call to stream, event or context synchronize. (default 0)cudaMemPoolReuseFollowEventDependencies
: (value type = int) AllowcudaMallocAsync
to use memory asynchronously freed in another stream as long as a stream ordering dependency of the allocating stream on the free action exists. Cuda events and null stream interactions can create the required stream ordered dependencies. (default enabled)cudaMemPoolReuseAllowOpportunistic
: (value type = int) Allow reuse of already completed frees when there is no dependency between the free and allocation. (default enabled)cudaMemPoolReuseAllowInternalDependencies
: (value type = int) AllowcudaMallocAsync
to insert new stream dependencies in order to establish the stream ordering required to reuse a piece of memory released bycudaFreeAsync
(default enabled).cudaMemPoolAttrReservedMemHigh
: (value type = cuuint64_t) Reset the high watermark that tracks the amount of backing memory that was allocated for the memory pool. It is illegal to set this attribute to a non-zero value.cudaMemPoolAttrUsedMemHigh
: (value type = cuuint64_t) Reset the high watermark that tracks the amount of used memory that was allocated for the memory pool. It is illegal to set this attribute to a non-zero value.
- Parameters:
pool (
CUmemoryPool
orcudaMemPool_t
) – The memory pool to modifyattr (
cudaMemPoolAttr
) – The attribute to modifyvalue (Any) – Pointer to the value to assign
- Returns:
- Return type:
- cuda.cudart.cudaMemPoolGetAttribute(memPool, attr: cudaMemPoolAttr)#
Gets attributes of a memory pool.
Supported attributes are:
cudaMemPoolAttrReleaseThreshold
: (value type = cuuint64_t) Amount of reserved memory in bytes to hold onto before trying to release memory back to the OS. When more than the release threshold bytes of memory are held by the memory pool, the allocator will try to release memory back to the OS on the next call to stream, event or context synchronize. (default 0)cudaMemPoolReuseFollowEventDependencies
: (value type = int) AllowcudaMallocAsync
to use memory asynchronously freed in another stream as long as a stream ordering dependency of the allocating stream on the free action exists. Cuda events and null stream interactions can create the required stream ordered dependencies. (default enabled)cudaMemPoolReuseAllowOpportunistic
: (value type = int) Allow reuse of already completed frees when there is no dependency between the free and allocation. (default enabled)cudaMemPoolReuseAllowInternalDependencies
: (value type = int) AllowcudaMallocAsync
to insert new stream dependencies in order to establish the stream ordering required to reuse a piece of memory released bycudaFreeAsync
(default enabled).cudaMemPoolAttrReservedMemCurrent
: (value type = cuuint64_t) Amount of backing memory currently allocated for the mempool.cudaMemPoolAttrReservedMemHigh
: (value type = cuuint64_t) High watermark of backing memory allocated for the mempool since the last time it was reset.cudaMemPoolAttrUsedMemCurrent
: (value type = cuuint64_t) Amount of memory from the pool that is currently in use by the application.cudaMemPoolAttrUsedMemHigh
: (value type = cuuint64_t) High watermark of the amount of memory from the pool that was in use by the application since the last time it was reset.
- Parameters:
pool (
CUmemoryPool
orcudaMemPool_t
) – The memory pool to get attributes ofattr (
cudaMemPoolAttr
) – The attribute to get
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
value (Any) – Retrieved value
- cuda.cudart.cudaMemPoolSetAccess(memPool, descList: List[cudaMemAccessDesc], size_t count)#
Controls visibility of pools between devices.
- Parameters:
pool (
CUmemoryPool
orcudaMemPool_t
) – The pool being modifiedmap (List[
cudaMemAccessDesc
]) – Array of access descriptors. Each descriptor instructs the access to enable for a single gpucount (size_t) – Number of descriptors in the map array.
- Returns:
- Return type:
- cuda.cudart.cudaMemPoolGetAccess(memPool, cudaMemLocation location: cudaMemLocation)#
Returns the accessibility of a pool from a device.
Returns the accessibility of the pool’s memory from the specified location.
- Parameters:
memPool (
CUmemoryPool
orcudaMemPool_t
) – the pool being queriedlocation (
cudaMemLocation
) – the location accessing the pool
- Returns:
cudaError_t
flags (
cudaMemAccessFlags
) – the accessibility of the pool from the specified location
See also
- cuda.cudart.cudaMemPoolCreate(cudaMemPoolProps poolProps: cudaMemPoolProps)#
Creates a memory pool.
Creates a CUDA memory pool and returns the handle in pool. The poolProps determines the properties of the pool such as the backing device and IPC capabilities.
By default, the pool’s memory will be accessible from the device it is allocated on.
- Parameters:
poolProps (
cudaMemPoolProps
) – None- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorNotSupported
memPool (
cudaMemPool_t
) – None
See also
cuMemPoolCreate
,cudaDeviceSetMemPool
,cudaMallocFromPoolAsync
,cudaMemPoolExportToShareableHandle
,cudaDeviceGetDefaultMemPool
,cudaDeviceGetMemPool
Notes
Specifying cudaMemHandleTypeNone creates a memory pool that will not support IPC.
- cuda.cudart.cudaMemPoolDestroy(memPool)#
Destroys the specified memory pool.
If any pointers obtained from this pool haven’t been freed or the pool has free operations that haven’t completed when
cudaMemPoolDestroy
is invoked, the function will return immediately and the resources associated with the pool will be released automatically once there are no more outstanding allocations.Destroying the current mempool of a device sets the default mempool of that device as the current mempool for that device.
- Parameters:
memPool (
CUmemoryPool
orcudaMemPool_t
) – None- Returns:
- Return type:
See also
cuMemPoolDestroy
,cudaFreeAsync
,cudaDeviceSetMemPool
,cudaDeviceGetDefaultMemPool
,cudaDeviceGetMemPool
,cudaMemPoolCreate
Notes
A device’s default memory pool cannot be destroyed.
- cuda.cudart.cudaMallocFromPoolAsync(size_t size, memPool, stream)#
Allocates memory from a specified pool with stream ordered semantics.
Inserts an allocation operation into hStream. A pointer to the allocated memory is returned immediately in *dptr. The allocation must not be accessed until the the allocation operation completes. The allocation comes from the specified memory pool.
- Parameters:
bytesize (size_t) – Number of bytes to allocate
memPool (
CUmemoryPool
orcudaMemPool_t
) – The pool to allocate fromstream (
CUstream
orcudaStream_t
) – The stream establishing the stream ordering semantic
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorNotSupported
,cudaErrorOutOfMemory
ptr (Any) – Returned device pointer
See also
cuMemAllocFromPoolAsync
,cudaMallocAsync
,cudaMallocAsync
,cudaFreeAsync
,cudaDeviceGetDefaultMemPool
,cudaMemPoolCreate
,cudaMemPoolSetAccess
,cudaMemPoolSetAttribute
Notes
During stream capture, this function results in the creation of an allocation node. In this case, the allocation is owned by the graph instead of the memory pool. The memory pool’s properties are used to set the node’s creation parameters.
Exports a memory pool to the requested handle type.
Given an IPC capable mempool, create an OS handle to share the pool with another process. A recipient process can convert the shareable handle into a mempool with
cudaMemPoolImportFromShareableHandle
. Individual pointers can then be shared with thecudaMemPoolExportPointer
andcudaMemPoolImportPointer
APIs. The implementation of what the shareable handle is and how it can be transferred is defined by the requested handle type.- Parameters:
pool (
CUmemoryPool
orcudaMemPool_t
) – pool to exporthandleType (
cudaMemAllocationHandleType
) – the type of handle to createflags (unsigned int) – must be 0
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorOutOfMemory
handle_out (Any) – pointer to the location in which to store the requested handle
See also
cuMemPoolExportToShareableHandle
,cudaMemPoolImportFromShareableHandle
,cudaMemPoolExportPointer
,cudaMemPoolImportPointer
Notes
: To create an IPC capable mempool, create a mempool with a CUmemAllocationHandleType other than cudaMemHandleTypeNone.
imports a memory pool from a shared handle.
Specific allocations can be imported from the imported pool with
cudaMemPoolImportPointer
.- Parameters:
handle (Any) – OS handle of the pool to open
handleType (
cudaMemAllocationHandleType
) – The type of handle being importedflags (unsigned int) – must be 0
- Returns:
cudaError_t –
cudaSuccess
,cudaErrorInvalidValue
,cudaErrorOutOfMemory
pool_out (
cudaMemPool_t
) – Returned memory pool
See also
cuMemPoolImportFromShareableHandle
,cudaMemPoolExportToShareableHandle
,cudaMemPoolExportPointer
,cudaMemPoolImportPointer
Notes
Imported memory pools do not support creating new allocations. As such imported memory pools may not be used in
cudaDeviceSetMemPool
orcudaMallocFromPoolAsync
calls.